Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
fix(ui): switch projects in the page and keep the loaded agent (K24)
Bernhard Jackiewicz3b909a06b68a
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsxindex 3443bbf8c..1df21cac2 100644--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@ -130,7 +130,7 @@ import { resolveRepositorySelection, useRepositorySnapshot } from './architecturimport ActivityPanel from './agents/ActivityPanel';import WelcomePanel from './app/WelcomePanel';import BrowserChatDock from './browser-ai/BrowserChatDock';-import { requestAgentResume } from './browser-ai/agent-resume';+import { switchKeepingAgent } from './browser-ai/agent-handover';import { browserChatHistoryProjectKey } from './browser-ai/chat-history-cache';import type { BrowserChatAttachment } from './browser-ai/BrowserChatDock';import { browserGraphContext } from './browser-ai/graph-context';@@ -311,7 +311,7 @@ import type { SettingsMeasurement } from './settings/SettingsPanel';import AddProjectIndexDialog from './projects/AddProjectIndexDialog';import ProjectSwitcher from './projects/ProjectSwitcher';import type { ProjectsSource } from './projects/ProjectsPanel';-import { projectHref } from './projects/projects-model';+import { ProjectWindows, type ProjectWindow } from './app/project-windows';import { MODEL_SUGGESTIONS, fetchCommand } from './settings/model-catalog';import { modelKey, readModelPreference, recordModelPreference } from './settings/model-preference';import {@@ -746,10 +746,32 @@ declare global {var __atlasLlm: AtlasLlmSeam | undefined;}+/** Was ein Projektfenster dem naechsten mitgibt (K24): den Arbeitsbereich, die Kopfzeile des Agenten und ob der Chat offen ist. */+interface WindowCarry {+ workspace: Workspace;+ chatOpen: boolean;+ agentState: 'off' | 'loading' | 'active' | 'busy' | 'error';+ agentModelName: string;+ agentHasOpened: boolean;+}++/**+ * Jedes Projekt bekommt ein frisches Fenster in derselben Seite (K24, Kopf von+ * src/app/project-windows.tsx). Der Agent reicht beim Wechsel sein geladenes+ * Modell an das Fenster des neuen Projekts weiter.+ */export default function App(): JSX.Element {+ return <ProjectWindows<WindowCarry> around={switchKeepingAgent}>+ {shown => <ProjectWindowView key={shown.key} projectWindow={shown} />}+ </ProjectWindows>;+}++function ProjectWindowView({ projectWindow }: { projectWindow: ProjectWindow<WindowCarry> }): JSX.Element {+ const carried = projectWindow.carried;const [workspace, setWorkspace] = useState<Workspace>(() => {try {- const requested = new URLSearchParams(window.location.search).get('workspace');+ // A project switch keeps the workspace in view; Back and Forward restore the one of their entry (K24).+ const requested = new URLSearchParams(window.location.search).get('workspace') ?? carried?.workspace ?? null;let saved: string | null = null;try { saved = localStorage.getItem('cbm.workspace'); } catch { /* URL navigation works without storage. */ }return initialWorkspace(requested, saved);@@ -769,11 +791,15 @@ export default function App(): JSX.Element {const [welcomeOpen, setWelcomeOpen] = useState(() => {try { return localStorage.getItem('cbm.workspace.setup') !== 'done'; } catch { return false; }});- const [browserAiOpen, setBrowserAiOpen] = useState(false);- const [localAgentState, setLocalAgentState] = useState<'off' | 'loading' | 'active' | 'busy' | 'error'>('off');+ // The agent's lamp and the chat stay as they were across a project switch (K24).+ const [browserAiOpen, setBrowserAiOpen] = useState(carried?.chatOpen ?? false);+ const [localAgentState, setLocalAgentState] = useState<'off' | 'loading' | 'active' | 'busy' | 'error'>(carried?.agentState ?? 'off');const [agentSettingsRequest, setAgentSettingsRequest] = useState(0);- const [agentModelName, setAgentModelName] = useState('');- const agentHasOpened = useRef(false);+ const [agentModelName, setAgentModelName] = useState(carried?.agentModelName ?? '');+ const agentHasOpened = useRef(carried?.agentHasOpened ?? false);+ useEffect(() => {+ projectWindow.report({ workspace, chatOpen: browserAiOpen, agentState: localAgentState, agentModelName, agentHasOpened: agentHasOpened.current });+ });const onAgentStateChange = useCallback((state: 'off' | 'loading' | 'active' | 'busy' | 'error') => {setLocalAgentState(state);if ((state === 'active' || state === 'busy') && !agentHasOpened.current) {@@ -796,16 +822,17 @@ export default function App(): JSX.Element {try { localStorage.setItem('cbm.workspace.setup', 'done'); } catch { /* Session-only preference. */ }};const guidance: Guidance = 'brief';- const client = useMemo(() => new RpcIntelligenceClient({}), []);- const api = useMemo(() => new AtlasApi({}), []);+ // Requests of this window end with it: a switch to another project aborts them (K24).+ const client = useMemo(() => new RpcIntelligenceClient({ signal: projectWindow.signal }), [projectWindow.signal]);+ const api = useMemo(() => new AtlasApi({ signal: projectWindow.signal }), [projectWindow.signal]);const [diagnosticsPath, setDiagnosticsPath] = useState<string>();/** What the projects panel asks the server. The list comes over /rpc like* every other read of this window; the rest are the /api routes the panel- * names in its own text. Opening a project reloads the page with the- * query the start-up code reads, because every panel of this window is- * keyed to the project it started with.+ * names in its own text. Opening a project replaces this window with a+ * fresh one for that project in the same page, because every panel of this+ * window is keyed to the project it started with (K24).*/const projectsSource = useMemo<ProjectsSource>(() => ({@@ -823,12 +850,8 @@ export default function App(): JSX.Element {}),[client, api],);- // Opening a project reloads the page; a loaded agent comes back from the cache (K24).- const agentStateRef = useRef(localAgentState); agentStateRef.current = localAgentState;- const openProject = useCallback((name: string) => {- if (agentStateRef.current === 'active' || agentStateRef.current === 'busy' || agentStateRef.current === 'loading') requestAgentResume();- window.location.assign(projectHref(name));- }, []);+ // Opening a project stays in this page and keeps a loaded agent (K24).+ const openProject = projectWindow.open;const [project, setProject] = useState('');const selectionScope = `${project}:${workspace}`;diff --git a/graph-ui/src/app/atlas-api.ts b/graph-ui/src/app/atlas-api.tsindex d51baeda2..0c0b4717f 100644--- a/graph-ui/src/app/atlas-api.ts+++ b/graph-ui/src/app/atlas-api.ts@@ -49,6 +49,8 @@ export interface AtlasApiOptions {base?: string;/** Ersetzbares fetch, damit Tests ohne Netz laufen. */fetch?: typeof globalThis.fetch;+ /** Abbruchsignal fuer jeden Aufruf: das Projektfenster bricht so beim Wechsel ab (K24). */+ signal?: AbortSignal;}/** Was `/api/repo-info` ueber ein Projekt weiss. Leere Felder heissen "unbekannt". */@@ -128,10 +130,14 @@ export class AtlasApi {init.headers = { Accept: 'application/json', 'Content-Type': 'application/json' };init.body = JSON.stringify(payload);}+ if (this.options.signal !== undefined) init.signal = this.options.signal;response = await doFetch(url, init);} catch (error) {const message = error instanceof Error ? error.message : String(error);- throw announce(new AtlasApiError(route, 0, `${route} war nicht erreichbar: ${message}`));+ const failure = new AtlasApiError(route, 0, `${route} war nicht erreichbar: ${message}`);+ // Ein abgebrochener Aufruf ist die Sache des Aufrufers und kein Fehler des Servers.+ if (this.options.signal?.aborted) throw failure;+ throw announce(failure);}const body = await response.text();if (!response.ok) {diff --git a/graph-ui/src/app/project-windows.test.tsx b/graph-ui/src/app/project-windows.test.tsxnew file mode 100644index 000000000..9580aa5f7--- /dev/null+++ b/graph-ui/src/app/project-windows.test.tsx@@ -0,0 +1,87 @@+// @vitest-environment jsdom+import { act, useEffect } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { ProjectWindows, type ProjectWindow } from './project-windows';++/*+ * K24: a project switch stays in the page. Each project gets a fresh window (fresh state in+ * every panel, as after a reload), the address changes with the history API, Back and Forward+ * switch the same way, and requests of the old window are cancelled.+ */++let container: HTMLDivElement;+let root: Root;+beforeEach(() => {+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ window.history.replaceState(null, '', '/?project=django-demo&workspace=galaxy');+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.restoreAllMocks(); });++interface Carry { chatOpen: boolean }+const mounted: string[] = [];+const unmounted: string[] = [];+let current: ProjectWindow<Carry> | undefined;+function Window({ window: shown }: { window: ProjectWindow<Carry> }) {+ current = shown;+ useEffect(() => { mounted.push(shown.project); return () => { unmounted.push(shown.project); }; }, []);+ useEffect(() => { shown.report({ chatOpen: shown.project === 'django-demo' }); });+ return <p data-project={shown.project}>{shown.project}:{String(shown.carried?.chatOpen)}</p>;+}+const shownProject = () => container.querySelector('p')?.getAttribute('data-project');++describe('an in-page project switch (K24)', () => {+ beforeEach(() => { mounted.length = 0; unmounted.length = 0; current = undefined; });++ it('opens another project without reloading: new address, a fresh window, the old one cancelled', async () => {+ const push = vi.spyOn(window.history, 'pushState');+ await act(async () => root.render(<ProjectWindows<Carry>>{shown => <Window key={shown.key} window={shown} />}</ProjectWindows>));+ expect(shownProject()).toBe('django-demo');+ const first = current!;+ await act(async () => first.open('cbm'));+ expect(push).toHaveBeenCalledOnce();+ expect(window.location.search).toBe('?project=cbm');+ expect(shownProject()).toBe('cbm');+ expect(mounted).toEqual(['django-demo', 'cbm']);+ expect(unmounted).toEqual(['django-demo']);+ // The old window's requests are cancelled; the new window's are not.+ expect(first.signal.aborted).toBe(true);+ expect(current!.signal.aborted).toBe(false);+ // What the old window reported travels to the new one.+ expect(container.textContent).toBe('cbm:true');+ });++ it('stays put for the project already shown', async () => {+ const push = vi.spyOn(window.history, 'pushState');+ await act(async () => root.render(<ProjectWindows<Carry>>{shown => <Window key={shown.key} window={shown} />}</ProjectWindows>));+ await act(async () => current!.open('django-demo'));+ expect(push).not.toHaveBeenCalled();+ expect(mounted).toEqual(['django-demo']);+ });++ it('switches back and forward with the browser history in the page', async () => {+ await act(async () => root.render(<ProjectWindows<Carry>>{shown => <Window key={shown.key} window={shown} />}</ProjectWindows>));+ await act(async () => current!.open('cbm'));+ await act(async () => {+ window.history.replaceState(null, '', '/?project=django-demo&workspace=galaxy');+ window.dispatchEvent(new PopStateEvent('popstate'));+ });+ expect(shownProject()).toBe('django-demo');+ expect(mounted).toEqual(['django-demo', 'cbm', 'django-demo']);+ // A popstate that keeps the project (another query parameter) keeps the window.+ await act(async () => {+ window.history.replaceState(null, '', '/?project=django-demo&workspace=explore');+ window.dispatchEvent(new PopStateEvent('popstate'));+ });+ expect(mounted).toHaveLength(3);+ });++ it('commits the switch inside the frame it is given, so the old window is gone and the new one there when it ends', async () => {+ const seen: string[] = [];+ const around = (commit: () => void) => { seen.push(`before:${mounted.join(',')}`); commit(); seen.push(`after:${mounted.join(',')}|${unmounted.join(',')}`); };+ await act(async () => root.render(<ProjectWindows<Carry> around={around}>{shown => <Window key={shown.key} window={shown} />}</ProjectWindows>));+ await act(async () => current!.open('cbm'));+ expect(seen).toEqual(['before:django-demo', 'after:django-demo,cbm|django-demo']);+ });+});diff --git a/graph-ui/src/app/project-windows.tsx b/graph-ui/src/app/project-windows.tsxnew file mode 100644index 000000000..5669e8165--- /dev/null+++ b/graph-ui/src/app/project-windows.tsx@@ -0,0 +1,80 @@+/**+ * Ein Projektwechsel bleibt in der Seite (K24).+ *+ * Bis K24 lud ein Wechsel die ganze Seite neu, weil jedes Panel dieses Fensters+ * an das Projekt gebunden ist, mit dem es startete. Mit dem Neuladen gingen der+ * Worker des lokalen Agenten und seine Gewichte mit, und die Lampe stand+ * sekundenlang auf "loading". Jetzt bekommt jedes Projekt ein frisches Fenster:+ * derselbe Baum unter einem neuen Schluessel, also frischer Zustand in jedem+ * Panel wie nach einem Neuladen, aber ohne die Seite zu verlassen.+ *+ * Drei Entscheidungen:+ *+ * 1. **Ein neuer Schluessel statt eines Zuruecksetzens.** Das Fenster haelt+ * rund hundert Zustaende, und jeder vergessene waere eine Anzeige des alten+ * Projekts im neuen. Ein neuer Schluessel vergisst keinen. Was das alte+ * Fenster dem neuen mitgibt, meldet es ausdruecklich (`report`), und nur+ * das kommt an (`carried`).+ * 2. **Die Adresse wechselt mit pushState.** Zurueck und Vor des Browsers+ * wechseln das Projekt ebenso in der Seite (popstate); ein popstate, das das+ * Projekt behaelt, laesst das Fenster stehen.+ * 3. **Das alte Fenster ist weg, wenn der Wechsel endet.** Der Wechsel wird mit+ * flushSync festgeschrieben, innerhalb des Rahmens `around`, in dem der+ * Agent sein Modell weiterreicht (browser-ai/agent-handover.ts). Danach+ * bricht das Signal des alten Fensters ab: was es noch fragt, geht nicht+ * mehr hinaus, und was noch antwortet, landet in einem ausgehaengten Baum.+ */+import { useCallback, useEffect, useRef, useState, type JSX, type ReactNode } from 'react';+import { flushSync } from 'react-dom';+import { projectHref } from '../projects/projects-model';++/** Das Projekt aus `?project=`, leer, wenn die Adresse keins nennt. */+export function projectOfLocation(search = window.location.search): string {+ return new URLSearchParams(search).get('project') ?? '';+}++export interface ProjectWindow<C> {+ /** Wechselt mit jedem Projekt; als React-Schluessel des Fensters gedacht. */+ key: number;+ /** Das Projekt der Adresse beim Oeffnen des Fensters, leer ohne `?project=`. */+ project: string;+ /** Bricht ab, sobald ein anderes Projekt das Fenster ersetzt hat. */+ signal: AbortSignal;+ /** Was das vorige Fenster zuletzt gemeldet hat. */+ carried?: C;+ /** Oeffnet ein anderes Projekt in dieser Seite. */+ open: (project: string) => void;+ /** Meldet, was ein naechstes Fenster mitbekommen soll. */+ report: (carry: C) => void;+}++interface Shown<C> { key: number; project: string; controller: AbortController; carried?: C }++export function ProjectWindows<C>({ children, around = commit => commit() }: {+ children: (window: ProjectWindow<C>) => ReactNode;+ around?: (commit: () => void) => void;+}): JSX.Element {+ const [shown, setShown] = useState<Shown<C>>(() => ({ key: 0, project: projectOfLocation(), controller: new AbortController() }));+ const current = useRef(shown); current.current = shown;+ const carry = useRef<C | undefined>(undefined);+ const show = useCallback((project: string) => {+ const previous = current.current;+ if (project === previous.project) return;+ const next: Shown<C> = { key: previous.key + 1, project, controller: new AbortController(), ...carry.current === undefined ? {} : { carried: carry.current } };+ current.current = next;+ around(() => flushSync(() => setShown(next)));+ previous.controller.abort();+ }, [around]);+ const open = useCallback((project: string) => {+ if (project === current.current.project) return;+ window.history.pushState(null, '', projectHref(project));+ show(project);+ }, [show]);+ const report = useCallback((value: C) => { carry.current = value; }, []);+ useEffect(() => {+ const back = () => show(projectOfLocation());+ window.addEventListener('popstate', back);+ return () => window.removeEventListener('popstate', back);+ }, [show]);+ return <>{children({ key: shown.key, project: shown.project, signal: shown.controller.signal, carried: shown.carried, open, report })}</>;+}diff --git a/graph-ui/src/browser-ai/BrowserChatDock.handover.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.handover.test.tsxnew file mode 100644index 000000000..002bb7e20--- /dev/null+++ b/graph-ui/src/browser-ai/BrowserChatDock.handover.test.tsx@@ -0,0 +1,158 @@+// @vitest-environment jsdom+import { act, StrictMode } from 'react';+import { flushSync } from 'react-dom';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import BrowserChatDock, { type BrowserChatDockProps, type BrowserChatReaderContext } from './BrowserChatDock';+import type { BrowserAiProgress, BrowserChatMessage } from './browser-ai-runtime';+import type { BrowserChatOptions } from './browser-ai-controller';+import { switchKeepingAgent } from './agent-handover';++/*+ * K24: a project switch stays in the page. The window of the old project unmounts and the+ * window of the new one mounts in the same commit; the dock of the old project hands its+ * loaded model to the dock of the new one, which neither creates a worker nor loads again.+ */++let container: HTMLDivElement;+let root: Root;+beforeEach(() => {+ (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;+ window.localStorage.clear();+ container = document.createElement('div'); document.body.appendChild(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.restoreAllMocks(); vi.useRealTimers(); });++const reader = (project: string, text: string): BrowserChatReaderContext => ({ project, path: 'src/sum.ts', status: 'ready',+ source: { id: `reader-${project}`, text, path: 'src/sum.ts', project, startLine: 1, startColumn: 1, endLine: 1, endColumn: 1, sourceVersion: 'sha256:1', kind: 'file' } });+function fixture() {+ const runtime = {+ prepare: vi.fn(async (_progress: (value: BrowserAiProgress) => void, _options?: { cacheOnly?: boolean }) => {}),+ explain: vi.fn(async () => 'Legacy'),+ countTokens: vi.fn(async (_messages: readonly BrowserChatMessage[]) => 100),+ chat: vi.fn(async (_messages: readonly BrowserChatMessage[], _onToken: (chunk: string) => void, _options?: BrowserChatOptions) => 'Adds the two values.'),+ stop: vi.fn(), dispose: vi.fn(), setFatalHandler: vi.fn(),+ };+ const states: string[] = [];+ const props: BrowserChatDockProps = { proactive: false, open: true, onClose: vi.fn(), onAttachmentConsumed: vi.fn(), createRuntime: vi.fn(() => runtime),+ removeCache: vi.fn(async () => {}), isCached: vi.fn(async () => true), onAgentStateChange: state => { states.push(state); } };+ return { runtime, props, states };+}+const dock = (props: BrowserChatDockProps, project: string, strict = false) => {+ const element = <BrowserChatDock key={project} {...props} historyKey={`origin:${project}`} readerContext={reader(project, `SOURCE_OF_${project}`)} />;+ return strict ? <StrictMode>{element}</StrictMode> : element;+};+function button(label: string): HTMLButtonElement {+ const target = [...document.body.querySelectorAll('button')].find(item => item.textContent === label || item.getAttribute('aria-label') === label);+ expect(target, `button ${label}`).toBeDefined(); return target!;+}+/** Opens the agent configuration (a new settings request) and loads the cached model. */+async function configure(props: BrowserChatDockProps, project: string, strict = false): Promise<void> {+ await act(async () => root.render(dock(props, project, strict)));+ await act(async () => root.render(dock({ ...props, settingsRequest: 1 }, project, strict)));+}+async function load(props: BrowserChatDockProps, project: string, strict = false): Promise<void> {+ await configure(props, project, strict);+ await act(async () => button('Load model (cached, no download)').click());+}+async function type(value: string): Promise<void> {+ const input = container.querySelector('textarea')!;+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(input, value);+ input.dispatchEvent(new Event('input', { bubbles: true }));+ });+}+/** The switch as the project window runs it: the new window replaces the old one in one commit. */+async function switchTo(props: BrowserChatDockProps, project: string, strict = false): Promise<void> {+ await act(async () => switchKeepingAgent(() => flushSync(() => root.render(dock(props, project, strict)))));+}+function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>(yes => { resolve = yes; });+ return { promise, resolve };+}++describe('the loaded model across an in-page project switch (K24)', () => {+ it('hands the loaded model to the next project without a new worker, a second load or an "off" lamp', async () => {+ const { props, runtime, states } = fixture();+ await load(props, 'django-demo');+ expect(states.at(-1)).toBe('active');+ states.length = 0;+ await switchTo(props, 'cbm');+ expect(props.createRuntime).toHaveBeenCalledOnce();+ expect(runtime.prepare).toHaveBeenCalledOnce();+ expect(runtime.dispose).not.toHaveBeenCalled();+ expect(states.filter(state => state !== 'active')).toEqual([]);+ expect(container.textContent).not.toContain('Enable the local agent');+ // The new project's dock answers on the same worker, with the new project's file.+ await type('What does this file do?');+ await act(async () => button('Send ↑').click());+ expect(runtime.chat).toHaveBeenCalledOnce();+ const sent = runtime.chat.mock.calls[0][0].map(message => message.content).join('\n');+ expect(sent).toContain('SOURCE_OF_cbm');+ expect(sent).not.toContain('SOURCE_OF_django-demo');+ // The worker's fatal faults now reach the new dock.+ expect(runtime.setFatalHandler).toHaveBeenCalledTimes(2);+ });++ it('lets an answer of the old project settle first and never shows it in the new one', async () => {+ const { props, runtime } = fixture(); const old = deferred<string>();+ await load(props, 'django-demo');+ runtime.chat.mockReturnValueOnce(old.promise);+ await type('Old project question');+ await act(async () => button('Send ↑').click());+ await switchTo(props, 'cbm');+ expect(runtime.stop).toHaveBeenCalled();+ expect(runtime.dispose).not.toHaveBeenCalled();+ expect(container.querySelector('textarea')).not.toBeNull();+ await act(async () => old.resolve('OLD_PROJECT_ANSWER'));+ await type('New project question');+ await act(async () => button('Send ↑').click());+ expect(runtime.chat).toHaveBeenCalledTimes(2);+ expect(runtime.chat.mock.calls[1][0].at(-1)?.content).toContain('New project question');+ expect(container.textContent).not.toContain('OLD_PROJECT_ANSWER');+ expect(container.textContent).not.toContain('Old project question');+ });++ it('keeps a model that is still loading and finishes loading it in the new project', async () => {+ const { props, runtime, states } = fixture(); const loading = deferred<void>();+ runtime.prepare.mockReturnValueOnce(loading.promise);+ await load(props, 'django-demo');+ expect(states.at(-1)).toBe('loading');+ await switchTo(props, 'cbm');+ expect(runtime.dispose).not.toHaveBeenCalled();+ await act(async () => loading.resolve());+ expect(runtime.prepare).toHaveBeenCalledOnce();+ expect(props.createRuntime).toHaveBeenCalledOnce();+ expect(states.at(-1)).toBe('active');+ });++ it('unloads the model when no dock takes it, and on an unmount that is not a switch', async () => {+ const first = fixture();+ await load(first.props, 'django-demo');+ await act(async () => switchKeepingAgent(() => flushSync(() => root.render(<div />))));+ expect(first.runtime.dispose).toHaveBeenCalledOnce();+ const second = fixture();+ await load(second.props, 'cbm');+ await act(async () => root.render(<div />));+ expect(second.runtime.dispose).toHaveBeenCalledOnce();+ });++ it('says in the configuration what a project switch does with a loaded model', async () => {+ const { props } = fixture();+ await configure(props, 'django-demo');+ const title = document.querySelector('#cbm-chat-auto-load')?.closest('label')?.getAttribute('title') ?? '';+ expect(title).toContain('A project switch stays in this page and keeps a loaded model without loading it again');+ expect(title).toContain('when the page is opened or reloaded');+ });++ it('survives the development double effect of StrictMode', async () => {+ const { props, runtime, states } = fixture();+ await load(props, 'django-demo', true);+ states.length = 0;+ await switchTo(props, 'cbm', true);+ expect(runtime.dispose).not.toHaveBeenCalled();+ expect(props.createRuntime).toHaveBeenCalledOnce();+ expect(states.filter(state => state !== 'active')).toEqual([]);+ });+});diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsxindex f7b1a2acb..fe0d94ab2 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx@@ -1494,14 +1494,12 @@ describe('a cached model across reloads and project switches (K10, K24)', () =>expect(props.createRuntime).not.toHaveBeenCalled();});- it('resumes a model that was active before a project switch, once, without the automatic option', async () => {- window.sessionStorage.setItem('cbm-agent-resume', JSON.stringify({ at: Date.now() }));- const { props, runtime } = fixture();+ it('does not load by itself on a page that opens after another project, without the automatic option', async () => {+ // A project switch stays in the page and hands the model over (BrowserChatDock.handover.test.tsx);+ // a page that is opened or reloaded starts with the agent off unless asked to load on start.+ const { props } = fixture();await render({ ...props, isCached: vi.fn(async () => true) });- expect(props.createRuntime).toHaveBeenCalledOnce();- expect(runtime.prepare.mock.calls[0][1]).toEqual({ cacheOnly: true });- // A later reload of this tab starts with the agent off again.- expect(JSON.parse(window.sessionStorage.getItem('cbm-agent-resume')!).page).toBe(performance.timeOrigin);+ expect(props.createRuntime).not.toHaveBeenCalled();});});diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsxindex 2a4882e96..9b260e5f7 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx@@ -2,7 +2,7 @@ import { useEffect, useMemo, useRef, useState, type FormEvent, type JSX, type Reimport type { BrowserAiProgress } from './browser-ai-controller';import { createBrowserChatRuntime, type BrowserChatRuntime } from './browser-ai-runtime';import { BROWSER_MODELS, getBrowserModel, isBrowserModelCached, removeBrowserModelCache, type BrowserModel } from './model-policy';-import { takeAgentResume } from './agent-resume';+import { keepAgent, offerAgent, peekAgent, takeAgent, type AgentHandover } from './agent-handover';import { buildChatMessages, selectionLocation, snapshotAttachment, snapshotReaderContext, trimChatHistory, type BrowserChatAttachment, type BrowserChatContext, type BrowserChatReaderContext, type BrowserChatSource, type BrowserChatTurn } from './chat-model';import { explanationInput, EXPLANATION_DELAY_MS, type ExplanationInput } from './proactive-selection';import { prepareExplanationContext, selectionSummary, type PreparedExplanationContext } from './explanation-context';@@ -175,7 +175,8 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "// Evidence for a manual question grows with the input limit: about 1.5 characters per// token leave room for the question, history and instructions (2048 tokens: 3200).const chatEvidence = Math.max(800, Math.floor(limits.inputTokens * 25 / 16));- const [phase, setPhase] = useState<Phase>('off');+ // A model handed over by the dock of the last project is loaded from the first frame (K24).+ const [phase, setPhase] = useState<Phase>(() => { const handover = peekAgent(model.id); return !handover ? 'off' : handover.ready ? 'preparing' : handover.settled ? 'counting' : 'ready'; });const { draft, setDraft, turns, setTurns, ready: historyReady, historyNotice, clearHistory } = useChatHistory<ChatTurn>(historyKey);const [error, setError] = useState<string>();const [runtimeFailed, setRuntimeFailed] = useState(false);@@ -196,6 +197,8 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "const runtime = useRef<BrowserChatRuntime | undefined>(undefined);/** The model the worker was created for; the stored choice can change in another tab. */const runtimeModel = useRef<string | undefined>(undefined);+ /** The model still loading, so a project switch can hand it over unfinished (K24). */+ const loading = useRef<Promise<void> | undefined>(undefined);const epoch = useRef(0);const pending = useRef(false);const stopRequested = useRef(false);@@ -206,24 +209,37 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "const input = useRef<HTMLTextAreaElement>(null);const busy = phase === 'preparing' || phase === 'counting' || phase === 'generating' || phase === 'removing';- useEffect(() => () => { epoch.current += 1; runtime.current?.dispose(); runtime.current = undefined; }, []);useEffect(() => {- // A model active before a project switch comes back, as does the chosen one when asked- // to load on start; both only from the cache (K10, K24).- const resume = takeAgentResume();+ // A project switch hands this dock the model of the last project's dock (K24).+ const handover = takeAgent(model.id);+ if (handover) adopt(handover);+ const withdraw = offerAgent(handOver);+ return () => {+ withdraw(); epoch.current += 1;+ const current = runtime.current, id = runtimeModel.current;+ runtime.current = undefined; runtimeModel.current = undefined;+ // Inside a switch (also React's development double effect) the model stays for the next dock.+ if (current && !(id && keepAgent(handoverOf(current, id)))) current.dispose();+ };+ }, []);+ useEffect(() => {+ // The chosen model loads on start when asked to, only from the cache (K10).let alive = true;void Promise.all(BROWSER_MODELS.filter(candidate => candidate.availability === 'available').map(async candidate => [candidate.id, await isCached(candidate.id)] as const)).then(entries => {if (!alive) return;const found = new Set(entries.filter(([, inCache]) => inCache).map(([id]) => id));setCached(found);- if ((resume || preferences.autoLoad) && found.has(model.id) && !runtime.current && !pending.current) void prepare(true);+ if (preferences.autoLoad && found.has(model.id) && !runtime.current && !pending.current) void prepare(true);});return () => { alive = false; };}, []);useEffect(() => {if (historyProject.current === historyKey) return;+ const previous = historyProject.current;historyProject.current = historyKey;+ // The first project of this window is no switch: there is nothing of another project to drop.+ if (previous === undefined) return;explanations.current.clear(); symbolSources.current.clear(); readSources.current.clear(); resetProject();setSelectedContext([]); setHandledContextId(undefined); setNewExplanation(false);}, [historyKey]);@@ -442,6 +458,42 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "pending.current = false; stopRequested.current = false; setStopping(false); setPhase('ready');});};+ const handoverOf = (current: BrowserChatRuntime, modelId: string): AgentHandover => ({ runtime: current, modelId,+ ...operationSettled.current ? { settled: operationSettled.current } : {}, ...loading.current ? { ready: loading.current } : {} });+ /** Gives the model to the dock of the next project (K24). What this dock was doing stops,+ * and its late results land nowhere: its epoch has moved on. */+ const handOver = (): AgentHandover | undefined => {+ const current = runtime.current, id = runtimeModel.current;+ if (!current || !id) return undefined;+ if (autoRun.current) autoRun.current.cancelled = true;+ if (manualRequest.current) manualRequest.current.cancelled = true;+ epoch.current += 1; current.stop();+ const handover = handoverOf(current, id);+ runtime.current = undefined; runtimeModel.current = undefined;+ return handover;+ };+ /** The model the last project's dock handed over: no new worker and no second load. A+ * stopped answer settles, and a model still loading finishes, before this project uses it. */+ const adopt = (handover: AgentHandover): void => {+ const adopted = handover.runtime;+ runtime.current = adopted; runtimeModel.current = handover.modelId;+ adopted.setFatalHandler?.(failure => { if (runtime.current === adopted) invalidateRuntime(failure); });+ const waiting = handover.ready ?? handover.settled;+ if (!waiting) { setPhase('ready'); return; }+ const ticket = epoch.current;+ pending.current = true;+ if (handover.ready) { loading.current = handover.ready; setPhase('preparing'); }+ else { stopRequested.current = true; setStopping(true); setPhase('counting'); }+ void waiting.then(() => {+ if (epoch.current !== ticket || runtime.current !== adopted) return;+ pending.current = false; stopRequested.current = false; loading.current = undefined; setStopping(false);+ if (handover.ready) setCached(previous => new Set(previous).add(handover.modelId));+ setPhase('ready');+ }, (failure: unknown) => {+ if (epoch.current !== ticket || runtime.current !== adopted) return;+ release(); setError(messageOf(failure));+ });+ };const release = (): void => {if (manualRequest.current) manualRequest.current.cancelled = true;manualRequest.current = undefined; operationSettled.current = undefined; setQuestionQueued(false);@@ -451,7 +503,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "if (id) setTurns(previous => previous.map(turn => turn.id === id ? { ...turn, status: 'stopped' } : turn));epoch.current += 1; pending.current = false; activeTurn.current = undefined;stopRequested.current = false; setStopping(false);- runtime.current?.dispose(); runtime.current = undefined; runtimeModel.current = undefined;+ runtime.current?.dispose(); runtime.current = undefined; runtimeModel.current = undefined; loading.current = undefined;setProgress(undefined); setPhase('off'); setRuntimeFailed(false);};const invalidateRuntime = (failure: unknown): void => {@@ -469,8 +521,11 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "const nextRuntime = createRuntime(model.id);runtime.current = nextRuntime; runtimeModel.current = model.id;nextRuntime.setFatalHandler?.(failure => { if (runtime.current === nextRuntime) invalidateRuntime(failure); });- await nextRuntime.prepare(value => { if (epoch.current === ticket) setProgress(value); }, cacheOnly ? { cacheOnly } : undefined);+ const loaded = nextRuntime.prepare(value => { if (epoch.current === ticket) setProgress(value); }, cacheOnly ? { cacheOnly } : undefined);+ loading.current = loaded;+ await loaded;if (epoch.current !== ticket) return;+ loading.current = undefined;setCached(previous => new Set(previous).add(model.id));setPhase('ready'); setProgress(undefined); setSettingsOpen(false); pending.current = false;} catch (failure) {diff --git a/graph-ui/src/browser-ai/agent-handover.test.ts b/graph-ui/src/browser-ai/agent-handover.test.tsnew file mode 100644index 000000000..716d080e0--- /dev/null+++ b/graph-ui/src/browser-ai/agent-handover.test.ts@@ -0,0 +1,70 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest';+import { keepAgent, offerAgent, peekAgent, switchKeepingAgent, takeAgent, type AgentHandover } from './agent-handover';+import type { BrowserChatRuntime } from './browser-ai-runtime';+import { BROWSER_MODEL, browserModelBaseUrl, BROWSER_MODELS, isBrowserModelCached } from './model-policy';++afterEach(() => { vi.unstubAllGlobals(); });++const runtime = () => ({ prepare: vi.fn(), explain: vi.fn(), countTokens: vi.fn(), chat: vi.fn(), stop: vi.fn(), dispose: vi.fn() }) as unknown as BrowserChatRuntime & { dispose: ReturnType<typeof vi.fn> };++describe('handing the loaded model to the next project (K24)', () => {+ it('takes the model from the offering dock before the new window renders and gives it to the next dock', () => {+ const model = runtime();+ const withdraw = offerAgent(() => ({ runtime: model, modelId: 'qwen' }));+ let seen: AgentHandover | undefined, taken: AgentHandover | undefined;+ switchKeepingAgent(() => { seen = peekAgent('qwen'); taken = takeAgent('qwen'); });+ withdraw();+ expect(seen?.runtime).toBe(model);+ expect(taken?.runtime).toBe(model);+ expect(model.dispose).not.toHaveBeenCalled();+ });++ it('unloads a model no dock takes, and one of another choice', () => {+ const left = runtime();+ const withdraw = offerAgent(() => ({ runtime: left, modelId: 'qwen' }));+ switchKeepingAgent(() => {});+ withdraw();+ expect(left.dispose).toHaveBeenCalledOnce();+ const other = runtime();+ const again = offerAgent(() => ({ runtime: other, modelId: 'qwen' }));+ switchKeepingAgent(() => { expect(peekAgent('lfm')).toBeUndefined(); expect(takeAgent('lfm')).toBeUndefined(); });+ again();+ expect(other.dispose).toHaveBeenCalledOnce();+ });++ it('keeps a model only inside a switch', () => {+ const model = runtime();+ expect(keepAgent({ runtime: model, modelId: 'qwen' })).toBe(false);+ expect(takeAgent('qwen')).toBeUndefined();+ switchKeepingAgent(() => {+ expect(keepAgent({ runtime: model, modelId: 'qwen' })).toBe(true);+ expect(takeAgent('qwen')?.runtime).toBe(model);+ });+ expect(model.dispose).not.toHaveBeenCalled();+ });+});++describe('a cached model (K10)', () => {+ const cacheWith = (urls: string[]) => ({ has: vi.fn(async () => true), open: vi.fn(async () => ({ keys: async () => urls.map(url => new Request(url)) })) });++ it('is cached only when every pinned file is in its dedicated cache', async () => {+ const model = BROWSER_MODELS[0];+ const all = model.files.map(file => `${browserModelBaseUrl(model)}${file}`);+ vi.stubGlobal('caches', cacheWith(all));+ expect(await isBrowserModelCached(model)).toBe(true);+ vi.stubGlobal('caches', cacheWith(all.slice(0, -1)));+ expect(await isBrowserModelCached(model)).toBe(false);+ vi.stubGlobal('caches', cacheWith(all.map(url => url.replace(BROWSER_MODEL.revision, 'main'))));+ expect(await isBrowserModelCached(model)).toBe(false);+ });++ it('never creates the cache it checks, and says not cached without Cache Storage', async () => {+ const storage = { has: vi.fn(async () => false), open: vi.fn() };+ vi.stubGlobal('caches', storage);+ expect(await isBrowserModelCached(BROWSER_MODELS[0])).toBe(false);+ expect(storage.open).not.toHaveBeenCalled();+ vi.stubGlobal('caches', undefined);+ expect(await isBrowserModelCached(BROWSER_MODELS[0])).toBe(false);+ });+});diff --git a/graph-ui/src/browser-ai/agent-handover.ts b/graph-ui/src/browser-ai/agent-handover.tsnew file mode 100644index 000000000..656884768--- /dev/null+++ b/graph-ui/src/browser-ai/agent-handover.ts@@ -0,0 +1,63 @@+import type { BrowserChatRuntime } from './browser-ai-runtime';++/** A project switch stays in the page (K24): the window of the old project unmounts and the+ * window of the new one mounts in the same commit (app/project-windows.tsx). The chat dock+ * of the old project hands its worker with the loaded model to the dock of the new one, so+ * nothing is created, read from the cache or downloaded again, and the lamp stays on.+ *+ * The hand-over is bounded by the switch: outside `switchKeepingAgent` an unmounting dock+ * unloads its model as before, and a model no dock takes is unloaded when the switch ends. */+export interface AgentHandover {+ runtime: BrowserChatRuntime;+ modelId: string;+ /** An answer of the old project that was stopped and has not settled yet; the new dock waits for it. */+ settled?: Promise<void>;+ /** A model that is still loading; the new dock finishes loading it. */+ ready?: Promise<void>;+}++let offered: (() => AgentHandover | undefined) | undefined;+let switching = false;+let handed: AgentHandover | undefined;++/** The mounted dock offers to give up its model; the returned function withdraws the offer. */+export function offerAgent(release: () => AgentHandover | undefined): () => void {+ offered = release;+ return () => { if (offered === release) offered = undefined; };+}++/** Runs a switch that replaces the window synchronously (flushSync inside `commit`). The model+ * is taken from the old dock before the new window renders, so its first frame is loaded. */+export function switchKeepingAgent(commit: () => void): void {+ switching = true;+ handed = offered?.();+ try { commit(); } finally {+ switching = false;+ const left = handed; handed = undefined;+ left?.runtime.dispose();+ }+}++/** An unmounting dock during a switch keeps its model for the next one instead of unloading+ * it; this is also how React's development double effect gives the model back. */+export function keepAgent(handover: AgentHandover): boolean {+ if (!switching) return false;+ if (handed && handed.runtime !== handover.runtime) handed.runtime.dispose();+ handed = handover;+ return true;+}++/** What the next dock is about to take, for its first render. */+export function peekAgent(modelId: string): AgentHandover | undefined {+ return handed?.modelId === modelId ? handed : undefined;+}++/** The mounting dock takes the handed-over model. A model of another choice is unloaded. */+export function takeAgent(modelId: string): AgentHandover | undefined {+ const handover = handed;+ if (!handover) return undefined;+ handed = undefined;+ if (handover.modelId === modelId) return handover;+ handover.runtime.dispose();+ return undefined;+}diff --git a/graph-ui/src/browser-ai/agent-resume.test.ts b/graph-ui/src/browser-ai/agent-resume.test.tsdeleted file mode 100644index 0b9aa5a95..000000000--- a/graph-ui/src/browser-ai/agent-resume.test.ts+++ /dev/null@@ -1,52 +0,0 @@-// @vitest-environment jsdom-import { afterEach, describe, expect, it, vi } from 'vitest';-import { AGENT_RESUME_KEY, AGENT_RESUME_WINDOW_MS, requestAgentResume, takeAgentResume } from './agent-resume';-import { BROWSER_MODEL, browserModelBaseUrl, BROWSER_MODELS, isBrowserModelCached } from './model-policy';--afterEach(() => { vi.unstubAllGlobals(); window.sessionStorage.clear(); });--describe('keeping the agent across a project switch (K24)', () => {- it('resumes on the first page after the switch, in this tab, shortly after it', () => {- requestAgentResume(1000);- expect(JSON.parse(window.sessionStorage.getItem(AGENT_RESUME_KEY)!)).toEqual({ at: 1000 });- expect(takeAgentResume(1000 + AGENT_RESUME_WINDOW_MS - 1, 7)).toBe(true);- // The same page reads it again (React's development double effect); a later reload does not.- expect(takeAgentResume(1000, 7)).toBe(true);- expect(takeAgentResume(1000, 8)).toBe(false);- expect(window.sessionStorage.getItem(AGENT_RESUME_KEY)).toBeNull();- });-- it('does not resume after the window, from malformed data or without storage', () => {- requestAgentResume(1000);- expect(takeAgentResume(1000 + AGENT_RESUME_WINDOW_MS + 1)).toBe(false);- window.sessionStorage.setItem(AGENT_RESUME_KEY, '{bad');- expect(takeAgentResume(1000)).toBe(false);- vi.stubGlobal('sessionStorage', { getItem: () => { throw new Error('blocked'); }, setItem: () => { throw new Error('blocked'); }, removeItem: () => {} });- expect(() => requestAgentResume()).not.toThrow();- expect(takeAgentResume()).toBe(false);- });-});--describe('a cached model (K10)', () => {- const cacheWith = (urls: string[]) => ({ has: vi.fn(async () => true), open: vi.fn(async () => ({ keys: async () => urls.map(url => new Request(url)) })) });-- it('is cached only when every pinned file is in its dedicated cache', async () => {- const model = BROWSER_MODELS[0];- const all = model.files.map(file => `${browserModelBaseUrl(model)}${file}`);- vi.stubGlobal('caches', cacheWith(all));- expect(await isBrowserModelCached(model)).toBe(true);- vi.stubGlobal('caches', cacheWith(all.slice(0, -1)));- expect(await isBrowserModelCached(model)).toBe(false);- vi.stubGlobal('caches', cacheWith(all.map(url => url.replace(BROWSER_MODEL.revision, 'main'))));- expect(await isBrowserModelCached(model)).toBe(false);- });-- it('never creates the cache it checks, and says not cached without Cache Storage', async () => {- const storage = { has: vi.fn(async () => false), open: vi.fn() };- vi.stubGlobal('caches', storage);- expect(await isBrowserModelCached(BROWSER_MODELS[0])).toBe(false);- expect(storage.open).not.toHaveBeenCalled();- vi.stubGlobal('caches', undefined);- expect(await isBrowserModelCached(BROWSER_MODELS[0])).toBe(false);- });-});diff --git a/graph-ui/src/browser-ai/agent-resume.ts b/graph-ui/src/browser-ai/agent-resume.tsdeleted file mode 100644index 30e61144a..000000000--- a/graph-ui/src/browser-ai/agent-resume.ts+++ /dev/null@@ -1,24 +0,0 @@-/** Opening another project reloads the page, and the worker with the loaded model goes- * with it (K24). The switch leaves a short note in this tab; the next page loads the- * same model again, only from the browser cache. */-export const AGENT_RESUME_KEY = 'cbm-agent-resume';-/** A switch is a navigation of a few seconds; a stale note must not load a model later. */-export const AGENT_RESUME_WINDOW_MS = 60_000;--const thisPage = (): number => typeof performance === 'undefined' ? 0 : performance.timeOrigin;--export function requestAgentResume(now = Date.now()): void {- try { window.sessionStorage.setItem(AGENT_RESUME_KEY, JSON.stringify({ at: now })); } catch { /* Without storage the next page starts with the agent off. */ }-}--/** True for a fresh note, for the first page that reads it only: a later reload does not- * resume again, while a second read on the same page (React's development double effect) does. */-export function takeAgentResume(now = Date.now(), page = thisPage()): boolean {- try {- const note = JSON.parse(window.sessionStorage.getItem(AGENT_RESUME_KEY) ?? 'null') as { at?: unknown; page?: unknown } | null;- const fresh = typeof note?.at === 'number' && now >= note.at && now - note.at <= AGENT_RESUME_WINDOW_MS;- if (!fresh || (note!.page !== undefined && note!.page !== page)) { window.sessionStorage.removeItem(AGENT_RESUME_KEY); return false; }- window.sessionStorage.setItem(AGENT_RESUME_KEY, JSON.stringify({ at: note!.at, page }));- return true;- } catch { return false; }-}diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.tsindex c8ba2427b..78ab503d4 100644--- a/graph-ui/src/browser-ai/strings.ts+++ b/graph-ui/src/browser-ai/strings.ts@@ -139,7 +139,7 @@ export const browserChatText = {cached: 'Cached',loadCached: 'Load model (cached, no download)',autoLoad: 'Load the chosen model on start when it is cached',- autoLoadNote: 'Only from this browser\'s cache; nothing is downloaded on start. Switching projects keeps a loaded model either way.',+ autoLoadNote: 'Only from this browser\'s cache; nothing is downloaded on start. A project switch stays in this page and keeps a loaded model without loading it again, so this option only matters when the page is opened or reloaded.',resumeFailed: 'The cached model could not be loaded without a download. Load it in the agent configuration.',/** Under an answer that names what its source and graph facts do not contain (K12). */unsupportedNames: (names: readonly string[]) => `Not in the source or graph facts this answer was given: ${names.join(', ')}. Check these names before relying on them.`,