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): reuse selection explanations and wait for complete scopes
Bernhard Jackiewicz0fb950408502
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsxindex 7e1f47310..97f82efeb 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import BrowserChatDock, { type BrowserChatAttachment, type BrowserChatDockProps, type BrowserChatReaderContext } from './BrowserChatDock';import type { BrowserAiProgress, BrowserChatMessage } from './browser-ai-runtime';import { BROWSER_MODELS } from './model-policy';-import { JSONB_AGG_CALLERS, jsonbAggEvidence } from './galaxy-evidence.fixture';+import { JSONB_AGG_CALLERS, jsonbAggEvidence, jsonbAggScope } from './galaxy-evidence.fixture';let container: HTMLDivElement;let root: Root;@@ -934,3 +934,62 @@ describe('graph answers and answer limits', () => {expect(container.querySelectorAll('.cbm-chat-answer-note')[0]?.textContent).toMatch(/earlier messages were left out to fit the input limit/);});});+++describe('per-selection explanation cache', () => {+ afterEach(() => vi.useRealTimers());+ async function settleSelection() { await act(async () => { await vi.advanceTimersByTimeAsync(650); }); }+ const card = () => container.querySelector('[aria-label="Current selection explanation"]')?.textContent ?? '';++ it('shows the cached explanation when returning to a selection without running the model again', async () => {+ vi.useFakeTimers(); const { props, runtime } = fixture();+ runtime.chat.mockResolvedValueOnce('JSONBAgg is called by its tests.').mockResolvedValueOnce('Two layers around JSONBAgg.');+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence() }); await click('Download & load');+ await settleSelection(); expect(runtime.chat).toHaveBeenCalledOnce();+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence({ depth: 2 }) });+ await settleSelection(); expect(runtime.chat).toHaveBeenCalledTimes(2);+ expect(card()).toContain('Two layers around JSONBAgg.');+ // Back to the first selection while its scope reloads, then once it is complete again.+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence({ state: 'loading-partial-preview' }) });+ expect(card()).toContain('JSONBAgg is called by its tests.');+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence() });+ await settleSelection();+ expect(runtime.chat).toHaveBeenCalledTimes(2);+ expect(runtime.countTokens).toHaveBeenCalledTimes(2);+ expect(card()).toContain('JSONBAgg is called by its tests.');+ expect(card()).not.toContain('Explaining selection');+ });++ it('starts an explanation only once the scope is complete', async () => {+ vi.useFakeTimers(); const { props, runtime } = fixture();+ const preview = jsonbAggEvidence({ edges: jsonbAggScope().edges.slice(0, 3), state: 'loading-partial-preview' });+ await render({ ...props, proactive: true, proactiveSelection: preview }); await click('Download & load');+ await settleSelection();+ expect(runtime.countTokens).not.toHaveBeenCalled();+ expect(card()).toContain('Waiting for the complete scope');+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence() });+ await settleSelection();+ expect(runtime.chat).toHaveBeenCalledOnce();+ expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toContain('Incoming relationships: 23 from 12 symbols.');+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence({ state: 'partial' }) });+ await settleSelection(); expect(runtime.chat).toHaveBeenCalledOnce();+ });++ it('regenerates on request and keeps the cache bounded', async () => {+ vi.useFakeTimers(); const { props, runtime } = fixture();+ let calls = 0; runtime.chat.mockImplementation(async () => `Explanation number ${++calls}.`);+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence() }); await click('Download & load');+ await settleSelection(); expect(card()).toContain('Explanation number 1.');+ await click('Explain again'); await settleSelection();+ expect(card()).toContain('Explanation number 2.');+ for (let depth = 2; depth <= 33; depth++) {+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence({ depth }) }); await settleSelection();+ }+ expect(runtime.chat).toHaveBeenCalledTimes(34);+ // 32 later selections pushed the first one out of the cache.+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence() }); await settleSelection();+ expect(runtime.chat).toHaveBeenCalledTimes(35);+ await render({ ...props, proactive: true, proactiveSelection: jsonbAggEvidence({ depth: 33 }) }); await settleSelection();+ expect(runtime.chat).toHaveBeenCalledTimes(35);+ });+});diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsxindex fbe353963..b852d0e39 100644--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx@@ -41,6 +41,9 @@ export interface BrowserChatDockProps {type Phase = 'off' | 'preparing' | 'ready' | 'counting' | 'generating' | 'removing';type ChatTurn = BrowserChatTurn & { evidence?: PreparedExplanationContext };+type Explanation = { key: string; label: string; answer: string; status: string; error?: string; packet?: PreparedExplanationContext; citation?: ReturnType<typeof citedInterpretation>; mode?: 'interpretation'; shortened?: boolean };+/** 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 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`;@@ -86,7 +89,8 @@ 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 }: BrowserChatDockProps): JSX.Element {const [automatic, setAutomatic] = useState(true);- const [explanation, setExplanation] = useState<{ key: string; label: string; answer: string; status: string; error?: string; packet?: PreparedExplanationContext; citation?: ReturnType<typeof citedInterpretation>; mode?: 'interpretation'; shortened?: boolean }>();+ const [explanation, setExplanation] = useState<Explanation>();+ const explanations = useRef(new Map<string, Explanation>());const [retryExplanation, setRetryExplanation] = useState(0);const autoRun = useRef<{ key: string; cancelled: boolean; settled: Promise<void> } | undefined>(undefined);const manualRequest = useRef<{ cancelled: boolean } | undefined>(undefined);@@ -130,7 +134,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "useEffect(() => {if (historyProject.current === historyKey) return;historyProject.current = historyKey;- resetProject();+ explanations.current.clear(); resetProject();setSelectedContext([]); setHandledContextId(undefined); setNewExplanation(false);}, [historyKey]);useEffect(() => {@@ -174,11 +178,24 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "}}, [selected?.key, automatic, proactive]);useEffect(() => {- if (!historyReady || !proactive || !automatic || !selected || phase !== 'ready' || manualRequest.current || pending.current || lastAttempt.current === selected.key) return;+ // Returning to an explained selection shows what was already written.+ const cached = selected && explanations.current.get(selected.key);+ if (!cached) return;+ lastAttempt.current = cached.key;+ setExplanation(previous => previous?.key === cached.key ? previous : cached);+ }, [selected?.key]);+ useEffect(() => {+ if (!historyReady || !proactive || !automatic || !selected || selected.waiting || phase !== 'ready' || manualRequest.current || pending.current+ || lastAttempt.current === selected.key || explanations.current.has(selected.key)) return;const snapshot = selected;const timer = setTimeout(() => { void explain(snapshot); }, EXPLANATION_DELAY_MS);return () => clearTimeout(timer);- }, [selected?.key, phase, automatic, proactive, retryExplanation, historyReady]);+ }, [selected?.key, selected?.waiting, phase, automatic, proactive, retryExplanation, historyReady]);+ const remember = (entry: Explanation): void => {+ const cache = explanations.current;+ cache.delete(entry.key); cache.set(entry.key, entry);+ while (cache.size > EXPLANATION_CACHE_SIZE) cache.delete(cache.keys().next().value!);+ };const explain = async (snapshot: ExplanationInput): Promise<void> => {const currentRuntime = runtime.current;@@ -216,9 +233,10 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "if (valid()) {const result = parseExplanationResponse(answer, packet);if (!followExplanation.current) setNewExplanation(true);- setExplanation(result.status === 'generated'- ? { key: snapshot.key, label: snapshot.label, answer: result.markdown, status: 'complete', mode: 'interpretation', packet, citation: result.citation, ...shortened ? { shortened } : {} }- : { key: snapshot.key, label: snapshot.label, answer: '', status: 'error', packet, error: result.reason });+ if (result.status === 'generated') {+ const complete: Explanation = { key: snapshot.key, label: snapshot.label, answer: result.markdown, status: 'complete', mode: 'interpretation', packet, citation: result.citation, ...shortened ? { shortened } : {} };+ remember(complete); setExplanation(complete);+ } else setExplanation({ key: snapshot.key, label: snapshot.label, answer: '', status: 'error', packet, error: result.reason });}} catch (failure) {if (epoch.current === ticket && isGpuRuntimeFailure(failure)) { invalidateRuntime(failure); return; }@@ -434,7 +452,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "{proactive && <label><input type="checkbox" checked={automatic} onChange={event => setAutomatic(event.target.checked)} /> Explain selections automatically</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(); setModelId(event.target.value); setError(undefined); setNotice(undefined); }}>+ <select id="cbm-chat-model" value={modelId} disabled={busy} onChange={event => { release(); explanations.current.clear(); setModelId(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>)}</select><p>{sizeLabel(model.bytes)} download · {model.license}. Memory use is higher.</p>@@ -482,8 +500,11 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "<ChatMarkdown text={explanation.answer || (explanation.status === 'generating' ? 'Explaining selection…' : explanation.status === 'stopped' ? 'Explanation stopped.' : '')} />{explanation.status !== 'generating' && <AnswerNotes shortened={explanation.shortened} packet={explanation.packet} model={model.displayName} />}{explanation.error && <p className="cbm-chat-turn-error" role="alert">{explanation.error}</p>}- {explanation.status !== 'generating' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready'} onClick={() => { lastAttempt.current = undefined; setRetryExplanation(value => value + 1); }}>Explain again</button>}- </> : <p>{manualRequest.current ? 'This selection will be explained after your answer.' : 'Preparing explanation…'}</p>}+ {explanation.status !== 'generating' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready' || !!selected.waiting} onClick={() => {+ lastAttempt.current = undefined; explanations.current.delete(selected.key); setRetryExplanation(value => value + 1);+ }}>Explain again</button>}+ </> : <p>{selected.waiting === 'loading' ? browserChatText.waitingForScope : selected.waiting === 'partial' ? browserChatText.partialScope+ : manualRequest.current ? 'This selection will be explained after your answer.' : 'Preparing explanation…'}</p>}</section>}{turns.length === 0 && !(proactive && automatic && selected) && <div className="cbm-chat-empty"><span aria-hidden="true">⌁</span><h3>Ask about the code.</h3><p>{readerContext ? 'The current file is included automatically. Mark code to focus your next message on that exact selection.' : 'Ask a question, or add source and graph context to your next message.'}</p></div>}{turns.map((turn, index) => <article className="cbm-chat-turn" key={turn.id}>diff --git a/graph-ui/src/browser-ai/proactive-selection.test.ts b/graph-ui/src/browser-ai/proactive-selection.test.tsnew file mode 100644index 000000000..654b54b5d--- /dev/null+++ b/graph-ui/src/browser-ai/proactive-selection.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it } from 'vitest';+import { jsonbAggEvidence, jsonbAggScope } from './galaxy-evidence.fixture';+import { explanationInput } from './proactive-selection';++const key = (scope: string, context = jsonbAggEvidence()) => explanationInput(scope, undefined, context)!.key;++describe('selection identity for explanations', () => {+ it('keys a Galaxy selection by project, workspace, scope, direction, edge types and depth only', () => {+ const base = key('django-demo:galaxy');+ // Counts, rendered sizes and loading state change while a scope loads; they are not identity.+ const fewer = jsonbAggEvidence({ edges: jsonbAggScope().edges.slice(0, 5), state: 'loading-partial-preview' });+ expect(key('django-demo:galaxy', fewer)).toBe(base);+ expect(key('cbm:galaxy')).not.toBe(base);+ expect(key('django-demo:explore')).not.toBe(base);+ expect(key('django-demo:galaxy', jsonbAggEvidence({ depth: 2 }))).not.toBe(base);+ expect(key('django-demo:galaxy', jsonbAggEvidence({ direction: 'inbound' }))).not.toBe(base);+ const filtered = JSON.parse(jsonbAggEvidence().text);+ filtered.evidence.scope.edgeTypes = ['CALLS'];+ expect(key('django-demo:galaxy', { id: 'f', label: 'JSONBAgg', text: JSON.stringify(filtered) })).not.toBe(base);+ const other = JSON.parse(jsonbAggEvidence().text);+ other.evidence.selected.scope = { kind: 'node', id: 7, name: 'OrderableAggMixin' };+ expect(key('django-demo:galaxy', { id: 'o', label: 'OrderableAggMixin', text: JSON.stringify(other) })).not.toBe(base);+ });++ it('marks incomplete Galaxy scopes as waiting and leaves other graph evidence unchanged', () => {+ expect(explanationInput('p:galaxy', undefined, jsonbAggEvidence())?.waiting).toBeUndefined();+ expect(explanationInput('p:galaxy', undefined, jsonbAggEvidence({ state: 'loading-partial-preview' }))?.waiting).toBe('loading');+ expect(explanationInput('p:galaxy', undefined, jsonbAggEvidence({ state: 'partial' }))?.waiting).toBe('partial');+ const architecture = { id: 'a', label: 'Component', text: JSON.stringify({ evidence: { kind: 'current-selection-evidence', view: 'architecture-structure', selected: { name: 'api' } } }) };+ expect(explanationInput('p:architecture', undefined, architecture)).toEqual({ key: JSON.stringify(['p:architecture', 'Component', architecture.text]), label: 'Component', graph: architecture });+ });+});diff --git a/graph-ui/src/browser-ai/proactive-selection.ts b/graph-ui/src/browser-ai/proactive-selection.tsindex dd46a1b7c..39fa82625 100644--- a/graph-ui/src/browser-ai/proactive-selection.ts+++ b/graph-ui/src/browser-ai/proactive-selection.ts@@ -1,4 +1,5 @@import { snapshotReaderContext, selectionLocation, type BrowserChatContext, type BrowserChatReaderContext } from './chat-model';+import { readGalaxyEvidence } from './galaxy-evidence';export const EXPLANATION_DELAY_MS = 600;export const EXPLANATION_PROMPT = 'Explain the current selection in at most three short bullets: what it is responsible for, how its visible relationships or code work, and one important condition or limitation if evidenced. Use only the supplied source and graph evidence. Distinguish inference from facts. Do not claim runtime execution from static edges. Do not repeat raw metadata or inventories. If evidence is insufficient, say what is missing briefly.';@@ -8,6 +9,8 @@ export interface ExplanationInput {label: string;reader?: BrowserChatReaderContext;graph?: BrowserChatContext;+ /** A Galaxy scope that is not complete yet is shown, never explained. */+ waiting?: 'loading' | 'partial';}/** Snapshot exact evidence; generated UI event IDs are not selection identity. */@@ -19,5 +22,11 @@ export function explanationInput(scope: string, reader?: BrowserChatReaderContexreturn { key: JSON.stringify([scope, source]), label: source.kind === 'selection' ? selectionLocation(snapshot.source) : source.path, reader: snapshot };}if (!graph?.text.trim()) return;+ const galaxy = readGalaxyEvidence(graph.text);+ if (galaxy) {+ // The selection and how its scope is drawn; counts and loading state change while it loads.+ const key = JSON.stringify([scope, 'galaxy', galaxy.identity, galaxy.direction, galaxy.edgeTypes, galaxy.depth]);+ return { key, label: graph.label, graph: { ...graph }, ...galaxy.state === 'complete' ? {} : { waiting: galaxy.state } };+ }return { key: JSON.stringify([scope, graph.label, graph.text]), label: graph.label, graph: { ...graph } };}diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.tsindex 2a3204fde..2bc44d5b4 100644--- a/graph-ui/src/browser-ai/strings.ts+++ b/graph-ui/src/browser-ai/strings.ts@@ -115,4 +115,6 @@ export const browserChatText = {capacity: (nodes: number, edges: number, model: string, shown: number) =>`${nodes} nodes / ${edges} edges: too large for the local ${model} model; showing ${shown}`,historyTrimmed: (count: number) => `${count} earlier ${count === 1 ? 'message was' : 'messages were'} left out to fit the input limit.`,+ waitingForScope: 'Waiting for the complete scope before explaining…',+ partialScope: 'This scope did not load completely, so it is not explained automatically.',};