diff --git a/apps/readest-app/src/__tests__/app/reader/annotator/DictionarySheet.test.tsx b/apps/readest-app/src/__tests__/app/reader/annotator/DictionarySheet.test.tsx index 677902d72..47f9681ab 100644 --- a/apps/readest-app/src/__tests__/app/reader/annotator/DictionarySheet.test.tsx +++ b/apps/readest-app/src/__tests__/app/reader/annotator/DictionarySheet.test.tsx @@ -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 }; diff --git a/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary-streaming.test.ts b/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary-streaming.test.ts new file mode 100644 index 000000000..08e094877 --- /dev/null +++ b/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary-streaming.test.ts @@ -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; + const body = new ReadableStream({ + start(c) { + controller = c; + }, + }); + const send = (delta: Record, 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: 'private reasoning' }); + await settle(); + expect(onUpdate).not.toHaveBeenCalled(); + stream.send({ content: '\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); + }); +}); diff --git a/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary.test.ts b/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary.test.ts index 6f6e6a188..0b5cb213e 100644 --- a/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary.test.ts +++ b/apps/readest-app/src/__tests__/services/dictionaries/contextDictionary.test.ts @@ -4,7 +4,16 @@ const { generateTextMock } = vi.hoisted(() => ({ generateTextMock: vi.fn() })); vi.mock('ai', async (importOriginal) => { const actual = await importOriginal(); - 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() })); diff --git a/apps/readest-app/src/__tests__/services/dictionaries/contextProvider.test.ts b/apps/readest-app/src/__tests__/services/dictionaries/contextProvider.test.ts index 7ea1a0282..b27ebef60 100644 --- a/apps/readest-app/src/__tests__/services/dictionaries/contextProvider.test.ts +++ b/apps/readest-app/src/__tests__/services/dictionaries/contextProvider.test.ts @@ -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** ' }); + 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(); diff --git a/apps/readest-app/src/__tests__/services/translators/custom/thinking.test.ts b/apps/readest-app/src/__tests__/services/translators/custom/thinking.test.ts index 6517db955..3677f6420 100644 --- a/apps/readest-app/src/__tests__/services/translators/custom/thinking.test.ts +++ b/apps/readest-app/src/__tests__/services/translators/custom/thinking.test.ts @@ -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', diff --git a/apps/readest-app/src/app/reader/components/annotator/DictionaryResultsView.tsx b/apps/readest-app/src/app/reader/components/annotator/DictionaryResultsView.tsx index 713f8f256..a51319b36 100644 --- a/apps/readest-app/src/app/reader/components/annotator/DictionaryResultsView.tsx +++ b/apps/readest-app/src/app/reader/components/annotator/DictionaryResultsView.tsx @@ -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; diff --git a/apps/readest-app/src/services/dictionaries/contextDictionary.ts b/apps/readest-app/src/services/dictionaries/contextDictionary.ts index 2bb2d72ec..988cbc0a9 100644 --- a/apps/readest-app/src/services/dictionaries/contextDictionary.ts +++ b/apps/readest-app/src/services/dictionaries/contextDictionary.ts @@ -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 || ''.startsWith(markdown) || markdown.startsWith('')) 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 diff --git a/apps/readest-app/src/services/dictionaries/providers/contextProvider.ts b/apps/readest-app/src/services/dictionaries/providers/contextProvider.ts index bde91db83..61ef410d3 100644 --- a/apps/readest-app/src/services/dictionaries/providers/contextProvider.ts +++ b/apps/readest-app/src/services/dictionaries/providers/contextProvider.ts @@ -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', diff --git a/apps/readest-app/src/services/dictionaries/types.ts b/apps/readest-app/src/services/dictionaries/types.ts index 36a633536..a35da24eb 100644 --- a/apps/readest-app/src/services/dictionaries/types.ts +++ b/apps/readest-app/src/services/dictionaries/types.ts @@ -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 diff --git a/apps/readest-app/src/services/translators/custom/openaiCompatible.ts b/apps/readest-app/src/services/translators/custom/openaiCompatible.ts index e732e6a24..85b506277 100644 --- a/apps/readest-app/src/services/translators/custom/openaiCompatible.ts +++ b/apps/readest-app/src/services/translators/custom/openaiCompatible.ts @@ -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; + onProgress?: () => void; }, ): Promise => { - 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}`;