fix(dictionary): stream context dictionary responses (#7285)
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
CodeQL Advanced / Analyze (rust) (push) Waiting to run
Publish Docker image / build (linux/amd64, ubuntu-latest) (push) Waiting to run
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm) (push) Waiting to run
Publish Docker image / merge (push) Blocked by required conditions
Build with Nix / tests (push) Waiting to run
PR checks / test_web_app (2) (push) Waiting to run
PR checks / nix_flake_check (push) Waiting to run
PR checks / rust_lint (push) Waiting to run
PR checks / koplugin_rust_lint (push) Waiting to run
PR checks / build_web_app (push) Waiting to run
PR checks / test_web_app (1) (push) Waiting to run
PR checks / test_web_browser (push) Waiting to run
PR checks / test_extensions (push) Waiting to run
PR checks / build_tauri_app (push) Waiting to run
Scorecard supply-chain security / Scorecard analysis (push) Waiting to run
Deploy to vercel on merge / build_and_deploy (push) Waiting to run

* fix(dictionary): stream context dictionary responses

Request SSE from custom OpenAI-compatible endpoints and reveal structured
entries or sanitized Markdown while generation is still running. Reset the
60-second timeout on stream activity, including reasoning, and preserve
cancellation, final validation, cache integrity, and thinking-option fallback.

Verification on current origin/main:
- New SSE regression fails without the change: expected undefined to be true
  for the request's stream flag; passes with the change.
- Six affected test files: 88 tests passed.
- Full unit suite: 1233 files passed, 4 skipped; 14992 tests passed, 16 skipped.
- pnpm lint, changed-file formatting, and git diff --check passed.
- Google Chrome with local Ollama qwen3 streamed and completed both built-in
  JSON and custom Markdown; partial content appeared before completion.
- Controlled SSE browser checks covered cancellation and phone dark/e-ink/RTL.
- Gemma3 streamed Markdown successfully but returned malformed final JSON,
  which retained the existing visible validation error.
- Native iOS and Tauri were not exercised.

Fixes #7279
Reported by noideaforeal on GitHub

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(dictionary): preserve streamed provider error messages

Normalize structured SSE errors into Error instances so the dictionary shows
the provider's explanation instead of [object Object]. Preserve existing Error
instances and their HTTP status for the thinking-option fallback.

Verification:
- New regression fails before the fix: expected the structured provider error
  to be an instance of Error; passes after normalization and checks the message.
- Six affected suites: 89 tests passed.
- git diff --check passed. The push hook runs lint and the full unit suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

* fix(dictionary): clear partial entries when streaming fails

Remove incomplete context dictionary content before displaying a stream,
timeout, or final-validation failure. Keep the aborted-request guard so an
older lookup cannot clear the next lookup's container.

Verification:
- Three new regression cases fail before the change because the partial
  definition remains visible after an error, and pass with the change.
- Added cancellation regression preserves the next lookup's content.
- Three affected suites: 55 tests passed; git diff --check passed.
- The required push hook runs formatting, lint, and the full unit suite.

Co-Authored-By: Claude Code <noreply@anthropic.com>

---------

Co-authored-by: Claude Code <noreply@anthropic.com>
This commit is contained in:
Huang Xin 2026-11-03 20:13:34 +08:00 • committed by GitHub
parent 7a0e98f533
commit 617db1aa3c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
10 changed files with 430 additions and 9 deletions

View file

