Skip to content

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.

fix(ui): read the symbol source for a listed answer and its model question

Bernhard Jackiewicz3620691adcf8
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
index b5e5b524e..9ddf32e81 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
@@ -1343,6 +1343,52 @@ describe('grounded automatic explanations (K14, K7)', () => {
expect(listed.textContent).toContain('class JSONBAgg(OrderableAggMixin, Aggregate):');
});
+ it('reads the source for a listed answer and asks the model with it when automatic explanations are off', async () => {
+ const { props, runtime } = fixture();
+ const readSource = vi.fn(async () => snippet);
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource }); await click('Download & load');
+ const last = () => [...container.querySelectorAll('.cbm-chat-turn')].at(-1)!;
+ await type('Who calls JSONBAgg?'); await click('Send ↑');
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(readSource).toHaveBeenCalledExactlyOnceWith('django-demo.JSONBAgg', { maxLines: 40 });
+ const disclosure = last().querySelector('.cbm-chat-source-content')!;
+ expect(disclosure.textContent).not.toContain('Source unavailable');
+ expect(disclosure.textContent).toContain('class JSONBAgg(OrderableAggMixin, Aggregate):');
+ await click('Ask the model');
+ const prompt = runtime.chat.mock.calls[0][0].map(message => message.content).join('\n');
+ expect(prompt).toContain('function = "JSONB_AGG"');
+ expect(prompt).not.toContain('Source unavailable');
+ expect(readSource).toHaveBeenCalledOnce();
+ });
+
+ it('reads the source again for a suggestion asked of the model after the first read failed', async () => {
+ const { props, runtime } = fixture();
+ const readSource = vi.fn(async () => snippet).mockRejectedValueOnce(new Error('offline'));
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource }); await click('Download & load');
+ const last = () => [...container.querySelectorAll('.cbm-chat-turn')].at(-1)!;
+ await type('jsonbagg calls'); await click('Send ↑');
+ expect(last().querySelector('.cbm-chat-answer-text')?.textContent).toContain('Did you mean: what JSONBAgg calls?');
+ expect(readSource).toHaveBeenCalledOnce();
+ await click('Ask the model');
+ expect(readSource).toHaveBeenCalledTimes(2);
+ const prompt = runtime.chat.mock.calls[0][0].map(message => message.content).join('\n');
+ expect(prompt).toContain('function = "JSONB_AGG"');
+ expect(prompt).not.toContain('Source unavailable');
+ });
+
+ it('keeps the source of a suggestion that is turned into the list', async () => {
+ const { props, runtime } = fixture();
+ const readSource = vi.fn(async () => snippet);
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource }); await click('Download & load');
+ const last = () => [...container.querySelectorAll('.cbm-chat-turn')].at(-1)!;
+ await type('jsonbagg calls'); await click('Send ↑');
+ await click('Show the list');
+ expect(last().querySelector('.cbm-chat-source-content')?.textContent).toContain('class JSONBAgg(OrderableAggMixin, Aggregate):');
+ await click('Ask the model');
+ expect(runtime.chat.mock.calls[0][0].map(message => message.content).join('\n')).toContain('function = "JSONB_AGG"');
+ expect(readSource).toHaveBeenCalledOnce();
+ });
+
it('shows only the listed facts when the model names what the evidence lacks', async () => {
vi.useFakeTimers(); const { props, runtime } = fixture();
const readSource = vi.fn(async () => snippet);
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsx
index 8031e1e59..6c23a9474 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx
@@ -108,11 +108,14 @@ function AnswerNotes({ shortened, packet, model, historyOmitted, unsupported = [
</>;
}
-/** `codeOnly` where the listed facts already stand above it, in the explanation card. */
+/** `codeOnly` where the listed facts already stand above it, in the explanation card. The
+ * source does not push the first graph facts out: a listed answer shows both (K14). */
function PacketSource({ packet, citation, codeOnly = false }: { packet: PreparedExplanationContext; citation?: ReturnType<typeof citedInterpretation>; codeOnly?: boolean }): JSX.Element {
+ const code = packet.evidence.filter(item => item.source === 'code').slice(0, 3);
+ const facts = codeOnly ? [] : packet.evidence.filter(item => item.source !== 'code').slice(0, 3);
return <>
{packet.limitations.map((limit, index) => <p className="cbm-chat-evidence-note" key={index}>{limit}</p>)}
- {citation ? <pre>{citation.quote}</pre> : packet.evidence.filter(item => !codeOnly || item.source === 'code').slice(0, 3).map(item => <div key={item.id}>
+ {citation ? <pre>{citation.quote}</pre> : [...code, ...facts].map(item => <div key={item.id}>
{item.location && <small>{item.location.path}:{item.location.startLine}-{item.location.endLine}</small>}<pre>{item.text}</pre>
</div>)}
</>;
@@ -321,6 +324,16 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
const target = sourceTargetOf(context);
return carriedSource(context) ?? (target ? readSources.current.get(target.qualifiedName) : undefined);
};
+ /** A listed answer or suggestion stands on the selection's source as an explanation does:
+ * read once, also when no automatic explanation read it first (K14). */
+ const listSource = (id: string, context: BrowserChatContext): void => {
+ if (knownSource(context) || !sourceTargetOf(context)) return;
+ const budget = chatEvidence;
+ void sourceFor(context).then(symbol => {
+ if (symbol) setTurns(previous => previous.map(item => item.id === id && (item.answeredFrom === 'graph' || item.answeredFrom === 'suggestion')
+ ? { ...item, evidence: prepareExplanationContext(undefined, context, budget, symbol) } : item));
+ });
+ };
const remember = (entry: Explanation): void => {
const cache = explanations.current;
cache.delete(entry.key); cache.set(entry.key, entry);
@@ -494,7 +507,10 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
let packet = retry?.evidence;
// A listed answer or a suggestion asked again goes to the model: the same question and evidence in a fresh request.
const ask = retry?.answeredFrom === 'graph' || retry?.answeredFrom === 'suggestion';
+ // The graph evidence it was listed from, read again with its source (K14).
+ const askFrom = ask ? retry.listedFrom ?? retry.suggestion?.context : undefined;
const currentGraph = !retry && !reader && proactiveSelection ? [{ ...proactiveSelection }] : [];
+ const packetGraph = askFrom ? [askFrom] : currentGraph;
const consume = (): void => {
setDraft(previous => previous === prompt ? '' : previous);
setSelectedContext(previous => previous.filter(item => !extra.some(sent => sent.id === item.id && sent.text === item.text)));
@@ -515,19 +531,21 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
// without the model: a small model drops and repeats names in long lists.
const listed = !retry && !source ? relationshipAnswer(prompt, [...currentGraph, ...extra]) : undefined;
if (listed) {
- setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, context: extra, topic,
+ const id = `local-turn-${crypto.randomUUID()}`;
+ setTurns(previous => [...previous, { id, prompt, context: extra, topic, listedFrom: listed.context,
evidence: prepareExplanationContext(undefined, listed.context, chatEvidence, knownSource(listed.context)), modelId: model.id, request: [],
answer: listed.markdown, status: 'complete', answeredFrom: 'graph' }]);
- consume();
+ consume(); listSource(id, listed.context);
return;
}
// Sounds like callers or callees but is not certain: offer the list, do not guess with the model.
const suggested = !retry && !source ? relationshipSuggestion(prompt, [...currentGraph, ...extra]) : undefined;
if (suggested) {
- setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, context: extra, topic,
+ const id = `local-turn-${crypto.randomUUID()}`;
+ setTurns(previous => [...previous, { id, prompt, context: extra, topic,
evidence: prepareExplanationContext(undefined, suggested.context, chatEvidence, knownSource(suggested.context)), modelId: model.id, request: [],
answer: suggested.markdown, status: 'complete', answeredFrom: 'suggestion', suggestion: { question: suggested.question, context: suggested.context } }]);
- consume();
+ consume(); listSource(id, suggested.context);
return;
}
// Answers about another file or selection stay out, and so do those from before the
@@ -538,12 +556,12 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
const queued = { cancelled: false }; manualRequest.current = queued;
const waitingEpoch = epoch.current;
// The selected symbol's source grounds a question as it grounds the explanation (K14).
- const symbol = !retry && !reader && currentGraph.length ? await sourceFor(currentGraph[0]) : undefined;
+ const symbol = (!retry || askFrom) && !reader && packetGraph.length ? await sourceFor(packetGraph[0]) : undefined;
if (queued.cancelled || manualRequest.current !== queued || epoch.current !== waitingEpoch || runtime.current !== currentRuntime) {
if (manualRequest.current === queued) manualRequest.current = undefined;
return;
}
- if (!retry && ((reader?.source?.text.length ?? 0) > 5000 || currentGraph.length)) packet = prepareExplanationContext(reader, currentGraph, chatEvidence, symbol);
+ if ((!retry || askFrom) && ((reader?.source?.text.length ?? 0) > 5000 || packetGraph.length)) packet = prepareExplanationContext(reader, packetGraph, chatEvidence, symbol);
let request = retry && !ask ? retry.request.map(message => ({ ...message })) : makeRequest();
if (automaticRun) {
automaticRun.cancelled = true; lastAttempt.current = undefined;
@@ -569,8 +587,8 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
request = makeRequest(); count = await currentRuntime.countTokens(request);
if (epoch.current !== ticket || stopRequested.current) return;
}
- for (let budget = packet ? Math.floor(chatEvidence * .6) : chatEvidence; !retry && count > limit && (reader?.source || currentGraph.length) && budget >= 300; budget = Math.floor(budget * .6)) {
- packet = prepareExplanationContext(reader, currentGraph, budget, symbol);
+ for (let budget = packet ? Math.floor(chatEvidence * .6) : chatEvidence; (!retry || askFrom) && count > limit && (reader?.source || packetGraph.length) && budget >= 300; budget = Math.floor(budget * .6)) {
+ packet = prepareExplanationContext(reader, packetGraph, budget, symbol);
request = makeRequest(); count = await currentRuntime.countTokens(request);
if (epoch.current !== ticket || stopRequested.current) return;
}
@@ -613,8 +631,9 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
const showSuggestedList = (turn: ChatTurn): void => {
const listed = turn.suggestion && relationshipAnswer(turn.suggestion.question, [turn.suggestion.context]);
if (!listed) return;
- setTurns(previous => previous.map(item => item.id === turn.id ? { ...item, answer: listed.markdown, answeredFrom: 'graph', suggestion: undefined,
+ setTurns(previous => previous.map(item => item.id === turn.id ? { ...item, answer: listed.markdown, answeredFrom: 'graph', suggestion: undefined, listedFrom: listed.context,
evidence: prepareExplanationContext(undefined, listed.context, chatEvidence, knownSource(listed.context)) } : item));
+ listSource(turn.id, listed.context);
};
const deleteCache = async (): Promise<void> => {
if (pending.current) return;
diff --git a/graph-ui/src/browser-ai/chat-history-cache.test.ts b/graph-ui/src/browser-ai/chat-history-cache.test.ts
index 24ac03a02..ddf93ce77 100644
--- a/graph-ui/src/browser-ai/chat-history-cache.test.ts
+++ b/graph-ui/src/browser-ai/chat-history-cache.test.ts
@@ -137,6 +137,15 @@ describe('browser-local chat history', () => {
expect((await cache.load(key))?.turns).toEqual(turns);
});
+ it('keeps the graph evidence a listed answer was listed from, and rejects a damaged one (K14)', async () => {
+ const { cache } = setup();
+ const listedFrom = { id: 'galaxy', label: 'JSONBAgg', text: '{"kind":"galaxy-scope-evidence"}' };
+ const turns = [{ ...turn(), answeredFrom: 'graph' as const, listedFrom }];
+ await cache.save(key, { turns });
+ expect((await cache.load(key))?.turns).toEqual(turns);
+ await expect(cache.save(key, { turns: [{ ...turn(), listedFrom: { id: 'galaxy', label: 'JSONBAgg', text: 42 } } as unknown as BrowserChatTurn] })).rejects.toThrow('invalid snapshot');
+ });
+
it('rejects failed reads, saves and deletes so callers can retain in-memory state', async () => {
const { cache, storage } = setup();
await cache.save(key, { turns: [turn()] });
diff --git a/graph-ui/src/browser-ai/chat-history-cache.ts b/graph-ui/src/browser-ai/chat-history-cache.ts
index 0a4e42e7c..ac8675668 100644
--- a/graph-ui/src/browser-ai/chat-history-cache.ts
+++ b/graph-ui/src/browser-ai/chat-history-cache.ts
@@ -87,6 +87,10 @@ function isPreparedEvidence(value: unknown): value is PreparedExplanationContext
Number.isSafeInteger((item.location as Record<string, unknown>)[key]) && Number((item.location as Record<string, unknown>)[key]) >= 1))));
}
+function isContext(value: unknown): boolean {
+ return isObject(value) && ['id', 'label', 'text'].every(key => typeof value[key] === 'string');
+}
+
function isTurn(value: unknown): boolean {
return isObject(value) && ['id', 'prompt', 'modelId', 'answer'].every(key => typeof value[key] === 'string')
&& ['counting', 'generating', 'complete', 'stopped', 'error'].includes(String(value.status))
@@ -94,8 +98,8 @@ function isTurn(value: unknown): boolean {
&& (value.evidence === undefined || isPreparedEvidence(value.evidence))
&& (value.attachment === undefined || isAttachment(value.attachment))
&& (value.readerContext === undefined || isReaderContext(value.readerContext))
- && (value.context === undefined || (Array.isArray(value.context) && value.context.every(item =>
- isObject(item) && ['id', 'label', 'text'].every(key => typeof item[key] === 'string'))))
+ && (value.context === undefined || (Array.isArray(value.context) && value.context.every(isContext)))
+ && (value.listedFrom === undefined || isContext(value.listedFrom))
&& Array.isArray(value.request) && value.request.every(message => isObject(message)
&& ['system', 'user', 'assistant'].includes(String(message.role)) && typeof message.content === 'string');
}
diff --git a/graph-ui/src/browser-ai/chat-model.ts b/graph-ui/src/browser-ai/chat-model.ts
index dd986e8f4..51df841e9 100644
--- a/graph-ui/src/browser-ai/chat-model.ts
+++ b/graph-ui/src/browser-ai/chat-model.ts
@@ -48,6 +48,9 @@ export interface BrowserChatTurn {
answeredFrom?: 'graph' | 'suggestion' | 'local';
/** The listed question a suggestion offers, with the graph evidence it lists from. */
suggestion?: { question: string; context: BrowserChatContext };
+ /** The graph evidence a listed answer was listed from: asking the model about it reads
+ * the same selection's source (K14). */
+ listedFrom?: BrowserChatContext;
/** Earlier turns left out of this request to fit the input limit. */
historyOmitted?: number;
/** What the question was about; undefined for a question without context. */