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): keep the listed answer when the model is asked about it

Bernhard Jackiewicza3432f8b8e1d
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.ask-model.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.ask-model.test.tsx
new file mode 100644
index 000000000..6dd383256
--- /dev/null
+++ b/graph-ui/src/browser-ai/BrowserChatDock.ask-model.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest';
+import { JSONB_AGG_CALLERS, jsonbAggEvidence } from './galaxy-evidence.fixture';
+import { dockHarness, readerOf } from './chat-dock.fixture';
+
+const dock = dockHarness();
+const PRE_COMMIT = 'repos:\n - repo: https://github.com/PyCQA/isort\n rev: 5.13.2\n hooks:\n - id: isort\n';
+
+/** "Ask the model" under an answer the chat gave itself put the model's text in its place: the
+ * 11 listed callers became one sentence naming one of them, and nothing said who wrote it (B1). */
+describe('the model answer to a listed, grounded or file answer is a turn of its own (B1)', () => {
+ it('keeps the listed callers and adds the model answer below them, marked as generated', async () => {
+ const { props, runtime } = dock.setup();
+ runtime.chat.mockResolvedValueOnce('The call to JSONBAgg is made by the test_jsonb_agg method.');
+ await dock.render({ ...props, proactiveSelection: jsonbAggEvidence() }); await dock.load();
+ await dock.ask('Who calls JSONBAgg?');
+ await dock.click('Ask the model', dock.last());
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ const [listed, asked] = dock.turns();
+ expect(dock.turns()).toHaveLength(2);
+ for (const name of JSONB_AGG_CALLERS) expect(dock.answerOf(listed)).toContain(name);
+ expect(dock.answerOf(listed)).toContain('not generated by the model');
+ expect(asked.querySelector('.cbm-chat-question')?.textContent).toContain('Who calls JSONBAgg?');
+ expect(asked.querySelector('.cbm-chat-asked-model')?.textContent).toBe('Asked the local model');
+ expect(dock.answerOf(asked)).toBe('The call to JSONBAgg is made by the test_jsonb_agg method.');
+ expect(dock.notesOf(asked)).toContain('Generated by the local model; it can be wrong.');
+ // Only the last turn offers a button: asking again repeats the model's answer in place.
+ expect(dock.buttonsOf(listed)).toEqual([]);
+ expect(dock.buttonsOf(asked)).toEqual(['Ask again']);
+ await dock.click('Ask again', asked);
+ expect(runtime.chat).toHaveBeenCalledTimes(2);
+ expect(runtime.chat.mock.calls[1][0]).toEqual(runtime.chat.mock.calls[0][0]);
+ expect(dock.turns()).toHaveLength(2);
+ });
+
+ it('keeps German facts and adds the model answer with a German note', async () => {
+ const { props, runtime } = dock.setup();
+ runtime.chat.mockResolvedValueOnce('`JSONBAgg` setzt `function` auf "JSONB_AGG".').mockResolvedValueOnce('Diese Klasse ist eine Aggregation.');
+ await dock.render({ ...props, proactiveSelection: jsonbAggEvidence() }); await dock.load();
+ await dock.ask('was macht diese klasse? sehr kurze antwort');
+ const facts = dock.answerOf(dock.last());
+ expect(facts).toContain('Ausgewählt: JSONBAgg (Class)');
+ await dock.click('Modell fragen', dock.last());
+ const [grounded, asked] = dock.turns();
+ expect(dock.turns()).toHaveLength(2);
+ expect(dock.answerOf(grounded)).toBe(facts);
+ expect(asked.querySelector('.cbm-chat-asked-model')?.textContent).toBe('An das lokale Modell gestellt');
+ expect(dock.answerOf(asked)).toBe('Diese Klasse ist eine Aggregation.');
+ expect(dock.notesOf(asked)).toContain('Vom lokalen Modell erzeugt; kann falsch sein.');
+ expect(dock.buttonsOf(asked)).toEqual(['Erneut fragen']);
+ });
+
+ it('keeps a file outline and adds the model answer below it', async () => {
+ const { props, runtime } = dock.setup();
+ runtime.chat.mockResolvedValueOnce('This file configures pre-commit hooks.');
+ await dock.render({ ...props, selectionScope: 'django-demo:explore', readerContext: readerOf(PRE_COMMIT, '.pre-commit-config.yaml') }); await dock.load();
+ await dock.ask('What does this file do?');
+ const outline = dock.answerOf(dock.last());
+ expect(outline).toContain('repos (list of 1):');
+ await dock.click('Ask the model', dock.last());
+ expect(dock.turns()).toHaveLength(2);
+ expect(dock.answerOf(dock.turns()[0])).toBe(outline);
+ expect(dock.answerOf(dock.last())).toBe('This file configures pre-commit hooks.');
+ // The model is asked about the file, and the outline is not handed to it as an earlier answer.
+ const request = runtime.chat.mock.calls[0][0];
+ expect(request[0].content).toContain('--- BEGIN EXACT SOURCE TEXT ---\nrepos:');
+ expect(request.filter(message => message.role === 'assistant')).toHaveLength(0);
+ // A follow-up carries both: the outline and the model's answer.
+ await dock.ask('Which hook runs isort?');
+ expect(dock.questionsIn(runtime.chat.mock.calls[1][0])).toEqual(['What does this file do?', 'What does this file do?', 'Which hook runs isort?']);
+ });
+
+ it('marks every free model answer as generated, in the language of the question', async () => {
+ const { props, runtime } = dock.setup();
+ runtime.chat.mockResolvedValueOnce('It adds two values.').mockResolvedValueOnce('Es addiert zwei Werte.');
+ await dock.render({ ...props, readerContext: readerOf('export const sum = (a: number, b: number) => a + b;', 'src/sum.ts') }); await dock.load();
+ await dock.ask('Which values does it add, and where is it used?');
+ expect(dock.notesOf(dock.last())).toContain('Generated by the local model; it can be wrong.');
+ expect(dock.buttonsOf(dock.last())).toEqual(['Ask again']);
+ expect(dock.last().querySelector('.cbm-chat-asked-model')).toBeNull();
+ await dock.ask('Welche Werte addiert es, und wo wird es benutzt?');
+ expect(dock.notesOf(dock.last())).toContain('Vom lokalen Modell erzeugt; kann falsch sein.');
+ expect(dock.buttonsOf(dock.last())).toEqual(['Erneut fragen']);
+ });
+});
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
index a87cee2e7..a37dfd6ac 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
@@ -281,7 +281,7 @@ describe('persistent local browser chat', () => {
expect(runtime.chat.mock.calls[0][0].at(-1)?.content).not.toContain('changed graph');
expect(container.querySelector('.cbm-chat-pending')).toBeNull();
expect(container.querySelector('.cbm-chat-turn:last-child .cbm-chat-source-content pre')?.textContent).toBe('entry → sum');
- await click('Retry'); expect(runtime.chat.mock.calls[1][0]).toEqual(runtime.chat.mock.calls[0][0]);
+ await click('Ask again'); expect(runtime.chat.mock.calls[1][0]).toEqual(runtime.chat.mock.calls[0][0]);
});
it('sends controlled graph selection once with literal code and retains it for retry', async () => {
@@ -291,7 +291,7 @@ describe('persistent local browser chat', () => {
const first = runtime.chat.mock.calls[0][0].at(-1)!.content;
expect(first).toContain(selection.text); expect(first).toContain(pendingContext.text); expect(callbacks.onContextConsumed).toHaveBeenCalledExactlyOnceWith('galaxy-1');
expect(container.querySelector('[aria-label="Remove graph selection"]')).toBeNull();
- await click('Retry'); expect(runtime.chat.mock.calls[1][0]).toEqual(runtime.chat.mock.calls[0][0]);
+ await click('Ask again'); expect(runtime.chat.mock.calls[1][0]).toEqual(runtime.chat.mock.calls[0][0]);
await render({ ...props, ...callbacks, pendingContext }); await type('Follow up'); await click('Send ↑');
expect(runtime.chat.mock.calls[2][0].at(-1)!.content).toBe('Answer in English.\n\nFollow up'); expect(callbacks.onContextConsumed).toHaveBeenCalledOnce();
});
@@ -1051,9 +1051,11 @@ describe('graph answers and answer limits', () => {
expect(request.map(message => message.role)).toEqual(['system', 'user']);
expect(request[1].content).toContain('Who calls JSONBAgg?');
expect(request[1].content).toContain('Incoming relationships: 23 from 12 symbols.');
- expect(container.querySelectorAll('.cbm-chat-turn')).toHaveLength(1);
- expect(container.querySelector('.cbm-chat-answer-text')?.textContent).toBe('Adds the two values.');
- expect(button('Retry')).toBeDefined();
+ // The listed answer stays; the model's answer is a turn of its own below it (B1).
+ expect(container.querySelectorAll('.cbm-chat-turn')).toHaveLength(2);
+ expect(container.querySelector('.cbm-chat-answer-text')?.textContent).toContain('not generated by the model');
+ expect([...container.querySelectorAll('.cbm-chat-answer-text')].at(-1)?.textContent).toBe('Adds the two values.');
+ expect(button('Ask again')).toBeDefined();
});
// 40 callers with long names in their own files: the snapshot names 24, a default prompt fewer.
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsx
index 3b10ff2a0..a38594c23 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx
@@ -10,7 +10,7 @@ import { AUTO_INPUT_TOKENS, AUTO_OUTPUT_TOKENS, citedInterpretation, explanation
import { carriedSource, selectionSubject, SYMBOL_SOURCE_LINES, sourceTargetOf, symbolSource, type SymbolSourceReader } from './symbol-source';
import { relationshipAnswer, relationshipSuggestion } from './relationship-answer';
import { clampTokenLimits, tokenLimitBounds, tokenLimitsFor, useAgentPreferences, type TokenLimits } from './agent-preferences';
-import { browserChatText, groundedText, relationshipWords } from './strings';
+import { browserChatText, chatRound3Text, groundedText, relationshipWords } from './strings';
import { isGpuRuntimeFailure, BrowserRuntimeFatalError } from './runtime-fault';
import ChatMarkdown from './ChatMarkdown';
import AgentSettingsDialog from './AgentSettingsDialog';
@@ -56,7 +56,9 @@ type ChatTurn = BrowserChatTurn & { evidence?: PreparedExplanationContext };
/** `grounded`: the facts are listed in the card, so the prompt's name budget is not the reader's limit. */
type Explanation = { key: string; label: string; answer: string; status: string; error?: string; packet?: PreparedExplanationContext; citation?: ReturnType<typeof citedInterpretation>; mode?: 'interpretation'; shortened?: boolean; limit?: TokenLimits; evidence?: string; grounded?: boolean;
/** The facts of a configuration or text file, which the model was not asked about (K12). */
- askable?: boolean };
+ askable?: boolean;
+ /** The answer is the model's text alone, without listed facts: it says so (B1). */
+ generated?: 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')!;
@@ -444,7 +446,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
...shortened && checked.sentence ? { shortened, limit: { inputTokens: autoInput, outputTokens: autoOutput } } : {}, ...snapshot.evidence ? { evidence: snapshot.evidence } : {} };
remember(complete); setExplanation(complete);
} else if (result.status === 'generated') {
- const complete: Explanation = { key: snapshot.key, label: snapshot.label, answer: checked.sentence ?? result.markdown, status: 'complete', mode: 'interpretation', packet, citation: result.citation,
+ const complete: Explanation = { key: snapshot.key, label: snapshot.label, answer: checked.sentence ?? result.markdown, status: 'complete', mode: 'interpretation', packet, citation: result.citation, generated: true,
...shortened ? { shortened, limit: { inputTokens: autoInput, outputTokens: autoOutput } } : {}, ...snapshot.evidence ? { evidence: snapshot.evidence } : {} };
remember(complete); setExplanation(complete);
} else setExplanation({ key: snapshot.key, label: snapshot.label, answer: '', status: 'error', packet, error: result.reason });
@@ -727,16 +729,19 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
setError(`This prompt needs ${count.toLocaleString()} input tokens; the local working limit is ${limit.toLocaleString()}. Select less code or start a new conversation. Nothing was sent or shortened without disclosure.`);
return;
}
- const id = retry?.id ?? `local-turn-${crypto.randomUUID()}`;
+ // The model's answer to a listed, grounded or file answer is a turn of its own below it:
+ // the facts stay where they were (B1). Asking again repeats a model answer in place.
+ const id = retry && !ask ? retry.id : `local-turn-${crypto.randomUUID()}`;
const historyOmitted = retry && !ask ? retry.historyOmitted
: earlier.filter(item => item.status !== 'error' && item.status !== 'generating' && !history.includes(item)).length;
// A general question shows its facts at once; the model only adds a sentence.
const writing = grounded ? `${grounded.summary.map(line => `- ${line}`).join('\n')}\n\n_${groundedText[language].writingSentence}_` : '';
const turn: ChatTurn = { id, prompt, attachment: source, readerContext: reader, context: extra, evidence: packet, modelId: model.id, request, answer: writing, status: 'generating', topic,
- ...historyOmitted ? { historyOmitted } : {}, ...grounded ? { answeredFrom: 'grounded' as const, listedFrom: grounded.graph, replyLanguage: language } : {} };
+ ...historyOmitted ? { historyOmitted } : {}, ...grounded ? { answeredFrom: 'grounded' as const, listedFrom: grounded.graph, replyLanguage: language } : {},
+ ...ask || retry?.askedModel ? { askedModel: true } : {} };
activeTurn.current = id;
- if (retry) setTurns(previous => previous.map(item => item.id === id ? turn : item));
- else { setTurns(previous => [...previous, turn]); consume(); }
+ if (retry && !ask) setTurns(previous => previous.map(item => item.id === id ? turn : item));
+ else { setTurns(previous => [...previous, turn]); if (!retry) consume(); }
setPhase('generating');
let shortened = false;
const onComplete = ({ stopReason }: { stopReason: string }) => { shortened = stopReason === 'length'; };
@@ -862,6 +867,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
</SourceDisclosure>
{explanation?.key === selected.key ? <>
<ChatMarkdown text={explanation.answer || (explanation.status === 'generating' ? 'Explaining selection…' : explanation.status === 'stopped' ? 'Explanation stopped.' : '')} />
+ {explanation.generated && explanation.status === 'complete' && <small className="cbm-chat-model-note">{chatRound3Text.en.modelNote}</small>}
{explanation.status !== 'generating' && <AnswerNotes shortened={limitNote(explanation.shortened, explanation.limit, true)} packet={explanation.grounded ? undefined : 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' || !!selected.waiting} onClick={() => {
@@ -872,10 +878,14 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
: 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) => { const replyWords = relationshipWords[turn.replyLanguage === 'de' ? 'de' : 'en']; return <article className="cbm-chat-turn" key={turn.id}>
+ {turns.map((turn, index) => { const replyWords = relationshipWords[turn.replyLanguage === 'de' ? 'de' : 'en'];
+ // The model's own answers carry their note in the language of the question (B1).
+ const ownWords = chatRound3Text[turn.replyLanguage ?? questionLanguage(turn.prompt)];
+ return <article className="cbm-chat-turn" key={turn.id}>
{turn.topic && index > 0 && turn.topic.key !== turns.slice(0, index).reverse().find(item => item.topic)?.topic?.key
&& <p className="cbm-chat-topic-break">{browserChatText.topicBreak(turn.topic.label)}</p>}
- <div className="cbm-chat-question"><span className="cbm-chat-speaker">You</span><ChatMarkdown text={turn.prompt} /></div>
+ <div className="cbm-chat-question"><span className="cbm-chat-speaker">You</span><ChatMarkdown text={turn.prompt} />
+ {turn.askedModel && <small className="cbm-chat-asked-model">{ownWords.askedModel}</small>}</div>
<div className="cbm-chat-answer"><SourceDisclosure>
{turn.evidence || turn.attachment || turn.readerContext?.source || turn.context?.length ? <>
{turn.evidence ? <PacketSource packet={turn.evidence} /> : <>
@@ -886,12 +896,13 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
</> : null}
</SourceDisclosure><div className="cbm-chat-answer-text"><ChatMarkdown text={turn.answer || (turn.status === 'generating' ? 'Thinking…' : turn.status === 'stopped' ? 'Stopped before an answer.' : '')} /></div>
{turn.status === 'stopped' && turn.answer && <small>Stopped · partial answer</small>}
+ {!turn.answeredFrom && turn.answer && (turn.status === 'complete' || turn.status === 'stopped') && <small className="cbm-chat-model-note">{ownWords.modelNote}</small>}
{turn.status !== 'generating' && !turn.answeredFrom && <AnswerNotes shortened={limitNote(turn.shortened, turn.limit)} packet={turn.evidence}
unsupported={turn.answer ? namesNotIn(turn.answer, turn.request.map(message => message.content).join('\n')) : []} model={BROWSER_MODELS.find(candidate => candidate.id === turn.modelId)?.displayName ?? turn.modelId} historyOmitted={turn.historyOmitted} />}
{turn.status === 'error' && <p className="cbm-chat-turn-error" role="alert">{turn.error}</p>}
{index === turns.length - 1 && turn.answeredFrom === 'suggestion' && turn.suggestion && <button type="button" className="cbm-chat-retry"
onClick={() => showSuggestedList(turn)}>{replyWords.showList}</button>}
- {index === turns.length - 1 && turn.status !== 'generating' && turn.answeredFrom !== 'local' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready'} onClick={() => { void send(turn); }}>{turn.answeredFrom ? replyWords.askModel : 'Retry'}</button>}
+ {index === turns.length - 1 && turn.status !== 'generating' && turn.answeredFrom !== 'local' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready'} onClick={() => { void send(turn); }}>{turn.answeredFrom ? replyWords.askModel : turn.status === 'error' ? 'Retry' : ownWords.askAgain}</button>}
</div>
</article>; })}
</div>}
diff --git a/graph-ui/src/browser-ai/browser-chat.css b/graph-ui/src/browser-ai/browser-chat.css
index 1621b2bd3..3e7ce0b7c 100644
--- a/graph-ui/src/browser-ai/browser-chat.css
+++ b/graph-ui/src/browser-ai/browser-chat.css
@@ -128,3 +128,6 @@
.cbm-chat-dock .cbm-chat-new { padding: 4px 9px; font-size: 11px; color: #d0e8d8; }
.cbm-chat-topic-break { display: flex; align-items: center; gap: 8px; margin: 0 0 10px !important; color: var(--chat-muted); font-size: 10px; }
.cbm-chat-topic-break::before, .cbm-chat-topic-break::after { content: ""; flex: 1 1 16px; border-top: 1px solid var(--chat-border); }
+/* Who wrote an answer reads like the note under a listed answer: quiet, not a warning. */
+.cbm-chat-dock .cbm-chat-model-note { display: block; margin-top: 7px; color: var(--chat-muted); font-size: 11px; font-style: italic; }
+.cbm-chat-dock .cbm-chat-asked-model { display: block; margin-top: 6px; color: var(--chat-muted); font-size: 10px; }
diff --git a/graph-ui/src/browser-ai/chat-dock.fixture.tsx b/graph-ui/src/browser-ai/chat-dock.fixture.tsx
new file mode 100644
index 000000000..842a6a78a
--- /dev/null
+++ b/graph-ui/src/browser-ai/chat-dock.fixture.tsx
@@ -0,0 +1,80 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, expect, 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 type { SymbolSnippet } from './symbol-source';
+
+/** The chat dock in jsdom with a fake model, for tests that drive it like a reader:
+ * type, send, click the buttons under an answer and read what the model was sent. */
+
+/** JSONBAgg as get_code_snippet returns it from django-demo. */
+export const JSONB_AGG_SNIPPET: SymbolSnippet = { source: 'class JSONBAgg(OrderableAggMixin, Aggregate):\n function = "JSONB_AGG"\n'
+ + ' template = "%(function)s(%(distinct)s%(expressions)s %(order_by)s)"\n allow_distinct = True\n output_field = JSONField()\n',
+file_path: '/abs/django/contrib/postgres/aggregates/general.py', start_line: 50, end_line: 54, source_mode: 'full' };
+
+/** An open file or marked code in Explore. */
+export const readerOf = (text: string, path: string, kind: 'file' | 'selection' = 'file', lines?: { start: number; end: number }): BrowserChatReaderContext => {
+ const count = text.split('\n').length;
+ return { project: 'sample', path, status: 'ready', source: { id: `reader-${path}-${kind}`, text, path, kind, project: 'sample', startLine: lines?.start ?? 1, startColumn: 1,
+ endLine: lines?.end ?? count, endColumn: 1, sourceVersion: 'sha256:1' } };
+};
+
+export function dockHarness() {
+ let container: HTMLDivElement;
+ let root: Root;
+ let props: BrowserChatDockProps;
+ 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(); });
+
+ 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(),
+ });
+ /** A dock with a fake model that is loaded at once; `readSource` returns JSONBAgg. */
+ const setup = () => {
+ const model = runtime();
+ const readSource = vi.fn(async () => JSONB_AGG_SNIPPET);
+ const base: BrowserChatDockProps = { proactive: false, open: true, onClose: vi.fn(), onAttachmentConsumed: vi.fn(), onAttachmentRemoved: vi.fn(),
+ createRuntime: vi.fn(() => model), removeCache: vi.fn(async () => {}), readSource };
+ return { runtime: model, props: base, readSource };
+ };
+ const render = async (next: BrowserChatDockProps) => { props = next; await act(async () => root.render(<BrowserChatDock {...next} />)); };
+ const button = (label: string, scope: ParentNode = document.body) => {
+ const found = [...scope.querySelectorAll('button')].find(item => item.textContent === label || item.getAttribute('aria-label') === label);
+ expect(found, `button ${label}`).toBeDefined();
+ return found!;
+ };
+ const click = async (label: string, scope?: ParentNode) => { await act(async () => button(label, scope).click()); };
+ /** Opens the agent configuration and loads the fake model. */
+ const load = async () => {
+ await render({ ...props, settingsRequest: (props.settingsRequest ?? 0) + 1 });
+ await click('Download & load');
+ };
+ const type = async (value: string) => {
+ const input = container.querySelector('textarea')!;
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ };
+ const ask = async (question: string) => { await type(question); await click('Send ↑'); };
+ const turns = () => [...container.querySelectorAll('.cbm-chat-turn')];
+ const last = () => turns().at(-1)!;
+ const answerOf = (turn: Element) => turn.querySelector('.cbm-chat-answer-text')?.textContent ?? '';
+ const buttonsOf = (turn: Element) => [...turn.querySelectorAll('button.cbm-chat-retry')].map(item => item.textContent);
+ const notesOf = (turn: Element) => [...turn.querySelectorAll('.cbm-chat-answer-note, .cbm-chat-model-note')].map(item => item.textContent ?? '');
+ const dividers = () => [...container.querySelectorAll('.cbm-chat-topic-break')].map(item => item.textContent);
+ const card = () => container.querySelector('[aria-label="Current selection explanation"]');
+ /** The user messages of a request, each by its last line (the question). */
+ const questionsIn = (request: readonly BrowserChatMessage[]) => request.filter(message => message.role === 'user').map(message => message.content.split('\n').at(-1));
+ return { setup, render, load, click, button, type, ask, turns, last, answerOf, buttonsOf, notesOf, dividers, card, questionsIn, container: () => container };
+}
diff --git a/graph-ui/src/browser-ai/chat-model.ts b/graph-ui/src/browser-ai/chat-model.ts
index a2b36e4c5..ed5592e24 100644
--- a/graph-ui/src/browser-ai/chat-model.ts
+++ b/graph-ui/src/browser-ai/chat-model.ts
@@ -61,6 +61,9 @@ export interface BrowserChatTurn {
historyOmitted?: number;
/** What the question was about; undefined for a question without context. */
topic?: ChatTopic;
+ /** The model's answer to a question the chat had answered itself ("Ask the model"). It
+ * stands below that answer instead of replacing it: the listed facts stay (B1). */
+ askedModel?: boolean;
}
export interface BrowserChatContext {
diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.ts
index 96f287a49..b389df598 100644
--- a/graph-ui/src/browser-ai/strings.ts
+++ b/graph-ui/src/browser-ai/strings.ts
@@ -381,3 +381,22 @@ export const fileWords = {
patterns: (total: number, items: readonly string[]) => `${counted(total, 'pattern', 'patterns')}: ${listed(items, total)}.`,
root: (name: string) => `Root element: ${name}.`,
};
+
+/** Third hand test round (B1 to B7): the chat's own words for an answer handed to the model,
+ * a topic the reader comes back to, a follow-up without context, facts read from code and the
+ * purpose of well-known files. New strings only; the ones above keep their own wording. */
+const englishRound3Text = {
+ /** Under the question of a turn asked of the model from an answer the chat gave itself (B1). */
+ askedModel: 'Asked the local model',
+ /** Under every answer the model wrote freely (B1). */
+ modelNote: 'Generated by the local model; it can be wrong.',
+ askAgain: 'Ask again',
+};
+export const chatRound3Text: { en: typeof englishRound3Text; de: typeof englishRound3Text } = {
+ en: englishRound3Text,
+ de: {
+ askedModel: 'An das lokale Modell gestellt',
+ modelNote: 'Vom lokalen Modell erzeugt; kann falsch sein.',
+ askAgain: 'Erneut fragen',
+ },
+};