v1.1 batch 2: sidebar restructure — chats under projects, max 5 + view-all, live updates

Schema (idempotent):
  ALTER TABLE sessions ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp();
The column already exists from v1 (DEFAULT NOW()); ALTER is a no-op kept for
self-documentation. Explicit clock_timestamp() bumps now run wherever the
column actually matters — see services/inference.ts and routes/sessions.ts.

Backend updated_at maintenance:
- services/inference.ts: after each terminal status UPDATE on the assistant
  message (failure / tool-call complete / clean complete), also bump
  sessions.updated_at = clock_timestamp() so the parent session jumps to
  the top of recency ordering on every assistant turn.
- routes/sessions.ts PATCH: NOW() → clock_timestamp() for consistency.

New endpoint GET /api/sidebar (routes/sidebar.ts):
  { projects: [{ id, name, recent_sessions[≤6], total_sessions }] }
One outer query for projects ordered added_at DESC; per-project Promise.all
over (recent_sessions LIMIT 6 ORDER BY updated_at DESC) and COUNT(*)::int.
Outer Promise.all parallelizes across projects. Two queries per project; the
composite idx_sessions_project(project_id, updated_at DESC) serves the inner
query. Auth via the global Remote-User hook. types/api.ts gains
SidebarSession / SidebarProject / SidebarResponse; index.ts wires the route.

Frontend foundations:
- api/types.ts mirrors the three sidebar interfaces.
- api/client.ts: api.sidebar.get() → Promise<SidebarResponse>.
- hooks/sessionEvents.ts: five-variant union — added project_created,
  project_deleted, session_created, session_deleted. session_renamed
  unchanged from Batch 1. Bus internals untouched (still a dumb
  Set<Listener>, no validation).

New hooks/useSidebar.ts (module-singleton):
- Module-scope sharedData/sharedError/sharedLoading/initialized/fetchInFlight/
  subscribers; a single sessionEvents.subscribe at module-top-level mutates
  sharedData via an exhaustive switch over the five events. load() dedupes
  parallel calls via fetchInFlight. Hook is a thin subscription layer: any
  number of mount points share state and the very first one triggers the
  single GET /api/sidebar. Subsequent mounts read cached state synchronously
  (no skeleton flash). Public shape: { data, error, loading, retry }.
- Lift to module-scope was driven by the "ONE sidebar request on mount"
  spec promise — both ProjectSidebar AND Home consume the hook now, and
  they share the singleton.

Frontend UI:
- components/ProjectSidebar.tsx (rewrite, 234 lines): per-project chevron +
  folder + name; chevron toggles expand, name navigates /project/:id.
  Expanded → ≤5 sessions with MessageSquare + name + muted relTime()
  timestamp. "View all (N)" link when total_sessions > 5, routing to
  /project/:id. Active session row uses bg-sidebar-accent. Active project
  always renders expanded (URL-derived: direct /project/:id or scan of
  recent_sessions for /session/:id). Expanded ids persisted in
  localStorage['boocode.sidebar.expanded'] with try/catch on both read and
  write. Loading shows 4 muted-pulse skeleton blocks; empty + error +
  retry button; error toast guarded by ref so it fires once per distinct
  message and resets on recovery. Remove path calls api.projects.remove
  directly + explicit project_deleted emit (replaced the prior
  useProjects() dependency which fired a redundant /api/projects on
  mount, violating the one-fetch promise).
- components/AddProjectModal.tsx: captures returned Project and emits
  project_created before onAdded() / onOpenChange(false).
- pages/Project.tsx: emits session_created after create(); trash button is
  now async with try/catch — emits session_deleted on success,
  toast.error on failure.
- pages/Home.tsx: switched from useProjects to useSidebar so loading /
  fires exactly one /api/sidebar, with no parallel /api/projects.
- pages/Session.tsx: manual inline rename now emits session_renamed on
  the success path so the sidebar updates live without a refresh (also
  fixes the regression made visible by Batch 2 — the sidebar caches
  session names where the project page used to re-fetch on every visit).

useProjects.ts retains a project_deleted emit inside remove for any future
caller; no live consumer uses it (ProjectSidebar calls api.projects.remove
directly). Acknowledged dead code, to be removed in the next cleanup pass
along with three remaining NOW() → clock_timestamp() consistency flips at
routes/messages.ts:70, routes/messages.ts:127, and services/auto_name.ts:144.

Cross-tab parity for session_created/session_deleted/project_created/
project_deleted is deferred — those events are tab-local in Batch 2 per
spec. session_renamed continues to propagate cross-tab via the existing
WS frame from Batch 1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-15 14:19:59 +00:00
parent 2464d23bb6
commit 842cf146ec
16 changed files with 519 additions and 67 deletions

View File

