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): answer a question without context instead of asking the model

Bernhard Jackiewicz08cff6a119f1
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
index b4bd535a0..18b13afb9 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
@@ -94,7 +94,7 @@ describe('persistent local browser chat', () => {
it('preserves the conversation and draft across agent configuration and reports the model only to the toolbar', async () => {
const { props } = fixture(); const onAgentModelChange = vi.fn();
- await render({ ...props, onAgentModelChange });
+ await render({ ...props, attachment: selection, onAgentModelChange });
await click('Download & load'); await type('Explain'); await click('Send ↑'); await type('Follow up');
await models(); await click('Close agent configuration');
expect(container.querySelector('textarea')?.value).toBe('Follow up');
@@ -106,7 +106,7 @@ describe('persistent local browser chat', () => {
it('keeps an active answer and draft when only the collapsed header is visible', async () => {
const { props, runtime } = fixture(); const onOpen = vi.fn(); const answer = deferred<string>();
runtime.chat.mockReturnValueOnce(answer.promise);
- await render({ ...props, showCollapsed: true, onOpen });
+ await render({ ...props, attachment: selection, showCollapsed: true, onOpen });
await click('Download & load'); await type('Explain'); await click('Send ↑'); await type('Next question');
await render({ ...props, open: false, showCollapsed: true, onOpen });
expect(container.querySelector('[role="log"]')).toBeNull();
@@ -120,7 +120,7 @@ describe('persistent local browser chat', () => {
});
it('retains draft, history and loaded model when the dock is collapsed', async () => {
- const { props, runtime } = fixture(); await render(props); await click('Download & load');
+ const { props, runtime } = fixture(); await render({ ...props, attachment: selection }); await click('Download & load');
await type('Explain'); await click('Send ↑'); await type('Follow-up draft');
await click('Collapse local chat'); expect(props.onClose).toHaveBeenCalledOnce();
await render({ ...props, open: false });
@@ -182,7 +182,7 @@ describe('persistent local browser chat', () => {
const { props, runtime } = fixture();
const answer = deferred<string>(); let stream!: (chunk: string) => void;
runtime.chat.mockImplementationOnce((_messages, onToken) => { stream = onToken; return answer.promise; });
- await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑');
+ await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑');
await act(async () => stream('First part.')); await click('Stop');
expect(runtime.stop).toHaveBeenCalledOnce(); expect(button('Stopping…').disabled).toBe(true);
await type('Next question');
@@ -214,7 +214,7 @@ describe('persistent local browser chat', () => {
});
it('unloads and deletes cached files separately while preserving the conversation', async () => {
- const { props, runtime } = fixture(); await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑');
+ const { props, runtime } = fixture(); await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑');
await models(); await click('Unload model');
expect(runtime.dispose).toHaveBeenCalledOnce(); expect(props.removeCache).not.toHaveBeenCalled();
expect(container.textContent).toContain('Adds the two values.');
@@ -224,7 +224,7 @@ describe('persistent local browser chat', () => {
});
it('changes models without automatic download or losing conversation', async () => {
- const { props, runtime } = fixture(); await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑'); await models();
+ const { props, runtime } = fixture(); await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑'); await models();
await act(async () => { const select = document.querySelector('#cbm-chat-model') as HTMLSelectElement; select.value = BROWSER_MODELS[1].id; select.dispatchEvent(new Event('change', { bubbles: true })); });
expect(runtime.dispose).toHaveBeenCalledOnce(); expect(props.createRuntime).toHaveBeenCalledOnce();
expect(container.textContent).toContain('Adds the two values.'); expect(button('Send ↑').disabled).toBe(true);
@@ -234,7 +234,7 @@ describe('persistent local browser chat', () => {
it('does not move scroll position while the reader is inspecting earlier output', async () => {
const { props, runtime } = fixture(); const answer = deferred<string>(); let stream!: (chunk: string) => void;
runtime.chat.mockImplementationOnce((_messages, onToken) => { stream = onToken; return answer.promise; });
- await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑');
+ await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑');
const log = container.querySelector('.cbm-chat-transcript') as HTMLDivElement;
Object.defineProperties(log, { scrollHeight: { configurable: true, value: 1000 }, clientHeight: { configurable: true, value: 200 } });
log.scrollTop = 100;
@@ -246,7 +246,7 @@ describe('persistent local browser chat', () => {
});
it('clears conversation only after explicit confirmation', async () => {
- const { props } = fixture(); await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑');
+ const { props } = fixture(); await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑');
const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true);
await click('New conversation'); expect(container.textContent).toContain('Adds the two values.');
await click('New conversation'); expect(container.textContent).not.toContain('Adds the two values.'); expect(confirm).toHaveBeenCalledTimes(2);
@@ -255,7 +255,7 @@ describe('persistent local browser chat', () => {
it('unloads an active worker and ignores stale output while retaining its sent question', async () => {
const { props, runtime } = fixture(); const answer = deferred<string>(); let stream!: (chunk: string) => void;
runtime.chat.mockImplementationOnce((_messages, onToken) => { stream = onToken; return answer.promise; });
- await render(props); await click('Download & load'); await type('Explain'); await click('Send ↑'); await models();
+ await render({ ...props, attachment: selection }); await click('Download & load'); await type('Explain'); await click('Send ↑'); await models();
await act(async () => stream('Partial answer')); await click('Unload model');
await act(async () => { stream('Ignored stale chunk'); answer.resolve('Ignored stale final'); });
expect(runtime.dispose).toHaveBeenCalledOnce(); expect(container.textContent).toContain('Partial answer');
@@ -266,17 +266,18 @@ describe('persistent local browser chat', () => {
it('includes graph evidence only after explicit choice, freezes it, and clears it after send', async () => {
const { props, runtime } = fixture(); const evidence = { id: 'callers-1', label: 'Known callers', text: 'entry → sum' };
await render({ ...props, context: [evidence] }); await click('Download & load'); await type('First question'); await click('Send ↑');
- expect(runtime.chat.mock.calls[0][0].at(-1)?.content).toBe('First question');
+ // Offered but not chosen: the question has no context and the model is not asked.
+ expect(runtime.chat).not.toHaveBeenCalled();
await act(async () => (container.querySelector('input[type=checkbox]') as HTMLInputElement).click());
evidence.text = 'changed graph';
await render({ ...props, context: [] });
expect(container.querySelector('.cbm-chat-pending pre')?.textContent).toBe('entry → sum');
await type('Second question'); await click('Send ↑');
- expect(runtime.chat.mock.calls[1][0].at(-1)?.content).toContain('entry → sum');
- expect(runtime.chat.mock.calls[1][0].at(-1)?.content).not.toContain('changed graph');
+ expect(runtime.chat.mock.calls[0][0].at(-1)?.content).toContain('entry → sum');
+ 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[2][0]).toEqual(runtime.chat.mock.calls[1][0]);
+ await click('Retry'); 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 () => {
@@ -304,7 +305,9 @@ describe('persistent local browser chat', () => {
const { props, runtime } = fixture(); const pendingContext = { id: 'galaxy-1', label: 'Graph node main', text: 'Selected node facts' }; const onContextConsumed = vi.fn(); const onContextRemoved = vi.fn();
await render({ ...props, pendingContext, onContextConsumed, onContextRemoved }); await click('Remove graph selection');
expect(onContextRemoved).toHaveBeenCalledExactlyOnceWith('galaxy-1'); expect(onContextConsumed).not.toHaveBeenCalled();
- await click('Download & load'); await type('Question'); await click('Send ↑'); expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toBe('Question');
+ await click('Download & load'); await type('Question'); await click('Send ↑');
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(container.querySelector('.cbm-chat-answer-text')?.textContent).toContain('Nothing is selected for me to explain yet.');
});
it('keeps a newer graph selection when an earlier send finishes checking context', async () => {
@@ -368,7 +371,8 @@ describe('persistent local browser chat', () => {
expect(props.onAttachmentConsumed).not.toHaveBeenCalled();
expect(container.querySelectorAll('.cbm-chat-answer .cbm-chat-attachment')).toHaveLength(3);
await render(props); await type('Ask from another workspace'); await click('Send ↑');
- expect(runtime.chat.mock.calls[3][0].map(message => message.content).join('\n')).not.toMatch(/WHOLE_FIRST_FILE|WHOLE_SECOND_FILE/);
+ expect(runtime.chat).toHaveBeenCalledTimes(3);
+ expect([...container.querySelectorAll('.cbm-chat-answer-text')].at(-1)?.textContent).not.toMatch(/WHOLE_FIRST_FILE|WHOLE_SECOND_FILE/);
});
it('uses the same frozen reader snapshot for counting and generation despite navigation or prop mutation', async () => {
@@ -414,9 +418,10 @@ describe('persistent local browser chat', () => {
expect(container.textContent).toContain('Loading current file');
await render({ ...props, attachment: selection, readerContext: { project: 'sample', path: 'new.ts', status: 'unavailable' } });
await click('Send ↑');
- expect(runtime.chat.mock.calls[0][0][0].content).toContain('"status":"unavailable"');
- expect(runtime.chat.mock.calls[0][0].map(message => message.content).join('\n')).not.toContain(selection.text);
- expect(runtime.chat.mock.calls[0][0].map(message => message.content).join('\n')).not.toMatch(/OLD_CODE|STALE_CODE/);
+ // No current source and no stale fallback: the model is not asked at all.
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(container.querySelector('.cbm-chat-answer-text')?.textContent).toContain('The source of new.ts is not available.');
+ expect(container.querySelector('.cbm-chat-transcript')?.textContent).not.toMatch(/OLD_CODE|STALE_CODE/);
await render({ ...props, readerContext: { project: 'sample', status: 'empty' } });
expect(container.querySelector('.cbm-chat-source-state')?.textContent).toContain('Open a file');
});
@@ -867,7 +872,7 @@ describe('live-browser regressions', () => {
it('invalidates a failed GPU runtime and reports error instead of active', async () => {
const { props, runtime } = fixture(); const onAgentStateChange = vi.fn();
runtime.chat.mockRejectedValueOnce(new Error("failed to call OrtRun(): GPUBuffer mapAsync invalid buffer"));
- await render({ ...props, onAgentStateChange }); await click('Download & load');
+ await render({ ...props, attachment: selection, onAgentStateChange }); await click('Download & load');
await type('Explain'); await click('Send ↑');
expect(runtime.dispose).toHaveBeenCalledOnce();
expect(onAgentStateChange).toHaveBeenLastCalledWith('error');
@@ -935,6 +940,29 @@ describe('graph answers and answer limits', () => {
expect(request.some(message => message.content.includes('Meintest du'))).toBe(false);
});
+ it('does not ask the model without any context and says what to select, in the language of the question (K11)', async () => {
+ const { props, runtime } = fixture();
+ await render(props); await click('Download & load');
+ const last = () => [...container.querySelectorAll('.cbm-chat-turn')].at(-1)!;
+ await type('was kansnt du mir über den code sagen'); await click('Send ↑');
+ expect(runtime.countTokens).not.toHaveBeenCalled();
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(last().querySelector('.cbm-chat-answer-text')?.textContent).toContain('Wähle einen Knoten in Galaxy oder einen Teil in Architecture, oder öffne eine Datei in Explore');
+ expect(last().textContent).toContain('Ohne das Modell beantwortet');
+ expect([...last().querySelectorAll('button')].some(item => item.textContent === 'Retry')).toBe(false);
+ await type('test'); await click('Send ↑');
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(last().querySelector('.cbm-chat-answer-text')?.textContent).toContain('Select a node in Galaxy or a part in Architecture, or open a file in Explore');
+ await render({ ...props, readerContext: { project: 'sample', status: 'empty' } });
+ await type('what is in this file?'); await click('Send ↑');
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(last().querySelector('.cbm-chat-answer-text')?.textContent).toContain('No file is open in Explore.');
+ await render({ ...props, proactiveSelection: jsonbAggEvidence() });
+ await type('What does this class do?'); await click('Send ↑');
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ expect(runtime.chat.mock.calls[0][0].some(message => /Wähle einen Knoten|Select a node in Galaxy/.test(message.content))).toBe(false);
+ });
+
it('hands a listed answer to the model on request, with its evidence and without the list as history', async () => {
const { props, runtime } = fixture();
await render({ ...props, proactiveSelection: jsonbAggEvidence() }); await click('Download & load');
@@ -1058,7 +1086,7 @@ describe('graph answers and answer limits', () => {
it('leaves the oldest history out when the input limit is exceeded and says so', async () => {
const { props, runtime } = fixture();
- await render(props); await click('Download & load');
+ await render({ ...props, readerContext: reader('const a = 1;') }); await click('Download & load');
for (const question of ['First question', 'Second question', 'Third question']) { await type(question); await click('Send ↑'); }
runtime.countTokens.mockImplementation(async messages => messages.length > 4 ? 5000 : 100);
await type('Fourth question'); await click('Send ↑');
@@ -1196,7 +1224,7 @@ describe('agent configuration limits', () => {
});
it('applies the limits to the manual chat budget and the output tokens it asks for', async () => {
- const { props, runtime } = fixture(); await render(props); await models();
+ const { props, runtime } = fixture(); await render({ ...props, attachment: selection }); await models();
await setLimit('cbm-chat-output-tokens', 128); await setLimit('cbm-chat-input-tokens', 1024);
await click('Download & load');
runtime.countTokens.mockResolvedValueOnce(1500);
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsx
index 5b1b132f7..ea11c7946 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx
@@ -13,6 +13,7 @@ import { isGpuRuntimeFailure, BrowserRuntimeFatalError } from './runtime-fault';
import ChatMarkdown from './ChatMarkdown';
import AgentSettingsDialog from './AgentSettingsDialog';
import { useChatHistory } from './use-chat-history';
+import { chatTopic, followedTopic, missingContextAnswer } from './chat-context';
import './browser-chat.css';
export type { BrowserChatAttachment, BrowserChatContext, BrowserChatReaderContext, BrowserChatSource } from './chat-model';
@@ -415,11 +416,21 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
if (source) onAttachmentConsumed(source.id);
if (selectedGraph) { setHandledContextId(selectedGraph.id); onContextConsumed?.(selectedGraph.id); }
};
+ // A question without its own context may follow up on attached code in this view.
+ const topic = retry ? retry.topic : chatTopic(selectionScope, { reader, graph: currentGraph[0], attachment: source, context: extra })
+ ?? followedTopic(turns, selectionScope);
+ // Without code or graph facts the model can only guess: say what to select instead.
+ if (!retry && !topic) {
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, modelId: model.id, request: [],
+ answer: missingContextAnswer(prompt, reader), status: 'complete', answeredFrom: 'local' }]);
+ consume();
+ return;
+ }
// Callers and callees of the selection come from the loaded graph, complete and
// 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,
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, context: extra, topic,
evidence: prepareExplanationContext(undefined, listed.context, chatEvidence), modelId: model.id, request: [],
answer: listed.markdown, status: 'complete', answeredFrom: 'graph' }]);
consume();
@@ -428,7 +439,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
// 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,
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, context: extra, topic,
evidence: prepareExplanationContext(undefined, suggested.context, chatEvidence), modelId: model.id, request: [],
answer: suggested.markdown, status: 'complete', answeredFrom: 'suggestion', suggestion: { question: suggested.question, context: suggested.context } }]);
consume();
@@ -477,7 +488,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
const id = 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;
- const turn: ChatTurn = { id, prompt, attachment: source, readerContext: reader, context: extra, evidence: packet, modelId: model.id, request, answer: '', status: 'generating',
+ const turn: ChatTurn = { id, prompt, attachment: source, readerContext: reader, context: extra, evidence: packet, modelId: model.id, request, answer: '', status: 'generating', topic,
...historyOmitted ? { historyOmitted } : {} };
activeTurn.current = id;
if (retry) setTurns(previous => previous.map(item => item.id === id ? turn : item));
@@ -619,7 +630,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
{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)}>{relationshipWords.en.showList}</button>}
- {index === turns.length - 1 && turn.status !== 'generating' && <button type="button" className="cbm-chat-retry" disabled={phase !== 'ready'} onClick={() => { void send(turn); }}>{turn.answeredFrom ? browserChatText.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 ? browserChatText.askModel : 'Retry'}</button>}
</div>
</article>)}
</div>}
diff --git a/graph-ui/src/browser-ai/chat-context.test.ts b/graph-ui/src/browser-ai/chat-context.test.ts
new file mode 100644
index 000000000..2b98d795b
--- /dev/null
+++ b/graph-ui/src/browser-ai/chat-context.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { chatTopic, followedTopic, missingContextAnswer, questionLanguage } from './chat-context';
+import type { BrowserChatTurn } from './chat-model';
+import { jsonbAggEvidence } from './galaxy-evidence.fixture';
+
+const attachment = { id: 'a', text: 'x', path: 'src/sum.ts', project: 'p', startLine: 1, startColumn: 1, endLine: 1, endColumn: 2, sourceVersion: 'v' };
+const turn = (topic: BrowserChatTurn['topic'], extra: Partial<BrowserChatTurn> = {}): BrowserChatTurn =>
+ ({ id: String(Math.random()), prompt: 'q', modelId: 'm', request: [], answer: 'a', status: 'complete', topic, ...extra });
+
+describe('questions without context (K11)', () => {
+ it.each([
+ ['was kansnt du mir über den code sagen', 'de'], ['was macht das', 'de'], ['Erklär mir die Datei', 'de'],
+ ['test', 'en'], ['What does this do?', 'en'], ['explain the code', 'en'], ['Why was this added?', 'en'],
+ ] as const)('answers %s in %s', (prompt, language) => {
+ expect(questionLanguage(prompt)).toBe(language);
+ });
+
+ it('names what is missing and how to give context, without blaming the model', () => {
+ expect(missingContextAnswer('was kannst du mir über den code sagen')).toMatch(/^Es ist noch nichts ausgewählt.*Wähle einen Knoten in Galaxy.*öffne eine Datei in Explore/);
+ expect(missingContextAnswer('test')).toMatch(/^Nothing is selected for me to explain yet\. Select a node in Galaxy/);
+ expect(missingContextAnswer('what is this?', { project: 'p', status: 'empty' })).toMatch(/^No file is open in Explore\./);
+ expect(missingContextAnswer('what is this?', { project: 'p', path: 'a.yml', status: 'unavailable' })).toMatch(/^The source of `a\.yml` is not available\./);
+ expect(missingContextAnswer('test')).toContain('_Answered without the model');
+ });
+});
+
+describe('what a question is about', () => {
+ it('keys a Galaxy selection by the selected item, not by how its scope is drawn', () => {
+ const one = chatTopic('django-demo:galaxy', { graph: jsonbAggEvidence() });
+ const deeper = chatTopic('django-demo:galaxy', { graph: jsonbAggEvidence({ depth: 2, direction: 'inbound' }) });
+ expect(one).toEqual(deeper);
+ expect(one).toMatchObject({ kind: 'graph', label: 'JSONBAgg' });
+ expect(chatTopic('django-demo:architecture', { graph: jsonbAggEvidence() })?.key).not.toBe(one?.key);
+ });
+
+ it('prefers the open file, then the graph selection, then attached code and context', () => {
+ const reader = { project: 'p', path: 'a.yml', status: 'ready' as const, source: { ...attachment, path: 'a.yml', kind: 'file' as const } };
+ expect(chatTopic('p:explore', { reader, graph: jsonbAggEvidence(), attachment })?.kind).toBe('file');
+ expect(chatTopic('p:galaxy', { attachment, context: [{ id: 'c', label: 'Callers', text: 't' }] })?.kind).toBe('attachment');
+ expect(chatTopic('p:galaxy', { context: [{ id: 'c', label: 'Callers', text: 't' }] })).toMatchObject({ kind: 'context', label: 'Callers' });
+ expect(chatTopic('p:galaxy', {})).toBeUndefined();
+ expect(chatTopic('p:explore', { reader: { project: 'p', path: 'a.yml', status: 'unavailable' } })).toBeUndefined();
+ });
+
+ it('follows up on attached code in the same view, never on a selection that is gone', () => {
+ const attached = chatTopic('p:galaxy', { attachment })!;
+ const selected = chatTopic('p:galaxy', { graph: jsonbAggEvidence() })!;
+ expect(followedTopic([turn(attached)], 'p:galaxy')).toEqual(attached);
+ expect(followedTopic([turn(attached), turn(undefined, { answeredFrom: 'local' })], 'p:galaxy')).toEqual(attached);
+ expect(followedTopic([turn(attached)], 'p:explore')).toBeUndefined();
+ expect(followedTopic([turn(attached), turn(selected)], 'p:galaxy')).toBeUndefined();
+ expect(followedTopic([], 'p:galaxy')).toBeUndefined();
+ });
+});
diff --git a/graph-ui/src/browser-ai/chat-context.ts b/graph-ui/src/browser-ai/chat-context.ts
new file mode 100644
index 000000000..44b88b521
--- /dev/null
+++ b/graph-ui/src/browser-ai/chat-context.ts
@@ -0,0 +1,49 @@
+import type { BrowserChatAttachment, BrowserChatContext, BrowserChatReaderContext, BrowserChatTurn } from './chat-model';
+import { readGalaxyEvidence } from './galaxy-evidence';
+import { browserChatContextText } from './strings';
+
+/** What a question is about: the open file, the selected graph item, attached code or
+ * attached context, within one project and view. Turns about another one are another
+ * topic; their answers are not sent along (K17). */
+export interface ChatTopic { key: string; label: string; kind: 'file' | 'graph' | 'attachment' | 'context' }
+
+export function chatTopic(scope: string, sources: { reader?: BrowserChatReaderContext; graph?: BrowserChatContext; attachment?: BrowserChatAttachment;
+ context?: readonly BrowserChatContext[] }): ChatTopic | undefined {
+ const { reader, graph, attachment, context = [] } = sources;
+ if (reader?.source) return { kind: 'file', label: reader.source.path, key: JSON.stringify([scope, 'file', reader.source.path]) };
+ if (graph) {
+ // The selected item itself; depth, direction and edge types only redraw its scope.
+ const galaxy = readGalaxyEvidence(graph.text);
+ return { kind: 'graph', label: galaxy?.label ?? graph.label, key: JSON.stringify([scope, 'graph', galaxy ? galaxy.identity : graph.label]) };
+ }
+ if (attachment) return { kind: 'attachment', label: attachment.path, key: JSON.stringify([scope, 'attachment', attachment.path]) };
+ if (context.length) return { kind: 'context', label: context.map(item => item.label).join(', '), key: JSON.stringify([scope, 'context', ...context.map(item => item.id)]) };
+ return undefined;
+}
+
+/** A question without its own context follows up on explicitly attached code or context
+ * in the same view. A selection or file that is gone leaves nothing to follow up on. */
+export function followedTopic(turns: readonly BrowserChatTurn[], scope: string): ChatTopic | undefined {
+ for (let index = turns.length - 1; index >= 0; index--) {
+ const topic = turns[index].topic;
+ if (!topic || turns[index].answeredFrom === 'local') continue;
+ const [turnScope] = JSON.parse(topic.key) as [string];
+ return turnScope === scope && (topic.kind === 'attachment' || topic.kind === 'context') ? topic : undefined;
+ }
+ return undefined;
+}
+
+/** German when the question reads German; the chat's own replies follow the question.
+ * "was" and "die" are English words too and decide nothing on their own. */
+const GERMAN = /[äöüß]|\b(?:ich|du|der|das|und|ist|nicht|wie|wer|wo|warum|kannst|über|mir|mich|diese[rsnm]?|datei|sagen|erkl\w*|zeig\w*|welche\w*|gibt|wird|macht)\b/i;
+export function questionLanguage(prompt: string): 'en' | 'de' {
+ return GERMAN.test(prompt) ? 'de' : 'en';
+}
+
+/** Said instead of asking the model when a question has nothing to stand on: no
+ * selection, no open file, no attached code (K11). */
+export function missingContextAnswer(prompt: string, reader?: BrowserChatReaderContext): string {
+ const text = browserChatContextText[questionLanguage(prompt)];
+ const reason = !reader ? text.nothingSelected : reader.status === 'empty' || !reader.path ? text.noFileOpen : text.sourceUnavailable(reader.path);
+ return `${reason}\n\n_${text.notAsked}_`;
+}
diff --git a/graph-ui/src/browser-ai/chat-model.ts b/graph-ui/src/browser-ai/chat-model.ts
index b7160d380..ea2e0ef4f 100644
--- a/graph-ui/src/browser-ai/chat-model.ts
+++ b/graph-ui/src/browser-ai/chat-model.ts
@@ -1,4 +1,5 @@
import type { BrowserChatMessage } from './browser-ai-runtime';
+import type { ChatTopic } from './chat-context';
/** An immutable snapshot, not a live reference to the reader selection. */
export interface BrowserChatAttachment {
@@ -41,12 +42,15 @@ export interface BrowserChatTurn {
shortened?: boolean;
/** The limits that answer ran into. */
limit?: { inputTokens: number; outputTokens: number };
- /** Listed from the loaded graph without the model, or a suggestion to list it. */
- answeredFrom?: 'graph' | 'suggestion';
+ /** Listed from the loaded graph without the model, a suggestion to list it, or the chat's
+ * own reply that a question has no context to answer from. */
+ answeredFrom?: 'graph' | 'suggestion' | 'local';
/** The listed question a suggestion offers, with the graph evidence it lists from. */
suggestion?: { question: string; context: 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. */
+ topic?: ChatTopic;
}
export interface BrowserChatContext {
@@ -118,7 +122,7 @@ export function buildChatMessages(turns: readonly BrowserChatTurn[], prompt: str
+ JSON.stringify(currentContext.map(({ label, text }) => ({ label, text }))) + '\n--- END CURRENT GRAPH DATA ---' : '') }];
for (const turn of turns) {
// A suggestion is a question back to the reader, not an answer the model should build on.
- if (turn.status === 'error' || turn.status === 'generating' || turn.answeredFrom === 'suggestion') continue;
+ if (turn.status === 'error' || turn.status === 'generating' || turn.answeredFrom === 'suggestion' || turn.answeredFrom === 'local') 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 });
}
diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.ts
index ac0f1931b..7005fdc24 100644
--- a/graph-ui/src/browser-ai/strings.ts
+++ b/graph-ui/src/browser-ai/strings.ts
@@ -144,3 +144,19 @@ export const browserChatText = {
limitRange: (min: number, max: number) => `${min.toLocaleString('en-US')} to ${max.toLocaleString('en-US')} tokens`,
limitsNote: (input: number, output: number) => `Stored in this browser for each model. Automatic explanations use at most ${input.toLocaleString('en-US')} input and ${output.toLocaleString('en-US')} output tokens.`,
};
+
+/** The chat's own reply when a question has no code or graph context (K11), in the language of the question. */
+export const browserChatContextText = {
+ en: {
+ nothingSelected: 'Nothing is selected for me to explain yet. Select a node in Galaxy or a part in Architecture, or open a file in Explore, then ask again.',
+ noFileOpen: 'No file is open in Explore. Open a file, or mark code in it, then ask again.',
+ sourceUnavailable: (path: string) => `The source of \`${path.replace(/`/g, "'")}\` is not available. Open the file again or choose another one, then ask again.`,
+ notAsked: 'Answered without the model: without code or graph facts it could only guess.',
+ },
+ de: {
+ nothingSelected: 'Es ist noch nichts ausgewählt, das ich erklären könnte. Wähle einen Knoten in Galaxy oder einen Teil in Architecture, oder öffne eine Datei in Explore, und frage dann noch einmal.',
+ noFileOpen: 'In Explore ist keine Datei geöffnet. Öffne eine Datei oder markiere Code darin und frage dann noch einmal.',
+ sourceUnavailable: (path: string) => `Der Quelltext von \`${path.replace(/`/g, "'")}\` ist nicht verfügbar. Öffne die Datei noch einmal oder wähle eine andere und frage dann noch einmal.`,
+ notAsked: 'Ohne das Modell beantwortet: ohne Code oder Graph-Fakten könnte es nur raten.',
+ },
+};