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): keep the agent across reloads and project switches from the cache
Bernhard Jackiewicz95a33156cb89
diff --git a/graph-ui/src/App.tsx b/graph-ui/src/App.tsxindex 37f3dca88..caa8f16a4 100644--- a/graph-ui/src/App.tsx+++ b/graph-ui/src/App.tsx@@ -130,6 +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 { browserChatHistoryProjectKey } from './browser-ai/chat-history-cache';import type { BrowserChatAttachment } from './browser-ai/BrowserChatDock';import { browserGraphContext } from './browser-ai/graph-context';@@ -822,7 +823,10 @@ 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));}, []);diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsxindex 4f44f6cf6..212f49680 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx@@ -25,7 +25,7 @@ const selection: BrowserChatAttachment = { id: 'selection-1', text: '\t a +\r\nconst reader = (text: string, kind: 'file' | 'selection' = 'file', path = 'src/sum.ts'): BrowserChatReaderContext => ({ project: 'sample', path, status: 'ready', source: { ...selection, text, path, kind, id: `reader-${path}-${kind}` } });function fixture() {const runtime = {- prepare: vi.fn(async (_progress: (value: BrowserAiProgress) => void) => {}),+ 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.'),@@ -43,7 +43,7 @@ function button(label: string): HTMLButtonElement {expect(target, `button ${label}`).toBeDefined(); return target!;}async function click(label: string): Promise<void> {- if (['Download & load', 'Load model', 'Reload model'].includes(label) && !document.querySelector('#cbm-chat-model')) await models();+ if (['Download & load', 'Load model (cached, no download)', 'Reload model'].includes(label) && !document.querySelector('#cbm-chat-model')) await models();await act(async () => button(label).click());}async function type(value: string): Promise<void> {@@ -604,7 +604,7 @@ describe('proactive selection explanations', () => {expect(runtime.chat).toHaveBeenCalledOnce();expect(container.textContent).not.toContain('LATE_ANSWER');expect(container.querySelector('.cbm-chat-turn')).toBeNull();- await click('Load model'); await click('Send ↑');+ await click('Load model (cached, no download)'); await click('Send ↑');expect(runtime.chat).toHaveBeenCalledTimes(2);expect(runtime.chat.mock.calls[1][0].at(-1)?.content).toBe('Do not send after unload');});@@ -1354,3 +1354,51 @@ describe('grounded automatic explanations (K14, K7)', () => {expect(prompt).not.toMatch(/Selected\.|members\[\d+\]|startLine/);});});++describe('a cached model across reloads and project switches (K10, K24)', () => {+ const configButtons = () => [...document.querySelectorAll('dialog .cbm-chat-model-actions button')].map(item => item.textContent);++ it('says the model is cached and loads it without a download label', async () => {+ const { props, runtime } = fixture(); const isCached = vi.fn(async (id: string) => id === BROWSER_MODELS[0].id);+ await render({ ...props, isCached }); await models();+ expect(document.querySelector<HTMLSelectElement>('#cbm-chat-model')?.selectedOptions[0].textContent).toBe(`${BROWSER_MODELS[0].displayName} · Cached`);+ expect(configButtons()).toContain('Load model (cached, no download)');+ expect(configButtons()).not.toContain('Download & load');+ expect(props.createRuntime).not.toHaveBeenCalled();+ await act(async () => button('Load model (cached, no download)').click());+ expect(runtime.prepare).toHaveBeenCalledOnce();+ expect(runtime.prepare.mock.calls[0][1]).toEqual({ cacheOnly: true });+ });++ it('offers loading the chosen model on start, off by default, and then loads it from the cache by itself', async () => {+ const first = fixture(); const isCached = vi.fn(async () => true);+ await render({ ...first.props, isCached }); await models();+ const option = document.querySelector<HTMLInputElement>('#cbm-chat-auto-load')!;+ expect(option.checked).toBe(false);+ expect(first.props.createRuntime).not.toHaveBeenCalled();+ await act(async () => option.click());+ await act(async () => root.unmount());+ root = createRoot(container);+ const second = fixture();+ await render({ ...second.props, isCached });+ expect(second.props.createRuntime).toHaveBeenCalledOnce();+ expect(second.runtime.prepare.mock.calls[0][1]).toEqual({ cacheOnly: true });+ });++ it('does not load by itself when the files are not cached', async () => {+ window.localStorage.setItem(AGENT_PREFERENCES_KEY, JSON.stringify({ version: 1, preferences: { modelId: BROWSER_MODELS[0].id, automatic: true, autoLoad: true, limits: {} } }));+ const { props } = fixture();+ await render({ ...props, isCached: vi.fn(async () => false) });+ 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();+ await render({ ...props, isCached: vi.fn(async () => true) });+ expect(props.createRuntime).toHaveBeenCalledOnce();+ expect(runtime.prepare.mock.calls[0][1]).toEqual({ cacheOnly: true });+ expect(window.sessionStorage.getItem('cbm-agent-resume')).toBeNull();+ });+});+diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsxindex 5c9abf30b..902d5fe9b 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx@@ -1,7 +1,8 @@import { useEffect, useMemo, useRef, useState, type FormEvent, type JSX, type ReactNode } from 'react';import type { BrowserAiProgress } from './browser-ai-controller';import { createBrowserChatRuntime, type BrowserChatRuntime } from './browser-ai-runtime';-import { BROWSER_MODELS, removeBrowserModelCache, type BrowserModel } from './model-policy';+import { BROWSER_MODELS, getBrowserModel, isBrowserModelCached, removeBrowserModelCache, type BrowserModel } from './model-policy';+import { takeAgentResume } from './agent-resume';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';@@ -42,6 +43,8 @@ export interface BrowserChatDockProps {removeCache?: (modelId: string) => Promise<void>;/** Reads a selected symbol's source (get_code_snippet), so explanations stand on code, not names. */readSource?: SymbolSourceReader;+ /** Whether a model's files are in the browser cache (K10). */+ isCached?: (modelId: string) => Promise<boolean>;}type Phase = 'off' | 'preparing' | 'ready' | 'counting' | 'generating' | 'removing';@@ -50,6 +53,7 @@ type Explanation = { key: string; label: string; answer: string; status: string;/** Finished explanations per selection, so returning to one does not run the model again. */const EXPLANATION_CACHE_SIZE = 32;const initialModel = BROWSER_MODELS.find(model => model.availability === 'available')!;+const cachedInBrowser = (modelId: string) => isBrowserModelCached(getBrowserModel(modelId)).catch(() => false);const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error);const sizeLabel = (bytes: number): string => bytes >= 1_000_000_000 ? `${(bytes / 1_000_000_000).toFixed(2)} GB` : `${Math.ceil(bytes / 1_000_000)} MB`;/** Symbol sources read for explanations and questions, newest last. */@@ -136,7 +140,7 @@ function ContextSnapshot({ context }: { context: BrowserChatContext }): JSX.Elem}/** Keep mounted when collapsed: state and worker lifetime are independent of visibility. */-export default function BrowserChatDock({ proactiveSelection, selectionScope = "", historyKey, proactive = true, onAgentStateChange, onAgentModelChange, settingsRequest = 0, open, onClose, showCollapsed = false, onOpen, attachment, readerContext, context = [], pendingContext, onContextConsumed, onContextRemoved, onAttachmentConsumed, onAttachmentRemoved, createRuntime = createBrowserChatRuntime, removeCache = removeBrowserModelCache, readSource }: BrowserChatDockProps): JSX.Element {+export default function BrowserChatDock({ proactiveSelection, selectionScope = "", historyKey, proactive = true, onAgentStateChange, onAgentModelChange, settingsRequest = 0, open, onClose, showCollapsed = false, onOpen, attachment, readerContext, context = [], pendingContext, onContextConsumed, onContextRemoved, onAttachmentConsumed, onAttachmentRemoved, createRuntime = createBrowserChatRuntime, removeCache = removeBrowserModelCache, readSource, isCached = cachedInBrowser }: BrowserChatDockProps): JSX.Element {const { preferences, setPreferences } = useAgentPreferences();const automatic = preferences.automatic;const [explanation, setExplanation] = useState<Explanation>();@@ -168,7 +172,8 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "const [runtimeFailed, setRuntimeFailed] = useState(false);const [notice, setNotice] = useState<string>();const [progress, setProgress] = useState<BrowserAiProgress>();- const [downloaded, setDownloaded] = useState<Set<string>>(() => new Set());+ /** Models whose files are in the browser cache: checked on start, not remembered per session (K10). */+ const [cached, setCached] = useState<ReadonlySet<string>>(() => new Set());const [settingsOpen, setSettingsOpen] = useState(false);/** The token-limit note opens the configuration at its output limit. */const focusOutputLimit = useRef(false);@@ -193,6 +198,20 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "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();+ 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);+ });+ return () => { alive = false; };+ }, []);useEffect(() => {if (historyProject.current === historyKey) return;historyProject.current = historyKey;@@ -413,7 +432,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "release(); setRuntimeFailed(true); setError(message);if (id) setTurns(previous => previous.map(turn => turn.id === id ? { ...turn, status: 'error', error: message } : turn));};- const prepare = async (): Promise<void> => {+ const prepare = async (cacheOnly = cached.has(model.id)): Promise<void> => {if (pending.current || model.availability !== 'available') return;release(); pending.current = true;const ticket = epoch.current;@@ -422,13 +441,15 @@ 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); });+ await nextRuntime.prepare(value => { if (epoch.current === ticket) setProgress(value); }, cacheOnly ? { cacheOnly } : undefined);if (epoch.current !== ticket) return;- setDownloaded(previous => new Set(previous).add(model.id));+ setCached(previous => new Set(previous).add(model.id));setPhase('ready'); setProgress(undefined); setSettingsOpen(false); pending.current = false;} catch (failure) {if (epoch.current !== ticket) return;- release(); setError(messageOf(failure));+ release();+ if (cacheOnly) { setCached(previous => { const next = new Set(previous); next.delete(model.id); return next; }); setError(browserChatText.resumeFailed); }+ else setError(messageOf(failure));}};const stop = (): void => {@@ -589,7 +610,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "try {await removeCache(model.id);if (epoch.current !== ticket) return;- setDownloaded(previous => { const next = new Set(previous); next.delete(model.id); return next; });+ setCached(previous => { const next = new Set(previous); next.delete(model.id); return next; });setNotice('Cached model files deleted. Your conversation is still here.');} catch (failure) { if (epoch.current === ticket) setError(messageOf(failure)); }finally { if (epoch.current === ticket) { pending.current = false; setPhase('off'); } }@@ -607,10 +628,11 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "{settingsOpen && <AgentSettingsDialog onClose={() => setSettingsOpen(false)}><section id="cbm-chat-model-settings" className="cbm-chat-settings" aria-label="Local model settings">{proactive && <label><input type="checkbox" checked={automatic} onChange={event => setPreferences({ automatic: event.target.checked })} /> Explain selections automatically</label>}+ <label title={browserChatText.autoLoadNote}><input id="cbm-chat-auto-load" type="checkbox" checked={preferences.autoLoad} onChange={event => setPreferences({ autoLoad: event.target.checked })} /> {browserChatText.autoLoad}</label><span className="cbm-chat-status" role="status">{status}</span><label htmlFor="cbm-chat-model">Model</label><select id="cbm-chat-model" value={modelId} disabled={busy} onChange={event => { release(); setPreferences({ modelId: event.target.value }); setError(undefined); setNotice(undefined); }}>- {BROWSER_MODELS.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.displayName} · {candidate.availability === 'unsupported' ? 'Requires runtime support' : candidate.id === model.id && phase === 'ready' ? 'Loaded' : downloaded.has(candidate.id) ? 'Downloaded this session' : 'Available'}</option>)}+ {BROWSER_MODELS.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.displayName} · {candidate.availability === 'unsupported' ? 'Requires runtime support' : candidate.id === model.id && phase === 'ready' ? 'Loaded' : cached.has(candidate.id) ? browserChatText.cached : 'Available'}</option>)}</select><p>{sizeLabel(model.bytes)} download · {model.license}. Memory use is higher.</p>{model.compatibilityNote && <p>{model.compatibilityNote}</p>}@@ -624,7 +646,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "</fieldset><p><a href={model.modelCard} target="_blank" rel="noreferrer">Model details</a> · Downloads come from Hugging Face. No model downloads automatically.</p><div className="cbm-chat-model-actions">- {phase === 'off' && <button type="button" className="cbm-chat-primary" disabled={model.availability !== 'available'} onClick={() => { void prepare(); }}>{runtimeFailed ? 'Reload model' : downloaded.has(model.id) ? 'Load model' : 'Download & load'}</button>}+ {phase === 'off' && <button type="button" className="cbm-chat-primary" disabled={model.availability !== 'available'} onClick={() => { void prepare(); }}>{runtimeFailed ? 'Reload model' : cached.has(model.id) ? browserChatText.loadCached : 'Download & load'}</button>}{(phase === 'ready' || phase === 'generating' || phase === 'counting') && <button type="button" onClick={() => { release(); setNotice('Model unloaded. Conversation and cached files retained.'); }}>Unload model</button>}<button type="button" disabled={busy} onClick={() => { void deleteCache(); }}>Delete cached model</button></div>diff --git a/graph-ui/src/browser-ai/agent-preferences.test.ts b/graph-ui/src/browser-ai/agent-preferences.test.tsindex a890261b8..faf2659b2 100644--- a/graph-ui/src/browser-ai/agent-preferences.test.ts+++ b/graph-ui/src/browser-ai/agent-preferences.test.ts@@ -21,7 +21,7 @@ describe('browser-local agent preferences', () => {it('restores a saved model, automatic flag and limits per model', () => {store({ modelId: second.id, automatic: false, limits: { [second.id]: { inputTokens: 4096, outputTokens: 256 } } });const restored = readAgentPreferences();- expect(restored).toEqual({ modelId: second.id, automatic: false, limits: { [second.id]: { inputTokens: 4096, outputTokens: 256 } } });+ expect(restored).toEqual({ modelId: second.id, automatic: false, autoLoad: false, limits: { [second.id]: { inputTokens: 4096, outputTokens: 256 } } });expect(readAgentPreferences()).toBe(restored);expect(tokenLimitsFor(restored, second)).toEqual({ inputTokens: 4096, outputTokens: 256 });expect(tokenLimitsFor(restored, first)).toEqual(defaultTokenLimits(first));@@ -42,13 +42,22 @@ describe('browser-local agent preferences', () => {expect(readAgentPreferences().limits).toEqual({ [second.id]: { inputTokens: 1024, outputTokens: 64 } });});+ it('loads the chosen model on start only when asked to, off by default (K10)', () => {+ expect(DEFAULT_AGENT_PREFERENCES.autoLoad).toBe(false);+ store({ modelId: second.id, autoLoad: 'yes' });+ expect(readAgentPreferences().autoLoad).toBe(false);+ setAgentPreferences({ autoLoad: true });+ expect(JSON.parse(window.localStorage.getItem(AGENT_PREFERENCES_KEY)!).preferences.autoLoad).toBe(true);+ expect(readAgentPreferences()).toMatchObject({ modelId: second.id, autoLoad: true });+ });+it('saves a versioned record and clamps requested limits into the model policy', () => {const limits = clampTokenLimits(first, defaultTokenLimits(first), { inputTokens: 99_999, outputTokens: 1 });expect(limits).toEqual({ inputTokens: first.contextTokens - MIN_OUTPUT_TOKENS, outputTokens: MIN_OUTPUT_TOKENS });expect(clampTokenLimits(first, limits, { outputTokens: 512 })).toEqual({ inputTokens: first.contextTokens - 512, outputTokens: 512 });setAgentPreferences({ automatic: false, limits: { [first.id]: limits } });expect(JSON.parse(window.localStorage.getItem(AGENT_PREFERENCES_KEY)!)).toEqual({ version: 1,- preferences: { modelId: first.id, automatic: false, limits: { [first.id]: limits } } });+ preferences: { modelId: first.id, automatic: false, autoLoad: false, limits: { [first.id]: limits } } });expect(readAgentPreferences()).toMatchObject({ automatic: false, limits: { [first.id]: limits } });});});diff --git a/graph-ui/src/browser-ai/agent-preferences.ts b/graph-ui/src/browser-ai/agent-preferences.tsindex cb231db9b..d0ffe1e23 100644--- a/graph-ui/src/browser-ai/agent-preferences.ts+++ b/graph-ui/src/browser-ai/agent-preferences.ts@@ -10,12 +10,14 @@ export interface TokenLimits { inputTokens: number; outputTokens: number }export interface AgentPreferences {modelId: string;automatic: boolean;+ /** Load the chosen model on start when its files are cached; off unless chosen (K10). */+ autoLoad: boolean;/** Only models whose limits were changed; every other model uses its defaults. */limits: Readonly<Record<string, TokenLimits>>;}const AVAILABLE = BROWSER_MODELS.filter(model => model.availability === 'available');-export const DEFAULT_AGENT_PREFERENCES: Readonly<AgentPreferences> = Object.freeze({ modelId: AVAILABLE[0].id, automatic: true, limits: Object.freeze({}) });+export const DEFAULT_AGENT_PREFERENCES: Readonly<AgentPreferences> = Object.freeze({ modelId: AVAILABLE[0].id, automatic: true, autoLoad: false, limits: Object.freeze({}) });export const AGENT_PREFERENCES_KEY = 'cbm-agent-preferences-v1';const CHANGE = 'cbm-agent-preferences-change';@@ -57,6 +59,7 @@ function validated(value: unknown): Readonly<AgentPreferences> {return Object.freeze({modelId: BROWSER_MODELS.some(model => model.id === row.modelId) ? row.modelId as string : DEFAULT_AGENT_PREFERENCES.modelId,automatic: typeof row.automatic === 'boolean' ? row.automatic : DEFAULT_AGENT_PREFERENCES.automatic,+ autoLoad: typeof row.autoLoad === 'boolean' ? row.autoLoad : DEFAULT_AGENT_PREFERENCES.autoLoad,limits: Object.freeze(limits),});}@@ -94,7 +97,7 @@ export function setAgentPreferences(update: Partial<AgentPreferences> | ((currenwindow.dispatchEvent(new CustomEvent(CHANGE));}-/** Browser-local: the chosen model, automatic explanations and token limits per model. */+/** Browser-local: the chosen model, automatic explanations, loading on start and token limits per model. */export function useAgentPreferences(): { preferences: Readonly<AgentPreferences>; setPreferences: typeof setAgentPreferences } {const subscribe = useCallback((listener: () => void) => {const stored = (event: StorageEvent) => { if (event.key === null || event.key === AGENT_PREFERENCES_KEY) listener(); };diff --git a/graph-ui/src/browser-ai/agent-resume.test.ts b/graph-ui/src/browser-ai/agent-resume.test.tsnew file mode 100644index 000000000..e06db497f--- /dev/null+++ b/graph-ui/src/browser-ai/agent-resume.test.ts@@ -0,0 +1,49 @@+// @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 once, in this tab, shortly after the switch', () => {+ requestAgentResume(1000);+ expect(JSON.parse(window.sessionStorage.getItem(AGENT_RESUME_KEY)!)).toEqual({ at: 1000 });+ expect(takeAgentResume(1000 + AGENT_RESUME_WINDOW_MS - 1)).toBe(true);+ expect(takeAgentResume(1000)).toBe(false);+ });++ 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.tsnew file mode 100644index 000000000..89099eda4--- /dev/null+++ b/graph-ui/src/browser-ai/agent-resume.ts@@ -0,0 +1,20 @@+/** 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;++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 once for a fresh note; reading removes it. */+export function takeAgentResume(now = Date.now()): boolean {+ let raw: string | null = null;+ try { raw = window.sessionStorage.getItem(AGENT_RESUME_KEY); window.sessionStorage.removeItem(AGENT_RESUME_KEY); } catch { return false; }+ try {+ const at = (JSON.parse(raw ?? 'null') as { at?: unknown } | null)?.at;+ return typeof at === 'number' && now >= at && now - at <= AGENT_RESUME_WINDOW_MS;+ } catch { return false; }+}diff --git a/graph-ui/src/browser-ai/browser-ai-controller.ts b/graph-ui/src/browser-ai/browser-ai-controller.tsindex e1d96a246..e87314552 100644--- a/graph-ui/src/browser-ai/browser-ai-controller.ts+++ b/graph-ui/src/browser-ai/browser-ai-controller.ts@@ -1,7 +1,8 @@export interface BrowserAiSource { text: string; path: string; startLine: number; project: string }export interface BrowserAiProgress { file?: string; loaded?: number; total?: number; progress?: number }export interface BrowserAiRuntime {- prepare(onProgress: (progress: BrowserAiProgress) => void): Promise<void>;+ /** `cacheOnly` loads from the browser cache and fails rather than download. */+ prepare(onProgress: (progress: BrowserAiProgress) => void, options?: { cacheOnly?: boolean }): Promise<void>;explain(source: BrowserAiSource): Promise<string>;dispose(): void;}diff --git a/graph-ui/src/browser-ai/browser-ai-runtime.test.ts b/graph-ui/src/browser-ai/browser-ai-runtime.test.tsindex 3161f0ea6..79d9dce5f 100644--- a/graph-ui/src/browser-ai/browser-ai-runtime.test.ts+++ b/graph-ui/src/browser-ai/browser-ai-runtime.test.ts@@ -135,6 +135,16 @@ describe('browser chat worker boundary', () => {runtime.dispose();});+ it('asks the worker for a cache-only load when told to (K10, K24)', async () => {+ const runtime = createBrowserChatRuntime();+ const worker = WorkerStub.instances[0];+ const preparing = runtime.prepare(vi.fn(), { cacheOnly: true });+ expect(worker.last()).toEqual({ id: 1, kind: 'prepare', modelId: BROWSER_MODELS[0].id, cacheOnly: true });+ worker.send({ id: 1, kind: 'ready' });+ await preparing;+ runtime.dispose();+ });+it('streams only the active request, preserves exact content, and counts via the worker', async () => {const runtime = createBrowserChatRuntime(); const worker = WorkerStub.instances[0];const messages = [{ role: 'user' as const, content: '\t' + 'x'.repeat(7000) + '\r\n ' }];diff --git a/graph-ui/src/browser-ai/browser-ai-runtime.ts b/graph-ui/src/browser-ai/browser-ai-runtime.tsindex 1c35f0aa1..5511604b7 100644--- a/graph-ui/src/browser-ai/browser-ai-runtime.ts+++ b/graph-ui/src/browser-ai/browser-ai-runtime.ts@@ -13,6 +13,8 @@ export interface BrowserWorkerRequest {messages?: readonly BrowserChatMessage[];maxOutputTokens?: number;generationProfile?: BrowserChatOptions['generationProfile'];+ /** Prepare from the browser cache only: no model download is allowed. */+ cacheOnly?: boolean;}export interface BrowserWorkerResponse {id: number;@@ -83,7 +85,7 @@ export function createBrowserChatRuntime(modelId: string = BROWSER_MODEL.id): Br}});return {- prepare: async progress => { await request({ kind: 'prepare' }, { progress }); },+ prepare: async (progress, options) => { await request({ kind: 'prepare', ...options?.cacheOnly ? { cacheOnly: true } : {} }, { progress }); },countTokens: async messages => {const response = await request({ kind: 'count', messages });if (!Number.isSafeInteger(response.count) || response.count! < 0) throw new Error('The model returned an invalid token count.');diff --git a/graph-ui/src/browser-ai/browser-ai.worker.test.ts b/graph-ui/src/browser-ai/browser-ai.worker.test.tsindex 1c42460f4..bc678153c 100644--- a/graph-ui/src/browser-ai/browser-ai.worker.test.ts+++ b/graph-ui/src/browser-ai/browser-ai.worker.test.ts@@ -215,6 +215,17 @@ describe('browser generation worker', () => {await expect(fake.env.fetch!(allowed)).rejects.toThrow('outside');});+ it('loads from the cache only, without one network request, when the chat resumes a cached model (K10, K24)', async () => {+ const allowed = browserModelBaseUrl(BROWSER_MODELS[0]) + 'config.json';+ fake.tokenizerLoad.mockImplementationOnce(async () => {+ await expect(fake.env.fetch!(allowed)).rejects.toThrow('outside');+ return { apply_chat_template: fake.template };+ });+ await send({ id: 1, kind: 'prepare', cacheOnly: true });+ expect(replies().at(-1)).toEqual({ id: 1, kind: 'ready' });+ expect(fetchMock).not.toHaveBeenCalled();+ });+it('keeps the bundled runtime module at a direct same-origin URL under restrictive CSP', async () => {fake.modelLoad.mockImplementationOnce(async () => {const wasm = fake.env.backends.onnx.wasm as { wasmPaths: { mjs: string; wasm: string }; proxy: boolean };diff --git a/graph-ui/src/browser-ai/browser-ai.worker.ts b/graph-ui/src/browser-ai/browser-ai.worker.tsindex 4fbf5b2df..e2f53fde5 100644--- a/graph-ui/src/browser-ai/browser-ai.worker.ts+++ b/graph-ui/src/browser-ai/browser-ai.worker.ts@@ -62,7 +62,7 @@ globalThis.fetch = async (input: RequestInfo | URL, options?: RequestInit): Promreturn response;};-async function prepare(id: number, modelId: string): Promise<void> {+async function prepare(id: number, modelId: string, cacheOnly = false): Promise<void> {const next = getBrowserModel(modelId);if (next.availability !== 'available') throw new Error(next.compatibilityNote);if (model && tokenizer) {@@ -99,7 +99,8 @@ async function prepare(id: number, modelId: string): Promise<void> {post({ id, kind: 'progress', progress: { file: update.file, loaded: update.loaded, total: update.total, progress: update.progress } });},};- downloadsAllowed = true;+ // A resumed model loads from Cache Storage; a missing file fails instead of downloading.+ downloadsAllowed = !cacheOnly;try {tokenizer = await AutoTokenizer.from_pretrained(selected.id, options);// CausalLM loads only decoder + embeddings for Qwen3.5; the policy excludes all vision files.@@ -199,7 +200,7 @@ self.onmessage = async (event: MessageEvent<BrowserWorkerRequest>) => {activeId = id;try {if (kind === 'prepare') {- await prepare(id, event.data.modelId ?? BROWSER_MODEL.id);+ await prepare(id, event.data.modelId ?? BROWSER_MODEL.id, event.data.cacheOnly === true);post({ id, kind: 'ready' });} else if (kind === 'count') {post({ id, kind: 'count', count: tokenize(messages ?? []).input_ids.dims.at(-1) });diff --git a/graph-ui/src/browser-ai/model-policy.ts b/graph-ui/src/browser-ai/model-policy.tsindex c7809f839..f4ec53279 100644--- a/graph-ui/src/browser-ai/model-policy.ts+++ b/graph-ui/src/browser-ai/model-policy.ts@@ -104,6 +104,14 @@ export function isPinnedModelRequest(value: string, modelId: string = BROWSER_MO} catch { return false; }}+/** Whether every pinned file of the model is in its dedicated Cache Storage. Checking+ * never creates the cache and never downloads (K10). */+export async function isBrowserModelCached(model: BrowserModel): Promise<boolean> {+ if (typeof caches === 'undefined' || !caches || !(await caches.has(model.cacheName))) return false;+ const stored = new Set((await (await caches.open(model.cacheName)).keys()).map(request => request.url));+ return model.files.every(file => stored.has(`${browserModelBaseUrl(model)}${file}`));+}+export async function removeBrowserModelCache(modelId: string = BROWSER_MODEL.id): Promise<void> {const model = getBrowserModel(modelId);if (typeof caches !== 'undefined') await caches.delete(model.cacheName);diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.tsindex 266b4ce6c..773e19b21 100644--- a/graph-ui/src/browser-ai/strings.ts+++ b/graph-ui/src/browser-ai/strings.ts@@ -132,6 +132,12 @@ export const browserChatText = {largerModels: 'A larger model may stay closer to the question. Each needs a one-time download, and its memory use is higher than the download:',modelDownload: (name: string, size: string) => `${name} · ${size} download`,newConversation: 'New conversation',+ /** The model's state in the agent configuration (K10). */+ 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.',+ 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.`,/** Who wrote which part of a grounded automatic explanation (K7). */