Files
openchamber/packages/ui/src/hooks/useSessionGoal.ts
T
Bohdan Triapitsyn edfc9779cf perf(chat): make session switching feel instant
Switching sessions ran as one synchronous commit: sidebar highlight, URL,
a full timeline remount with markdown re-parse, and around nine requests,
so nothing changed on screen for 150-250ms after the click.

- ChatContainer swaps the timeline on a deferred copy of the selection, so
  the active row, URL, and tab commit first and the timeline renders behind
  them; selection policy keeps reading the live store value.
- The message fetch starts before the selection is published.
- Sidebar rows stop re-rendering on a project switch: directory-scoped sync
  hooks read the runtime context and a subscribable current-directory source
  instead of the directory-bearing context; the grouping builder reads git
  branches through a ref and section caches key the branches they use;
  descendant ids are keyed by content. Rows per switch went from 73 to 8.
- Markdown skips the async re-render when the settled cached blocks are
  already painted, and mounts synchronously once its lazy module is loaded;
  the module is preloaded at boot.
- A timeline reveal gate holds a freshly opened session at opacity 0 while
  any provisional markdown paint catches up (250ms cap), then fades the whole
  timeline in once, so text, tools, and recap appear together.
- Switch fan-out trimmed: knowledge summary deduped, MCP status refreshed only
  when stale, non-repo directories cached by the git repo check, OpenChamber
  defaults cached briefly, agent memory reused for the same project, goal
  text cached, PWA manifest rebuilt after the switch settles.
- Header tabs snap into the active state and keep the title at the same
  height in both states.
- Prefetch on row press; composer focus moved off the commit.

`bun run profile:switch` records ack/content latency, longest task, and
requests per switch, cold and warm, and compares runs against a baseline.
Measured warm switch: ack 228ms to about 40-60ms, content 228ms to about
100-120ms.
2026-08-29 17:01:15 +03:00

65 lines
2.6 KiB
TypeScript

import React from 'react';
import { useSession } from '@/sync/sync-context';
import { getSessionGoal, type SessionGoalPayload } from '@/lib/sessionGoalMetadata';
import { fetchGoalObjectiveContent } from '@/lib/sessionGoalActions';
import { useUIStore } from '@/stores/useUIStore';
export interface SessionGoalState {
/** Parsed goal payload, or null when the session has no goal. */
goal: SessionGoalPayload | null;
/** The Settings → Chat toggle; when off, goal UI stays hidden. */
enabled: boolean;
}
// Live goal state: the payload rides session.updated, so subscribing to the
// session record is all the plumbing needed.
export function useSessionGoal(sessionId: string, directory?: string): SessionGoalState {
const session = useSession(sessionId, directory);
const enabled = useUIStore((state) => state.sessionGoalEnabled);
return {
goal: getSessionGoal(session),
enabled,
};
}
const OBJECTIVE_CONTENT_CACHE_MAX = 64;
const objectiveContentByFetchKey = new Map<string, Promise<string | null>>();
// Effective objective text for display. Inline goals return the metadata
// text directly; file-backed goals fetch the server-side file once per
// goal edit (keyed by id + updatedAt). Display-only: a failed fetch yields
// null and callers degrade gracefully (e.g. VS Code, where the OpenChamber
// route is unavailable — the strip then shows only the audit note).
export function useGoalObjectiveContent(sessionId: string, goal: SessionGoalPayload | null): string | null {
const [fetched, setFetched] = React.useState<string | null>(null);
const fetchKey = goal?.objectiveFile ? `${sessionId}:${goal.id}:${goal.updatedAt}` : '';
React.useEffect(() => {
if (!fetchKey) {
setFetched(null);
return undefined;
}
let alive = true;
// The key already names the goal edit, so a remount (every session switch
// remounts the strip) reuses the text instead of fetching the file again.
let request = objectiveContentByFetchKey.get(fetchKey);
if (!request) {
request = fetchGoalObjectiveContent(sessionId);
objectiveContentByFetchKey.set(fetchKey, request);
if (objectiveContentByFetchKey.size > OBJECTIVE_CONTENT_CACHE_MAX) {
const oldest = objectiveContentByFetchKey.keys().next().value;
if (oldest !== undefined) objectiveContentByFetchKey.delete(oldest);
}
}
void request.then((content) => {
if (alive) setFetched(content);
});
return () => {
alive = false;
};
}, [fetchKey, sessionId]);
if (!goal) return null;
return goal.objectiveFile ? fetched : goal.objective;
}