@ -745,6 +745,35 @@ describe('DictionarySheet — empty state', () => {
});
});
describe('DictionarySheet — streaming results', () => {
it('reveals an entry while its provider is still generating (#7279)', async () => {
let context!: DictionaryLookupContext;
let finish!: (outcome: DictionaryLookupOutcome) => void;
providersForNextRender.push({
id: 'streaming',
kind: 'builtin',
label: 'Streaming',
lookup(_word, ctx) {
context = ctx;
return new Promise((resolve) => {
finish = resolve;
});
},
});
renderSheet({ word: 'bank' });
await waitFor(() => expect(context).toBeDefined());
await act(async () => {
context.container.textContent = 'A river side';
(context as DictionaryLookupContext & { onUpdate?: () => void }).onUpdate?.();
});
expect(context.container.classList.contains('hidden')).toBe(false);
expect(screen.queryByTestId('dict-card-skeleton')).toBeNull();
await act(async () => {
finish({ ok: true });
});
});
});
describe('DictionarySheet — abort on unmount', () => {
it('aborts in-flight provider lookups when the sheet unmounts', async () => {
const observer = { aborted: false };

View file

@ -0,0 +1,218 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const { fetchMock } = vi.hoisted(() => ({ fetchMock: vi.fn() }));
vi.mock('@/services/ai/utils/httpFetch', () => ({ getAIFetch: () => fetchMock }));
import {
__clearContextCacheForTests,
lookupInContext,
} from '@/services/dictionaries/contextDictionary';
import type { CustomTranslator } from '@/types/translation';
import { loadSDK } from '@/services/translators/custom/openaiCompatible';
const translator: CustomTranslator = {
id: 'stream-test',
type: 'openai-compatible',
name: 'Local model',
baseUrl: 'http://localhost:11434/v1',
model: 'local',
addedAt: 1,
updatedAt: 1,
};
const input = { text: 'bank', before: 'river', after: '', targetLang: 'en' };
const responseStream = () => {
let controller!: ReadableStreamDefaultController<Uint8Array>;
const body = new ReadableStream<Uint8Array>({
start(c) {
controller = c;
},
});
const send = (delta: Record<string, string>, finishReason: string | null = null) => {
const data = JSON.stringify({
id: 'test',
created: 1,
model: 'local',
choices: [{ index: 0, delta, finish_reason: finishReason }],
});
controller.enqueue(new TextEncoder().encode(`data: ${data}\n\n`));
};
return {
response: new Response(body, { headers: { 'Content-Type': 'text/event-stream' } }),
send,
fail(error: Error) {
controller.error(error);
},
finish() {
send({}, 'stop');
controller.close();
},
};
};
// Flush the real SDK's stream pipeline without advancing request timers.
const settle = async () => {
await vi.advanceTimersByTimeAsync(0);
};
describe('context dictionary streaming (#7279)', () => {
beforeEach(async () => {
await loadSDK();
vi.useFakeTimers();
fetchMock.mockReset();
__clearContextCacheForTests();
});
afterEach(() => {
vi.useRealTimers();
});
it('requests SSE and publishes a partial JSON entry before generation finishes', async () => {
const stream = responseStream();
fetchMock.mockImplementation(async (_url, init: RequestInit) => {
if (JSON.parse(String(init.body)).stream) return stream.response;
return new Response(
JSON.stringify({
choices: [
{
message: { role: 'assistant', content: '{"definition":"river side"}' },
finish_reason: 'stop',
},
],
}),
{ headers: { 'Content-Type': 'application/json' } },
);
});
const onUpdate = vi.fn();
const options = {
onUpdate,
};
const pending = lookupInContext(translator, input, new AbortController().signal, options);
await settle();
expect(JSON.parse(fetchMock.mock.calls[0]![1].body).stream).toBe(true);
stream.send({ content: '{"headword":"bank","definition":"the river' });
await settle();
expect(onUpdate).toHaveBeenLastCalledWith(expect.objectContaining({ definition: 'the river' }));
stream.send({ content: ' side","examples":[],"synonyms":[]}' });
stream.finish();
expect((await pending).definition).toBe('the river side');
});
it('keeps an active response alive beyond 60 seconds, including reasoning chunks', async () => {
const stream = responseStream();
fetchMock.mockResolvedValue(stream.response);
const pending = lookupInContext(translator, input, new AbortController().signal);
const outcome = pending.then(
(value) => value,
(error) => error,
);
await settle();
await vi.advanceTimersByTimeAsync(45_000);
stream.send({ reasoning_content: 'Working out the sense' });
await settle();
await vi.advanceTimersByTimeAsync(45_000);
const signal = fetchMock.mock.calls[0]![1].signal as AbortSignal;
expect(signal.aborted).toBe(false);
stream.send({ content: '{"definition":"river side"}' });
stream.finish();
expect(await outcome).toMatchObject({ definition: 'river side' });
await vi.advanceTimersByTimeAsync(120_000);
expect(signal.aborted).toBe(false);
});
it('streams custom Markdown while withholding an incomplete leading reasoning block', async () => {
const stream = responseStream();
fetchMock.mockResolvedValue(stream.response);
const onUpdate = vi.fn();
const options = {
systemPrompt: 'Explain the meaning.',
onUpdate,
};
const pending = lookupInContext(translator, input, new AbortController().signal, options);
await settle();
stream.send({ content: '<think>private reasoning' });
await settle();
expect(onUpdate).not.toHaveBeenCalled();
stream.send({ content: '</think>\n**River**' });
await settle();
expect(onUpdate).toHaveBeenLastCalledWith(expect.objectContaining({ markdown: '**River**' }));
stream.finish();
await pending;
});
it('times out an idle stream and still cancels when the popup closes', async () => {
for (const closePopup of [false, true]) {
const stream = responseStream();
fetchMock.mockResolvedValueOnce(stream.response);
const caller = new AbortController();
const pending = lookupInContext(translator, input, caller.signal);
const assertion = expect(pending).rejects.toThrow();
await settle();
stream.send({ content: '{"definition":"partial' });
await settle();
const signal = fetchMock.mock.calls.at(-1)![1].signal as AbortSignal;
if (closePopup) caller.abort();
else await vi.advanceTimersByTimeAsync(60_001);
expect(signal.aborted).toBe(true);
stream.finish();
await assertion;
}
});
it('retries without the thinking parameter when the streaming endpoint rejects it', async () => {
const stream = responseStream();
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ error: { message: 'reasoning_effort unsupported' } }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
}),
)
.mockResolvedValueOnce(stream.response);
const pending = lookupInContext(
{ ...translator, thinking: 'off' },
input,
new AbortController().signal,
);
await settle();
expect(fetchMock).toHaveBeenCalledTimes(2);
expect(JSON.parse(fetchMock.mock.calls[0]![1].body).reasoning_effort).toBe('none');
expect(JSON.parse(fetchMock.mock.calls[1]![1].body).reasoning_effort).toBeUndefined();
stream.send({ content: '{"definition":"river side"}' });
stream.finish();
expect(await pending).toMatchObject({ definition: 'river side' });
});
it('preserves the message of an error sent inside an SSE response', async () => {
fetchMock.mockResolvedValue(
new Response('data: {"error":{"message":"Insufficient credits","code":402}}\n\n', {
headers: { 'Content-Type': 'text/event-stream' },
}),
);
const pending = lookupInContext(translator, input, new AbortController().signal);
const outcome = pending.catch((error: unknown) => error);
await settle();
const error = await outcome;
expect(error).toBeInstanceOf(Error);
expect(String(error)).toContain('Insufficient credits');
});
it('surfaces a stream error and does not cache the partial answer', async () => {
const stream = responseStream();
fetchMock
.mockResolvedValueOnce(stream.response)
.mockResolvedValueOnce(
new Response(JSON.stringify({ error: { message: 'bad model' } }), { status: 401 }),
);
const pending = lookupInContext(translator, input, new AbortController().signal);
const assertion = expect(pending).rejects.toThrow();
await settle();
stream.send({ content: '{"definition":"partial' });
await settle();
stream.fail(new Error('connection lost'));
await assertion;
await expect(
lookupInContext(translator, input, new AbortController().signal),
).rejects.toThrow();
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});

View file

@ -4,7 +4,16 @@ const { generateTextMock } = vi.hoisted(() => ({ generateTextMock: vi.fn() }));
vi.mock('ai', async (importOriginal) => {
const actual = await importOriginal<typeof import('ai')>();
return { ...actual, generateText: generateTextMock };
return {
...actual,
generateText: generateTextMock,
streamText: (args: unknown) => ({
fullStream: (async function* () {
const { text } = await generateTextMock(args);
yield { type: 'text-delta', text };
})(),
}),
};
});
vi.mock('@/services/ai/utils/httpFetch', () => ({ getAIFetch: () => vi.fn() }));

View file

@ -128,6 +128,7 @@ describe('context dictionary provider', () => {
expect(mocks.lookupInContext.mock.calls[0]![3]).toEqual({
systemPrompt: 'Explain etymology.',
maxOutputTokens: 4096,
onUpdate: expect.any(Function),
});
expect(container.querySelector('h2')?.textContent).toBe('Origins');
expect(container.querySelector('strong')?.textContent).toBe('River');
@ -173,6 +174,63 @@ describe('context dictionary provider', () => {
expect(container.textContent).toContain('Unauthorized');
});
it.each([
'connection lost',
'Request cancelled',
'The AI provider returned an invalid reply.',
])('clears a partial entry before displaying a lookup failure: %s', async (message) => {
setTranslators([llm('a')]);
const container = document.createElement('div');
mocks.lookupInContext.mockImplementation(async (_translator, _input, _signal, options) => {
options.onUpdate(entry);
expect(container.textContent).toContain(entry.definition);
throw new Error(message);
});
expect((await lookup(container)).ok).toBe(true);
expect(container.textContent).toContain(`Context Dictionary failed: ${message}`);
expect(container.textContent).not.toContain(entry.definition);
expect(container.querySelector('h1')).toBeNull();
});
it('leaves the next lookup content untouched when an aborted stream rejects', async () => {
setTranslators([llm('a')]);
const controller = new AbortController();
const container = document.createElement('div');
mocks.lookupInContext.mockImplementation(async (_translator, _input, _signal, options) => {
options.onUpdate(entry);
controller.abort();
container.textContent = 'Next lookup';
throw new Error('Request cancelled');
});
const outcome = await contextProvider.lookup('bank', { container, signal: controller.signal });
expect(outcome.ok).toBe(false);
expect(container.textContent).toBe('Next lookup');
});
it('replaces partial entries, sanitizes streamed Markdown, and ignores late updates after cancellation', async () => {
setTranslators([llm('a')]);
const caller = new AbortController();
const container = document.createElement('div');
const onUpdate = vi.fn();
mocks.lookupInContext.mockImplementation(async (_translator, _input, _signal, options) => {
options.onUpdate({ ...entry, markdown: '**River** <img src=x onerror="alert(1)">' });
expect(container.querySelector('strong')?.textContent).toBe('River');
expect(container.querySelector('[onerror]')).toBeNull();
options.onUpdate(entry);
expect(container.querySelectorAll('h1')).toHaveLength(1);
caller.abort();
options.onUpdate({ ...entry, definition: 'stale answer' });
expect(container.textContent).not.toContain('stale answer');
return entry;
});
expect(
(await contextProvider.lookup('bank', { container, signal: caller.signal, onUpdate })).ok,
).toBe(false);
expect(onUpdate).toHaveBeenCalledTimes(2);
});
it('does not render an entry for a lookup cancelled while it was pending', async () => {
setTranslators([llm('a')]);
const controller = new AbortController();

View file

@ -62,9 +62,25 @@ describe('custom translator thinking off', () => {
});
it('applies to the AI context dictionary too', async () => {
fetchMock.mockImplementation(async () =>
reply(JSON.stringify({ headword: 'bank', definition: 'the land beside a river' })),
);
fetchMock.mockImplementation(async () => {
const chunk = JSON.stringify({
id: 'x',
created: 0,
model: 'm',
choices: [
{
index: 0,
delta: {
content: JSON.stringify({ headword: 'bank', definition: 'the land beside a river' }),
},
finish_reason: 'stop',
},
],
});
return new Response(`data: ${chunk}\n\ndata: [DONE]\n\n`, {
headers: { 'content-type': 'text/event-stream' },
});
});
await lookupInContext(
{
id: 't',

View file

@ -350,6 +350,14 @@ export function useDictionaryResults({
fg: themeCode.fg,
autoPlayPronunciation: autoPlayPronunciation && provider.id === autoPlayProviderId,
selection: currentSelection,
onUpdate: () => {
if (controller.signal.aborted) return;
setCards((prev) => {
const old = prev[provider.id];
if (!old || old.loadKey !== loadKey || old.state !== 'loading') return prev;
return { ...prev, [provider.id]: { ...old, state: 'loaded' } };
});
},
});
if (controller.signal.aborted) return;
if (outcome.ok || outcome.reason !== 'empty') break;

View file

@ -9,7 +9,11 @@
import type { CustomTranslator } from '@/types/translation';
import { md5Fingerprint } from '@/utils/md5';
import { renderPrompt } from '@/services/translators/custom/prompts';
import { generateChatText, stripReasoning } from '@/services/translators/custom/openaiCompatible';
import {
generateChatText,
loadSDK,
stripReasoning,
} from '@/services/translators/custom/openaiCompatible';
const REQUEST_TIMEOUT_MS = 60_000;
const MAX_CACHE_ENTRIES = 100;
@ -46,6 +50,7 @@ export interface ContextLookupInput {
export interface ContextLookupOptions {
systemPrompt?: string;
maxOutputTokens?: number;
onUpdate?: (entry: ContextEntry) => void;
}
export interface ContextEntry {
@ -123,6 +128,10 @@ export const parseContextEntry = (reply: string): ContextEntry => {
} catch {
throw new Error('The AI provider returned an invalid reply.');
}
return readContextEntry(parsed);
};
const readContextEntry = (parsed: unknown): ContextEntry => {
if (!isRecord(parsed)) throw new Error('The AI provider returned an invalid reply.');
const definition = readString(parsed, 'definition');
if (!definition) throw new Error('The AI provider returned an incomplete entry.');
@ -190,16 +199,44 @@ export const lookupInContext = async (
// finished request's signal fires (see openaiCompatible.ts).
const controller = new AbortController();
const abort = () => controller.abort();
const timer = setTimeout(abort, REQUEST_TIMEOUT_MS);
let timer = setTimeout(abort, REQUEST_TIMEOUT_MS);
const onProgress = () => {
clearTimeout(timer);
timer = setTimeout(abort, REQUEST_TIMEOUT_MS);
};
signal.addEventListener('abort', abort, { once: true });
try {
const [{ parsePartialJson }] = await loadSDK();
const text = await generateChatText(translator, {
system,
prompt,
maxOutputTokens,
maxRetries: 1,
abortSignal: controller.signal,
onProgress,
onText: async (reply) => {
if (!options.onUpdate || signal.aborted) return;
const markdown = stripReasoning(reply);
// A leading reasoning block may itself arrive across several chunks.
if (!markdown || '<think>'.startsWith(markdown) || markdown.startsWith('<think>')) return;
if (customPrompt) {
options.onUpdate({
headword: input.text,
definition: '',
examples: [],
synonyms: [],
markdown,
});
return;
}
const start = markdown.indexOf('{');
if (start < 0) return;
const { value } = await parsePartialJson(markdown.slice(start).replace(/\s*```\s*$/, ''));
if (!isRecord(value) || !readString(value, 'definition') || signal.aborted) return;
options.onUpdate(readContextEntry(value));
},
});
signal.throwIfAborted();
const markdown = stripReasoning(text);
if (!markdown) throw new Error('The AI provider returned an incomplete entry.');
const entry: ContextEntry = customPrompt

View file

@ -112,17 +112,28 @@ export const contextProvider: DictionaryProvider = {
bookAuthor: selection?.bookAuthor,
},
ctx.signal,
{ systemPrompt, maxOutputTokens: settings.contextMaxOutputTokens },
{
systemPrompt,
maxOutputTokens: settings.contextMaxOutputTokens,
onUpdate: (entry) => {
if (ctx.signal.aborted) return;
ctx.container.replaceChildren();
renderEntry(ctx.container, word, entry);
ctx.onUpdate?.();
},
},
);
// A cache hit resolves without looking at the signal; once cancelled,
// the container belongs to the next lookup.
if (ctx.signal.aborted) return { ok: false, reason: 'error', message: 'aborted' };
ctx.container.replaceChildren();
renderEntry(ctx.container, word, entry);
return { ok: true, headword: entry.headword || word, sourceLabel: translator.name };
} catch (err) {
if (ctx.signal.aborted) return { ok: false, reason: 'error', message: 'aborted' };
// Unlike a dictionary miss, a failed AI request (bad key, quota, model
// name) is something the user has to fix, so it stays visible.
ctx.container.replaceChildren();
append(
ctx.container,
'p',

View file

@ -24,6 +24,8 @@ export interface DictionaryLookupContext {
signal: AbortSignal;
/** Tab pane to render into. Provider populates this; never touch `document` selectors. */
container: HTMLElement;
/** Reveal content written while an incremental lookup is still running. */
onUpdate?(): void;
/**
* Called when the provider intercepts an in-popup link click and wants the
* shell to navigate (push to per-tab history). Optional — providers without

View file

@ -98,12 +98,45 @@ export const generateChatText = async (
maxOutputTokens?: number;
maxRetries: number;
abortSignal: AbortSignal;
/** When provided, request SSE and publish the accumulated answer. */
onText?: (text: string) => void | Promise<void>;
onProgress?: () => void;
},
): Promise<string> => {
const [{ generateText }] = await loadSDK();
const [{ generateText, streamText }] = await loadSDK();
const { onText, onProgress, ...settings } = options;
const run = async (thinkingOff: boolean) => {
const model = await createChatModel(config, thinkingOff);
const { text } = await generateText({ ...options, model, temperature: config.temperature });
const args = { ...settings, model, temperature: config.temperature };
if (!onText) {
const { text } = await generateText(args);
return text;
}
let text = '';
// textStream omits error events, including a rejected thinking parameter.
for await (const part of streamText(args).fullStream) {
if (part.type === 'error') {
const error = part.error;
if (
!(error instanceof Error) &&
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof error.message === 'string'
) {
throw new Error(error.message);
}
throw error;
}
settings.abortSignal.throwIfAborted();
if (part.type === 'abort') throw new DOMException('Aborted', 'AbortError');
onProgress?.();
if (part.type === 'text-delta') {
text += part.text;
await onText(text);
}
}
settings.abortSignal.throwIfAborted();
return text;
};
const key = `${config.baseUrl}\n${config.model}`;