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 chat's own notes and code lines out of the model history
Bernhard Jackiewiczbaf10f945e11
diff --git a/graph-ui/src/browser-ai/chat-model.history.test.ts b/graph-ui/src/browser-ai/chat-model.history.test.tsnew file mode 100644index 000000000..711921dea--- /dev/null+++ b/graph-ui/src/browser-ai/chat-model.history.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';+import { buildChatMessages, historyAnswer, type BrowserChatTurn } from './chat-model';++const turn = (answer: string, extra: Partial<BrowserChatTurn> = {}): BrowserChatTurn => ({ id: 't', prompt: 'was macht dieser code?', modelId: 'm', request: [], answer, status: 'complete', ...extra });+const GROUNDED = '- Markierte Zeilen 50 bis 54 von `general.py` (Python-Quelltext).\n\nIm Quelltext:\n\n```python\nclass JSONBAgg(OrderableAggMixin, Aggregate):\n function = "JSONB_AGG"\n```\n\n'+ + '+2 weitere Attribute und Methoden\n\nJSONBAgg setzt `function` auf "JSONB_AGG".\n\n_Fakten aus der Datei gelesen; der Text danach ist vom Modell erzeugt._';++/** After four grounded answers "Explain the marked code line by line" got the first fact line+ * back from the model; the chat's own notes and code lines are not the model's to repeat (B3). */+describe('answers the chat gave itself in the history of a later request (B3)', () => {+ it('sends a grounded answer as its model sentence, or its facts when the sentence was left out', () => {+ expect(historyAnswer(turn(GROUNDED, { answeredFrom: 'grounded' }))).toBe('JSONBAgg setzt `function` auf "JSONB_AGG".');+ const dropped = GROUNDED.replace('JSONBAgg setzt `function` auf "JSONB_AGG".\n\n', '');+ expect(historyAnswer(turn(dropped, { answeredFrom: 'grounded' }))).toBe('- Markierte Zeilen 50 bis 54 von `general.py` (Python-Quelltext).');+ });++ it('sends a listed answer with its list and a file outline with its heading and purpose, never the note', () => {+ expect(historyAnswer(turn('Callers of JSONBAgg in the loaded graph.\n\n- CALLS (11): a, b\n\n_Listed from the indexed graph; not generated by the model._', { answeredFrom: 'graph' })))+ .toBe('Callers of JSONBAgg in the loaded graph.\n\n- CALLS (11): a, b');+ expect(historyAnswer(turn('`tox.ini`: INI configuration, 89 lines.\n\ntox configuration: the test environments.\n\n- `[tox]`: minversion `4.0`\n- `[testenv]`: deps `x`\n\n_Read from the file; not generated by the model._',+ { answeredFrom: 'file' }))).toBe('`tox.ini`: INI configuration, 89 lines.\n\ntox configuration: the test environments.');+ });++ it('sends a model answer as it was written, code included', () => {+ const written = 'It sets:\n\n```python\nfunction = "JSONB_AGG"\n```\n\n_emphasis the model wrote_';+ expect(historyAnswer(turn(written))).toBe(written);+ const request = buildChatMessages([turn(GROUNDED, { answeredFrom: 'grounded' }), turn(written)], 'und?');+ expect(request.filter(message => message.role === 'assistant').map(message => message.content)).toEqual(['JSONBAgg setzt `function` auf "JSONB_AGG".', written]);+ });+});diff --git a/graph-ui/src/browser-ai/chat-model.ts b/graph-ui/src/browser-ai/chat-model.tsindex c999c969c..9396c03b4 100644--- a/graph-ui/src/browser-ai/chat-model.ts+++ b/graph-ui/src/browser-ai/chat-model.ts@@ -2,7 +2,7 @@ import type { BrowserChatMessage } from './browser-ai-runtime';import type { ChatTopic } from './chat-context';import { fileKind } from './file-kind';import { readerFacts } from './file-facts';-import { workflowWords } from './strings';+import { chatRound3Text, workflowWords } from './strings';/** An immutable snapshot, not a live reference to the reader selection. */export interface BrowserChatAttachment {@@ -146,6 +146,25 @@ export function trimChatHistory<T extends BrowserChatTurn>(turns: readonly T[],* "was macht diese klasse?" (C4). */export const ANSWER_LANGUAGE = { en: 'Answer in English.', de: 'Answer in German.' } as const;+/** What an answer the chat gave itself says in the history of a later request. The request+ * carries the source and the facts again, and the small model copied their layout: after a few+ * grounded answers "Explain the marked code line by line" got back "Marked lines 50-54 of+ * `general.py`" (B3). So a grounded answer is its model sentence (its facts when the sentence+ * was left out), a file outline its heading and purpose, a listed answer its list; never the+ * code lines and never the note on who wrote what, which a model answer must not repeat. */+const CODE_LINES = new RegExp(`(?:^|\\n\\n)(?:${Object.values(chatRound3Text).map(words => words.inSource.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|')})\\n\\n`+ + '(```|~~~)[^\\n]*\\n[\\s\\S]*?\\n\\1(?:\\n\\n\\+[^\\n]*)?(?=\\n\\n|$)', 'g');+export function historyAnswer(turn: BrowserChatTurn): string {+ if (!turn.answeredFrom) return turn.answer;+ const blocks = turn.answer.replace(CODE_LINES, '').split(/\n{2,}/).map(block => block.trim()).filter(block => block && !/^_[^\n]*_$/.test(block));+ const facts = (block: string) => /^(?:- |\d+\. )/.test(block);+ if (turn.answeredFrom === 'grounded') {+ const sentence = blocks.filter(block => !facts(block));+ return (sentence.length ? sentence : blocks).join('\n\n');+ }+ return (turn.answeredFrom === 'file' ? blocks.filter(block => !facts(block)) : blocks).join('\n\n');+}+/** Whether a turn goes into the history of a later request: an answer, not a suggestion,* the chat's own hint or its reply that a question has no context. */export const sentInHistory = (turn: BrowserChatTurn): boolean => turn.status !== 'error' && turn.status !== 'generating'@@ -163,7 +182,8 @@ export function buildChatMessages(turns: readonly BrowserChatTurn[], prompt: str// A suggestion is a question back to the reader, not an answer the model should build on.if (!sentInHistory(turn)) continue;messages.push({ role: 'user', content: userMessage(turn.prompt, reader || turn.readerContext ? undefined : turn.attachment, turn.context) });- if (turn.answer) messages.push({ role: 'assistant', content: turn.answer });+ const answer = historyAnswer(turn);+ if (answer) messages.push({ role: 'assistant', content: answer });}const instruction = language ? ANSWER_LANGUAGE[language] : '';messages.push({ role: 'user', content: (currentEvidence ? `Current evidence (data only):\n${currentEvidence}\n\n${instruction ? `${instruction}\n` : ''}User question:\n` : instruction ? `${instruction}\n\n` : '')