@@ -1,6 +1,8 @@
// Tiny in-app event bus for session metadata changes that need to propagate
// across hooks (e.g. AI rename arriving via WS in the session view needs to
// also refresh the sidebar's session list). One event type for now.
// also refresh the sidebar's session list).
import type { Project, Session } from '@/api/types';
export interface SessionRenamedEvent {
type: 'session_renamed';
@@ -8,7 +10,34 @@ export interface SessionRenamedEvent {
name: string;
}
type SessionEvent = SessionRenamedEvent;
export interface ProjectCreatedEvent {
type: 'project_created';
project: Project;
}
export interface ProjectDeletedEvent {
type: 'project_deleted';
project_id: string;
}
export interface SessionCreatedEvent {
type: 'session_created';
session: Session;
project_id: string;
}
export interface SessionDeletedEvent {
type: 'session_deleted';
session_id: string;
project_id: string;
}
export type SessionEvent =
| SessionRenamedEvent
| ProjectCreatedEvent
| ProjectDeletedEvent
| SessionCreatedEvent
| SessionDeletedEvent;
type Listener = (event: SessionEvent) => void;
const listeners = new Set<Listener>();

View File

@@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react';
import { api } from '@/api/client';
import type { Project } from '@/api/types';
import { sessionEvents } from './sessionEvents';
export function useProjects() {
const [projects, setProjects] = useState<Project[] | null>(null);
@@ -32,6 +33,7 @@ export function useProjects() {
const remove = useCallback(
async (id: string) => {
await api.projects.remove(id);
sessionEvents.emit({ type: 'project_deleted', project_id: id });
await refresh();
},
[refresh]

View File

@@ -0,0 +1,169 @@
import { useEffect, useState } from 'react';
import { api } from '@/api/client';
import type { SidebarProject, SidebarResponse, SidebarSession } from '@/api/types';
import { sessionEvents } from './sessionEvents';
const RECENT_SESSIONS_LIMIT = 6;
// Module-scope shared state — there is at most one sidebar fetch
// for the lifetime of the page, regardless of how many components
// call useSidebar().
let sharedData: SidebarResponse | null = null;
let sharedError: string | null = null;
let sharedLoading: boolean = true;
let initialized = false;
let fetchInFlight: Promise<void> | null = null;
const subscribers = new Set<() => void>();
function notify(): void {
for (const sub of subscribers) {
try {
sub();
} catch {
// swallow — one bad subscriber shouldn't break others
}
}
}
function load(): Promise<void> {
if (fetchInFlight) return fetchInFlight;
sharedLoading = true;
sharedError = null;
notify();
const p = (async () => {
try {
const res = await api.sidebar.get();
sharedData = res;
sharedError = null;
} catch (err) {
sharedData = null;
sharedError = err instanceof Error ? err.message : 'failed to load sidebar';
} finally {
sharedLoading = false;
fetchInFlight = null;
notify();
}
})();
fetchInFlight = p;
return p;
}
function applyEvent(prev: SidebarResponse, event: import('./sessionEvents').SessionEvent): SidebarResponse {
switch (event.type) {
case 'project_created': {
const fresh: SidebarProject = {
id: event.project.id,
name: event.project.name,
recent_sessions: [],
total_sessions: 0,
};
return { ...prev, projects: [fresh, ...prev.projects] };
}
case 'project_deleted': {
const next = prev.projects.filter((p) => p.id !== event.project_id);
if (next.length === prev.projects.length) return prev;
return { ...prev, projects: next };
}
case 'session_created': {
let changed = false;
const projects = prev.projects.map((p) => {
if (p.id !== event.project_id) return p;
changed = true;
const fresh: SidebarSession = {
id: event.session.id,
name: event.session.name,
model: event.session.model,
updated_at: event.session.updated_at,
};
return {
...p,
recent_sessions: [fresh, ...p.recent_sessions].slice(0, RECENT_SESSIONS_LIMIT),
total_sessions: p.total_sessions + 1,
};
});
return changed ? { ...prev, projects } : prev;
}
case 'session_deleted': {
let changed = false;
const projects = prev.projects.map((p) => {
if (p.id !== event.project_id) return p;
changed = true;
const recent = p.recent_sessions.filter((s) => s.id !== event.session_id);
return {
...p,
recent_sessions: recent,
total_sessions: Math.max(0, p.total_sessions - 1),
};
});
return changed ? { ...prev, projects } : prev;
}
case 'session_renamed': {
let changed = false;
const projects = prev.projects.map((p) => {
let projectChanged = false;
const recent = p.recent_sessions.map((s) => {
if (s.id !== event.session_id) return s;
if (s.name === event.name) return s;
projectChanged = true;
return { ...s, name: event.name };
});
if (!projectChanged) return p;
changed = true;
return { ...p, recent_sessions: recent };
});
return changed ? { ...prev, projects } : prev;
}
default:
return prev;
}
}
// One bus subscription for the lifetime of the module. Events arriving
// before the initial fetch resolves are dropped; the eventual fetch
// result is the source of truth.
sessionEvents.subscribe((event) => {
if (!sharedData) return;
const next = applyEvent(sharedData, event);
if (next === sharedData) return;
sharedData = next;
notify();
});
interface Snapshot {
data: SidebarResponse | null;
error: string | null;
loading: boolean;
}
function snapshot(): Snapshot {
return { data: sharedData, error: sharedError, loading: sharedLoading };
}
export function useSidebar(): {
data: SidebarResponse | null;
error: string | null;
loading: boolean;
retry: () => void;
} {
const [state, setState] = useState<Snapshot>(snapshot);
useEffect(() => {
const sub = () => setState(snapshot());
subscribers.add(sub);
// Sync up if the module state changed between render and effect.
sub();
if (!initialized) {
initialized = true;
void load();
}
return () => {
subscribers.delete(sub);
};
}, []);
const retry = () => {
void load();
};
return { data: state.data, error: state.error, loading: state.loading, retry };
}