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 general questions, empty prompts and file questions without guessing (C5, C6, C7)

Bernhard Jackiewicz1d861f6e6404
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
index cb6993757..a87cee2e7 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.test.tsx
@@ -317,11 +317,11 @@ describe('persistent local browser chat', () => {
it('keeps a newer graph selection when an earlier send finishes checking context', async () => {
const { props, runtime } = fixture(); const count = deferred<number>(); runtime.countTokens.mockReturnValueOnce(count.promise);
const oldContext = { id: 'old', label: 'Old selection', text: 'Old graph facts' }; const newContext = { id: 'new', label: 'New selection', text: 'New graph facts' }; const onContextConsumed = vi.fn();
- await render({ ...props, pendingContext: oldContext, onContextConsumed }); await click('Download & load'); await type('First'); await click('Send ↑');
+ await render({ ...props, pendingContext: oldContext, onContextConsumed }); await click('Download & load'); await type('What does the old selection show?'); await click('Send ↑');
await render({ ...props, pendingContext: newContext, onContextConsumed }); await act(async () => count.resolve(100));
expect(onContextConsumed).toHaveBeenCalledExactlyOnceWith('old');
expect(container.querySelector('.cbm-chat-pending pre')?.textContent).toBe('New graph facts');
- await type('Second'); await click('Send ↑');
+ await type('And the new one?'); await click('Send ↑');
expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toContain('Old graph facts');
expect(runtime.chat.mock.calls[1][0].at(-1)!.content).toContain('New graph facts');
expect(onContextConsumed.mock.calls).toEqual([['old'], ['new']]);
@@ -565,14 +565,14 @@ describe('proactive selection explanations', () => {
runtime.countTokens.mockReturnValueOnce(counting.promise);
await render({ ...props, proactive: true, readerContext: reader('SOURCE') });
await click('Download & load'); await settleSelection();
- await type('Question'); await click('Send ↑');
+ await type('Which values does it add?'); await click('Send ↑');
expect(runtime.stop).toHaveBeenCalledOnce();
expect(runtime.countTokens).toHaveBeenCalledOnce();
expect(runtime.chat).not.toHaveBeenCalled();
await act(async () => counting.resolve(100));
expect(runtime.countTokens).toHaveBeenCalledTimes(2);
expect(runtime.chat).toHaveBeenCalledOnce();
- expect(runtime.chat.mock.calls[0][0].at(-1)?.content).toBe('Answer in English.\n\nQuestion');
+ expect(runtime.chat.mock.calls[0][0].at(-1)?.content).toBe('Answer in English.\n\nWhich values does it add?');
});
it('cancels a queued question on Stop without silently sending or restarting it', async () => {
@@ -991,14 +991,14 @@ describe('graph answers and answer limits', () => {
runtime.chat.mockResolvedValueOnce('This runs the flake8 linter on Python files.');
const workflow = reader('name: New contributor message', 'file', '.github/workflows/new_contributor_pr.yml');
await render({ ...props, selectionScope: 'django-demo:explore', readerContext: workflow }); await click('Download & load');
- await type('was kannst du mir über dieses File sagen'); await click('Send ↑');
+ await type('welche Aktion nutzt dieses File?'); await click('Send ↑');
expect(container.querySelector('.cbm-chat-header')?.textContent).toContain('New conversation');
await render({ ...props, selectionScope: 'django-demo:galaxy', proactiveSelection: jsonbAggEvidence() });
await type('What does JSONBAgg do?'); await click('Send ↑');
const request = runtime.chat.mock.calls[1][0];
const text = request.map(message => message.content).join('\n');
expect(text).not.toContain('flake8');
- expect(text).not.toContain('was kannst du mir');
+ expect(text).not.toContain('welche Aktion');
expect(request.filter(message => message.role === 'assistant')).toHaveLength(0);
expect(container.querySelector('.cbm-chat-topic-break')?.textContent).toBe('New topic: JSONBAgg. Earlier messages are not sent with these questions.');
// A follow-up on the same selection keeps its own history.
@@ -1013,7 +1013,7 @@ describe('graph answers and answer limits', () => {
runtime.chat.mockResolvedValueOnce('This runs the flake8 linter on Python files.');
const workflow = reader('name: New contributor message', 'file', '.github/workflows/new_contributor_pr.yml');
await render({ ...props, selectionScope: 'django-demo:explore', readerContext: workflow }); await click('Download & load');
- await type('was kannst du mir über dieses File sagen'); await click('Send ↑');
+ await type('welche Aktion nutzt dieses File?'); await click('Send ↑');
await render({ ...props, selectionScope: 'django-demo:galaxy', proactiveSelection: jsonbAggEvidence() });
await type('What does JSONBAgg do?'); await click('Send ↑');
await render({ ...props, selectionScope: 'django-demo:explore', readerContext: workflow });
@@ -1035,7 +1035,7 @@ describe('graph answers and answer limits', () => {
runtime.chat.mockResolvedValueOnce('Dieses Script ruft `flake8` mit `subprocess.run` auf und prüft `pull_request_target`.');
const workflow = reader('name: New contributor message\n\non:\n pull_request_target:\n types: [opened]', 'file', '.github/workflows/new_contributor_pr.yml');
await render({ ...props, readerContext: workflow }); await click('Download & load');
- await type('was kannst du mir über dieses aktuelle File sagen'); await click('Send ↑');
+ await type('welche Trigger nutzt dieses aktuelle File?'); await click('Send ↑');
const note = [...container.querySelectorAll('.cbm-chat-turn .cbm-chat-answer-note')].map(item => item.textContent).find(text => /Not in the source/.test(text ?? ''));
expect(note).toBe('Not in the source or graph facts this answer was given: flake8, subprocess.run. Check these names before relying on them.');
});
@@ -1071,7 +1071,7 @@ describe('graph answers and answer limits', () => {
options?.onComplete?.({ stopReason: 'length' }); return 'A long list that';
});
await render({ ...props, proactiveSelection: longCallers() }); await click('Download & load');
- await type('Explain this class'); await click('Send ↑');
+ await type('Explain this class in detail'); await click('Send ↑');
const notes = [...container.querySelectorAll('.cbm-chat-answer-note')].map(item => item.textContent);
expect(container.querySelector('.cbm-chat-limit-note > summary')?.textContent).toBe('Token limit reached: the answer was cut short');
const capacity = notes.map(note => /^55 nodes \/ 40 edges: too large for the local Qwen2\.5 Coder 0\.5B model; showing (\d+)$/.exec(note ?? '')).find(Boolean);
@@ -1138,7 +1138,7 @@ describe('graph answers and answer limits', () => {
const { props, runtime } = fixture();
const many = Array.from({ length: 40 }, (_, index) => ({ source: 2000 + index, target: 32360, type: 'CALLS' }));
await render({ ...props, proactiveSelection: jsonbAggEvidence({ edges: many }) }); await click('Download & load');
- await type('Explain this class'); await click('Send ↑');
+ await type('Explain this class in detail'); await click('Send ↑');
expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toContain('+16 more');
expect(capacityNote()).toBeUndefined();
});
@@ -1146,7 +1146,7 @@ describe('graph answers and answer limits', () => {
it('gives a manual question more evidence when the input limit is raised', async () => {
const { props, runtime } = fixture();
await render({ ...props, proactiveSelection: longCallers() }); await click('Download & load');
- await type('Explain this class'); await click('Send ↑');
+ await type('Explain this class in detail'); await click('Send ↑');
const shown = (note?: string) => Number(/showing (\d+)$/.exec(note ?? '')?.[1] ?? 24);
const before = shown(capacityNote());
await models();
@@ -1156,7 +1156,7 @@ describe('graph answers and answer limits', () => {
input.dispatchEvent(new Event('input', { bubbles: true }));
});
await act(async () => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));
- await type('Explain this class'); await click('Send ↑');
+ await type('Explain this class in detail'); await click('Send ↑');
expect(runtime.chat.mock.calls[1][0].at(-1)!.content.length).toBeGreaterThan(runtime.chat.mock.calls[0][0].at(-1)!.content.length);
expect(before).toBeLessThan(24);
expect(capacityNote()).toBeUndefined();
@@ -1523,6 +1523,111 @@ describe('grounded automatic explanations (K14, K7)', () => {
});
});
+describe('general questions, prompts without a question and configuration files (C5, C6, C7)', () => {
+ const snippet = { source: 'class JSONBAgg(OrderableAggMixin, Aggregate):\n function = "JSONB_AGG"\n template = "%(function)s(%(distinct)s%(expressions)s %(order_by)s)"\n',
+ file_path: '/abs/django/contrib/postgres/aggregates/general.py', start_line: 50, end_line: 54, source_mode: 'full' };
+ const last = () => [...container.querySelectorAll('.cbm-chat-turn')].at(-1)!;
+ const answer = () => last().querySelector('.cbm-chat-answer-text')?.textContent ?? '';
+ const buttons = () => [...last().querySelectorAll('button.cbm-chat-retry')].map(item => item.textContent);
+
+ it('answers a short general question about the selection with the listed facts and one checked model sentence, in its language (C5)', async () => {
+ const { props, runtime } = fixture();
+ runtime.chat.mockResolvedValueOnce('`JSONBAgg` setzt `function` auf "JSONB_AGG". Sie gibt eine Liste von JSON-Daten zurück.');
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource: vi.fn(async () => snippet) }); await click('Download & load');
+ await type('was macht diese klasse? sehr kurze antwort'); await click('Send ↑');
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ const [request, , options] = runtime.chat.mock.calls[0];
+ expect(options).toMatchObject({ maxOutputTokens: 128, generationProfile: 'automatic-explanation' });
+ expect(request.at(-1)!.content).toContain('Describe this class in one short sentence that starts with `JSONBAgg`. Answer in German.');
+ expect(request.at(-1)!.content).toContain('function = "JSONB_AGG"');
+ expect(answer()).toContain('Ausgewählt: JSONBAgg (Class) in django/contrib/postgres/aggregates/general.py:50-54.');
+ expect(answer()).toContain('Eingehende Beziehungen: 23 aus 12 Symbolen (CALLS 11, TESTS 11, DEFINES 1).');
+ expect(answer()).toContain('Ausschnitt: 1 Schritt in beide Richtungen');
+ expect(answer()).toContain('JSONBAgg setzt function auf "JSONB_AGG".');
+ expect(answer()).not.toContain('Liste von');
+ expect(answer()).toContain('Fakten aus dem indizierten Graphen gelistet; der letzte Satz ist vom Modell erzeugt.');
+ expect(last().querySelector('.cbm-chat-answer-note')).toBeNull();
+ expect(buttons()).toEqual(['Modell fragen']);
+ // "Modell fragen" asks the model as before, with the question's language.
+ await act(async () => button('Modell fragen').click());
+ expect(runtime.chat).toHaveBeenCalledTimes(2);
+ expect(runtime.chat.mock.calls[1][2]?.generationProfile).toBeUndefined();
+ expect(runtime.chat.mock.calls[1][0].at(-1)!.content).toContain('Answer in German.\nUser question:\nwas macht diese klasse? sehr kurze antwort');
+ });
+
+ it('leaves out a sentence that claims what the code does not show, also in German (C5)', async () => {
+ const { props, runtime } = fixture();
+ runtime.chat.mockResolvedValueOnce('JSONBAgg gibt eine Liste von Werten zurück.');
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource: vi.fn(async () => snippet) }); await click('Download & load');
+ await type('was kansnt du mir über den code sagen'); await click('Send ↑');
+ expect(answer()).toContain('Ausgewählt: JSONBAgg (Class)');
+ expect(answer()).not.toContain('gibt eine Liste');
+ expect(answer()).toContain('Der Satz des Modells nannte etwas, das die Fakten nicht zeigen, und wurde weggelassen.');
+ });
+
+ it('lists only the facts without source and sends detail questions to the model as before (C5)', async () => {
+ const { props, runtime } = fixture();
+ await render({ ...props, proactiveSelection: jsonbAggEvidence(), readSource: vi.fn(async () => { throw new Error('offline'); }) }); await click('Download & load');
+ await type('what does this do'); await click('Send ↑');
+ expect(runtime.countTokens).not.toHaveBeenCalled();
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(answer()).toContain('Selected: JSONBAgg (Class) in django/contrib/postgres/aggregates/general.py:50-54.');
+ expect(answer()).toContain('Listed from the indexed graph; not generated by the model.');
+ expect(buttons()).toEqual(['Ask the model']);
+ await type('Explain this class in detail, line by line.'); await click('Send ↑');
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ expect(runtime.chat.mock.calls[0][2]?.generationProfile).toBeUndefined();
+ });
+
+ it('answers a prompt without a question locally with example questions, in its language (C6)', async () => {
+ const { props, runtime } = fixture();
+ await render({ ...props, proactiveSelection: jsonbAggEvidence() }); await click('Download & load');
+ await type('test'); await click('Send ↑');
+ expect(runtime.countTokens).not.toHaveBeenCalled();
+ expect(runtime.chat).not.toHaveBeenCalled();
+ expect(answer()).toContain('No question was recognized in "test". You can ask, for example:');
+ for (const example of ['What does JSONBAgg do?', 'Who calls JSONBAgg?', 'What does JSONBAgg call?']) expect(answer()).toContain(example);
+ expect(buttons()).toEqual(['Ask the model']);
+ await type('hallo'); await click('Send ↑');
+ expect(answer()).toContain('In "hallo" wurde keine Frage erkannt. Frage zum Beispiel:');
+ for (const example of ['Was macht JSONBAgg?', 'Wer ruft JSONBAgg auf?']) expect(answer()).toContain(example);
+ expect(buttons()).toEqual(['Modell fragen']);
+ expect(runtime.chat).not.toHaveBeenCalled();
+ await act(async () => button('Modell fragen').click());
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ expect(runtime.chat.mock.calls[0][0].at(-1)!.content).toContain('User question:\nhallo');
+ // A follow-up does not carry the hint as an answer.
+ await render({ ...props, readerContext: reader('repos:\n - repo: x\n', 'file', '.pre-commit-config.yaml') });
+ await type('?'); await click('Send ↑');
+ expect(answer()).toContain('No question was recognized in "?".');
+ expect(answer()).toContain('What does .pre-commit-config.yaml do?');
+ });
+
+ it('answers what a configuration file does from the file, in the language of the question, and asks the model only on request (C7)', async () => {
+ const { props, runtime } = fixture();
+ const text = 'repos:\n - repo: https://github.com/PyCQA/isort\n rev: 5.13.2\n hooks:\n - id: isort\n - repo: https://github.com/PyCQA/flake8\n rev: 7.1.1\n hooks:\n - id: flake8\n';
+ await render({ ...props, selectionScope: 'django-demo:explore', readerContext: reader(text, 'file', '.pre-commit-config.yaml') }); await click('Download & load');
+ for (const question of ['was macht diese datei?', 'erklär mir die datei detailliert']) {
+ await type(question); await click('Send ↑');
+ expect(answer()).toContain('.pre-commit-config.yaml: YAML-Konfiguration, 9 Zeilen. Aus der Datei gelesen:');
+ expect(answer()).toContain('repos (Liste mit 2 Einträgen):');
+ expect(answer()).toContain('repo https://github.com/PyCQA/flake8; rev 7.1.1; hooks (1): flake8');
+ expect(answer()).toContain('Aus der Datei gelesen, nicht vom Modell erzeugt.');
+ expect(buttons()).toEqual(['Modell fragen']);
+ }
+ expect(runtime.chat).not.toHaveBeenCalled();
+ await type('What does this file do?'); await click('Send ↑');
+ expect(answer()).toContain('.pre-commit-config.yaml: YAML configuration, 9 lines. Read from the file:');
+ expect(runtime.chat).not.toHaveBeenCalled();
+ await act(async () => button('Ask the model').click());
+ expect(runtime.chat).toHaveBeenCalledOnce();
+ expect(runtime.chat.mock.calls[0][0][0].content).toContain('--- BEGIN EXACT SOURCE TEXT ---\nrepos:');
+ // Other questions about the file go to the model.
+ await type('Which hook runs flake8?'); await click('Send ↑');
+ expect(runtime.chat).toHaveBeenCalledTimes(2);
+ });
+});
+
describe('a cached model across reloads and project switches (K10, K24)', () => {
const configButtons = () => [...document.querySelectorAll('dialog .cbm-chat-model-actions button')].map(item => item.textContent);
diff --git a/graph-ui/src/browser-ai/BrowserChatDock.tsx b/graph-ui/src/browser-ai/BrowserChatDock.tsx
index c5fbc695c..3b10ff2a0 100644
--- a/graph-ui/src/browser-ai/BrowserChatDock.tsx
+++ b/graph-ui/src/browser-ai/BrowserChatDock.tsx
@@ -10,13 +10,16 @@ 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, relationshipWords } from './strings';
+import { browserChatText, groundedText, relationshipWords } from './strings';
import { isGpuRuntimeFailure, BrowserRuntimeFatalError } from './runtime-fault';
import ChatMarkdown from './ChatMarkdown';
import AgentSettingsDialog from './AgentSettingsDialog';
import { useChatHistory } from './use-chat-history';
import { chatTopic, followedTopic, missingContextAnswer, questionLanguage, topicHistory } from './chat-context';
import { isDataFile, readerFacts } from './file-facts';
+import { fileOutline } from './file-outline';
+import { readGalaxyEvidence, type GalaxyEvidence } from './galaxy-evidence';
+import { generalQuestion, knownNames, noQuestion, noQuestionAnswer } from './question-intent';
import './browser-chat.css';
export type { BrowserChatAttachment, BrowserChatContext, BrowserChatReaderContext, BrowserChatSource } from './chat-model';
@@ -59,15 +62,21 @@ const EXPLANATION_CACHE_SIZE = 32;
const initialModel = BROWSER_MODELS.find(model => model.availability === 'available')!;
const cachedInBrowser = (modelId: string) => isBrowserModelCached(getBrowserModel(modelId)).catch(() => false);
const messageOf = (error: unknown): string => error instanceof Error ? error.message : String(error);
+/** The names a Galaxy selection goes by: its label and its symbols with their qualified names. */
+const galaxyNames = (galaxy: GalaxyEvidence): string[] => [galaxy.label, ...galaxy.roots.flatMap(root => [root.name, root.qualifiedName ?? ''])].filter(Boolean);
+/** Answers the chat gives itself, which "Ask the model" sends to the model as the question they answer. */
+const ASKABLE = new Set(['graph', 'suggestion', 'grounded', 'file', 'hint']);
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`;
/** Symbol sources read for explanations and questions, newest last. */
const SOURCE_CACHE_SIZE = 32;
/** The listed facts first, then the model's sentence if it stood the check, then who wrote what (K7).
- * The facts come from the indexed graph, or for an open workflow from the file itself (K12). */
-function groundedExplanation(summary: readonly string[], sentence: string | undefined, dropped: boolean, from: 'graph' | 'file' = 'graph'): string {
+ * The facts come from the indexed graph, or for an open workflow from the file itself (K12). The
+ * answer to a general question says it in the language of that question (C5). */
+function groundedExplanation(summary: readonly string[], sentence: string | undefined, dropped: boolean, from: 'graph' | 'file' = 'graph', language: 'en' | 'de' = 'en'): string {
+ const words = groundedText[language];
const note = from === 'file' ? sentence ? browserChatText.fileFactsAndSentence : dropped ? browserChatText.fileSentenceDropped : browserChatText.fileFactsOnly
- : sentence ? browserChatText.factsAndSentence : dropped ? browserChatText.sentenceDropped : browserChatText.factsOnly;
+ : sentence ? words.factsAndSentence : dropped ? words.sentenceDropped : words.factsOnly;
return [summary.map(line => `- ${line}`).join('\n'), ...sentence ? [sentence] : [], `_${note}_`].join('\n\n');
}
@@ -586,7 +595,7 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
const extra = (retry ? retry.context ?? [] : nextContext).map(item => ({ ...item }));
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';
+ const ask = retry !== undefined && ASKABLE.has(retry.answeredFrom ?? '');
// 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 }] : [];
@@ -628,6 +637,33 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
consume(); listSource(id, suggested.context);
return;
}
+ const language = questionLanguage(prompt);
+ const galaxy = currentGraph[0] ? readGalaxyEvidence(currentGraph[0].text) : undefined;
+ const fileSource = reader?.source;
+ // A prompt that asks nothing ("test", "hallo") gets questions it could ask, not an echo of the model (C6).
+ const known = knownNames({ galaxy, names: galaxy ? galaxyNames(galaxy) : fileSource ? [fileSource.path] : [],
+ texts: [fileSource?.text ?? '', source?.text ?? '', ...currentGraph.filter(() => !galaxy).map(item => item.label), ...extra.map(item => item.label)] });
+ if (!retry && noQuestion(prompt, known)) {
+ const subject = galaxy ? { kind: 'galaxy' as const, name: galaxy.label } : fileSource?.kind === 'selection' || source ? { kind: 'marked' as const }
+ : { kind: 'other' as const, name: fileSource ? fileSource.path.split('/').pop()! : topic?.label ?? '' };
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, attachment: source, readerContext: reader, context: extra, topic, replyLanguage: language,
+ ...currentGraph[0] ? { listedFrom: currentGraph[0] } : {}, modelId: model.id, request: [], answer: noQuestionAnswer(prompt, language, subject), status: 'complete', answeredFrom: 'hint' }]);
+ consume();
+ return;
+ }
+ // What a configuration file holds is read from it: the model hung its keys on the wrong items (C7).
+ const outline = !retry && !source && !extra.length && fileSource?.kind === 'file' && !fileSource.partial
+ && generalQuestion(prompt, [fileSource.path]) ? fileOutline(fileSource.path, fileSource.text, language) : undefined;
+ if (outline) {
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, readerContext: reader, context: extra, topic, replyLanguage: language,
+ modelId: model.id, request: [], answer: outline, status: 'complete', answeredFrom: 'file' }]);
+ consume();
+ return;
+ }
+ // A short general question about a Galaxy selection gets the shape of its explanation: the
+ // listed facts and one checked model sentence, in the language of the question (C5).
+ const grounded = !retry && !source && !extra.length && galaxy && generalQuestion(prompt, galaxyNames(galaxy)) === 'general'
+ ? { graph: currentGraph[0], summary: selectionSummary(currentGraph[0], language), subject: selectionSubject(currentGraph[0]) } : undefined;
// Answers about another file or selection stay out, and so do those from before the
// last change of topic: an earlier wrong answer must not become evidence for this one (K17).
const earlier = topicHistory(ask ? turns.filter(item => item.id !== retry.id) : turns, topic);
@@ -641,8 +677,17 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
if (manualRequest.current === queued) manualRequest.current = undefined;
return;
}
- 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 (grounded) packet = prepareExplanationContext(undefined, packetGraph, 3200, symbol);
+ else if ((!retry || askFrom) && ((reader?.source?.text.length ?? 0) > 5000 || packetGraph.length)) packet = prepareExplanationContext(reader, packetGraph, chatEvidence, symbol);
+ // Without source the model could only restate the facts: they are the answer (K7).
+ if (grounded && explanationMode(packet!) === 'graph') {
+ if (manualRequest.current === queued) manualRequest.current = undefined;
+ setTurns(previous => [...previous, { id: `local-turn-${crypto.randomUUID()}`, prompt, context: extra, topic, listedFrom: grounded.graph, replyLanguage: language, evidence: packet,
+ modelId: model.id, request: [], answer: groundedExplanation(grounded.summary, undefined, false, 'graph', language), status: 'complete', answeredFrom: 'grounded' }]);
+ consume();
+ return;
+ }
+ let request = grounded ? explanationMessages(packet!, grounded.subject, language) : retry && !ask ? retry.request.map(message => ({ ...message })) : makeRequest();
if (automaticRun) {
automaticRun.cancelled = true; lastAttempt.current = undefined;
setQuestionQueued(true); currentRuntime.stop();
@@ -659,15 +704,21 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
try {
let count = await currentRuntime.countTokens(request);
if (epoch.current !== ticket || stopRequested.current) return;
- const limit = Math.min(limits.inputTokens, model.contextTokens - limits.outputTokens);
+ const limit = grounded ? autoInput : Math.min(limits.inputTokens, model.contextTokens - limits.outputTokens);
+ // The sentence of a general question is bounded like that of an automatic explanation.
+ for (let budget = 1900; grounded && count > limit && budget >= 300; budget = Math.floor(budget * .6)) {
+ packet = prepareExplanationContext(undefined, packetGraph, budget, symbol);
+ request = explanationMessages(packet, grounded.subject, language); count = await currentRuntime.countTokens(request);
+ if (epoch.current !== ticket || stopRequested.current) return;
+ }
// Earlier turns give way first, oldest first; the question and its evidence stay.
- while ((!retry || ask) && count > limit && history.length) {
+ while (!grounded && (!retry || ask) && count > limit && history.length) {
const characters = request.reduce((sum, message) => sum + message.content.length, 0);
history = trimChatHistory(history, Math.ceil((count - limit) * characters / Math.max(1, count)));
request = makeRequest(); count = await currentRuntime.countTokens(request);
if (epoch.current !== ticket || stopRequested.current) return;
}
- for (let budget = packet ? Math.floor(chatEvidence * .6) : chatEvidence; (!retry || askFrom) && count > limit && (reader?.source || packetGraph.length) && budget >= 300; budget = Math.floor(budget * .6)) {
+ for (let budget = packet ? Math.floor(chatEvidence * .6) : chatEvidence; !grounded && (!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;
@@ -679,18 +730,29 @@ 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', topic,
- ...historyOmitted ? { historyOmitted } : {} };
+ // 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 } : {} };
activeTurn.current = id;
if (retry) setTurns(previous => previous.map(item => item.id === id ? turn : item));
else { setTurns(previous => [...previous, turn]); consume(); }
setPhase('generating');
let shortened = false;
+ const onComplete = ({ stopReason }: { stopReason: string }) => { shortened = stopReason === 'length'; };
const output = await currentRuntime.chat(request, chunk => {
- if (epoch.current !== ticket || stopRequested.current) return;
+ if (grounded || epoch.current !== ticket || stopRequested.current) return;
setTurns(previous => previous.map(item => item.id === id ? { ...item, answer: item.answer + chunk } : item));
- }, { maxOutputTokens: limits.outputTokens, onComplete: ({ stopReason }) => { shortened = stopReason === 'length'; } });
+ }, grounded ? { maxOutputTokens: autoOutput, generationProfile: 'automatic-explanation', onComplete } : { maxOutputTokens: limits.outputTokens, onComplete });
if (epoch.current !== ticket) return;
+ if (grounded) {
+ // One sentence beside the facts, checked like the sentence of the explanation card.
+ const result = parseExplanationResponse(output, packet!);
+ const checked = !stopRequested.current && result.status === 'generated' ? explanationSentence(result.markdown, packet!, request.map(message => message.content).join('\n')) : {};
+ const answer = groundedExplanation(grounded.summary, checked.sentence, checked.dropped !== undefined, 'graph', language);
+ setTurns(previous => previous.map(item => item.id === id ? { ...item, answer, status: stopRequested.current ? 'stopped' : 'complete' } : item));
+ return;
+ }
setTurns(previous => previous.map(item => item.id === id ? { ...item, answer: stopRequested.current ? item.answer : output, status: stopRequested.current ? 'stopped' : 'complete',
...shortened && !stopRequested.current ? { shortened, limit: { inputTokens: limits.inputTokens, outputTokens: limits.outputTokens } } : {} } : item));
} catch (failure) {
@@ -698,7 +760,8 @@ export default function BrowserChatDock({ proactiveSelection, selectionScope = "
if (isGpuRuntimeFailure(failure)) { invalidateRuntime(failure); return; }
const explanation = messageOf(failure);
const id = activeTurn.current;
- if (id) setTurns(previous => previous.map(turn => turn.id === id ? { ...turn, status: stopRequested.current ? 'stopped' : 'error', error: stopRequested.current ? undefined : explanation } : turn));
+ if (id) setTurns(previous => previous.map(turn => turn.id === id ? { ...turn, status: stopRequested.current ? 'stopped' : 'error', error: stopRequested.current ? undefined : explanation,
+ ...grounded ? { answer: groundedExplanation(grounded.summary, undefined, false, 'graph', language) } : {} } : turn));
else if (!stopRequested.current) setError(explanation);
} finally {
if (manualRequest.current === queued) manualRequest.current = undefined;
diff --git a/graph-ui/src/browser-ai/chat-context.ts b/graph-ui/src/browser-ai/chat-context.ts
index 82f3cfe7d..2e799649a 100644
--- a/graph-ui/src/browser-ai/chat-context.ts
+++ b/graph-ui/src/browser-ai/chat-context.ts
@@ -42,7 +42,7 @@ export function topicHistory<T extends BrowserChatTurn>(turns: readonly T[], top
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;
+ if (!topic || turns[index].answeredFrom === 'local' || turns[index].answeredFrom === 'hint') continue;
// Stored history is data: a damaged key ends the follow-up instead of the send.
let turnScope: unknown;
try { [turnScope] = JSON.parse(topic.key) as unknown[]; } catch { return undefined; }
diff --git a/graph-ui/src/browser-ai/chat-model.ts b/graph-ui/src/browser-ai/chat-model.ts
index 634830da6..a2b36e4c5 100644
--- a/graph-ui/src/browser-ai/chat-model.ts
+++ b/graph-ui/src/browser-ai/chat-model.ts
@@ -46,8 +46,10 @@ export interface BrowserChatTurn {
/** The limits that answer ran into. */
limit?: { inputTokens: number; outputTokens: number };
/** 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';
+ * own reply that a question has no context to answer from. `grounded`: the facts of a
+ * selection with one checked model sentence (C5); `file`: an outline read from the file (C7);
+ * `hint`: example questions for a prompt that asks nothing (C6). */
+ answeredFrom?: 'graph' | 'suggestion' | 'local' | 'grounded' | 'file' | 'hint';
/** 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
@@ -151,7 +153,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' || turn.answeredFrom === 'local') continue;
+ if (turn.status === 'error' || turn.status === 'generating' || turn.answeredFrom === 'suggestion' || turn.answeredFrom === 'local' || turn.answeredFrom === 'hint') 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/explanation-context.ts b/graph-ui/src/browser-ai/explanation-context.ts
index aec18bc9c..1346055ae 100644
--- a/graph-ui/src/browser-ai/explanation-context.ts
+++ b/graph-ui/src/browser-ai/explanation-context.ts
@@ -213,7 +213,7 @@ function galaxyFacts(galaxy: GalaxyEvidence): GraphPreparation {
...galaxy.relationships.beyond.length ? [words.beyond(counts(galaxy.relationships.beyond))] : [],
].join('\n');
return {
- facts: [fixedFact(selectionSentence(galaxy).join('\n')), fixedFact(scopeSentence(galaxy, words)),
+ facts: [fixedFact(selectionSentence(galaxy, words).join('\n')), fixedFact(scopeSentence(galaxy, words)),
relationshipFact(galaxy, 'incoming'), relationshipFact(galaxy, 'outgoing'), ...further ? [fixedFact(further)] : []],
limitations: ['Static graph relationships do not establish runtime execution or repository purpose.'],
scope: { nodes: galaxy.nodes, edges: galaxy.edges },
@@ -257,12 +257,13 @@ function graphEvidence(context: BrowserChatContext): GraphPreparation {
}
/** The selection in a few bullets, listed from the graph and never written by the model:
- * what is selected, its relationships by direction and type, how the scope was drawn (K7). */
-export function selectionSummary(context: BrowserChatContext | undefined): string[] {
+ * what is selected, its relationships by direction and type, how the scope was drawn (K7).
+ * The card lists them in English, the answer to a general question in its language (C5). */
+export function selectionSummary(context: BrowserChatContext | undefined, language: 'en' | 'de' = 'en'): string[] {
if (!context || context.text.length > 128_000) return [];
const galaxy = readGalaxyEvidence(context.text);
if (galaxy) {
- const words = relationshipWords.en;
+ const words = relationshipWords[language];
const side = (name: 'incoming' | 'outgoing') => {
const groups = galaxy.relationships[name];
if (!sideLoaded(galaxy, name)) return name === 'incoming' ? words.incomingNotLoaded : words.outgoingNotLoaded;
@@ -271,7 +272,7 @@ export function selectionSummary(context: BrowserChatContext | undefined): strin
const line = name === 'incoming' ? words.incoming(total, galaxy.relationships.incomingSymbols) : words.outgoing(total, galaxy.relationships.outgoingSymbols);
return `${line.slice(0, -1)} (${groups.map(group => `${group.type} ${group.count}`).join(', ')}).`;
};
- return [selectionSentence(galaxy)[0], side('incoming'), side('outgoing'), scopeSentence(galaxy, words)];
+ return [selectionSentence(galaxy, words)[0], side('incoming'), side('outgoing'), scopeSentence(galaxy, words)];
}
let parsed: Record<string, unknown> | undefined;
try { parsed = record(record(JSON.parse(context.text))?.evidence); } catch { return []; }
diff --git a/graph-ui/src/browser-ai/explanation-response.ts b/graph-ui/src/browser-ai/explanation-response.ts
index caac61425..a6a630659 100644
--- a/graph-ui/src/browser-ai/explanation-response.ts
+++ b/graph-ui/src/browser-ai/explanation-response.ts
@@ -1,6 +1,7 @@
import type { BrowserChatMessage } from './browser-ai-controller';
import type { PreparedExplanationContext } from './explanation-context';
import { fileKind } from './file-kind';
+import { ANSWER_LANGUAGE } from './chat-model';
import { workflowWords } from './strings';
export const AUTO_INPUT_TOKENS = 1536;
@@ -41,20 +42,32 @@ const EXPLANATION_TASK: Record<Exclude<ExplanationMode, 'symbol'>, string> = {
* beside it the small model described the tests instead and guessed inputs and outputs. */
const SYMBOL_SYSTEM = 'Answer only from the code you are given. Never state types, parameters, inputs, outputs, return values or purposes that the code does not show.';
-export function explanationMessages(packet: PreparedExplanationContext, subject?: { name: string; kind?: string }): BrowserChatMessage[] {
+/** `language` asks for the sentence of a general question in the language of that question (C5). */
+export function explanationMessages(packet: PreparedExplanationContext, subject?: { name: string; kind?: string }, language?: keyof typeof ANSWER_LANGUAGE): BrowserChatMessage[] {
const mode = explanationMode(packet);
+ const answerIn = language ? ` ${ANSWER_LANGUAGE[language]}` : '';
if (mode === 'symbol' && subject) {
const code = packet.evidence.filter(item => item.source === 'code').map(item => item.text).join('\n');
const kind = subject.kind?.toLowerCase() ?? 'code';
return [{ role: 'system', content: SYMBOL_SYSTEM },
- { role: 'user', content: `\`\`\`\n${code}\n\`\`\`\n\nDescribe this ${kind} in one short sentence that starts with \`${subject.name.replace(/`/g, "'")}\`.` }];
+ { role: 'user', content: `\`\`\`\n${code}\n\`\`\`\n\nDescribe this ${kind} in one short sentence that starts with \`${subject.name.replace(/`/g, "'")}\`.${answerIn}` }];
}
return [{ role: 'system', content: EXPLANATION_SYSTEM },
- { role: 'user', content: `${formatExplanationEvidence(packet)}\n\n${EXPLANATION_TASK[mode === 'symbol' ? 'code' : mode]} Stop after that.` }];
+ { role: 'user', content: `${formatExplanationEvidence(packet)}\n\n${EXPLANATION_TASK[mode === 'symbol' ? 'code' : mode]} Stop after that.${answerIn}` }];
}
/** Without source, a sentence about types, values or inputs and outputs is a guess. */
const UNSUPPORTED_CLAIM = /\b(?:returns?|returning|list of|lists of|integers?|strings?|booleans?|dict(?:ionar(?:y|ies))?|arrays?|inputs?|outputs?|parameters?|arguments?|data types?)\b/i;
+/** The same claims in a German sentence, each with the word the code would show for it (C5). */
+const GERMAN_CLAIMS: readonly [RegExp, string][] = [
+ [/\bgibt\b[^.!?]*?\bzurück|\bzurückgegeben|\brückgabe/iu, 'return'],
+ [/\blisten? (?:von|mit|aus)\b/iu, 'list'],
+ [/\bparameter/iu, 'parameter'],
+ [/\bargument/iu, 'argument'],
+ [/\beingabe/iu, 'input'],
+ [/\bausgabe/iu, 'output'],
+ [/\bdatentyp/iu, 'type'],
+];
/** Identifier-shaped words: snake_case, camelCase, PascalCase with an inner capital, or letters with digits. */
const IDENTIFIER = /\b(?:[A-Za-z]+_\w+|[a-z]+[A-Z]\w*|[A-Z][a-z0-9]+[A-Z]\w*|[A-Za-z]+\d+\w*)\b/g;
@@ -97,8 +110,9 @@ export function explanationSentence(output: string, packet: PreparedExplanationC
const named = [...sentence.matchAll(/`([^`]+)`/g)].map(match => match[1]).concat(sentence.replace(/`[^`]*`/g, ' ').match(IDENTIFIER) ?? []);
// Without source every type or input/output claim is a guess; with source only one the code itself shows.
const code = packet.evidence.filter(item => item.source === 'code').map(item => item.text).join('\n').toLowerCase();
- const claims = [...sentence.matchAll(new RegExp(UNSUPPORTED_CLAIM.source, 'gi'))].map(match => match[0].toLowerCase().replace(/(?:s|ing)$/, ''));
- if (named.some(name => !known(name)) ||(mode !== 'code' && claims.some(claim => mode === 'graph' || !code.includes(claim.split(' ')[0])))) return { dropped: 'unsupported' };
+ const claims = [...sentence.matchAll(new RegExp(UNSUPPORTED_CLAIM.source, 'gi'))].map(match => match[0].toLowerCase().replace(/(?:s|ing)$/, '').split(' ')[0])
+ .concat(GERMAN_CLAIMS.flatMap(([pattern, word]) => pattern.test(sentence) ? [word] : []));
+ if (named.some(name => !known(name)) || (mode !== 'code' && claims.some(claim => mode === 'graph' || !code.includes(claim)))) return { dropped: 'unsupported' };
return { sentence };
}
diff --git a/graph-ui/src/browser-ai/file-outline.test.ts b/graph-ui/src/browser-ai/file-outline.test.ts
new file mode 100644
index 000000000..14cfec5f1
--- /dev/null
+++ b/graph-ui/src/browser-ai/file-outline.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import { fileOutline } from './file-outline';
+
+/** django's .pre-commit-config.yaml as the hand test of 2026-10-04 read it. */
+export const PRE_COMMIT = `repos:
+ - repo: https://github.com/psf/black-pre-commit-mirror
+ rev: 25.1.0
+ hooks:
+ - id: black
+ exclude: \\.py-tpl$
+ - repo: https://github.com/adamchainz/blacken-docs
+ rev: 1.19.1
+ hooks:
+ - id: blacken-docs
+ additional_dependencies:
+ - black==25.1.0
+ files: 'docs/.*\\.txt$'
+ args: ["--rst-literal-block"]
+ - repo: https://github.com/PyCQA/isort
+ rev: 5.13.2
+ hooks:
+ - id: isort
+ - repo: https://github.com/PyCQA/flake8
+ rev: 7.1.1
+ hooks:
+ - id: flake8
+ - repo: https://github.com/pre-commit/mirrors-eslint
+ rev: v9.12.0
+ hooks:
+ - id: eslint
+`;
+const WORKFLOW = 'name: New contributor message\n\non:\n pull_request_target:\n types: [opened]\n\njobs:\n build:\n name: Hello new contributor\n runs-on: ubuntu-latest\n steps:\n - uses: actions/first-interaction@v1\n';
+
+describe('the outline of a configuration file, read from it (C7)', () => {
+ it('lists each repo of a pre-commit file with its revision and hooks', () => {
+ const outline = fileOutline('.pre-commit-config.yaml', PRE_COMMIT, 'en')!;
+ expect(outline).toContain('`.pre-commit-config.yaml`: YAML configuration, 26 lines. Read from the file:');
+ expect(outline).toContain('- `repos` (list of 5):');
+ expect(outline).toContain(' 1. repo `https://github.com/psf/black-pre-commit-mirror`; rev `25.1.0`; hooks (1): `black` (exclude `\\.py-tpl$`)');
+ expect(outline).toContain(' 2. repo `https://github.com/adamchainz/blacken-docs`; rev `1.19.1`; hooks (1): `blacken-docs` '
+ + '(additional_dependencies: `black==25.1.0`; files `docs/.*\\.txt$`; args: `--rst-literal-block`)');
+ expect(outline).toContain(' 5. repo `https://github.com/pre-commit/mirrors-eslint`; rev `v9.12.0`; hooks (1): `eslint`');
+ expect(outline).toContain('_Read from the file; not generated by the model._');
+ });
+
+ it('writes the outline in German for a German question', () => {
+ const outline = fileOutline('.pre-commit-config.yaml', PRE_COMMIT, 'de')!;
+ expect(outline).toContain('`.pre-commit-config.yaml`: YAML-Konfiguration, 26 Zeilen. Aus der Datei gelesen:');
+ expect(outline).toContain('- `repos` (Liste mit 5 Einträgen):');
+ expect(outline).toContain(' 4. repo `https://github.com/PyCQA/flake8`; rev `7.1.1`; hooks (1): `flake8`');
+ expect(outline).toContain('_Aus der Datei gelesen, nicht vom Modell erzeugt._');
+ });
+
+ it('keeps mappings by their keys and bounds long lists with "+N more"', () => {
+ const docs = 'version: 2\nbuild:\n os: ubuntu-22.04\n tools:\n python: "3.12"\nformats:\n - pdf\n - epub\n';
+ const outline = fileOutline('.readthedocs.yml', docs, 'en')!;
+ expect(outline).toContain('- `version`: `2`');
+ expect(outline).toContain('- `build`: os `ubuntu-22.04`; tools: python `3.12`');
+ expect(outline).toContain('- `formats` (list of 2): `pdf`, `epub`');
+ const long = `items:\n${Array.from({ length: 30 }, (_, index) => ` - name: item${index}\n value: ${index}`).join('\n')}\n`;
+ const bounded = fileOutline('long.yaml', long, 'en')!;
+ expect(bounded).toContain(' 10. name `item9`; value `9`');
+ expect(bounded).not.toContain('item10`');
+ expect(bounded).toContain(' +20 more');
+ expect(fileOutline('long.yaml', long, 'de')).toContain(' +20 weitere');
+ });
+
+ it('reads JSON and TOML files the same way', () => {
+ const json = fileOutline('package.json', '{"name": "demo", "scripts": {"build": "tsc", "test": "vitest"}, "files": ["dist", "src"]}', 'en')!;
+ expect(json).toContain('- `name`: `demo`');
+ expect(json).toContain('- `scripts`: build `tsc`; test `vitest`');
+ expect(json).toContain('- `files` (list of 2): `dist`, `src`');
+ const toml = fileOutline('pyproject.toml', '[project]\nname = "demo"\nversion = "1.0"\n\n[tool.ruff]\nline-length = 88\n', 'en')!;
+ expect(toml).toContain('- `[project]`: name `demo`; version `1.0`');
+ expect(toml).toContain('- `[tool.ruff]`: line-length `88`');
+ });
+
+ it('gives a workflow its counted facts, in the language of the question', () => {
+ const english = fileOutline('.github/workflows/new_contributor_pr.yml', WORKFLOW, 'en')!;
+ expect(english).toContain('- Workflow name: `New contributor message`.');
+ expect(english).toContain('- 1 job: `build` ("Hello new contributor", runs on ubuntu-latest, 1 step).');
+ expect(english).toContain('- Actions used: `actions/first-interaction@v1`.');
+ const german = fileOutline('.github/workflows/new_contributor_pr.yml', WORKFLOW, 'de')!;
+ expect(german).toContain('- Name des Workflows: `New contributor message`.');
+ expect(german).toContain('- Auslöser: `pull_request_target` (Typen: opened).');
+ expect(german).toContain('- 1 Job: `build` ("Hello new contributor", läuft auf ubuntu-latest, 1 Schritt).');
+ expect(german).toContain('- Verwendete Actions: `actions/first-interaction@v1`.');
+ });
+
+ it('has no outline for program code, text files or JSON that does not parse', () => {
+ expect(fileOutline('django/contrib/postgres/aggregates/general.py', 'class JSONBAgg: pass', 'en')).toBeUndefined();
+ expect(fileOutline('README.md', '# Demo', 'en')).toBeUndefined();
+ expect(fileOutline('broken.json', '{"name":', 'en')).toBeUndefined();
+ });
+});
diff --git a/graph-ui/src/browser-ai/file-outline.ts b/graph-ui/src/browser-ai/file-outline.ts
new file mode 100644
index 000000000..bc0fcfbdf
--- /dev/null
+++ b/graph-ui/src/browser-ai/file-outline.ts
@@ -0,0 +1,130 @@
+import { isGithubWorkflow } from './file-kind';
+import { fileOutlineWords, germanWorkflowWords, workflowWords } from './strings';
+import { workflowFactLines, yamlTree, type YamlValue } from './workflow-facts';
+
+/** "What does this file do?" about a configuration file, answered from the file (C7). The
+ * small model wrote "YAML-Konfiguration für den Black-Commit-Tool" for django's pre-commit
+ * file and, asked for detail, hung `additional_dependencies` on the wrong hooks. The outline
+ * names what the file holds: every key, a list of mappings item by item with its fields, a
+ * workflow by its counted facts. It is bounded, and says what it left out. */
+
+const ENTRIES = 12;
+const ITEMS = 10;
+const FIELDS = 8;
+const VALUE = 80;
+const BUDGET = 3600;
+/** The field that names an item of a nested list: "hooks (1): `black` (exclude ...)". */
+const NAMING = ['id', 'name', 'key', 'uses', 'run', 'repo'];
+
+type Words = typeof fileOutlineWords.en;
+const code = (value: string) => `\`${(value.length > VALUE ? `${value.slice(0, VALUE - 1)}…` : value).replace(/`/g, "'")}\``;
+const lineCount = (text: string) => text ? text.split(/\r?\n/).length - (/\r?\n$/.test(text) ? 1 : 0) : 0;
+const extension = (path: string) => (path.split('/').pop() ?? path).split('.').slice(1).pop()?.toLowerCase() ?? '';
+
+/** JSON as the same values as YAML. */
+function jsonValue(value: unknown): YamlValue {
+ if (Array.isArray(value)) return { kind: 'list', items: value.map(jsonValue) };
+ if (value !== null && typeof value === 'object') return { kind: 'map', entries: Object.entries(value).map(([key, item]): [string, YamlValue] => [key, jsonValue(item)]) };
+ return { kind: 'scalar', value: String(value) };
+}
+
+/** TOML: the keys before the first table, each `[table]` with its keys, each `[[table]]` as a list item. */
+function tomlTree(text: string): YamlValue | undefined {
+ const root: [string, YamlValue][] = [];
+ let current = root, quoted: string | undefined;
+ const value = (raw: string): YamlValue => {
+ const plain = raw.replace(/\s+#[^"']*$/, '').trim();
+ if (/^\[.*\]$/.test(plain)) return { kind: 'list', items: plain.slice(1, -1).split(',').map(item => item.trim().replace(/^(["'])(.*)\1$/, '$2')).filter(Boolean).map(item => ({ kind: 'scalar', value: item })) };
+ return { kind: 'scalar', value: plain.replace(/^(["'])(.*)\1$/, '$2') };
+ };
+ for (const raw of text.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (quoted) { if (line.split(quoted).length % 2 === 0) quoted = undefined; continue; }
+ if (!line || line.startsWith('#')) continue;
+ const table = /^(\[\[?)\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/.exec(line);
+ if (table) {
+ const entries: [string, YamlValue][] = [];
+ if (table[1] === '[[') {
+ const name = `[[${table[2]}]]`;
+ const list = root.find(([key]) => key === name)?.[1];
+ if (list?.kind === 'list') list.items.push({ kind: 'map', entries }); else root.push([name, { kind: 'list', items: [{ kind: 'map', entries }] }]);
+ } else root.push([`[${table[2]}]`, { kind: 'map', entries }]);
+ current = entries;
+ continue;
+ }
+ const key = /^([A-Za-z0-9_\-."']+)\s*=\s*(.*)$/.exec(line);
+ if (!key) continue;
+ const delimiter = ['"""', "'''"].find(mark => line.split(mark).length === 2);
+ if (delimiter) quoted = delimiter;
+ current.push([key[1], delimiter ? { kind: 'scalar', value: '' } : value(key[2])]);
+ }
+ return root.length ? { kind: 'map', entries: root } : undefined;
+}
+
+function treeOf(path: string, text: string): YamlValue | undefined {
+ switch (extension(path)) {
+ case 'yml': case 'yaml': return yamlTree(text);
+ case 'json': try { return jsonValue(JSON.parse(text)); } catch { return undefined; }
+ case 'toml': return tomlTree(text);
+ default: return undefined;
+ }
+}
+
+const isMap = (value: YamlValue): value is Extract<YamlValue, { kind: 'map' }> => value.kind === 'map';
+const scalarText = (value: YamlValue, words: Words) => value.kind === 'scalar' ? value.value === '' ? words.empty : /^[|>][-+0-9]*$/.test(value.value) ? words.text : code(value.value) : '';
+const more = (total: number, shown: number, words: Words, separator = '; ') => total > shown ? `${separator}${words.more(total - shown)}` : '';
+
+/** A mapping on one line: "repo `x`; rev `y`; hooks (1): `black` (exclude `z`)". */
+function inlineMap(value: Extract<YamlValue, { kind: 'map' }>, depth: number, words: Words): string {
+ if (!value.entries.length) return words.empty;
+ return value.entries.slice(0, FIELDS).map(([key, item]) => field(key, item, depth, words)).join('; ') + more(value.entries.length, FIELDS, words);
+}
+function field(key: string, value: YamlValue, depth: number, words: Words): string {
+ if (value.kind === 'scalar') return `${key} ${scalarText(value, words)}`;
+ if (value.kind === 'map') return depth < 2 ? `${key}: ${inlineMap(value, depth + 1, words)}` : `${key} (${words.keys(value.entries.length)})`;
+ if (!value.items.some(isMap)) return `${key}: ${value.items.slice(0, ITEMS).map(item => scalarText(item, words) || words.list(0)).join(', ')}${more(value.items.length, ITEMS, words, ', ')}`;
+ return `${key} (${value.items.length}): ${value.items.slice(0, ITEMS).map(item => named(item, depth + 1, words)).join('; ')}${more(value.items.length, ITEMS, words)}`;
+}
+/** An item of a nested list by its naming field, the others in parentheses. */
+function named(value: YamlValue, depth: number, words: Words): string {
+ if (!isMap(value)) return scalarText(value, words) || words.list(value.kind === 'list' ? value.items.length : 0);
+ const naming = NAMING.map(key => value.entries.find(([name, item]) => name === key && item.kind === 'scalar')).find(Boolean);
+ if (!naming) return depth < 3 ? `(${inlineMap(value, depth, words)})` : `(${words.keys(value.entries.length)})`;
+ const rest = value.entries.filter(entry => entry !== naming);
+ const details = rest.length && depth < 3 ? ` (${inlineMap({ kind: 'map', entries: rest }, depth, words)})` : '';
+ return `${scalarText(naming[1], words)}${details}`;
+}
+
+/** One top-level key as bullet lines. */
+function entryLines(key: string, value: YamlValue, words: Words): string[] {
+ if (value.kind === 'scalar') return [`- ${code(key)}: ${scalarText(value, words)}`];
+ if (value.kind === 'map') return [`- ${code(key)}: ${inlineMap(value, 1, words)}`];
+ if (!value.items.some(isMap)) return [`- ${code(key)} (${words.list(value.items.length)}): ${value.items.slice(0, ITEMS).map(item => scalarText(item, words) || words.list(0)).join(', ')}${more(value.items.length, ITEMS, words, ', ')}`];
+ return [`- ${code(key)} (${words.list(value.items.length)}):`, ...value.items.slice(0, ITEMS).map((item, at) => ` ${at + 1}. ${isMap(item) ? inlineMap(item, 1, words) : named(item, 1, words)}`),
+ ...value.items.length > ITEMS ? [` ${words.more(value.items.length - ITEMS)}`] : []];
+}
+
+/** The outline of a YAML, JSON or TOML file in the language of the question, or undefined
+ * for any other file and for text that does not parse. */
+export function fileOutline(path: string, text: string, language: 'en' | 'de'): string | undefined {
+ const words = fileOutlineWords[language];
+ const name = code(path.split('/').pop() ?? path);
+ if (isGithubWorkflow(path)) {
+ const facts = workflowFactLines(path, text, language === 'de' ? germanWorkflowWords : workflowWords);
+ if (facts.length) return [words.heading(name, words.kinds.workflow, lineCount(text)), facts.map(line => `- ${line}`).join('\n'), `_${words.note}_`].join('\n\n');
+ }
+ const tree = treeOf(path, text);
+ if (!tree) return undefined;
+ const kind = extension(path) === 'json' ? words.kinds.json : extension(path) === 'toml' ? words.kinds.toml : words.kinds.yaml;
+ const entries: [string, YamlValue][] = tree.kind === 'map' ? tree.entries : [['', tree]];
+ const lines: string[] = [];
+ let used = 0, shown = 0;
+ for (const [key, value] of entries.slice(0, ENTRIES)) {
+ const next = key ? entryLines(key, value, words) : value.kind === 'list' ? entryLines(name.slice(1, -1), value, words) : [`- ${scalarText(value, words)}`];
+ const size = next.join('\n').length;
+ if (used + size > BUDGET && lines.length) { lines.push(words.cut); break; }
+ lines.push(...next); used += size; shown++;
+ }
+ if (shown === Math.min(entries.length, ENTRIES) && entries.length > ENTRIES) lines.push(words.more(entries.length - ENTRIES));
+ return [words.heading(name, kind, lineCount(text)), lines.join('\n'), `_${words.note}_`].join('\n\n');
+}
diff --git a/graph-ui/src/browser-ai/galaxy-evidence.ts b/graph-ui/src/browser-ai/galaxy-evidence.ts
index b277a8e0a..ad9cd8cb1 100644
--- a/graph-ui/src/browser-ai/galaxy-evidence.ts
+++ b/graph-ui/src/browser-ai/galaxy-evidence.ts
@@ -148,16 +148,16 @@ export function sideLoaded(evidence: GalaxyEvidence, side: 'incoming' | 'outgoin
return evidence.depth > 0 && evidence.direction !== (side === 'incoming' ? 'outbound' : 'inbound');
}
-export function selectionSentence(evidence: GalaxyEvidence): string[] {
+/** What is selected, in the words of the prompt (English) or of a question (C5). */
+export function selectionSentence(evidence: GalaxyEvidence, words: RelationshipWords): string[] {
const [first] = evidence.roots;
const range = (root: GalaxyEvidence['roots'][number]) => root.filePath
? ` in ${root.filePath}${root.startLine ? `:${root.startLine}${root.endLine && root.endLine !== root.startLine ? `-${root.endLine}` : ''}` : ''}` : '';
if (evidence.rootCount <= 1 && first) {
- return [`Selected: ${first.name}${first.kind ? ` (${first.kind})` : ''}${range(first)}.`,
- ...first.documentation ? [`Documentation: ${first.documentation}`] : []];
+ return [words.selected(`${first.name}${first.kind ? ` (${first.kind})` : ''}${range(first)}`),
+ ...first.documentation ? [words.documentation(first.documentation)] : []];
}
- if (!first) return [`Selected: ${evidence.label} (${evidence.selectionKind}); its symbols are not in the loaded scope yet.`];
+ if (!first) return [words.notInScope(evidence.label, evidence.selectionKind)];
const listed = evidence.roots.map(root => `${root.name}${root.kind ? ` (${root.kind})` : ''}`).join(', ');
- const omitted = evidence.rootCount - evidence.roots.length;
- return [`Selected ${evidence.selectionKind}: ${evidence.label} with ${evidence.rootCount} symbols: ${listed}${omitted > 0 ? `; +${omitted} more` : ''}.`];
+ return [words.selectedGroup(evidence.selectionKind, evidence.label, evidence.rootCount, listed, evidence.rootCount - evidence.roots.length)];
}
diff --git a/graph-ui/src/browser-ai/grounded-explanation.test.ts b/graph-ui/src/browser-ai/grounded-explanation.test.ts
index 4fead8595..d4248c474 100644
--- a/graph-ui/src/browser-ai/grounded-explanation.test.ts
+++ b/graph-ui/src/browser-ai/grounded-explanation.test.ts
@@ -121,4 +121,25 @@ describe('the selected symbol source in a Galaxy explanation (K14)', () => {
expect(formatExplanationEvidence(prepareExplanationContext(undefined, jsonbAggRenderLimited(), 3200))).toContain(partial);
expect(selectionSummary(jsonbAggRenderLimited()).join('\n')).not.toContain('complete for the indexed graph');
});
+
+ it('checks a German sentence for the same unsupported claims and asks for it in German (C5)', () => {
+ const source = symbolSource(sourceTargetOf(jsonbAggEvidence())!, snippet, 'g1')!;
+ const packet = prepareExplanationContext(undefined, jsonbAggEvidence(), 3200, source);
+ for (const sentence of ['JSONBAgg gibt eine Liste von Werten zurück.', 'Die Rückgabe ist ein JSON-Objekt.', 'JSONBAgg nimmt Parameter entgegen.',
+ 'Die Argumente werden aggregiert.', 'Die Eingabe sind Zeilen.', 'Die Ausgabe ist JSON.', 'Der Datentyp ist JSONB.', 'Sie wird mit einer Liste von Feldern aufgerufen.']) {
+ expect(explanationSentence(sentence, packet)).toEqual({ dropped: 'unsupported' });
+ }
+ expect(explanationSentence('JSONBAgg setzt `function` auf "JSONB_AGG" und erlaubt distinct.', packet)).toEqual({ sentence: 'JSONBAgg setzt `function` auf "JSONB_AGG" und erlaubt distinct.' });
+ const german = explanationMessages(packet, { name: 'JSONBAgg', kind: 'Class' }, 'de');
+ expect(german[1].content.endsWith('Describe this class in one short sentence that starts with `JSONBAgg`. Answer in German.')).toBe(true);
+ });
+
+ it('summarizes the selection in German for a German question (C5)', () => {
+ expect(selectionSummary(jsonbAggEvidence(), 'de')).toEqual([
+ 'Ausgewählt: JSONBAgg (Class) in django/contrib/postgres/aggregates/general.py:50-54.',
+ 'Eingehende Beziehungen: 23 aus 12 Symbolen (CALLS 11, TESTS 11, DEFINES 1).',
+ 'Ausgehende Beziehungen: 2 zu 2 Symbolen (INHERITS 2).',
+ 'Ausschnitt: 1 Schritt in beide Richtungen, alle Beziehungstypen; 15 Symbole und 25 Beziehungen; vollständig für den indizierten Graphen.',
+ ]);
+ });
});
diff --git a/graph-ui/src/browser-ai/question-intent.test.ts b/graph-ui/src/browser-ai/question-intent.test.ts
new file mode 100644
index 000000000..7df40322c
--- /dev/null
+++ b/graph-ui/src/browser-ai/question-intent.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { generalQuestion, noQuestion } from './question-intent';
+
+const names = ['JSONBAgg', 'django.contrib.postgres.aggregates.general.JSONBAgg'];
+
+describe('short general questions about the selection (C5)', () => {
+ it.each([
+ 'was kannst du mir über den code sagen', 'was kansnt du mir über den code sagen', 'was macht diese klasse? sehr kurze antwort', 'Was macht diese Klasse?',
+ 'was ist das', 'erklär das', 'Erkläre mir diese Funktion', 'Erklaer das bitte kurz', 'wass macht dise klase', 'was tut diese methode?',
+ 'what does this do', 'What does this class do?', 'what is this', "what's this?", 'tell me about this code', 'explain this', 'Explain this class',
+ 'explain it briefly', 'What can you tell me about this code?', 'What does JSONBAgg do?', 'Was macht JSONBAgg?', 'was macht jsonbag?', 'explain JSONBAgg',
+ 'What does this file do?', 'was macht diese datei?', 'was kannst du mir über dieses aktuelle File sagen', 'what is in this file?', 'Describe this file',
+ ])('reads %s as a general question', prompt => {
+ expect(generalQuestion(prompt, names)).toBe('general');
+ });
+
+ it.each([
+ 'Explain this class in detail, line by line.', 'erklär mir die datei detailliert', 'Erklär diese Klasse ausführlich', 'Erklär diese Klasse Zeile für Zeile',
+ 'kannst du das genau erklären?', 'explain this file step by step', 'Summarize this file in detail',
+ ])('reads %s as a question that asks for detail', prompt => {
+ expect(generalQuestion(prompt, names)).toBe('detail');
+ });
+
+ it.each([
+ 'What does it configure?', 'Which tests use it?', 'What is in this area?', 'Hat diese Klasse Luft?', 'Who calls JSONBAgg?', 'What does test_jsonb_agg do?',
+ 'Why does JSONBAgg inherit from Aggregate?', 'Wie viele Jobs gibt es in dieser Datei?', 'Welche Jobs gibt es in dieser Datei?', 'How many jobs does this workflow have?',
+ 'Und was noch?', 'Write a test for JSONBAgg', 'what does this class do with distinct values?', 'Explain how the callers use JSONBAgg', 'test', 'what does BaseCommand do?',
+ ])('leaves %s to the other answers', prompt => {
+ expect(generalQuestion(prompt, names)).toBeUndefined();
+ });
+});
+
+describe('prompts that hold no question (C6)', () => {
+ const known = (word: string) => ['jsonbagg', 'test_jsonb_agg', 'general.py'].includes(word.toLowerCase());
+ it.each(['test', 'hallo', 'hi', '?', '...', 'Hallo du', 'ok danke', 'Thank you', 'Guten Morgen', 'tests'])('finds no question in %s', prompt => {
+ expect(noQuestion(prompt, known)).toBe(true);
+ });
+ it.each(['warum?', 'why', 'JSONBAgg', 'jsonbagg', 'test_jsonb_agg', 'explain', 'who calls it?', 'What does this do?', 'mehr', 'und?', 'test JSONBAgg'])('finds a question or a name in %s', prompt => {
+ expect(noQuestion(prompt, known)).toBe(false);
+ });
+});
diff --git a/graph-ui/src/browser-ai/question-intent.ts b/graph-ui/src/browser-ai/question-intent.ts
new file mode 100644
index 000000000..f4a05d620
--- /dev/null
+++ b/graph-ui/src/browser-ai/question-intent.ts
@@ -0,0 +1,120 @@
+import type { GalaxyEvidence } from './galaxy-evidence';
+import { typoBudget, withinEdits } from './relationship-answer';
+import { noQuestionText } from './strings';
+
+/** What a prompt asks of the current selection or open file, before any model sees it.
+ *
+ * A general question ("was macht diese Klasse?", "what does this do") got a long garbled
+ * guess from the small model, while the automatic explanation of the same selection, its
+ * listed facts and one checked sentence, was good (C5). Such questions get that shape; those
+ * that ask for detail ("line by line", "ausführlich") still go to the model. A prompt with
+ * no question at all ("test", "hallo") gets examples instead of an echo (C6). */
+
+/** Words before the name: articles, demonstratives, and what a selection or file is called. */
+const DET = 'der|die|das|den|dem|des|diese|dieser|dieses|diesen|diesem|dies|the|this|that|these|those|my|mein|meine';
+const ADJ = 'aktuelle|aktuellen|aktuelles|aktueller|ganze|ganzen|ganzes|geöffnete|geöffneten|geöffnetes|ausgewählte|ausgewählten|markierte|markierten|current|whole|entire|open|opened|selected|marked';
+const KIND = 'code|klasse|funktion|methode|datei|file|symbol|modul|module|class|function|method|node|knoten|auswahl|selection|teil|part|skript|script|workflow|konfiguration|config|configuration';
+const PRONOUN = 'das|dies|es|this|that|it|sie|ihn|hier|here';
+/** The selection or file: "diese Klasse", "the JSONBAgg class", "das", "it". */
+const OBJECT = `(?:(?:(?:${DET}) )?(?:(?:${ADJ}) )?(?:${KIND}|<name>)(?: (?:${KIND}))?|(?:${PRONOUN}))`;
+/** What may follow a general question without making it another one: "sehr kurze Antwort", "briefly". */
+const TAIL = 'bitte|please|kurz|kurze|kurzer|kurzen|knapp|knappe|sehr|antwort|einfach|mal|eigentlich|überhaupt|denn|nochmal|so|jetzt|now|again|briefly|brief|short|shortly|quick|quickly|simply|simple|in|a|an|one|sentence|einem|einen|satz|wenigen|worten|few|words|overall|insgesamt|zusammen|for|me|mir|uns|us|du';
+const END = `(?: (?:${TAIL}))*$`;
+
+const GENERAL = [
+ // German
+ String.raw`^(?:was|wass) (?:kannst|könntest|kann) (?:du|man) (?:(?:mir|uns) )?(?:(?:über|zu|von) ${OBJECT}|dazu|darüber) (?:sagen|erzählen|erklären)`,
+ String.raw`^(?:was|wass) (?:macht|tut|ist|bedeutet|enthält|steht in|passiert in) ${OBJECT}`,
+ String.raw`^(?:erklär|erkläre|erklären|erklärst|beschreib|beschreibe|fasse)(?: (?:mir|uns))?(?: bitte)?(?: mal)?(?: ${OBJECT})?(?: zusammen)?`,
+ String.raw`^(?:kannst|könntest) du (?:(?:mir|uns) )?${OBJECT}(?: (?:erklären|beschreiben|zusammenfassen))?`,
+ String.raw`^worum geht es(?: (?:in|bei) ${OBJECT})?`,
+ // English
+ String.raw`^what (?:can|could) you tell (?:me|us) about ${OBJECT}`,
+ String.raw`^(?:can|could) you (?:explain|describe|summarize|summarise) ${OBJECT}`,
+ String.raw`^tell (?:me|us) (?:more )?about ${OBJECT}`,
+ String.raw`^what (?:does|do) ${OBJECT} do`,
+ String.raw`^what is ${OBJECT}(?: (?:for|about))?`,
+ String.raw`^what is in ${OBJECT}`,
+ String.raw`^what does ${OBJECT} contain`,
+ String.raw`^(?:explain|describe|summarize|summarise)(?: to me)?(?: ${OBJECT})?`,
+].map(source => new RegExp(source + END, 'u'));
+
+/** Asking for detail: the model answers these as before. */
+const DETAIL = /(?:^| )(?:in details?|detailed|detailliert\S*|ausführlich\S*|line by line|zeile für zeile|step by step|schritt für schritt|genau(?= erklär)|im detail|in depth|thoroughly|every line|jede zeile)(?= |$)/gu;
+
+/** Words a typo is corrected to, as K16 does for "wer ruf": "kansnt" is "kannst". */
+const VOCABULARY = ['kannst', 'könntest', 'sagen', 'macht', 'klasse', 'funktion', 'methode', 'datei', 'erklär', 'erkläre', 'erklären', 'beschreib', 'beschreibe',
+ 'diese', 'dieser', 'dieses', 'diesen', 'diesem', 'über', 'erzählen', 'explain', 'describe', 'summarize', 'about', 'tell', 'what', 'does', 'this', 'that',
+ 'code', 'class', 'function', 'method', 'file', 'symbol', 'modul', 'module', 'zusammen', 'bedeutet', 'enthält', 'contain'];
+/** Words of the patterns themselves: never "corrected" into another one ("dies" is no "does"). */
+const OWN = new Set([...[DET, ADJ, KIND, PRONOUN, TAIL].flatMap(list => list.split('|')), ...VOCABULARY, 'was', 'wass', 'tut', 'ist', 'kann', 'man', 'dazu', 'darüber',
+ 'steht', 'passiert', 'worum', 'geht', 'bei', 'can', 'could', 'you', 'more', 'do', 'is', 'to', 'how', 'why', 'with', 'from', 'calls', 'call', 'used', 'uses']);
+const SPELLED = { erklaer: 'erklär', erklaere: 'erkläre', erklaeren: 'erklären', ueber: 'über', fuer: 'für', ausfuehrlich: 'ausführlich', koenntest: 'könntest', enthaelt: 'enthält' } as Record<string, string>;
+
+/** The prompt in lower case, words corrected, the selection's name as `<name>`. */
+function normalize(prompt: string, names: readonly string[]): string {
+ const own = names.flatMap(name => [name, name.split(/[./:]/).filter(Boolean).pop() ?? name]).map(name => name.toLowerCase()).filter(Boolean);
+ const text = prompt.toLowerCase().replace(/[’`"]/g, "'").replace(/\bwhat'?s\b/g, 'what is').replace(/'/g, ' ')
+ .replace(/[?!,;:()]+/g, ' ').replace(/\.+(?=\s|$)/g, ' ');
+ return text.split(/\s+/).filter(Boolean).map(word => {
+ if (own.includes(word) || own.includes(word.split(/[.:]/).pop()!)) return '<name>';
+ const spelled = SPELLED[word] ?? word;
+ if (OWN.has(spelled)) return spelled;
+ if (own.some(name => name.length >= 4 && withinEdits(word, name, typoBudget(name)))) return '<name>';
+ if (spelled.length < 4) return spelled;
+ return VOCABULARY.find(candidate => withinEdits(spelled, candidate, 1)) ?? spelled;
+ }).join(' ');
+}
+
+/** "general" for a short general question about the selection or the open file, "detail" for the
+ * same question asking for detail, undefined for any other prompt. `names` are the selection's. */
+export function generalQuestion(prompt: string, names: readonly string[]): 'general' | 'detail' | undefined {
+ const text = normalize(prompt, names);
+ const detail = new RegExp(DETAIL.source, 'u').test(text);
+ const asked = detail ? text.replace(DETAIL, ' ').replace(/\s+/g, ' ').trim() : text;
+ if (!GENERAL.some(pattern => pattern.test(asked))) return undefined;
+ return detail ? 'detail' : 'general';
+}
+
+/** Greetings and probes: a prompt of only these asks nothing. */
+const GREETINGS = new Set(['hi', 'hey', 'hello', 'hallo', 'moin', 'servus', 'huhu', 'yo', 'test', 'testing', 'tests', 'ok', 'okay', 'danke', 'thanks', 'thank', 'you',
+ 'du', 'ja', 'nein', 'yes', 'no', 'guten', 'morgen', 'tag', 'abend', 'good', 'morning', 'evening', 'there', 'bitte', 'please', 'na', 'hm', 'hmm', 'ping', 'asdf']);
+/** One word that still asks something, mostly of the answer before: "warum?", "more". */
+const ONE_WORD_QUESTION = /^(?:why|warum|wieso|weshalb|how|wie|what|was|who|wer|where|wo|when|wann|which|welche\w*|more|mehr|weiter|continue|und|and|sonst|else|details?|example|beispiel|explain\w*|erkl\S*|describe|beschreib\w*|summar\w*|zusammenfass\w*|callers?|callees?|aufrufer)$/u;
+
+/** A prompt with no question in it: no word at all ("?"), a single word that asks nothing
+ * ("test"), or only greetings ("hallo du"). The name of the selection or of a known symbol
+ * is a question about it. */
+export function noQuestion(prompt: string, known: (word: string) => boolean): boolean {
+ const words = prompt.toLowerCase().match(/[\p{L}\p{N}_][\p{L}\p{N}_.:/-]*/gu) ?? [];
+ if (!words.length) return true;
+ if (words.some(word => known(word.replace(/[.:/-]+$/, '')))) return false;
+ if (words.length === 1) return !ONE_WORD_QUESTION.test(words[0]);
+ return words.length <= 3 && words.every(word => GREETINGS.has(word));
+}
+
+/** What the examples of a prompt without a question are about. */
+export type ExampleSubject = { kind: 'galaxy' | 'other'; name: string } | { kind: 'marked' };
+
+/** "No question was recognized in "test"." and two or three questions that work for the selection (C6). */
+export function noQuestionAnswer(typed: string, language: 'en' | 'de', subject: ExampleSubject): string {
+ const text = noQuestionText[language];
+ const examples = subject.kind === 'marked' ? [text.markedDoes, text.markedInDetail]
+ : subject.kind === 'galaxy' ? [text.whatDoes(subject.name), text.whoCalls(subject.name), text.whatCalls(subject.name)]
+ : [text.whatDoes(subject.name), text.inDetail(subject.name)];
+ const shown = typed.replace(/\s+/g, ' ').replace(/["`]/g, "'").trim().slice(0, 40);
+ return `${text.heading(shown)}\n\n${examples.map(example => `- ${example}`).join('\n')}\n\n_${text.note}_`;
+}
+
+/** The names a prompt may use for what is at hand: the selection, the symbols around it, the
+ * words of the open file or attached code. A prompt that names one of them is a question. */
+export function knownNames(sources: { galaxy?: GalaxyEvidence; texts: readonly string[]; names: readonly string[] }): (word: string) => boolean {
+ const words = new Set<string>();
+ const add = (text: string) => { for (const word of text.match(/[\p{L}\p{N}_][\p{L}\p{N}_.-]*/gu) ?? []) words.add(word.toLowerCase()); };
+ sources.texts.forEach(add);
+ sources.names.forEach(name => { words.add(name.toLowerCase()); words.add((name.split(/[/.:]/).filter(Boolean).pop() ?? name).toLowerCase()); });
+ const galaxy = sources.galaxy;
+ if (galaxy) for (const group of [...galaxy.relationships.incoming, ...galaxy.relationships.outgoing]) for (const file of group.files) file.symbols.forEach(symbol => words.add(symbol.name.toLowerCase()));
+ const own = sources.names.map(name => name.toLowerCase()).filter(name => name.length >= 4);
+ return word => words.has(word.toLowerCase()) || own.some(name => withinEdits(word.toLowerCase(), name, typoBudget(name)));
+}
diff --git a/graph-ui/src/browser-ai/relationship-answer.ts b/graph-ui/src/browser-ai/relationship-answer.ts
index f56453ea3..62ff14408 100644
--- a/graph-ui/src/browser-ai/relationship-answer.ts
+++ b/graph-ui/src/browser-ai/relationship-answer.ts
@@ -83,7 +83,7 @@ const OWN_WORDS = new Set(['falls', 'fall', 'cells', 'cell', 'halls', 'hall', 'w
'aufrufen', 'rufen', 'gerufen', 'cache', 'caches']);
/** Optimal string alignment distance of at most `limit`. */
-function withinEdits(left: string, right: string, limit: number): boolean {
+export function withinEdits(left: string, right: string, limit: number): boolean {
if (Math.abs(left.length - right.length) > limit) return false;
const rows = [Array.from({ length: right.length + 1 }, (_, index) => index)];
for (let i = 1; i <= left.length; i++) {
@@ -137,7 +137,7 @@ const selectionNames = (evidence: GalaxyEvidence): string[] => [...new Set([evid
const neighbourNames = (evidence: GalaxyEvidence): Set<string> => new Set([...evidence.relationships.incoming, ...evidence.relationships.outgoing]
.flatMap(group => group.files.flatMap(file => file.symbols.map(symbol => symbol.name.toLowerCase()))));
/** How many typos a name of this length may carry and still mean it: two from seven letters on, one from four. */
-const typoBudget = (name: string) => name.length >= 7 ? 2 : name.length >= 4 ? 1 : 0;
+export const typoBudget = (name: string) => name.length >= 7 ? 2 : name.length >= 4 ? 1 : 0;
/** "jsonbgg", "JSONBAg": the selection's name with up to two typos, in any case (K16). An exact
* name of another symbol in the scope is that symbol. */
function nearSelection(word: string, evidence: GalaxyEvidence): boolean {
diff --git a/graph-ui/src/browser-ai/strings.ts b/graph-ui/src/browser-ai/strings.ts
index 480ab5bf1..e5e590ef1 100644
--- a/graph-ui/src/browser-ai/strings.ts
+++ b/graph-ui/src/browser-ai/strings.ts
@@ -63,6 +63,11 @@ const englishRelationshipWords = {
moreTypes: (count: number) => `+${en(count)} more relationship ${count === 1 ? 'type' : 'types'}`,
internal: (summary: string) => `Between the selected symbols: ${summary}.`,
beyond: (summary: string) => `Further out in the scope: ${summary}.`,
+ selected: (what: string) => `Selected: ${what}.`,
+ documentation: (text: string) => `Documentation: ${text}`,
+ notInScope: (label: string, kind: string) => `Selected: ${label} (${kind}); its symbols are not in the loaded scope yet.`,
+ selectedGroup: (kind: string, label: string, count: number, listed: string, omitted: number) =>
+ `Selected ${kind}: ${label} with ${en(count)} symbols: ${listed}${omitted > 0 ? `; +${en(omitted)} more` : ''}.`,
callersOf: (name: string) => `Callers of ${name} in the loaded graph`,
calleesOf: (name: string) => `What ${name} calls in the loaded graph`,
/** The total of a listed answer: "23 incoming relationships from 12 symbols", never "23 from 12" (C2). */
@@ -120,6 +125,11 @@ export const relationshipWords: { en: RelationshipWords; de: RelationshipWords }
moreTypes: (count: number) => `+${de(count)} weitere ${count === 1 ? 'Beziehungstyp' : 'Beziehungstypen'}`,
internal: (summary: string) => `Zwischen den ausgewählten Symbolen: ${summary}.`,
beyond: (summary: string) => `Weiter außen im Ausschnitt: ${summary}.`,
+ selected: (what: string) => `Ausgewählt: ${what}.`,
+ documentation: (text: string) => `Dokumentation: ${text}`,
+ notInScope: (label: string, kind: string) => `Ausgewählt: ${label} (${kind}); seine Symbole sind noch nicht im geladenen Ausschnitt.`,
+ selectedGroup: (kind: string, label: string, count: number, listed: string, omitted: number) =>
+ `Ausgewählt (${kind}): ${label} mit ${de(count)} Symbolen: ${listed}${omitted > 0 ? `; +${de(omitted)} weitere` : ''}.`,
callersOf: (name: string) => `Aufrufer von ${name} im geladenen Graphen`,
calleesOf: (name: string) => `Was ${name} im geladenen Graphen aufruft`,
total: (side: 'incoming' | 'outgoing', total: number, symbols?: number) => `${de(total)} ${side === 'incoming' ? 'eingehende' : 'ausgehende'} ${total === 1 ? 'Beziehung' : 'Beziehungen'}`
@@ -195,6 +205,42 @@ export const browserChatText = {
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.`,
};
+/** Who wrote which part of the answer to a general question about a selection, in its language (C5). */
+export const groundedText = {
+ en: { factsAndSentence: browserChatText.factsAndSentence, factsOnly: browserChatText.factsOnly, sentenceDropped: browserChatText.sentenceDropped,
+ writingSentence: browserChatText.writingSentence },
+ de: {
+ factsAndSentence: 'Fakten aus dem indizierten Graphen gelistet; der letzte Satz ist vom Modell erzeugt.',
+ factsOnly: 'Aus dem indizierten Graphen gelistet, nicht vom Modell erzeugt.',
+ sentenceDropped: 'Aus dem indizierten Graphen gelistet. Der Satz des Modells nannte etwas, das die Fakten nicht zeigen, und wurde weggelassen.',
+ writingSentence: 'Der Quelltext wird gelesen; das Modell fügt einen Satz hinzu…',
+ },
+};
+
+/** The reply to a prompt that asks nothing ("test", "hallo"): questions it could ask (C6). */
+export const noQuestionText = {
+ en: {
+ heading: (typed: string) => `No question was recognized in "${typed}". You can ask, for example:`,
+ note: 'Answered without the model.',
+ whatDoes: (name: string) => `What does ${name} do?`,
+ whoCalls: (name: string) => `Who calls ${name}?`,
+ whatCalls: (name: string) => `What does ${name} call?`,
+ inDetail: (name: string) => `Explain ${name} in detail.`,
+ markedDoes: 'What does the marked code do?',
+ markedInDetail: 'Explain the marked code line by line.',
+ },
+ de: {
+ heading: (typed: string) => `In "${typed}" wurde keine Frage erkannt. Frage zum Beispiel:`,
+ note: 'Ohne das Modell beantwortet.',
+ whatDoes: (name: string) => `Was macht ${name}?`,
+ whoCalls: (name: string) => `Wer ruft ${name} auf?`,
+ whatCalls: (name: string) => `Was ruft ${name} auf?`,
+ inDetail: (name: string) => `Erklär ${name} ausführlich.`,
+ markedDoes: 'Was macht der markierte Code?',
+ markedInDetail: 'Erklär den markierten Code Zeile für Zeile.',
+ },
+};
+
/** 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: {
@@ -260,6 +306,7 @@ export const architectureWords = {
};
const counted = (value: number, one: string, many: string) => `${value.toLocaleString('en-US')} ${value === 1 ? one : many}`;
+const gezaehlt = (value: number, one: string, many: string) => `${value.toLocaleString('de-DE')} ${value === 1 ? one : many}`;
/** A GitHub Actions workflow as facts counted from its keys: for the prompt and the explanation card (K12). */
export const workflowWords = {
heading: 'Facts read from the file (counted, not guessed):',
@@ -271,6 +318,45 @@ export const workflowWords = {
`${id} (${[name ? `"${name}"` : '', runsOn ? `runs on ${runsOn}` : '', counted(steps, 'step', 'steps')].filter(Boolean).join(', ')})`,
uses: (items: readonly string[]) => `Actions used: ${items.join(', ')}.`,
};
+export type WorkflowWords = typeof workflowWords;
+/** The same facts for an outline asked for in German (C7). */
+export const germanWorkflowWords: WorkflowWords = {
+ heading: 'Aus der Datei gelesene Fakten (gezählt, nicht geraten):',
+ name: (name: string) => `Name des Workflows: ${name}.`,
+ triggers: (items: readonly string[]) => `Auslöser: ${items.join(', ')}.`,
+ trigger: (event: string, types: readonly string[]) => `${event}${types.length ? ` (Typen: ${types.join(', ')})` : ''}`,
+ jobs: (total: number, items: readonly string[]) => `${gezaehlt(total, 'Job', 'Jobs')}: ${items.join('; ')}${total > items.length ? `; +${(total - items.length).toLocaleString('de-DE')} weitere` : ''}.`,
+ job: (id: string, name: string | undefined, runsOn: string | undefined, steps: number) =>
+ `${id} (${[name ? `"${name}"` : '', runsOn ? `läuft auf ${runsOn}` : '', gezaehlt(steps, 'Schritt', 'Schritte')].filter(Boolean).join(', ')})`,
+ uses: (items: readonly string[]) => `Verwendete Actions: ${items.join(', ')}.`,
+};
+
+/** The outline of a configuration file, answered from the file instead of the model (C7). */
+const englishOutlineWords = {
+ heading: (name: string, kind: string, lines: number) => `${name}: ${kind}, ${counted(lines, 'line', 'lines')}. Read from the file:`,
+ kinds: { yaml: 'YAML configuration', json: 'JSON data', toml: 'TOML configuration', workflow: 'GitHub Actions workflow' },
+ list: (total: number) => `list of ${total.toLocaleString('en-US')}`,
+ keys: (total: number) => counted(total, 'key', 'keys'),
+ empty: 'empty',
+ text: 'text block',
+ more: (total: number) => `+${total.toLocaleString('en-US')} more`,
+ cut: 'The rest of the file is left out here.',
+ note: 'Read from the file; not generated by the model.',
+};
+export const fileOutlineWords: { en: typeof englishOutlineWords; de: typeof englishOutlineWords } = {
+ en: englishOutlineWords,
+ de: {
+ heading: (name: string, kind: string, lines: number) => `${name}: ${kind}, ${gezaehlt(lines, 'Zeile', 'Zeilen')}. Aus der Datei gelesen:`,
+ kinds: { yaml: 'YAML-Konfiguration', json: 'JSON-Daten', toml: 'TOML-Konfiguration', workflow: 'GitHub-Actions-Workflow' },
+ list: (total: number) => `Liste mit ${gezaehlt(total, 'Eintrag', 'Einträgen')}`,
+ keys: (total: number) => gezaehlt(total, 'Schlüssel', 'Schlüssel'),
+ empty: 'leer',
+ text: 'Textblock',
+ more: (total: number) => `+${total.toLocaleString('de-DE')} weitere`,
+ cut: 'Der Rest der Datei ist hier ausgelassen.',
+ note: 'Aus der Datei gelesen, nicht vom Modell erzeugt.',
+ },
+};
const listed = (items: readonly string[], total: number) => `${items.join(', ')}${total > items.length ? `, +${(total - items.length).toLocaleString('en-US')} more` : ''}`;
/** A configuration or text file as facts read from its text: for the prompt and the explanation card (K12). */
diff --git a/graph-ui/src/browser-ai/workflow-facts.ts b/graph-ui/src/browser-ai/workflow-facts.ts
index fc76517a5..a7654f2a4 100644
--- a/graph-ui/src/browser-ai/workflow-facts.ts
+++ b/graph-ui/src/browser-ai/workflow-facts.ts
@@ -1,5 +1,5 @@
import { isGithubWorkflow } from './file-kind';
-import { workflowWords as words } from './strings';
+import { workflowWords as englishWorkflowWords, type WorkflowWords } from './strings';
/** A GitHub Actions workflow as facts counted from its keys. The small model answered
* "Es gibt 3 Jobs" for a file with one, and read the trigger type "opened" as a branch
@@ -84,6 +84,45 @@ export function yamlOutline(text: string): { key: string; keys: string[]; items:
});
}
+/** A YAML value as the block layout writes it: text, a list or a mapping (C7). */
+export type YamlValue = { kind: 'scalar'; value: string } | { kind: 'list'; items: YamlValue[] } | { kind: 'map'; entries: [string, YamlValue][] };
+
+/** "[a, b]" is a list, "{}" an empty mapping, "|" and ">" start a text block. */
+function scalarOf(value: string): YamlValue {
+ if (/^\[.*\]$/.test(value)) return { kind: 'list', items: flow(value).map(item => ({ kind: 'scalar', value: item })) };
+ if (value === '{}') return { kind: 'map', entries: [] };
+ return { kind: 'scalar', value };
+}
+/** The lines `indexes` as one value: a list when it starts with "- ", a mapping otherwise. */
+function valueOf(lines: readonly Line[], indexes: readonly number[]): YamlValue {
+ if (!indexes.length) return { kind: 'scalar', value: '' };
+ const first = lines[indexes[0]];
+ if (first.dash) {
+ const starts = indexes.filter(index => lines[index].dash && lines[index].indent === first.indent);
+ return { kind: 'list', items: starts.map((start, at) => {
+ const body = indexes.filter(index => index > start && index < (starts[at + 1] ?? Infinity));
+ const line = lines[start];
+ if (line.key === undefined) return body.length && !line.value ? valueOf(lines, body) : scalarOf(line.value);
+ return mappingOf(lines, [start, ...body], line.keyIndent);
+ }) };
+ }
+ return mappingOf(lines, indexes, Math.min(...indexes.map(index => lines[index].keyIndent)));
+}
+/** The keys at `level`, each with the lines below it as its value; an item's own "- key" line leads. */
+function mappingOf(lines: readonly Line[], indexes: readonly number[], level: number): YamlValue {
+ const keys = indexes.filter((index, at) => lines[index].keyIndent === level && lines[index].key !== undefined && (at === 0 || !lines[index].dash));
+ return { kind: 'map', entries: keys.map((key, at): [string, YamlValue] => {
+ const body = indexes.filter(index => index > key && index < (keys[at + 1] ?? Infinity));
+ const line = lines[key];
+ return [line.key!, line.value ? scalarOf(line.value) : valueOf(lines, body)];
+ }) };
+}
+/** The whole file as values, for an outline read from it (C7). */
+export function yamlTree(text: string): YamlValue | undefined {
+ const lines = linesOf(text);
+ return lines.length ? valueOf(lines, lines.map((_, index) => index)) : undefined;
+}
+
export function workflowFacts(text: string): WorkflowFacts | undefined {
const lines = linesOf(text);
if (!lines.length) return undefined;
@@ -113,8 +152,9 @@ export function workflowFacts(text: string): WorkflowFacts | undefined {
const quote = (value: string) => `\`${value.replace(/`/g, "'").slice(0, 120)}\``;
const LISTED = 8;
-/** The facts of a workflow file as sentences; nothing for other files. */
-export function workflowFactLines(path: string, text: string): string[] {
+/** The facts of a workflow file as sentences; nothing for other files. The prompt and the
+ * card use the English words, an outline asked for in German the German ones (C7). */
+export function workflowFactLines(path: string, text: string, words: WorkflowWords = englishWorkflowWords): string[] {
const facts = isGithubWorkflow(path) ? workflowFacts(text) : undefined;
if (!facts) return [];
const lines: string[] = [];