Spaces:
Running
Running
Sync from felladrin/MiniSearch@7e8885e
Browse filesFiles changed (43)
- .github/workflows/deploy-to-hugging-face.yml+18
- .source-commitAdded+1
- Dockerfile+2-2
- changelog.md+4
- client/components/AiResponse/ChatInputArea.test.tsx+16-34
- client/components/AiResponse/ChatInterface.test.tsx+121-85
- client/components/AiResponse/MessageList.test.tsx+15-11
- client/components/DictationButton.test.tsx+66-100
- client/components/Pages/Main/MainPage.test.tsx+10-12
- client/components/Pages/Main/Menu/ClearDataButton.test.tsx+11-24
- client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx+12-12
- client/components/Search/Form/SearchForm.test.tsx+2-6
- client/components/Search/History/HistoryDrawer.test.tsx+17-18
- client/components/Search/Results/Graphical/ImageResultsList.test.tsx+11-8
- client/components/Search/Results/Graphical/ImageSearchResults.test.tsxAdded+67
- client/components/Search/Results/Graphical/ImageSearchResults.tsx+6
- client/components/Search/Results/testUtils.ts+3-12
- client/enterToSubmitCases.tsAdded+10
- client/hooks/useSearchHistory.test.ts+14-20
- client/matchMediaStub.tsAdded+22
- client/modules/accessKey.test.ts+9-6
- client/modules/chatHelpers.test.ts+55-34
- client/modules/chatHelpers.ts+5-11
- client/modules/history.test.ts+52-67
- client/modules/pubSub.test.ts+28-14
- client/modules/pubSub.throttle.test.ts+17-10
- client/modules/search.test.ts+17-36
- client/modules/speechToText.test.ts+23-44
- client/modules/speechToText.ts+1-1
- client/modules/textGeneration.chatBudget.test.ts+90-118
- client/modules/textGeneration.degradation.test.ts+86-125
- client/modules/textGeneration.inference.test.ts+17-39
- client/modules/textGeneration.responsePersistence.test.ts+11-22
- client/modules/textGenerationTestUtils.tsAdded+121
- client/modules/textGenerationUtilities.test.ts+15-18
- client/modules/textGenerationWithHorde.test.ts+122-220
- client/modules/textGenerationWithInternalApi.test.ts+23-33
- client/modules/textGenerationWithWllama.test.ts+5-9
- client/modules/textToSpeech.test.ts+143-151
- client/setupTests.ts+2-10
- client/testMocks.tsAdded+40
- docs/configuration.md+13-13
- docs/development-commands.md+1-1
25 unmodified lines26272829303132333435363738394041424344454647484925 unmodified lines { echo '---'; cat .github/hf-space-config.yml; echo '---'; echo; cat README.md; } > README.space.md mv README.space.md README.md
# The file is generated here and must never be committed to the source # repository: a committed copy would freeze the reported commit for every # later build. It is not in .gitignore on purpose, because the upload has # to carry it and whether `hf upload` honours .gitignore is not something # this project should depend on. - name: Refuse a source commit file committed to the repository run: | if [ -e .source-commit ]; then echo "::error::.source-commit is written by this workflow; remove it from the repository." exit 1 fi
# The Space builds from this copy, so its own git history is the Space's, # not the source's. The build reads this file instead of its git history # to report which commit is running (shared/buildSourceCommit.ts). - name: Record the source commit for the Space build run: git rev-parse --short "$GITHUB_SHA" > .source-commit
- name: Sync to the Space run: | hf upload "$HF_SPACE" . . \17e8885e124 unmodified lines125126127128129128129130131132124 unmodified lines# at preview time stay because `npm start` runs `vite preview` and the server# hooks load with the config.RUN git config --global --add safe.directory ${APP_DIR} 2>/dev/null || true; \ git rev-parse --short HEAD >/dev/null 2>&1 || \ echo "WARNING: no usable git repository in the build context, so the app will report an empty commit hash."; \ { git rev-parse --short HEAD >/dev/null 2>&1 || [ -f .source-commit ]; } || \ echo "WARNING: no usable git repository and no .source-commit in the build context, so the app will report an empty commit hash."; \ npm run build && \ npm prune --omit=dev
3 unmodified lines456789101112133 unmodified lines
## 2026-11-27
- `/status` now says what kind of software its rejections come from, under `authorization.rejectedByClient`: `bot`, `curl`, `wget`, `python`, `node`, `java`, `go`, `browser` or `other`. A high rate of token rejections used to tell you something was hammering the instance and nothing more; now it tells you what that something claims to be, which is usually enough to tell a script from a browser tab. The client's own user-agent string is sorted into one of those labels and dropped, so the page still publishes no address, no token and no visitor string.- `/status` and the app version now report the commit the code came from, even on a Hugging Face Space. A Space is built from a copy of the repository, so its build used to name a commit of that copy, which nobody could look up in the source repository. The deploy workflow now records the source commit with the copy, and the build reports that.- Images found by a follow-up question are no longer lost when a second follow-up is sent before they arrive. The second follow-up's image search took over, so when the first one's images landed they were dropped, on screen and in history. They are now added to the list either way.- Images found by a follow-up question now show even when the first image search failed. The "Failed to search for images" alert stayed for the rest of the visit and hid them, although they were saved and showed after restoring the search. The alert now shows only while there are no images.- Restoring another search from history while a follow-up is being answered now stops that follow-up. The old chat stayed on screen under the restored search, so sending was blocked until the old answer ended, and that answer was built from the restored search's results and then suggested a question about the old search. The follow-up is now cancelled when the restore switches searches: its question is saved under its own search with "The answer was interrupted.", and the restored chat can be used at once.
## 2026-11-261234456783 unmodified lines1213141516171819202122232425262728293031323334353637383940411516171819202122232425262728293031113 unmodified lines145146147161162163164165166148149150151import { MantineProvider } from "@mantine/core";import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { useSyncExternalStore } from "react";import ChatInputArea from "@/components/AiResponse/ChatInputArea";import { ENTER_TO_SUBMIT_CASES } from "@/enterToSubmitCases";import { chatGenerationStatePubSub, chatInputPubSub,3 unmodified linesimport { defaultSettings } from "@/modules/settings";import { getDictationEngine, startDictation } from "@/modules/speechToText";
vi.mock("@/modules/speechToText", async () => { const { DictationError: RealDictationError } = await import( "@/modules/speechToText" ); return { DictationError: RealDictationError, getDictationEngine: vi.fn(() => "wasm" as const), startDictation: vi.fn(), };});
vi.mock("@mantine/notifications", () => ({ notifications: { show: vi.fn() },}));
/** Subscribes for real, so a channel written mid-test re-renders the area. */vi.mock("create-pubsub/react", () => ({ usePubSub: (pubSub: [unknown, unknown, unknown]) => { const [publish, subscribe, get] = pubSub as [ unknown, (listener: () => void) => () => void, () => unknown, ]; const value = useSyncExternalStore(subscribe, get, get); return [value, publish]; },}));// jscpd:ignore-start// Vitest hoists every vi.mock call above the imports, so the registration has// to be written out in each file; only the factory body can be shared, and it// is. The duplication is the framework's, not the tests'.vi.mock("@/modules/speechToText", async () => (await import("@/testMocks")).speechToTextMock(),);vi.mock("@mantine/notifications", async () => (await import("@/testMocks")).notificationsStub(),);vi.mock("create-pubsub/react", async () => (await import("@/testMocks")).pubSubReactMock(),);// jscpd:ignore-end
const stopFn = vi.fn();const cancelFn = vi.fn();113 unmodified lines settingsPubSub[0]({ ...defaultSettings }); });
it.each([ [true, "{Enter}", true], [true, "{Shift>}{Enter}{/Shift}", false], [false, "{Shift>}{Enter}{/Shift}", true], [false, "{Enter}", false], ])( it.each(ENTER_TO_SUBMIT_CASES)( "with enterToSubmit %s, pressing %s sends it: %s", async (enterToSubmit, keys, sends) => { settingsPubSub[0]({ ...defaultSettings, enterToSubmit });121 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123234 unmodified lines26726826916516616716816917017117217317427027127227326 unmodified lines300301302207208209210211212213303304305306143 unmodified lines4504514523633643653663673683693703713724534544554564578 unmodified lines46646746838738838939046947047147247347447539739839940040140240340440547647747847948048 unmodified lines5295305314604614624634644654664674684694704714725325335345355362 unmodified lines53954054148148248348454254354454576 unmodified lines6226236245675685695705716256266276286296306315785795806326336346354 unmodified lines64064164259159259359459559664364464564615 unmodified lines6626636646186196206216226656666676686696706716296306316726736746752 unmodified lines678679680640641642643644645681682683684121 unmodified lines );}
/** * Mounts the chat with one follow-up question in flight. Returns the deferred * that settles the question, plus the render's `unmount`. */async function mountWithFollowUpInFlight() { const question = deferred<string>(); vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(question.promise);
const view = renderChatInterface({ suppressInitialFollowUp: false });
await act(async () => {});
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); return { question, unmount: view.unmount };}
/** * Mounts the chat with two follow-up questions in flight, oldest first, and * returns both deferreds. */async function mountWithTwoFollowUpsInFlight() { const earlierQuestion = deferred<string>(); const newerQuestion = deferred<string>(); vi.mocked(generateFollowUpQuestion) .mockReturnValueOnce(earlierQuestion.promise) .mockReturnValueOnce(newerQuestion.promise);
renderChatInterface({ suppressInitialFollowUp: false }); await act(async () => {});
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); return { earlierQuestion, newerQuestion };}
/** * Mounts the chat with two follow-up questions in flight, then sends a message, * which orphans the older call. Returns both deferreds and the send promise. */async function sendDuringTwoFollowUpsInFlight() { const { earlierQuestion, newerQuestion } = await mountWithTwoFollowUpsInFlight();
let send: Promise<void> = Promise.resolve(); await act(async () => { send = sendMessage("And how do I use it?"); }); return { earlierQuestion, newerQuestion, send };}
/** Settles the newer question and waits for the send still running beside it. */async function settleNewestQuestion( newerQuestion: ReturnType<typeof deferred<string>>, send: Promise<void>,) { await act(async () => { newerQuestion.resolve("The newest question?"); await send; });}
/** * Unmounts the first chat inside `act`, then mounts the second one with no * `act` around the render. The caller sends the second chat's own message * right after, in its own `act`. */async function remountChatMidGeneration(first: { unmount: () => void }) { await act(async () => { first.unmount(); });
renderChatInterface();}
/** Settles the live answer and expects the response flag to clear with it. */async function settleLiveAnswer( secondResponse: ReturnType<typeof deferred<string>>, secondSend: Promise<void>,) { await act(async () => { secondResponse.resolve("The live answer."); await secondSend; });
expect(getChatGenerationState().isGeneratingResponse).toBe(false);}
/** Lets an earlier follow-up question land while the answer is still running. */async function settleEarlierQuestionMidResponse( followUpQuestion: ReturnType<typeof deferred<string>>,) { expect(getChatGenerationState().isGeneratingResponse).toBe(true);
await act(async () => { followUpQuestion.resolve("An earlier question?"); });
expect(getChatGenerationState().isGeneratingResponse).toBe(true);}
/** Checks the second mount's own generation started, and is not a stale flag. */function expectLiveGenerationStarted(calls: number) { expect(getChatGenerationState().isGeneratingResponse).toBe(true); expect(generateChatResponse).toHaveBeenCalledTimes(calls);}
function stubWakeLockApi() { const release = vi.fn(() => Promise.resolve()); const request = vi.fn(() =>34 unmodified lines
describe("ChatInterface generation state", () => { it("leaves the follow-up question flag off after sending during its generation", async () => { const earlierQuestion = deferred<string>(); vi.mocked(generateFollowUpQuestion).mockReturnValueOnce( earlierQuestion.promise, );
renderChatInterface({ suppressInitialFollowUp: false });
await act(async () => {});
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); const { question: earlierQuestion } = await mountWithFollowUpInFlight();
await act(async () => { await sendMessage("And how do I use it?");26 unmodified lines send = sendMessage("And how do I use it?"); });
expect(getChatGenerationState().isGeneratingResponse).toBe(true);
await act(async () => { followUpQuestion.resolve("An earlier question?"); });
expect(getChatGenerationState().isGeneratingResponse).toBe(true); await settleEarlierQuestionMidResponse(followUpQuestion);
await act(async () => { chatResponse.resolve("An answer.");143 unmodified lines });
it("keeps the follow-up question flag on until the newest call finishes", async () => { const earlierQuestion = deferred<string>(); const newerQuestion = deferred<string>(); vi.mocked(generateFollowUpQuestion) .mockReturnValueOnce(earlierQuestion.promise) .mockReturnValueOnce(newerQuestion.promise);
renderChatInterface({ suppressInitialFollowUp: false }); await act(async () => {});
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); const { earlierQuestion, newerQuestion } = await mountWithTwoFollowUpsInFlight();
let send: Promise<void> = Promise.resolve(); await act(async () => {8 unmodified lines expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); expect(getFollowUpQuestion()).toBe("");
await act(async () => { newerQuestion.resolve("The newest question?"); await send; }); await settleNewestQuestion(newerQuestion, send);
expect(getFollowUpQuestion()).toBe("The newest question?"); expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false); });
it("leaves both generation flags off after unmounting mid-generation", async () => { const heldQuestion = deferred<string>(); vi.mocked(generateFollowUpQuestion).mockReturnValueOnce( heldQuestion.promise, );
const { unmount } = renderChatInterface({ suppressInitialFollowUp: false }); await act(async () => {});
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); const { question: heldQuestion, unmount } = await mountWithFollowUpInFlight();
await act(async () => { unmount();48 unmodified lines });
it("blanks nothing when an orphaned call rejects after a newer one started", async () => { const earlierQuestion = deferred<string>(); const newerQuestion = deferred<string>(); vi.mocked(generateFollowUpQuestion) .mockReturnValueOnce(earlierQuestion.promise) .mockReturnValueOnce(newerQuestion.promise);
renderChatInterface({ suppressInitialFollowUp: false }); await act(async () => {});
let send: Promise<void> = Promise.resolve(); await act(async () => { send = sendMessage("And how do I use it?"); }); const { earlierQuestion, newerQuestion, send } = await sendDuringTwoFollowUpsInFlight();
// The orphaned call fails. Its catch must not blank the newer one's work. await act(async () => {2 unmodified lines
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
await act(async () => { newerQuestion.resolve("The newest question?"); await send; }); await settleNewestQuestion(newerQuestion, send);
expect(getFollowUpQuestion()).toBe("The newest question?"); expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);76 unmodified lines firstSend = sendMessage("And how do I use it?"); });
await act(async () => { first.unmount(); });
renderChatInterface(); await remountChatMidGeneration(first);
let secondSend: Promise<void> = Promise.resolve(); await act(async () => { secondSend = sendMessage("Does it work offline?"); });
expect(getChatGenerationState().isGeneratingResponse).toBe(true); // The live generation really started, rather than the flag being stale. expect(generateChatResponse).toHaveBeenCalledTimes(2); expectLiveGenerationStarted(2);
// The orphan's `finally` must not clear the live generation's flag, which // would drop the spinner and let a third send start alongside it.4 unmodified lines
expect(getChatGenerationState().isGeneratingResponse).toBe(true);
await act(async () => { secondResponse.resolve("The live answer."); await secondSend; });
expect(getChatGenerationState().isGeneratingResponse).toBe(false); await settleLiveAnswer(secondResponse, secondSend); });
it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {15 unmodified lines firstRegenerate = regenerateResponse(); });
await act(async () => { first.unmount(); });
renderChatInterface(); await remountChatMidGeneration(first);
let secondSend: Promise<void> = Promise.resolve(); await act(async () => { secondSend = sendMessage("Does it work offline?"); });
expect(getChatGenerationState().isGeneratingResponse).toBe(true); // The live generation really started, rather than the flag being stale. expect(generateChatResponse).toHaveBeenCalledTimes(3); expectLiveGenerationStarted(3);
await act(async () => { firstResponse.resolve("The orphaned regeneration.");2 unmodified lines
expect(getChatGenerationState().isGeneratingResponse).toBe(true);
await act(async () => { secondResponse.resolve("The live answer."); await secondSend; });
expect(getChatGenerationState().isGeneratingResponse).toBe(false); await settleLiveAnswer(secondResponse, secondSend); });
it("starts one re-generation when two regenerates land in the same task", async () => {28 unmodified lines293031323334353637383940414243444546474822 unmodified lines71727360617462636465666768697075767728 unmodified lines );}
// An empty answer is saved when the stream ends with no content.function chatWithEmptyAnswers(): ChatMessage[] { return [ { role: "user", content: "system instructions" }, { role: "assistant", content: "Ok!" }, { role: "user", content: "Q1" }, { role: "assistant", content: "" }, { role: "user", content: "Q2" }, { role: "assistant", content: "" }, { role: "user", content: "Q3" }, { role: "assistant", content: "A3" }, ];}
describe("MessageList", () => { it("renders nothing when there are no follow-up messages", () => { const messages: ChatMessage[] = [22 unmodified lines });
describe("an empty answer earlier in the chat", () => { // An empty answer is saved when the stream ends with no content. const messages: ChatMessage[] = [ const messages: ChatMessage[] = chatWithEmptyAnswers(); { role: "user", content: "system instructions" }, { role: "assistant", content: "Ok!" }, { role: "user", content: "Q1" }, { role: "assistant", content: "" }, { role: "user", content: "Q2" }, { role: "assistant", content: "" }, { role: "user", content: "Q3" }, { role: "assistant", content: "A3" }, ];
it("edits each question at its position in the chat", () => { const onEditMessage = vi.fn();1 unmodified line23455671 unmodified line91011131415121314151617181920212223242526272829303132333435363738394041424344454647484950511718192021225253242526272829303132333435363738394041425455565758596061626364656646 unmodified lines11311411595969798991161171181192 unmodified lines1221231241081091101111251261271289 unmodified lines138139140127128129130131132133141142143144106 unmodified lines251252253246247248249250251252253254255254255256257279 unmodified lines5375385395415405415422 unmodified lines5455465475505515485495505545555565575515525535544 unmodified lines55956056156856957057156256356456514 unmodified lines5805815825925835845852 unmodified lines5885895906016025915925935945956076086096105965975985996006156166176186016026036046056066246076086092 unmodified lines6126136146336346156166176376386396406186196206216446456466476226236246257 unmodified lines6336346356616626636646366376386391 unmodified line64164264367267367467564464564664713 unmodified lines6616626636956966976986646656666671 unmodified lineimport { notifications } from "@mantine/notifications";import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { useSyncExternalStore } from "react";import DictationButton from "@/components/DictationButton";import { DictationError,1 unmodified line startDictation,} from "@/modules/speechToText";
vi.mock("@/modules/speechToText", async () => { const { DictationError: RealDictationError } = await import( "@/modules/speechToText"// jscpd:ignore-start// Vitest hoists every vi.mock call above the imports, so the registration has// to be written out in each file; only the factory body can be shared, and it// is. The duplication is the framework's, not the tests'.vi.mock("@/modules/speechToText", async () => (await import("@/testMocks")).speechToTextMock(),);vi.mock("@mantine/notifications", async () => (await import("@/testMocks")).notificationsStub(),);vi.mock("create-pubsub/react", async () => (await import("@/testMocks")).pubSubReactMock(),);// jscpd:ignore-end
/** Turns dictation on or off in the settings the button subscribes to. */async function setDictationSetting(enableDictation: boolean) { const { settingsPubSub } = await import("@/modules/pubSub"); settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation });}
/** Presses the button and returns the callbacks it handed the engine. */async function pressAndWaitForEngine(user: ReturnType<typeof userEvent.setup>) { await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1)); return vi.mocked(startDictation).mock.calls[0][0];}
/** Re-renders the button as a field that went read-only mid-transcription. */function renderDisabledButton(view: ReturnType<typeof render>) { view.rerender( <MantineProvider> <DictationButton getValue={() => ""} setValue={() => {}} labelScope="the search query" disabled /> </MantineProvider>, ); return { DictationError: RealDictationError, getDictationEngine: vi.fn(() => "wasm" as const), startDictation: vi.fn(), };});}
vi.mock("@mantine/notifications", () => ({ notifications: { show: vi.fn() },}));
/** * Subscribes for real rather than reading a snapshot, so a settings change * during a test re-renders the button the way it does in the app. */vi.mock("create-pubsub/react", () => ({ usePubSub: (pubSub: [unknown, unknown, unknown]) => { const [publish, subscribe, get] = pubSub as [ unknown, (listener: () => void) => () => void, () => unknown, ]; const value = useSyncExternalStore(subscribe, get, get); return [value, publish]; },}));/** Waits for the engine to have been started with this local-model preference. */async function expectEngineStartedWith(localModel: boolean) { await waitFor(() => expect(startDictation).toHaveBeenCalledWith( expect.anything(), localModel, expect.any(AbortSignal), ), );}
function renderButton({ getValue = () => "",46 unmodified lines});
it("hides when the setting is off", async () => { const { settingsPubSub } = await import("@/modules/pubSub"); settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: false, }); await setDictationSetting(false); try { renderButton(); expect(2 unmodified lines } finally { // Restored even on a failure: this channel is module state, so leaking // `false` would hide the button in every later test in this file. settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: true, }); await setDictationSetting(true); }});
9 unmodified lines await user.click( screen.getByRole("button", { name: "Dictate the search query" }), ); await waitFor(() => expect(startDictation).toHaveBeenCalledWith( expect.anything(), false, expect.any(AbortSignal), ), ); await expectEngineStartedWith(false); expect(getDictationEngine).toHaveBeenCalledWith(false); } finally { settingsPubSub[0]({106 unmodified lines "transcribing", );
view.rerender( <MantineProvider> <DictationButton getValue={() => ""} setValue={() => {}} labelScope="the search query" disabled /> </MantineProvider>, ); renderDisabledButton(view);
// The transcript would otherwise land in a field that went read-only. await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));279 unmodified lines
it("stays quiet when a load abandoned by the setting fails", async () => { const user = userEvent.setup(); const { settingsPubSub } = await import("@/modules/pubSub"); let fail: ((error: Error) => void) | undefined; vi.mocked(startDictation).mockReturnValue( new Promise((_resolve, reject) => {2 unmodified lines );
renderButton(); await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1)); await pressAndWaitForEngine(user);
try { settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: false, }); await setDictationSetting(false); await waitFor(() => expect(vi.mocked(startDictation).mock.calls[0][2]?.aborted).toBe(true), );4 unmodified lines // The button is gone, so there is nothing for the failure to explain. expect(notifications.show).not.toHaveBeenCalled(); } finally { settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: true, }); await setDictationSetting(true); } });
14 unmodified lines
it("discards a session that arrives after the setting was turned off", async () => { const user = userEvent.setup(); const { settingsPubSub } = await import("@/modules/pubSub"); let release: ((value: typeof session) => void) | undefined; vi.mocked(startDictation).mockReturnValue( new Promise((resolve) => {2 unmodified lines );
renderButton(); await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1)); await pressAndWaitForEngine(user);
try { // Mid-load, with the session not yet in the ref: the button disappears, // and the microphone would otherwise open with nothing to stop it. settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: false, }); await setDictationSetting(false); release?.(session);
await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1)); } finally { settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: true, }); await setDictationSetting(true); } });
it("does not adopt a load an earlier press abandoned", async () => { const user = userEvent.setup(); const { settingsPubSub } = await import("@/modules/pubSub"); const first = { stop: vi.fn(), cancel: vi.fn() }; const second = { stop: vi.fn(), cancel: vi.fn() }; const releases: ((value: typeof session) => void)[] = [];2 unmodified lines );
renderButton(); await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1)); await pressAndWaitForEngine(user);
try { settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: false, }); await setDictationSetting(false); await waitFor(() => expect(screen.queryByRole("button")).not.toBeInTheDocument(), ); settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: true, }); await setDictationSetting(true);
await user.click(await screen.findByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(2));7 unmodified lines await waitFor(() => expect(first.cancel).toHaveBeenCalledTimes(1)); expect(second.cancel).not.toHaveBeenCalled(); } finally { settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation: true, }); await setDictationSetting(true); } });
1 unmodified line const user = userEvent.setup(); renderButton();
await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
const { onEnd } = vi.mocked(startDictation).mock.calls[0][0]; const { onEnd } = await pressAndWaitForEngine(user); act(() => onEnd?.());
// The engine ending by itself is not a failure, but the button has to13 unmodified lines const user = userEvent.setup(); renderButton();
await user.click(screen.getByRole("button")); await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
const { onError } = vi.mocked(startDictation).mock.calls[0][0]; const { onError } = await pressAndWaitForEngine(user); act(() => onError?.(new DictationError("engine", "the transcriber died")));
await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));103 unmodified lines10410510610710810911011111211311411511611773 unmodified lines1911921931861871881891901911941951961976 unmodified lines204205206204205206207208209207208209210103 unmodified lines return { ...utils, ...handlers };}
/** Renders the page with the AI-response prompt showing. */function promptPageState() { return createPageState({ query: "cats", settings: { showEnableAiResponsePrompt: true }, });}
describe("MainPage", () => { beforeEach(() => { vi.clearAllMocks();73 unmodified lines
it("enables AI response and triggers a search when the prompt is accepted", async () => { const user = userEvent.setup(); const { setSettings } = await renderMainPage( createPageState({ query: "cats", settings: { showEnableAiResponsePrompt: true }, }), ); const { setSettings } = await renderMainPage(promptPageState());
await user.click(await screen.findByRole("button", { name: "Accept" }));
6 unmodified lines
it("disables AI response without triggering a search when the prompt is declined", async () => { const user = userEvent.setup(); const { setSettings } = await renderMainPage( createPageState({ query: "cats", settings: { showEnableAiResponsePrompt: true }, }), ); const { setSettings } = await renderMainPage(promptPageState());
await user.click(await screen.findByRole("button", { name: "Decline" }));
29 unmodified lines303132333435363738394041424335 unmodified lines79808174757677787980818283848514 unmodified lines10010110210210310410510610710810910310410510622 unmodified lines12913013113813914014114214314414513213313413529 unmodified lines}
describe("ClearDataButton", () => { /** Presses the button and waits for the teardown to reload the page. */ async function pressClearAllData() { const user = userEvent.setup(); renderClearDataButton(); await user.click(screen.getByRole("button", { name: "Clear all data" })); await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1)); }
const originalLocation = self.location; const originalCachesDescriptor = Object.getOwnPropertyDescriptor( self,35 unmodified lines value: undefined, });
const user = userEvent.setup(); renderClearDataButton();
await user.click(screen.getByRole("button", { name: "Clear all data" }));
await waitFor(() => { expect(reloadMock).toHaveBeenCalledTimes(1); }); await pressClearAllData();
expect(localStorage.getItem("sample-key")).toBeNull(); expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");14 unmodified lines new Error("OPFS unavailable"), );
const user = userEvent.setup(); renderClearDataButton();
await user.click(screen.getByRole("button", { name: "Clear all data" }));
await waitFor(() => { expect(reloadMock).toHaveBeenCalledTimes(1); }); await pressClearAllData();
expect(addLogEntry).toHaveBeenCalledWith( "Error clearing data: OPFS unavailable",22 unmodified lines }, });
const user = userEvent.setup(); renderClearDataButton();
await user.click(screen.getByRole("button", { name: "Clear all data" }));
await waitFor(() => { expect(reloadMock).toHaveBeenCalledTimes(1); }); await pressClearAllData();
expect(keysMock).toHaveBeenCalledTimes(1); expect(deleteMock).toHaveBeenCalledWith("cache-a");93 unmodified lines9495969798991001011021031041051061071089910010110210310410911011111226 unmodified lines13914014113713813914014114214214314414593 unmodified lines );});
/** Renders the form, opens the voice select, and returns its options. */async function renderedVoiceOptions() { renderForm(); await screen.findByText("Voice Selection");
return openSelect(voiceInput()).getAllByRole("option", { hidden: true, });}
describe("VoiceSettingsForm", () => { it("lists only the local voices while the local engine is selected", async () => { renderForm(); await screen.findByText("Voice Selection");
const options = openSelect(voiceInput()).getAllByRole("option", { hidden: true, }); const options = await renderedVoiceOptions();
expect(options.map((option) => option.textContent)).toEqual([ "๐บ๐ธ lessac โข English (high)",26 unmodified lines
it("lists only the system voices while the system engine is selected", async () => { settings.current.textToSpeechEngine = "system"; renderForm(); await screen.findByText("Voice Selection");
const options = openSelect(voiceInput()).getAllByRole("option", { hidden: true, }); const options = await renderedVoiceOptions();
expect(options.map((option) => option.textContent)).toEqual([ "๐บ๐ธ OS Voice โข en-US",1 unmodified line2345678141 unmodified lines1501511521521531541551561571531541551561 unmodified lineimport { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import SearchForm from "@/components/Search/Form/SearchForm";import { ENTER_TO_SUBMIT_CASES } from "@/enterToSubmitCases";import { resetHandledQuery } from "@/modules/autoSearch";import { settingsPubSub } from "@/modules/pubSub";import { getRandomQuerySuggestion } from "@/modules/querySuggestions";141 unmodified lines settingsPubSub[0]({ ...defaultSettings }); });
it.each([ [true, "{Enter}", true], [true, "{Shift>}{Enter}{/Shift}", false], [false, "{Shift>}{Enter}{/Shift}", true], [false, "{Enter}", false], ])( it.each(ENTER_TO_SUBMIT_CASES)( "with enterToSubmit %s, pressing %s submits: %s", async (enterToSubmit, keys, submits) => { settingsPubSub[0]({ ...defaultSettings, enterToSubmit });77 unmodified lines787980818283848586878889909192939495969753 unmodified lines1511521531401411421431441451541551561571581591601521531541551561571611621631643 unmodified lines16816917016716816917017117217117217317477 unmodified lines });};
/** * Renders the drawer with one stored search and returns the select spy, the * entry, and the user for the click that follows. */function drawerWithOneEntry() { const onSearchSelect = vi.fn(); const entry = makeEntry(1, "quantum tunneling"); mockHistory({ filteredSearches: [entry] });
const user = userEvent.setup(); renderDrawer(onSearchSelect); return { user, onSearchSelect, entry };}
describe("HistoryDrawer component", () => { beforeEach(() => { mockSettings(true);53 unmodified lines });
it("selects an entry when its card is clicked", async () => { const onSearchSelect = vi.fn(); const entry = makeEntry(1, "quantum tunneling"); mockHistory({ filteredSearches: [entry] });
const user = userEvent.setup(); renderDrawer(onSearchSelect); const { user, onSearchSelect, entry } = drawerWithOneEntry(); await user.click(await screen.findByText("quantum tunneling"));
expect(onSearchSelect).toHaveBeenCalledWith(entry); });
it("selects an entry once when its query is clicked", async () => { const onSearchSelect = vi.fn(); const entry = makeEntry(1, "quantum tunneling"); mockHistory({ filteredSearches: [entry] });
const user = userEvent.setup(); renderDrawer(onSearchSelect); const { user, onSearchSelect, entry } = drawerWithOneEntry(); await user.click( await screen.findByRole("button", { name: /quantum tunneling/ }), );3 unmodified lines });
it("selects an entry from the keyboard", async () => { const onSearchSelect = vi.fn(); const entry = makeEntry(1, "quantum tunneling"); mockHistory({ filteredSearches: [entry] });
const user = userEvent.setup(); renderDrawer(onSearchSelect); const { user, onSearchSelect, entry } = drawerWithOneEntry(); const queryButton = await screen.findByRole("button", { name: /quantum tunneling/, });66 unmodified lines67686970717273747576777879808140 unmodified lines1221231241161171181191201251261271283 unmodified lines13213313413013113213513613713866 unmodified lines );}
/** Breaks the first thumbnail and waits for its tile to fall back. */async function breakFirstThumbnail() { const [img] = await screen.findAllByRole("img"); img.dispatchEvent(new Event("error"));
// The second tile still loads, so exactly one img survives the failure. await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1));}
describe("ImageResultsList", () => { it("renders thumbnails as named buttons", async () => { renderImageResultsList();40 unmodified lines it("shows the host name when a thumbnail fails to load", async () => { renderImageResultsList();
const [img] = await screen.findAllByRole("img"); img.dispatchEvent(new Event("error"));
// The second tile still loads, so exactly one img survives the failure. await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1)); await breakFirstThumbnail(); expect( screen.getByRole("button", { name: "Open image preview: First image" }), ).toHaveTextContent("example.com");3 unmodified lines const user = userEvent.setup(); renderImageResultsList();
const [img] = await screen.findAllByRole("img"); img.dispatchEvent(new Event("error")); await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1)); await breakFirstThumbnail();
await user.click( screen.getByRole("button", { name: "Open image preview: First image" }),12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { MantineProvider } from "@mantine/core";import { act, render, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";import { imageSearchResultsPubSub, imageSearchStatePubSub,} from "@/modules/pubSub";import type { ImageSearchResult } from "@/modules/types";import ImageSearchResults from "./ImageSearchResults";
vi.mock("./ImageResultsList", () => ({ default: ({ imageResults }: { imageResults: ImageSearchResult[] }) => ( <ul aria-label="Image results"> {imageResults.map(([title]) => ( <li key={title}>{title}</li> ))} </ul> ),}));
const [setImageSearchState] = imageSearchStatePubSub;const [setImageSearchResults] = imageSearchResultsPubSub;
const followUpImage: ImageSearchResult = [ "Follow-up image", "https://example.com/follow-up", "https://example.com/follow-up.jpg", "https://source.example.com/follow-up",];
function renderImageSearchResults() { return render( <MantineProvider> <ImageSearchResults /> </MantineProvider>, );}
afterEach(() => { act(() => { setImageSearchState("idle"); setImageSearchResults([]); });});
describe("ImageSearchResults", () => { it("shows a follow-up's images after the first image search failed", () => { setImageSearchState("failed"); renderImageSearchResults(); expect(screen.getByText("Failed to search for images")).toBeInTheDocument();
act(() => setImageSearchResults([followUpImage]));
expect(screen.getByText("Follow-up image")).toBeInTheDocument(); expect( screen.queryByText("Failed to search for images"), ).not.toBeInTheDocument(); });
it("keeps the failure alert when no images were added", () => { setImageSearchState("failed"); renderImageSearchResults();
expect(screen.getByText("Failed to search for images")).toBeInTheDocument(); expect(screen.queryByLabelText("Image results")).not.toBeInTheDocument(); });});34 unmodified lines35363738394041424344454634 unmodified lines }
if (searchState === "failed") { // A follow-up's image search can still add images after the first one // failed, and it does not change this state. if (results.length > 0) { return <ImageResultsList imageResults={results} />; }
return ( <Alert variant="light"123451 unmodified line7899101112131415161718192010111213import { vi } from "vitest";import { matchMediaStub, REDUCED_MOTION_QUERY } from "@/matchMediaStub";
/** * Overrides the global `matchMedia` mock from `setupTests.ts`. Only1 unmodified line * queries the result components rely on keep returning false. */export function setReducedMotionPreference(matches: boolean) { vi.mocked(window.matchMedia).mockImplementation( (query) => ({ matches: matches && query === "(prefers-reduced-motion: reduce)", media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), }) as MediaQueryList, vi.mocked(window.matchMedia).mockImplementation((query) => matchMediaStub(query, matches && query === REDUCED_MOTION_QUERY), );}12345678910/** * The `enterToSubmit` matrix: the setting, the key, and whether the key sends. * Shared by the search form and the chat input, which read the same setting. */export const ENTER_TO_SUBMIT_CASES: [boolean, string, boolean][] = [ [true, "{Enter}", true], [true, "{Shift>}{Enter}{/Shift}", false], [false, "{Shift>}{Enter}{/Shift}", true], [false, "{Enter}", false],];120 unmodified lines1211221231241251261271281291301311321331341351361371381391301311321331341401411421435 unmodified lines1491501511461471481491501521531541556 unmodified lines1621631641631641651661671651661671686 unmodified lines175176177180181182183184178179180181120 unmodified lines }}
/** Renders the pinned-aware two-entry window and waits for the first load. */async function renderPinnedAwareHistory() { const { result } = renderHook(() => useSearchHistory({ limit: 2, includeAllPinned: true }), ); await settle(); await untilLoaded(result); return result;}
describe("useSearchHistory with includeAllPinned", () => { it("keeps a pinned search older than the whole recent window", async () => { await pinOldestEntry(); // limit 2 reads the newest 4: the pinned entry is the 7th newest. await addNewerSearches(4);
const { result } = renderHook(() => useSearchHistory({ limit: 2, includeAllPinned: true }), ); await settle(); await untilLoaded(result); const result = await renderPinnedAwareHistory();
expect(queriesOf(result.current.filteredSearches)).toEqual([ "newer search 4",5 unmodified lines it("keeps a pinned search inside the window but past the limit", async () => { await pinOldestEntry();
const { result } = renderHook(() => useSearchHistory({ limit: 2, includeAllPinned: true }), ); await settle(); await untilLoaded(result); const result = await renderPinnedAwareHistory();
expect(queriesOf(result.current.filteredSearches)).toEqual([ "rust async tutorial",6 unmodified lines await pinOldestEntry(); await addNewerSearches(4);
const { result } = renderHook(() => useSearchHistory({ limit: 2, includeAllPinned: true }), ); await settle(); await untilLoaded(result); const result = await renderPinnedAwareHistory(); act(() => result.current.searchHistory("lisbon")); await settle();
6 unmodified lines await pinOldestEntry(); const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");
const { result } = renderHook(() => useSearchHistory({ limit: 2, includeAllPinned: true }), ); await settle(); await untilLoaded(result); const result = await renderPinnedAwareHistory(); expect(pinnedReadSpy).toHaveBeenCalledTimes(1);
for (const query of ["w", "we", "wea"]) {12345678910111213141516171819202122import { vi } from "vitest";
/** The only media query the app's components ask about by name. */export const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
/** * A `MediaQueryList` for `query`, matching or not. `setupTests.ts` installs it * as the global `matchMedia` mock and the result tests override that mock with * it to toggle the reduced-motion preference. */export function matchMediaStub(query: string, matches = false) { return { matches, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), } as MediaQueryList;}35 unmodified lines36373839404142434445464748154 unmodified lines2032042051992002012062072082092 unmodified lines21221321421021121221521621721835 unmodified lines
const TIMEOUT_HOURS = 24;
/** Checks that a stored key was dropped without a call to the server. */function expectStoredKeyDiscarded(result: unknown) { expect(result).toBe(false); expect(localStorage.getItem("accessKeyHash")).toBeNull(); expect(mockFetch).not.toHaveBeenCalled();}
describe("Access Key Module", () => { beforeEach(() => { vi.clearAllMocks();154 unmodified lines );
const result = await verifyStoredAccessKey(TIMEOUT_HOURS); expect(result).toBe(false); expect(localStorage.getItem("accessKeyHash")).toBeNull(); expect(mockFetch).not.toHaveBeenCalled(); expectStoredKeyDiscarded(result); });
it("deletes a stored value that is not JSON without asking the server", async () => {2 unmodified lines
const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
expect(result).toBe(false); expect(localStorage.getItem("accessKeyHash")).toBeNull(); expect(mockFetch).not.toHaveBeenCalled(); expectStoredKeyDiscarded(result); });
it("keeps the stored hash on a 429 instead of deleting it", async () => {11234493 unmodified lines49849950050150250350450550150250350450550850650750850951051151251351451551651751851952052152252352452552652752852953053151851952052153253353453553653752653853952852953053154054154253453554354454553753853954654754854955055155255355455555655755855956056156256356456556656756856957057157257357430 unmodified lines6056066075765775785795805815825835846086096106112 unmodified lines614615616593594595596617618619620import { beforeEach, describe, expect, it, vi } from "vitest";import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
beforeEach(() => vi.clearAllMocks());
493 unmodified lines mockGetCurrentSearchRunId.mockReturnValue("run-1"); });
it("drops a stale image refresh that resolves after a newer image refresh on the same run", async () => { let releaseFirst: (value: { results: ImageSearchResults; stale: boolean; }) => void = () => {}; /** Holds the next image search until the returned function releases it. */ function holdNextImageSearch() { let release: (results: ImageSearchResults) => void = () => {}; mockSearchImages.mockReturnValueOnce( new Promise((resolve) => { releaseFirst = resolve; release = (results) => resolve({ results, stale: false }); }), ); return (results: ImageSearchResults) => release(results); }
it("keeps both follow-ups' images when their refreshes land in reverse order", async () => { let shown: ImageSearchResults = []; vi.mocked(getImageSearchResults).mockImplementation(() => shown); mockUpdateImage.mockImplementation((results) => { shown = results; }); onTestFinished(() => { vi.mocked(getImageSearchResults).mockImplementation(() => []); mockUpdateImage.mockImplementation(() => {}); });
const releaseFirst = holdNextImageSearch();
const existingA: ImageSearchResults = [ ["Initial", "https://initial.com", "thumb-0", "src-0"], ]; shown = existingA; const first = refreshImageSearchResults("first", 10, existingA); await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalledTimes(1));
const existingB: ImageSearchResults = [ ["B0", "https://b0.com", "thumb-b0", "src-b0"], ...existingA, ]; // The second follow-up is sent before the first one's images land, so // the list it is handed does not have them. mockSearchImages.mockResolvedValueOnce({ results: [["B1", "https://b1.com", "thumb-b1", "src-b1"]], stale: false, }); await refreshImageSearchResults("second", 10, existingB); await refreshImageSearchResults("second", 10, existingA);
releaseFirst({ results: [["Late A", "https://a.com", "thumb-a", "src-a"]], stale: false, }); releaseFirst([["Late A", "https://a.com", "thumb-a", "src-a"]]); await first;
expect(mockUpdateImage).toHaveBeenCalledTimes(1); expect(mockUpdateImage).toHaveBeenCalledWith([ const both: ImageSearchResults = [ ["Late A", "https://a.com", "thumb-a", "src-a"], ["B1", "https://b1.com", "thumb-b1", "src-b1"], ...existingB, ]); expect(mergeSearchImageResults).toHaveBeenCalledTimes(1); ...existingA, ]; expect(mockUpdateImage).toHaveBeenLastCalledWith(both); expect(mergeSearchImageResults).toHaveBeenCalledTimes(2); expect(mergeSearchImageResults).toHaveBeenLastCalledWith("run-1", { type: "image", items: both.map(([title, url, thumbnail, sourceUrl]) => ({ title, url, thumbnail, sourceUrl, })), }); });
it("drops an image refresh that lands after a retry on the same run", async () => { const releaseImages = holdNextImageSearch(); const refresh = refreshImageSearchResults("query", 10, [], "run-1"); await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalledTimes(1));
recordSearchAttempt("run-1", (getLatestSearchAttempt("run-1") ?? 0) + 1); releaseImages([["Old", "https://old.com", "thumb-o", "src-o"]]); await refresh;
expect(mockUpdateImage).not.toHaveBeenCalled(); expect(mergeSearchImageResults).not.toHaveBeenCalled(); });
it("drops a stale text refresh that resolves after a newer text refresh on the same run", async () => {30 unmodified lines });
it("adds a late image refresh to its own run's stored images after leaving the search", async () => { let releaseImages: (value: { results: ImageSearchResults; stale: boolean; }) => void = () => {}; mockSearchImages.mockReturnValueOnce( new Promise((resolve) => { releaseImages = resolve; }), ); const releaseImages = holdNextImageSearch(); const handed: ImageSearchResults = [ ["Shown", "https://shown.com", "thumb-s", "src-s"], ];2 unmodified lines
// The user restored or started another search meanwhile. mockGetCurrentSearchRunId.mockReturnValue("run-2"); releaseImages({ results: [["Fresh", "https://fresh.com", "thumb-f", "src-f"]], stale: false, }); releaseImages([["Fresh", "https://fresh.com", "thumb-f", "src-f"]]); await refresh;
expect(mockUpdateImage).not.toHaveBeenCalled();42 unmodified lines4344454646474948495068 unmodified lines11912012112412512212312412512612812912713013113213312812913025 unmodified lines15615715816515916016116242 unmodified lines return () => getLatestSearchAttempt(searchRunId) === attempt;}let textRefreshInvocation = 0;let imageRefreshInvocation = 0;let pageContentsReadInvocation = 0;const latestTextRefreshByRunId = new Map<string, number>();const latestImageRefreshByRunId = new Map<string, number>();
/** * Returns the fresh results the answer is grounded on (empty when nothing came68 unmodified lines existingResults: ImageSearchResults, searchRunId = getCurrentSearchRunId(),): Promise<void> { const invocation = ++imageRefreshInvocation; latestImageRefreshByRunId.set(searchRunId, invocation); // No newest-refresh check, unlike text: image refreshes merge into the list // on screen and into history, so an older one landing after a newer one // adds its images instead of overwriting the newer ones. const isSameAttempt = sameSearchAttempt(searchRunId); const isCurrent = () => invocation === imageRefreshInvocation && searchRunId === getCurrentSearchRunId() && searchRunId === getCurrentSearchRunId() && isSameAttempt(); isSameAttempt(); const isRunCurrent = () => latestImageRefreshByRunId.get(searchRunId) === invocation && isSameAttempt();
const { results: imageResults } = await searchImages( searchQuery,25 unmodified lines updateImageSearchResults(updatedImageResults); }
if (isRunCurrent()) { if (isSameAttempt()) { mergeSearchImageResults(searchRunId, { type: "image", items: updatedImageResults.map(18 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152163 unmodified lines21621721819119219319421922022122228 unmodified lines25125225322923023123225425525625711 unmodified lines2692702712502512522532722732742757 unmodified lines2832842852672682692702862872882898 unmodified lines29829930028528628728830130230330421 unmodified lines3263273283163173183193293303313326 unmodified lines33934034133233333433534234334434536 unmodified lines38238338438538638738838939039139239339439555 unmodified lines4514524534394404414424544554564577 unmodified lines46546646745645745845946846947047130 unmodified lines5025035044964974984995055065075086 unmodified lines51551651751251351451551851952052110 unmodified lines53253353453253353453553553653753896 unmodified lines63563663763863964064164264364464563863964064864965065164164264364438 unmodified lines68368468569669769869968668768868971 unmodified lines76176276377777877976476576676718 unmodified lines ...overrides,});
/** A one-item text result set, the shape most of these tests store. */function oneTextResult() { return { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], };}/** Turns auto-cleanup on with a five-entry window and no retention. */async function enableAutoCleanup() { const { getSettings } = await import("./pubSub"); const { defaultSettings } = await import("./settings"); vi.mocked(getSettings).mockReturnValue({ ...defaultSettings, historyAutoCleanup: true, historyRetentionDays: 0, historyMaxEntries: 5, });}
/** Checks that every history store came back empty. */async function expectStoresEmpty( db: typeof import("./history")["historyDatabase"],) { expect(await db.searches.count()).toBe(0); expect(await db.llmResponses.count()).toBe(0); expect(await db.chatHistory.count()).toBe(0);}
describe("History Module - Search Run ID Management", () => { beforeEach(async () => { vi.resetModules();163 unmodified lines describe("addSearchToHistory", () => { it("should add a text search entry and return an ID", async () => { const { addSearchToHistory } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult(); const id = await addSearchToHistory("test query", results); expect(id).toBeDefined(); expect(typeof id).toBe("number");28 unmodified lines const { addSearchToHistory, getRecentSearches } = await import( "./history" ); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
// Insert "second" with the earlier timestamp so it proves sorting by timestamp, not ID. vi.setSystemTime(new Date(2000, 0, 2));11 unmodified lines const { addSearchToHistory, getRecentSearches } = await import( "./history" ); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
for (let i = 0; i < 5; i++) { await addSearchToHistory(`query ${i}`, results);7 unmodified lines const { addSearchToHistory, getRecentSearches } = await import( "./history" ); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
for (let i = 0; i < 12; i++) { await addSearchToHistory(`query ${i}`, results);8 unmodified lines it("returns only pinned entries, newest first, however old", async () => { const { addSearchToHistory, getPinnedSearches, historyDatabase } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
vi.setSystemTime(new Date(2000, 0, 1)); const oldest = await addSearchToHistory("pinned long ago", results);21 unmodified lines const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } = await import("./history"); const runId = getCurrentSearchRunId(); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
await addSearchToHistory("round trip query", results, "user"); const [entry] = await getRecentSearches();6 unmodified lines const { addSearchToHistory, getRecentSearches } = await import( "./history" ); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
await addSearchToHistory("fields test", results); const [entry] = await getRecentSearches();36 unmodified lines });
describe("mergeSearchImageResults", () => { /** The two image results these tests merge, in the order the screen shows. */ function freshAndFirstImages() { return [ image("Fresh", "https://fresh.com"), image("First", "https://first.com"), ]; }
const image = (title: string, url: string) => ({ title, url,55 unmodified lines type: "image", items: [image("Fresh", "https://fresh.com")], }); expect(await storedItems()).toEqual([ image("Fresh", "https://fresh.com"), image("First", "https://first.com"), ]); expect(await storedItems()).toEqual(freshAndFirstImages());
// The reverse order: a follow-up stored first, the first search lands // after it. Its images go after the follow-up's, as on screen.7 unmodified lines { type: "image", items: [image("First", "https://first.com")] }, { newFirst: false }, ); expect(await storedItems()).toEqual([ image("Fresh", "https://fresh.com"), image("First", "https://first.com"), ]); expect(await storedItems()).toEqual(freshAndFirstImages());
// A retry on the run clears the list before its own images arrive. await updateSearchResults(runId, { type: "image", items: [] });30 unmodified lines saveLlmResponseForQuery, getLatestLlmResponseForEntry, } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
await addSearchToHistory("llm test", results); await saveLlmResponseForQuery("llm test", "AI answer", "model-x");6 unmodified lines it("should store searchId back-link from llmResponses to the search row", async () => { const { addSearchToHistory, historyDatabase, saveLlmResponseForQuery } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
const id = await addSearchToHistory("llm link test", results); await saveLlmResponseForQuery("llm link test", "answer", "m");10 unmodified lines saveLlmResponseForQuery, getLatestLlmResponseForEntry, } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
await addSearchToHistory("multi llm", results); vi.setSystemTime(new Date(2000, 0, 2));96 unmodified lines
describe("cleanup after add", () => { it("should not throw TransactionInactiveError when auto-cleanup is enabled", async () => { const { getSettings } = await import("./pubSub"); const { defaultSettings } = await import("./settings"); vi.mocked(getSettings).mockReturnValue({ ...defaultSettings, historyAutoCleanup: true, historyRetentionDays: 0, historyMaxEntries: 5, }); await enableAutoCleanup();
const { addSearchToHistory, historyDatabase } = await import("./history"); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult();
// Cleanup must run after the add transaction completes: inside it, the // async import causes a TransactionInactiveError.38 unmodified lines vi.spyOn(historyDatabase.searches, "add").mockRejectedValue( new Error("boom"), ); const results = { type: "text" as const, items: [{ title: "T", url: "https://t.com", snippet: "S" }], }; const results = oneTextResult(); const id = await addSearchToHistory("q", results); expect(id).toBeUndefined(); });71 unmodified lines
await clearAllHistory();
expect(await historyDatabase.searches.count()).toBe(0); expect(await historyDatabase.llmResponses.count()).toBe(0); expect(await historyDatabase.chatHistory.count()).toBe(0); await expectStoresEmpty(historyDatabase); }); });});22 unmodified lines2324252627282930313233343536373839404142434425 unmodified lines707172575859606173747576777879808182686970718384858687888990919278798081829394959697989922 unmodified lines vi.resetModules();});
/** * Checks that a stored value the module cannot use fell back to its default, * was dropped from storage, and was logged. */function expectUnusableStoredValue( key: string, read: () => unknown, fallback: unknown,) { expect(read()).toEqual(fallback); expect(localStorage.getItem(key)).toBeNull(); expect(addLogEntry).toHaveBeenCalledWith( `Discarded an unusable stored value for '${key}'`, );}
describe("PubSub localStorage persistence", () => { it("updates query suggestions and persists to localStorage", async () => { const { updateQuerySuggestions, getQuerySuggestions } = await import(25 unmodified lines it("falls back to the default and drops the value when the stored JSON is corrupted", async () => { localStorage.setItem("menuExpandedAccordions", "{not valid json"); const { menuExpandedAccordionsPubSub } = await import("./pubSub"); const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub; expect(getMenuExpandedAccordions()).toEqual([]); expect(localStorage.getItem("menuExpandedAccordions")).toBeNull(); expect(addLogEntry).toHaveBeenCalledWith( "Discarded an unusable stored value for 'menuExpandedAccordions'", expectUnusableStoredValue( "menuExpandedAccordions", () => menuExpandedAccordionsPubSub[2](), [], ); });
it("falls back to the default and drops the value when the stored JSON has the wrong type", async () => { localStorage.setItem("lastSearchTokenHash", "123"); const { getLastSearchTokenHash } = await import("./pubSub"); expect(getLastSearchTokenHash()).toBe(""); expect(localStorage.getItem("lastSearchTokenHash")).toBeNull(); expect(addLogEntry).toHaveBeenCalledWith( "Discarded an unusable stored value for 'lastSearchTokenHash'", expectUnusableStoredValue( "lastSearchTokenHash", () => getLastSearchTokenHash(), "", ); });
it("falls back to the default and drops the value when the stored value is empty", async () => { localStorage.setItem("menuExpandedAccordions", ""); const { menuExpandedAccordionsPubSub } = await import("./pubSub"); const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub; expect(getMenuExpandedAccordions()).toEqual([]); expect(localStorage.getItem("menuExpandedAccordions")).toBeNull(); expect(addLogEntry).toHaveBeenCalledWith( "Discarded an unusable stored value for 'menuExpandedAccordions'", expectUnusableStoredValue( "menuExpandedAccordions", () => menuExpandedAccordionsPubSub[2](), [], ); });});8 unmodified lines910111213141516171819202122232425262728295 unmodified lines35363723242526273839404115 unmodified lines5758594950515253606162638 unmodified lines return await import("./pubSub");}
/** Subscribes to the response channel and records each published value. */function collectPublished( responsePubSub: [ unknown, (listener: (value: string) => void) => () => void, unknown, ],) { const published: string[] = []; const unsubscribe = responsePubSub[1]((value) => { published.push(value); }); return { published, unsubscribe };}
describe("response publishing", () => { beforeEach(() => { vi.useFakeTimers();5 unmodified lines
it("publishes one leading and one trailing value per throttle window", async () => { const { responsePubSub, updateResponse } = await loadResponseChannel(); const published: string[] = []; const [, onResponseChange] = responsePubSub; const unsubscribe = onResponseChange((value) => { published.push(value); }); const { published, unsubscribe } = collectPublished(responsePubSub);
updateResponse("Hello"); updateResponse("Hello world");15 unmodified lines updateResponse, updateResponseImmediately, } = await loadResponseChannel(); const published: string[] = []; const [, onResponseChange] = responsePubSub; const unsubscribe = onResponseChange((value) => { published.push(value); }); const { published, unsubscribe } = collectPublished(responsePubSub);
updateResponse("Hello"); updateResponse("Hello world, but truncated");16 unmodified lines1718192021222324252627282930422 unmodified lines45345445544844945045145645745845914 unmodified lines47447547647247347447547747847948016 unmodified lines4974984994984995005015005015025034 unmodified lines5085095105125135145155115125135144 unmodified lines5195205215265275285295225235245259 unmodified lines5355365375455465475485385395405416 unmodified lines54854955056156256356455155255355411 unmodified lines56656756858258358458556957057157224 unmodified lines59759859961661761861960060160260316 unmodified lines}));
const mockFetch = vi.fn();
/** Answers every following `/search` fetch with `results`. */function mockSearchResponse(results: string[][]) { mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(results), });}vi.stubGlobal("fetch", mockFetch);vi.stubGlobal("self", { location: new URL("http://localhost:3000"),422 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
const firstResults = await searchModule.searchText("cached query"); expect(firstResults).toEqual({ results: mockResults, stale: false });14 unmodified lines const mockResults: string[][] = [ ["Image", "Alt", "https://example.com/img.jpg"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
const firstResults = await searchModule.searchImages("cached images"); expect(firstResults).toEqual({ results: mockResults, stale: false });16 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
await searchModule.searchText("query A"); await searchModule.searchText("query B");4 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
await searchModule.searchText("same query", 5); await searchModule.searchText("same query", 10);4 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
await searchModule.searchText("ttl query"); expect(mockFetch).toHaveBeenCalledTimes(1);9 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
searchModule.searchServiceInstance.updateCacheConfig({ enabled: false });
6 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
await searchModule.searchText("cross-store query"); expect(mockFetch).toHaveBeenCalledTimes(1);11 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
const first = await searchModule.searchText("stale query"); expect(first).toEqual({ results: mockResults, stale: false });24 unmodified lines const mockResults: string[][] = [ ["Title", "Snippet", "https://example.com"], ]; mockFetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue(mockResults), }); mockSearchResponse(mockResults);
try { // Cache an entry, then move past the 24-hour stale retention.4 unmodified lines567891011223 unmodified lines235236237238239240241242243244245246247248249250285 unmodified lines5365375385285295305315325395405415425 unmodified lines54854955054454554654754855155255355458 unmodified lines61361461561361461561661761861962062162262362462562662762861661761861983 unmodified lines7037047057187067077087097107117127247257267277287137147157167177187197207217227235 unmodified lines7297307317427437447457467477487497507517527537327337347354 unmodified lines getDictationEngine, MAX_RECORDING_SECONDS, resampleTo16k, type SpeechRecognitionLike, startDictation, stripLanguageTag,} from "@/modules/speechToText";223 unmodified lines });});
/** Starts a wasm-engine session with a fresh transcript spy. */async function startWasmSession() { const { stream } = makeMediaStream(); stubWasmSupport(vi.fn().mockResolvedValue(stream)); const onTranscript = vi.fn();
const session = await startDictation({ onTranscript }, true); return { session, onTranscript };}
describe("startDictation with the wasm engine", () => { /** Minimal `SpeechRecognition` stand-in; reports whether it was started. */ function installLocalRecognitionFake() {285 unmodified lines });
it("gives a second stop the same transcript instead of resolving early", async () => { const { stream } = makeMediaStream(); stubWasmSupport(vi.fn().mockResolvedValue(stream)); const onTranscript = vi.fn();
const session = await startDictation({ onTranscript }, true); const { session, onTranscript } = await startWasmSession(); capture(4800); const first = session.stop(); const second = session.stop();5 unmodified lines });
it("skips the transcription when nothing was recorded", async () => { const { stream } = makeMediaStream(); stubWasmSupport(vi.fn().mockResolvedValue(stream)); const onTranscript = vi.fn();
const session = await startDictation({ onTranscript }, true); const { session, onTranscript } = await startWasmSession(); await session.stop();
expect(wllama.createTranscription).not.toHaveBeenCalled();58 unmodified lines});
describe("startDictation with the web speech fallback", () => { interface RecognitionFake { continuous: boolean; interimResults: boolean; lang: string; onresult: | ((event: { resultIndex: number; results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>; }) => void) | null; onerror: ((event: { error: string }) => void) | null; onend: (() => void) | null; start: () => void; stop: () => void; stopped: boolean; } type RecognitionFake = SpeechRecognitionLike & { stopped: boolean };
let instance: RecognitionFake | undefined;
83 unmodified lines await session.stop(); });
it("ends the session quietly when the recognizer stops on its own", async () => { /** Starts a web-speech session with fresh `onEnd` and `onError` spies. */ async function startRecognitionSession() { installRecognitionFake(); const onError = vi.fn(); const onEnd = vi.fn();
const session = await startDictation( { onTranscript: vi.fn(), onEnd, onError, }, { onTranscript: vi.fn(), onEnd, onError }, true, ); return { session, onEnd, onError }; }
it("ends the session quietly when the recognizer stops on its own", async () => { const { session, onEnd, onError } = await startRecognitionSession();
// Chrome ends after silence even with `continuous`. The session is over, // but there is nothing the user needs told about.5 unmodified lines });
it("says nothing when the recognizer ends because it was stopped", async () => { installRecognitionFake(); const onError = vi.fn(); const onEnd = vi.fn();
const session = await startDictation( { onTranscript: vi.fn(), onEnd, onError, }, true, ); const { session, onEnd, onError } = await startRecognitionSession();
await session.stop(); instance?.onend?.();50 unmodified lines515253545455565750 unmodified linesconst DICTATION_CONTEXT_SIZE = 4096;
/** The minimum the app needs from `window.SpeechRecognition`. */interface SpeechRecognitionLike {export interface SpeechRecognitionLike { continuous: boolean; interimResults: boolean; lang: string;12345678910115 unmodified lines171819131415161718192021222324252627282930313233343536373839404142432021222324252627282930313233343536373836 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108109130 unmodified lines24024124222822923023123224324424524624723723823924024824925025127 unmodified lines2792802812742752762772822832842857 unmodified lines29329429529129229329429529629729829629729829910 unmodified lines3103113123153133143153167 unmodified lines32432532632932732832933033333433533633733833934033133233333420 unmodified lines355356357367358359360370371372373374375376377378379380381382361362363364365384385386387388389390391366367368369370371372373374375376377378379380394395396397398399400401402403404405406407408409410411412413414415381382383384385386387417388389419420421422423424425426427428429390391392393394395396397398399400401402403404import { beforeEach, describe, expect, it, vi } from "vitest";import { historyMock, logEntriesMock, notificationsMock, pubSubMock, searchMock,} from "./textGenerationTestUtils";
const state = vi.hoisted(() => ({ settings: { inferenceType: "browser" } as {5 unmodified lines systemPrompt: "",}));
vi.mock("./pubSub", () => ({ getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })), getQuery: vi.fn(() => ""), getResponse: vi.fn(() => ""), getSettings: vi.fn(() => state.settings), getTextGenerationState: vi.fn(() => "idle"), listenToSettingsChanges: vi.fn(() => vi.fn()), updateChatMessages: vi.fn(), updateConversationSummary: vi.fn(), updateImageSearchResults: vi.fn(), updateImageSearchState: vi.fn(), updateLlmTextSearchResults: vi.fn(), updateResponse: vi.fn(), updateResponseImmediately: vi.fn(), updateSearchPromise: vi.fn(), updateTextGenerationState: vi.fn(), updateTextSearchResults: vi.fn(), updateTextSearchState: vi.fn(),}));vi.mock("./history", () => ({ replaceChatConversation: vi.fn(() => Promise.resolve()), getCurrentSearchRunId: vi.fn(() => "run-1"), saveLlmResponseForQuery: vi.fn(() => Promise.resolve()), updateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));vi.mock("./search", () => ({ searchImages: vi.fn(() => Promise.resolve([])), searchText: vi.fn(() => Promise.resolve([])),}));// jscpd:ignore-start// Vitest hoists every vi.mock call above the imports, so the registration has// to be written out in each file; only the factory body can be shared, and it// is. The duplication is the framework's, not the tests'.vi.mock("./pubSub", () => pubSubMock(() => state.settings));vi.mock("./history", () => historyMock(() => "run-1"));vi.mock("./logEntries", () => logEntriesMock());vi.mock("./notifications", () => notificationsMock());vi.mock("./search", () => searchMock());// The system prompt stands in for everything that fills it (instructions,// search results, page excerpts), so its length sets how much of the window// is left for the conversation.vi.mock("./systemPrompt", () => ({ getSystemPrompt: vi.fn(() => state.systemPrompt),}));// jscpd:ignore-endvi.mock("./textGenerationUtilities", async (importOriginal) => ({ ...(await importOriginal<typeof import("./textGenerationUtilities")>()), getFormattedSearchResults: vi.fn(() => Promise.resolve("")),36 unmodified lines );}
/** Total characters in a chat, which is its token count under this tokenizer. */function contentLength(chat: ChatMessage[]) { return chat.reduce((total, message) => total + message.content.length, 0);}
/** * A summary slot that survives between turns, as the pubsub store does. The * mock reads and writes it, so a test can watch what the turns folded in. */function stubPersistentSummarySlot() { const slot: { current: ReturnType<typeof getConversationSummary> } = { current: { conversationId: "", summary: "" }, }; vi.mocked(getConversationSummary).mockImplementation(() => slot.current); vi.mocked(updateConversationSummary).mockImplementation((next) => { slot.current = next; }); return slot;}
/** Answers the summarizer with a summary of exactly this many tokens. */function mockSummarizerReturningTokens(tokens: number) { vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => chat[0].content.startsWith(summarizerInstruction) ? "z".repeat(tokens) : "the answer", );}
function callsTo(generateChat: typeof generateChatWithWllama) { const calls = vi .mocked(generateChat)130 unmodified lines { role: "assistant", content: "d".repeat(400) }, { role: "user", content: "q".repeat(300) }, ]; vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => chat[0].content.startsWith(summarizerInstruction) ? "z".repeat(summaryTokens) : "the answer", ); mockSummarizerReturningTokens(summaryTokens);
await generateChatResponse(messages, () => {});
const { answer, summarizer } = callsTo(generateChatWithWllama); const sentTokens = answer[0].reduce( (total, message) => total + message.content.length, 0, ); const sentTokens = contentLength(answer[0]); expect(sentTokens).toBeLessThanOrEqual(3072); expect(answer[0].slice(2)).toEqual(messages.slice(4)); for (const dropped of messages.slice(0, 4)) {27 unmodified lines await generateChatResponse(messages, () => {});
const { answer } = callsTo(generateChatWithWllama); const sentTokens = answer[0].reduce( (total, message) => total + message.content.length, 0, ); const sentTokens = contentLength(answer[0]); expect(sentTokens).toBeLessThanOrEqual(3072); expect(answer[0][0].content).toContain("z"); expect(answer[0].slice(2)).toEqual(messages.slice(2));7 unmodified lines
it("folds each dropped turn into the summary once across turns", async () => { // The summary slot persists between turns, as the pubsub store does. let slot: ReturnType<typeof getConversationSummary> = { conversationId: "", summary: "", }; vi.mocked(getConversationSummary).mockImplementation(() => slot); vi.mocked(updateConversationSummary).mockImplementation((next) => { slot = next; }); const slot = stubPersistentSummarySlot(); mockGenerateChat(generateChatWithWllama); state.systemPrompt = "s".repeat(2000); const firstExchange: ChatMessage[] = [10 unmodified lines [...firstExchange, { role: "user", content: "c".repeat(300) }], () => {}, ); expect(slot.summarizedCount).toBe(2); expect(slot.current.summarizedCount).toBe(2);
const turnTwo = [...firstExchange, ...secondExchange, question]; await generateChatResponse(turnTwo, () => {});7 unmodified lines expect(summarizer[1][0].content).toContain("d".repeat(300)); expect(summarizer[1][0].content).not.toContain("a".repeat(500)); expect(summarizer[1][0].content).not.toContain("b".repeat(500)); expect(slot.summarizedCount).toBe(4); expect(slot.current.summarizedCount).toBe(4); });
it("folds again from the start once an edit reaches into the summary", async () => { let slot: ReturnType<typeof getConversationSummary> = { conversationId: "", summary: "", }; vi.mocked(getConversationSummary).mockImplementation(() => slot); vi.mocked(updateConversationSummary).mockImplementation((next) => { slot = next; }); const slot = stubPersistentSummarySlot(); mockGenerateChat(generateChatWithWllama); state.systemPrompt = "s".repeat(2000); const question: ChatMessage = { role: "user", content: "c".repeat(300) };20 unmodified lines expect(summarizer[1][0].content).toContain("a".repeat(500)); expect(summarizer[1][0].content).toContain("x".repeat(500)); expect(summarizer[1][0].content).toContain("Previous summary:\n(none)"); expect(slot.summarizedCount).toBe(2); expect(slot.current.summarizedCount).toBe(2); });
it("keeps the stored summary when the summarizer rejects and the fallback returns empty", async () => { state.systemPrompt = "s".repeat(2000); const messages: ChatMessage[] = [ { role: "user", content: "first question" }, { role: "assistant", content: "x".repeat(1500) }, { role: "user", content: "follow-up question" }, ]; vi.mocked(getConversationSummary).mockReturnValue({ conversationId: "first question", summary: "S1", }); vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => { if (chat[0].content.startsWith(summarizerInstruction)) { it.each([ { title: "rejects", summarize: () => { throw new Error("summarizer unavailable"); } return "the answer"; });
await generateChatResponse(messages, () => {});
expect(updateConversationSummary).toHaveBeenCalledWith( expect.objectContaining({ }, }, { title: "resolves to an empty string", summarize: () => "" }, ])( "keeps the stored summary when the summarizer $title", async ({ summarize }) => { state.systemPrompt = "s".repeat(2000); const messages: ChatMessage[] = [ { role: "user", content: "first question" }, { role: "assistant", content: "x".repeat(1500) }, { role: "user", content: "follow-up question" }, ]; vi.mocked(getConversationSummary).mockReturnValue({ conversationId: "first question", summary: "S1", summarizedCount: 0, }), ); const { answer } = callsTo(generateChatWithWllama); expect(answer).toHaveLength(1); expect(answer[0][0].content).toContain("S1"); });
it("keeps the stored summary when the summarizer resolves to an empty string", async () => { state.systemPrompt = "s".repeat(2000); const messages: ChatMessage[] = [ { role: "user", content: "first question" }, { role: "assistant", content: "x".repeat(1500) }, { role: "user", content: "follow-up question" }, ]; vi.mocked(getConversationSummary).mockReturnValue({ conversationId: "first question", summary: "S1", }); vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => chat[0].content.startsWith(summarizerInstruction) ? "" : "the answer", ); }); vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => chat[0].content.startsWith(summarizerInstruction) ? summarize() : "the answer", );
await generateChatResponse(messages, () => {}); await generateChatResponse(messages, () => {});
expect(updateConversationSummary).toHaveBeenCalledWith( expect.objectContaining({ conversationId: "first question", summary: "S1", summarizedCount: 0, }), ); const { answer } = callsTo(generateChatWithWllama); expect(answer).toHaveLength(1); expect(answer[0][0].content).toContain("S1"); }); expect(updateConversationSummary).toHaveBeenCalledWith( expect.objectContaining({ conversationId: "first question", summary: "S1", summarizedCount: 0, }), ); const { answer } = callsTo(generateChatWithWllama); expect(answer).toHaveLength(1); expect(answer[0][0].content).toContain("S1"); }, );});
describe("reasoning in earlier assistant turns", () => {33 unmodified lines3435363738394041424344454647484952 unmodified lines102103104959697989910010110510610310710810510911010710810911111211311436 unmodified lines15115215315215315415515415515615715 unmodified lines17317417517717817918018118218318417617717817918018118218318418518618718818919019119219319419519619719819920020120220320418620520620720820921019019121121221321421521621721821922022122222322422522622722822923071 unmodified lines3023033042692702712722732743053063073085 unmodified lines31431531628628728828929029131731831932089 unmodified lines4104114123873883893903913923933943953963973983994004014024134144154169 unmodified lines4264274284184194204214224234294304314324334284344354364372 unmodified lines4404414424374384394404414424434444454464474484494504514434444454465 unmodified lines45245345446346446546646746845545645747145845946046197 unmodified lines5595605615755765775785795805815825835625635645656 unmodified lines57257357459657557657757831 unmodified lines61061161263463563663763863964064164261361461561661761861964962062162262322 unmodified lines64664764867864965065165269 unmodified lines7227237247547557567577587597257267277282 unmodified lines73173273376873473573673773873977474074174274342 unmodified lines7867877888238248258268278287897907917924 unmodified lines79779879983980080180284280380480580627 unmodified lines83483583687683783883987984084184284323 unmodified lines86786886990987087187287335 unmodified lines90991091195191291391491533 unmodified lines };});
import { contentFrame, historyMock, logEntriesMock, notificationsMock, pageContentMock, sseStream, wllamaMock,} from "./textGenerationTestUtils";
vi.mock("./pubSub", () => ({ getImageSearchResults: () => harness.state.imageSearchResults, getConversationSummary: () => ({ conversationId: "", summary: "" }),52 unmodified lines getConfig: vi.fn(() => Promise.resolve({})),}));
vi.mock("./history", () => ({ replaceChatConversation: vi.fn(() => Promise.resolve()), getCurrentSearchRunId: vi.fn(() => harness.state.searchRunId), saveLlmResponseForQuery: vi.fn(() => Promise.resolve()), updateSearchResults: vi.fn(() => Promise.resolve()), mergeSearchImageResults: vi.fn(() => Promise.resolve()),}));vi.mock("./history", () => historyMock(() => harness.state.searchRunId));
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./logEntries", () => logEntriesMock());
vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));vi.mock("./notifications", () => notificationsMock());
vi.mock("./pageContent", () => ({ fetchPageContents: vi.fn(() => Promise.resolve({})),}));vi.mock("./pageContent", () => pageContentMock());
vi.mock("./search", () => ({ searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),36 unmodified lines default: { encode: vi.fn(() => [1, 2, 3]) },}));
vi.mock("./textGenerationWithWllama", () => ({ generateTextWithWllama: vi.fn(() => Promise.resolve()), generateChatWithWllama: vi.fn(() => Promise.resolve("")),}));vi.mock("./textGenerationWithWllama", () => wllamaMock());
import { mergeSearchImageResults,15 unmodified linesconst mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);
function sseStream(frames: string[]) { const encoder = new TextEncoder(); return new Response( new ReadableStream({ start(controller) { for (const frame of frames) controller.enqueue(encoder.encode(frame)); controller.close(); },/** Makes the search endpoint reject a blank query, as the real one does. */function stubEmptyQueryRejection() { vi.mocked(searchText).mockImplementation(async (query) => { if (!query.trim()) { throw new Error("Query cannot be empty or whitespace only"); } return { results: [], stale: false }; });}
const LATE_IMAGE_RESULTS: ImageSearchResults = [ ["Late", "https://late.example.com", "t", "https://late.example.com"],];
/** * Fails the text search and holds the image search open, with the AI response * and the image search on. Returns the function that releases the held search. */function failTextAndHoldImages() { vi.mocked(searchText).mockRejectedValueOnce( new Error("HTTP error! status: 502"), ); let release: | ((value: { results: ImageSearchResults; stale: boolean }) => void) | undefined; vi.mocked(searchImages).mockReturnValueOnce( new Promise<{ results: ImageSearchResults; stale: boolean }>((resolve) => { release = resolve; }), { status: 200 }, ); harness.state.settings.enableAiResponse = true; harness.state.settings.enableImageSearch = true; return () => release?.({ results: LATE_IMAGE_RESULTS, stale: false });}
function contentFrame(content: string) { return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;/** Lets an in-flight continuation drain before the next assertion. */async function drainContinuations() { await new Promise((resolve) => setTimeout(resolve, 0));}
/** Queues run B: its own query, run id and text results. */function queueSecondSearch() { const resultsB: TextSearchResults = [ ["B title", "B snippet", "https://b.example"], ]; harness.state.query = "search b"; harness.state.searchRunId = "run-b"; vi.mocked(searchText).mockResolvedValueOnce({ results: resultsB, stale: false, }); return resultsB;}
describe("search degradation", () => {71 unmodified lines
it("completes with no results when a stopword-only query leaves no keywords to retry with", async () => { harness.state.query = "how about that"; vi.mocked(searchText).mockImplementation(async (query) => { if (!query.trim()) { throw new Error("Query cannot be empty or whitespace only"); } return { results: [], stale: false }; }); stubEmptyQueryRejection();
await searchAndRespond(); await harness.state.searchPromise;5 unmodified lines
it("completes without searching when an over-long query has no keywords", async () => { harness.state.query = "that ".repeat(401); vi.mocked(searchText).mockImplementation(async (query) => { if (!query.trim()) { throw new Error("Query cannot be empty or whitespace only"); } return { results: [], stale: false }; }); stubEmptyQueryRejection();
await searchAndRespond(); await harness.state.searchPromise;89 unmodified lines
it("lets a newer search keep the grounding channel when an older image fallback resolves last", async () => { // Run 1: text fails, image in flight. vi.mocked(searchText).mockRejectedValueOnce( new Error("HTTP error! status: 502"), ); let releaseImages: (value: { results: ImageSearchResults; stale: boolean; }) => void = () => {}; vi.mocked(searchImages).mockReturnValueOnce( new Promise<{ results: ImageSearchResults; stale: boolean }>( (resolve) => { releaseImages = resolve; }, ), ); harness.state.settings.enableAiResponse = true; harness.state.settings.enableImageSearch = true; const releaseLateImages = failTextAndHoldImages();
const first = searchAndRespond(); await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());9 unmodified lines await harness.state.searchPromise;
// Run 1's image search now lands, after run 2 already owns the channel. releaseImages({ results: [ ["Late", "https://late.example.com", "t", "https://late.example.com"], ], stale: false, }); releaseLateImages(); // Let run 1's in-flight continuation fully drain: without the guard its // publish lands on later microtasks, after the test's own `await` has // resumed, so asserting without draining would race the very write the // guard blocks. await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.llmTextSearchResults).toEqual([2 unmodified lines });
it("keeps restored grounding when an older image fallback resolves after a restore", async () => { vi.mocked(searchText).mockRejectedValueOnce( new Error("HTTP error! status: 502"), ); let releaseImages: | ((value: { results: ImageSearchResults; stale: boolean }) => void) | undefined; vi.mocked(searchImages).mockReturnValueOnce( new Promise<{ results: ImageSearchResults; stale: boolean }>( (resolve) => { releaseImages = resolve; }, ), ); harness.state.settings.enableAiResponse = true; harness.state.settings.enableImageSearch = true; const releaseLateImages = failTextAndHoldImages();
const first = searchAndRespond(); await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());5 unmodified lines ["Restored", "snippet", "https://restored.example.com"], ];
releaseImages?.({ results: [ ["Late", "https://late.example.com", "t", "https://late.example.com"], ], stale: false, }); releaseLateImages(); // The publish sits behind the awaited image search; drain the // continuation before asserting, as in the cross-run test above. await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.llmTextSearchResults).toEqual([97 unmodified lines const first = searchAndRespond(); await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
const resultsB: TextSearchResults = [ ["B title", "B snippet", "https://b.example"], ]; harness.state.query = "search b"; harness.state.searchRunId = "run-b"; vi.mocked(searchText).mockResolvedValueOnce({ results: resultsB, stale: false, }); const resultsB = queueSecondSearch(); vi.mocked(fetchPageContents).mockResolvedValueOnce({ "https://b.example": "B page excerpt", });6 unmodified lines ["A title", "A snippet", "https://a.example"], ]; deferredA.release({ results: resultsA, stale: true }); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.textSearchResults).toEqual(resultsB);31 unmodified lines const first = searchAndRespond(); await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
const resultsB: TextSearchResults = [ ["B title", "B snippet", "https://b.example"], ]; harness.state.query = "search b"; harness.state.searchRunId = "run-b"; vi.mocked(searchText).mockResolvedValueOnce({ results: resultsB, stale: false, }); const resultsB = queueSecondSearch();
const second = searchAndRespond(); await second; await harness.state.searchPromise;
deferredA.fail(new Error("late failure")); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.textSearchState).toBe("completed");22 unmodified lines return { finishImages: async (results: ImageSearchResults) => { deferredImages.release({ results, stale: false }); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await running; }, };69 unmodified lines const imagesB: ImageSearchResults = [ ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"], ]; harness.state.query = "search b"; harness.state.searchRunId = "run-b"; vi.mocked(searchText).mockResolvedValueOnce({ results: [["B title", "B snippet", "https://b.example"]], stale: false, }); queueSecondSearch(); vi.mocked(searchImages).mockResolvedValueOnce({ results: imagesB, stale: false,2 unmodified lines const second = searchAndRespond(); await second; await harness.state.searchPromise; await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations();
const imagesA: ImageSearchResults = [ ["Img A", "https://a.example/img.png", "thumb-a", "https://a.example"], ]; deferredImagesA.release({ results: imagesA, stale: false }); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith(42 unmodified lines const first = searchAndRespond(); await vi.waitFor(() => expect(searchImages).toHaveBeenCalledTimes(1));
harness.state.query = "search b"; harness.state.searchRunId = "run-b"; vi.mocked(searchText).mockResolvedValueOnce({ results: [["B title", "B snippet", "https://b.example"]], stale: false, }); queueSecondSearch(); vi.mocked(searchImages).mockResolvedValueOnce({ results: [ ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],4 unmodified lines const second = searchAndRespond(); await second; await harness.state.searchPromise; await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations();
deferredImagesA.fail(new Error("late image error")); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(27 unmodified lines const fourth = searchAndRespond(); await fourth; await harness.state.searchPromise; await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations();
deferredImagesC.fail(new Error("late fire-and-forget image error")); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await third;
expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(23 unmodified lines results: [["Old", "Old snippet", "https://old.example"]], stale: true, }); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.textSearchResults).toEqual(retryResults);35 unmodified lines results: [["Late A", "Late snippet", "https://late.example"]], stale: true, }); await new Promise((resolve) => setTimeout(resolve, 0)); await drainContinuations(); await first;
expect(harness.state.textSearchResults).toEqual(restoredResults);1234567234567891011121314151 unmodified line171819151617181920212223242526272829303132333435363738394041424320212223242526278 unmodified lines3637385859606139404142import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("./pubSub", () => ({ getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })), getQuery: vi.fn(() => ""), getResponse: vi.fn(() => ""), getSettings: vi.fn(() => ({import { historyMock, logEntriesMock, notificationsMock, pubSubMock, searchMock, wllamaMock,} from "./textGenerationTestUtils";
vi.mock("./pubSub", () => pubSubMock(() => ({ inferenceType: "browser", enableAiResponse: true, enableTextSearch: true,1 unmodified line searchResultsLimit: 10, allowAiModelDownload: true, })), getTextGenerationState: vi.fn(() => "idle"), listenToSettingsChanges: vi.fn(() => vi.fn()), updateChatMessages: vi.fn(), updateConversationSummary: vi.fn(), updateImageSearchResults: vi.fn(), updateImageSearchState: vi.fn(), updateLlmTextSearchResults: vi.fn(), updateResponse: vi.fn(), updateResponseImmediately: vi.fn(), updateSearchPromise: vi.fn(), updateTextGenerationState: vi.fn(), updateTextSearchResults: vi.fn(), updateTextSearchState: vi.fn(), updateTextSearchStale: vi.fn(), updateSuppressNextFollowUp: vi.fn(), updatePageContents: vi.fn(),}));vi.mock("./history", () => ({ replaceChatConversation: vi.fn(() => Promise.resolve()), getCurrentSearchRunId: vi.fn(() => "run-1"), saveLlmResponseForQuery: vi.fn(() => Promise.resolve()), updateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));vi.mock("./search", () => ({ searchImages: vi.fn(() => Promise.resolve([])), searchText: vi.fn(() => Promise.resolve([])),})););vi.mock("./history", () => historyMock(() => "run-1"));vi.mock("./logEntries", () => logEntriesMock());vi.mock("./notifications", () => notificationsMock());vi.mock("./search", () => searchMock());vi.mock("./systemPrompt", () => ({ getSystemPrompt: vi.fn(() => "") }));vi.mock("./textGenerationUtilities", () => ({ ChatGenerationError: class ChatGenerationError extends Error {},8 unmodified linesvi.mock("pretty-ms", () => ({ default: vi.fn(() => "100ms"),}));vi.mock("./textGenerationWithWllama", () => ({ generateTextWithWllama: vi.fn(() => Promise.resolve()), generateChatWithWllama: vi.fn(() => Promise.resolve("")),}));vi.mock("./textGenerationWithWllama", () => wllamaMock());
import gptTokenizer from "gpt-tokenizer";import {4 unmodified lines567891011121314151617186 unmodified lines25262720282930315 unmodified lines3738393240413435364243444523 unmodified lines69707166676869707172737475767778798081827273744 unmodified lines responseAtCompletion: { current: null as string | null },}));
import { contentFrame, logEntriesMock, notificationsMock, pageContentMock, sseStream,} from "./textGenerationTestUtils";
vi.mock("./history", () => ({ replaceChatConversation: vi.fn(() => Promise.resolve()), getCurrentSearchRunId: vi.fn(() => "run-1"),6 unmodified lines updateSearchResults: vi.fn(() => Promise.resolve()),}));
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./logEntries", () => logEntriesMock());
// The internal API sizes its budgets from /api/config; `fetch` below only// answers /inference.5 unmodified lines };});
vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));vi.mock("./notifications", () => notificationsMock());
vi.mock("./pageContent", () => ({ fetchPageContents: vi.fn(() => Promise.resolve({})),}));vi.mock("./pageContent", () => pageContentMock());
vi.mock("./search", () => ({ searchText: vi.fn(() =>23 unmodified linesconst mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);
function sseStream(frames: string[]) { const encoder = new TextEncoder(); return new Response( new ReadableStream({ start(controller) { for (const frame of frames) controller.enqueue(encoder.encode(frame)); controller.close(); }, }), { status: 200 }, );}
function contentFrame(content: string) { return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;}
describe("response persistence", () => { beforeEach(() => { harness.saved.length = 0;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import { vi } from "vitest";
/** * The `./textGenerationUtilities` override shared by the per-engine generation * tests. The helpers that read pubSub state become mocks, so a generation test * does not have to drive the UI channels; everything else (`ChatGenerationError`, * `defaultContextSize`) stays real, so `instanceof` checks still work. * * Returns the factory rather than the object so a `vi.mock` call can stay a * one-liner. Call it from inside a `vi.mock` factory that loads this module with * `await import(...)`: vitest hoists the registration above the imports, so a * static import here would only be initialised in time by accident of the import * order. */export function textGenerationUtilitiesMock( overrides: Record<string, unknown> = {},) { return async ( importOriginal: () => Promise<typeof import("./textGenerationUtilities")>, ) => ({ ...(await importOriginal()), canStartResponding: vi.fn().mockResolvedValue(undefined), getFormattedSearchResults: vi.fn().mockReturnValue("None."), ...overrides, });}
/** The `./textGenerationWithWllama` override: both generators answer nothing. */export function wllamaMock() { return { generateTextWithWllama: vi.fn(() => Promise.resolve()), generateChatWithWllama: vi.fn(() => Promise.resolve("")), };}
/** * A `Response` that streams `frames` as SSE, the shape the OpenAI-compatible * and internal-API paths produce. */export function sseStream(frames: string[]) { const encoder = new TextEncoder(); return new Response( new ReadableStream({ start(controller) { for (const frame of frames) controller.enqueue(encoder.encode(frame)); controller.close(); }, }), { status: 200 }, );}
/** One `chat.completion.chunk` delta frame carrying `content`. */export function contentFrame(content: string) { return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;}
/** * The `./history` override shared by the textGeneration tests: every write is * a resolved mock, and the run id is fixed so the supersede guards pass. */export function historyMock(getCurrentSearchRunId: () => string) { return { replaceChatConversation: vi.fn(() => Promise.resolve()), getCurrentSearchRunId: vi.fn(getCurrentSearchRunId), saveLlmResponseForQuery: vi.fn(() => Promise.resolve()), updateSearchResults: vi.fn(() => Promise.resolve()), mergeSearchImageResults: vi.fn(() => Promise.resolve()), };}
/** The `./logEntries` and `./notifications` overrides, with no behaviour. */export function logEntriesMock() { return { addLogEntry: vi.fn() };}
export function notificationsMock() { return { showAiCompleteNotification: vi.fn() };}
/** The `./pageContent` override: every read comes back empty. */export function pageContentMock() { return { fetchPageContents: vi.fn(() => Promise.resolve({})) };}
/** The `./search` override: both searches answer with nothing. */export function searchMock() { return { searchImages: vi.fn(() => Promise.resolve([])), searchText: vi.fn(() => Promise.resolve([])), };}
/** * The pubsub surface `textGeneration` reads. `getSettings` is the one part * tests rewrite per case, so it is passed in as a getter. */export function pubSubMock(getSettings: () => unknown) { return { getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })), getQuery: vi.fn(() => ""), getResponse: vi.fn(() => ""), getSettings: vi.fn(getSettings), getTextGenerationState: vi.fn(() => "idle"), listenToSettingsChanges: vi.fn(() => vi.fn()), updateChatMessages: vi.fn(), updateConversationSummary: vi.fn(), updateImageSearchResults: vi.fn(), updateImageSearchState: vi.fn(), updateLlmTextSearchResults: vi.fn(), updatePageContents: vi.fn(), updateResponse: vi.fn(), updateResponseImmediately: vi.fn(), updateSearchPromise: vi.fn(), updateSuppressNextFollowUp: vi.fn(), updateTextGenerationState: vi.fn(), updateTextSearchResults: vi.fn(), updateTextSearchStale: vi.fn(), updateTextSearchState: vi.fn(), };}126 unmodified lines127128129130131132133134135136137138139140141142143144145365 unmodified lines511512513501502503504505506507508509514515516517518514515516517518519520521522519520521522126 unmodified lines });});
/** Points the formatter at a worker that fails, and expects the fallback. */async function expectMainThreadFallback(worker: { terminate: () => void }) { setWorkerFactory(() => worker as unknown as Worker); setPageContents({ "https://a.example/": "sentence about cats. ".repeat(500), });
const formatted = await getFormattedSearchResults(true);
expect(formatted).toContain("โฆ"); expect(worker.terminate).toHaveBeenCalled();}
describe("getFormattedSearchResults", () => { beforeEach(() => { state.searchResults = results;365 unmodified lines data: { type: "error", message: "tokenization failed" }, } as MessageEvent<WorkerResponse>), ); setWorkerFactory(() => worker as unknown as Worker); setPageContents({ "https://a.example/": "sentence about cats. ".repeat(500), });
const formatted = await getFormattedSearchResults(true);
expect(formatted).toContain("โฆ"); expect(worker.terminate).toHaveBeenCalled(); await expectMainThreadFallback(worker); });
it("falls back when the worker dies before answering", async () => { const worker = createFailingWorker((deadWorker) => deadWorker.onerror?.()); setWorkerFactory(() => worker as unknown as Worker); setPageContents({ "https://a.example/": "sentence about cats. ".repeat(500), });
const formatted = await getFormattedSearchResults(true);
expect(formatted).toContain("โฆ"); expect(worker.terminate).toHaveBeenCalled(); await expectMainThreadFallback(worker); });
it("does not start a worker when no page content was read", async () => {23 unmodified lines2425262728293031323334352728293031394041323334353613 unmodified lines50515253545556575859606162636465666768697071727374757677784 unmodified lines8384857172738687888926 unmodified lines1161171181061071081191201211225 unmodified lines1281291301201211221311321331347 unmodified lines14214314413613713813914014114214514614714814915 unmodified lines1651661671641651661681691701717 unmodified lines1791801811801811821831841851861821831841881891901911921931851861871885 unmodified lines1941951962052062072082092102112122132142152162171971981992002012022 unmodified lines2052062072262272282082092102116 unmodified lines2182192202412422432212222232246 unmodified lines2312322332562572582342352362379 unmodified lines24724824927427527625025125225313 unmodified lines2672682692962972982702712722738 unmodified lines28228328431331431528528628728826 unmodified lines3153163173483493503183193203217 unmodified lines3293303313643653663323333343359 unmodified lines34534634738238338434834935035116 unmodified lines3683693704074084093713723733749 unmodified lines38438538642542642738738838939010 unmodified lines40140240344444544640440540640773 unmodified lines48148248348448548648748848949049149249349449549649749849950050150250324 unmodified lines52852953055655755855956056153153253353412 unmodified lines5475485495805815825505515525538 unmodified lines5625635645975985996006016025655665675684 unmodified lines57357457561361461561661757657761861962062157857958058158258313 unmodified lines5975985996426436446456466476486496506006016026036046056066071 unmodified line60961061161261361461561661761861962062162266262362466466566666766866967067167262562662762811 unmodified lines6406416426906916926936436446456466476976986997006486496506516526531 unmodified line6556566577097107117126586596606616621 unmodified line6646656667207217227236676686696706716721 unmodified line6746756767327337347356776786796806812 unmodified lines6846856867447457467476876886896906916922 unmodified lines69569669775775875976069869970070170276476576676770370470570670770870971077477577677771171271371471578171671771871913 unmodified lines7337347358018028037367377387392 unmodified lines74274374481281381481574574674774874981975075175275375475575682682782875775875976076176283483583683783883984084184284384484576376476576676785085185285376876977077177277377485986086186277577677777877978013 unmodified lines79479579688388488588688779779888989089179980080180212 unmodified lines81581681791091191291391481881982091791891982182282382423 unmodified lines sleep: vi.fn().mockResolvedValue(undefined),}));
// canStartResponding/getDefaultChatMessages/getFormattedSearchResults depend// on pubSub state we don't want to drive here; ChatGenerationError and// defaultContextSize have no such dependency, so keep them real.vi.mock("./textGenerationUtilities", async (importOriginal) => { const actual = await importOriginal<typeof import("./textGenerationUtilities")>(); return { ...actual, canStartResponding: vi.fn().mockResolvedValue(undefined),vi.mock("./textGenerationUtilities", async (importOriginal) => (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock({ getDefaultChatMessages: vi .fn() .mockReturnValue([{ role: "user", content: "hi" }]), getFormattedSearchResults: vi.fn().mockReturnValue("None."), };}); })(importOriginal),);
const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);13 unmodified lines vi.mocked(getSettings).mockReturnValue({ ...defaultSettings, ...overrides });}
/** Queues a submit, one in-progress poll, and a final empty reply. */function queueInterruptedPolling(id: string) { mockFetch .mockResolvedValueOnce(jsonResponse({ id })) .mockResolvedValueOnce( jsonResponse({ done: false, is_possible: true, generations: [] }), ) .mockResolvedValueOnce(jsonResponse({}));}
function abortWhenGenerating() { const controller = new AbortController(); vi.mocked(updateTextGenerationState).mockImplementation((next) => { if (next === "generating") controller.abort(); }); return controller;}
/** Loads the generator under test, after the fetch routes are in place. */async function loadHordeGenerator() { return (await import("./textGenerationWithHorde")).generateTextWithHorde;}
describe("textGenerationWithHorde", () => { beforeEach(() => { vi.clearAllMocks();4 unmodified lines
describe("generateTextWithHorde", () => { it("starts a generation, polls until done, and streams the response", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-1" }))26 unmodified lines });
it("throws ChatGenerationError when the generation is faulted", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-2" }))5 unmodified lines });
it("throws ChatGenerationError when the model reports generation is not possible", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-3" }))7 unmodified lines });
it("stops polling and publishes nothing once the user interrupts generation", async () => { const controller = new AbortController(); vi.mocked(updateTextGenerationState).mockImplementation((next) => { if (next === "generating") controller.abort(); }); const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const controller = abortWhenGenerating(); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-4" }))15 unmodified lines });
it('submits nothing and never enters "generating" once a newer search aborted it', async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); const controller = new AbortController(); controller.abort();
7 unmodified lines it("can be interrupted once it is generating, and cancels the queued job", async () => { // The UI only offers Stop while the state is "generating", so the // interrupt can only happen after the engine has entered it. const controller = new AbortController(); vi.mocked(updateTextGenerationState).mockImplementation((next) => { if (next === "generating") controller.abort(); }); const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const controller = abortWhenGenerating(); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-queued" })) .mockResolvedValueOnce( jsonResponse({ done: false, is_possible: true, generations: [] }), ) .mockResolvedValueOnce(jsonResponse({})); queueInterruptedPolling("gen-queued");
await expect(generateTextWithHorde(controller.signal)).rejects.toThrow( "Generation interrupted",5 unmodified lines });
it("cancels the job exactly once when the user interrupts", async () => { const controller = new AbortController(); vi.mocked(updateTextGenerationState).mockImplementation((next) => { if (next === "generating") controller.abort(); }); const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-stop" })) .mockResolvedValueOnce( jsonResponse({ done: false, is_possible: true, generations: [] }), ) .mockResolvedValueOnce(jsonResponse({})); const controller = abortWhenGenerating(); const generateTextWithHorde = await loadHordeGenerator(); queueInterruptedPolling("gen-stop");
await expect(generateTextWithHorde(controller.signal)).rejects.toThrow( "Generation interrupted",2 unmodified lines });
it("cancels a pinned-model job that faults", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-fault" })) .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))6 unmodified lines });
it("cancels a pinned-model job that the model cannot take", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-offline" })) .mockResolvedValueOnce(jsonResponse({ done: true, is_possible: false }))6 unmodified lines });
it("does not cancel a job whose answer was returned", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-ok" })) .mockResolvedValueOnce(9 unmodified lines });
it("keeps the original error and logs once when the cancel fails", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-x" })) .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))13 unmodified lines });
it("sends the cancel with a timeout and keepalive", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-k" })) .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))8 unmodified lines
it("includes the configured model in the generation request body", async () => { mockSettings({ hordeModel: "custom-model" }); const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator();
mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-5" }))26 unmodified lines });
it("keeps polling through a rate limit and finishes the generation", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-rate" })) .mockResolvedValueOnce(7 unmodified lines });
it("recovers when a gateway answers a poll with an HTML error page", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-gateway" })) .mockResolvedValueOnce(9 unmodified lines });
it("gives up on a status check that keeps failing without calling the model impossible", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-down" })) .mockImplementation(async () =>16 unmodified lines });
it("stops at once when the job is gone, with the server's message", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-gone" })) .mockResolvedValueOnce(9 unmodified lines });
it("rejects a finished generation that carries no text", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch .mockResolvedValueOnce(jsonResponse({ id: "gen-empty" })) .mockResolvedValueOnce(10 unmodified lines });
it("reports the server's reason when the job is refused at submit", async () => { const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); mockFetch.mockResolvedValueOnce( jsonResponse({ message: "Invalid API key" }, 401), );73 unmodified lines ); }
/** Routes a worker whose job faults and expects the generation to reject. */ async function expectFaultedGenerationRejects() { routeSingleWorker(() => ({ done: true, faulted: true }));
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).rejects.toThrow( "Generation failed", ); }
/** Runs one generation to its end and returns the generation request bodies. */ async function generationBodiesAfterOneRun() { const generateTextWithHorde = await loadHordeGenerator(); await generateTextWithHorde(); return generationRequestBodies(); }
function generationRequestBodies() { return mockFetch.mock.calls .filter(([url]) => String(url).includes("/generate/text/async"))24 unmodified lines statusResponder: () => doneResponse, });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); await generateTextWithHorde();
const bodies = generationRequestBodies(); const bodies = await generationBodiesAfterOneRun(); expect(bodies).toHaveLength(2); for (const body of bodies) { expect(body.models).toEqual(["m-f", "m-e", "m-d", "m-c", "m-b"]);12 unmodified lines statusResponder: () => doneResponse, });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); await generateTextWithHorde();
for (const body of generationRequestBodies()) {8 unmodified lines statusResponder: () => doneResponse, });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); await generateTextWithHorde();
const bodies = generationRequestBodies(); const bodies = await generationBodiesAfterOneRun(); expect(bodies).toHaveLength(2); for (const body of bodies) { expect(body.models).toBeUndefined();4 unmodified lines });
it("retries with any available model when the top models cannot take the job", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: (pollIndex) => pollIndex < 2 ? { done: true, is_possible: false } : doneResponse, routeSingleWorker((pollIndex) => pollIndex < 2 ? { done: true, is_possible: false } : doneResponse, });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await generateTextWithHorde();
expect(updateResponse).toHaveBeenCalledWith("Top model answer");13 unmodified lines });
it("does not submit a second round when the status checks keep failing", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: () => jsonResponse({ message: "Too many requests" }, 429), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" routeSingleWorker(() => jsonResponse({ message: "Too many requests" }, 429), );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).rejects.toThrow( "Too many requests", );1 unmodified line });
it("does not retry when the generation faults", async () => { await expectFaultedGenerationRejects(); expect(generationRequestBodies()).toHaveLength(2); });
/** One worker with ten monthly generations, the shape most tests need. */ function routeSingleWorker( statusResponder: (pollIndex: number, url: string) => unknown, ) { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: () => ({ done: true, faulted: true }), statusResponder, });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); await expect(generateTextWithHorde()).rejects.toThrow( "Generation failed", ); expect(generationRequestBodies()).toHaveLength(2); }); }
/** Answers each job's polls from its own script, by the job id in the URL. */ function perJobResponder(11 unmodified lines const pendingResponse = { done: false, is_possible: true, generations: [] };
it("serves the healthy job when its sibling faults first", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => ({ done: true, faulted: true }), "gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse), }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
expect(updateResponse).toHaveBeenCalledWith("Top model answer");1 unmodified line });
it("still retries with any model when one job faults and the other cannot take the job", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ // The faulted job is first in submission order, so picking the // first error would hide the "not possible" that the retry needs. "gen-1": () => ({ done: true, faulted: true }),1 unmodified line "gen-3": () => doneResponse, "gen-4": () => doneResponse, }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
expect(generationRequestBodies()).toHaveLength(4);1 unmodified line
it("reports an interrupt during the race and submits no retry", async () => { const controller = new AbortController(); routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => ({ done: true, is_possible: false }), "gen-2": (poll) => { // The user presses Stop while this job is still queued, after its2 unmodified lines return pendingResponse; }, }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde(controller.signal)).rejects.toThrow( "Generation interrupted", );2 unmodified lines });
it("cancels the losing job and not the winner", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => doneResponse, "gen-2": () => pendingResponse, }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer"); expect(cancelledIds()).toEqual(["gen-2"]); });
it("cancels the loser whose submit was still in flight when the race ended", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => doneResponse, "gen-2": () => pendingResponse, }), }); ); const routed = mockFetch.getMockImplementation(); let submits = 0; let releaseSecondSubmit: () => void = () => {};13 unmodified lines }, );
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer"); expect(cancelledIds()).toEqual([]);
2 unmodified lines });
it("returns the winner's answer without waiting for the loser's cancel", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => doneResponse, "gen-2": () => pendingResponse, }), }); ); const routed = mockFetch.getMockImplementation(); // A Horde that never answers the DELETE. mockFetch.mockImplementation((url: string, init?: { method?: string }) => init?.method === "DELETE" ? new Promise(() => {}) : routed?.(url, init), );
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer"); expect(cancelledIds()).toEqual(["gen-2"]); });
it("cancels both jobs when the race fails", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: () => ({ done: true, faulted: true }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); await expect(generateTextWithHorde()).rejects.toThrow( "Generation failed", ); await expectFaultedGenerationRejects(); expect(cancelledIds().sort()).toEqual(["gen-1", "gen-2"]); });
it("cancels the first round before submitting the fallback round", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: perJobResponder({ routeSingleWorker( perJobResponder({ "gen-1": () => ({ done: true, is_possible: false }), "gen-2": () => ({ done: true, is_possible: false }), "gen-3": () => doneResponse, "gen-4": () => pendingResponse, }), });
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" );
const generateTextWithHorde = await loadHordeGenerator(); await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
const calls = mockFetch.mock.calls.map(([url, init]) =>13 unmodified lines });
it("reuses the cached ranking for the next generation", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: () => doneResponse, }); routeSingleWorker(() => doneResponse);
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); await generateTextWithHorde(); await generateTextWithHorde();
12 unmodified lines });
it("refetches the ranking after the cache expires", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], monthStats: { "m-a": 10 }, statusResponder: () => doneResponse, }); routeSingleWorker(() => doneResponse); const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);
const { generateTextWithHorde } = await import( "./textGenerationWithHorde" ); const generateTextWithHorde = await loadHordeGenerator(); await generateTextWithHorde(); nowSpy.mockReturnValue(5 * 60 * 1000 + 1); await generateTextWithHorde();22 unmodified lines232425262728293031323334352627282930314041323334353618 unmodified lines5556576667585960616962636465666768697071727374757677787980838485868788899091928182838485868788899091130 unmodified lines222223224229230231232225226227228108 unmodified lines33733833934734834935034034134234322 unmodified lines getSystemPrompt: vi.fn().mockReturnValue("system prompt"),}));
// canStartResponding/getFormattedSearchResults depend on pubSub state we// don't want to drive here; ChatGenerationError has no such dependency, so// keep it real so `instanceof` checks against it still work.vi.mock("./textGenerationUtilities", async (importOriginal) => { const actual = await importOriginal<typeof import("./textGenerationUtilities")>(); return { ...actual, canStartResponding: vi.fn().mockResolvedValue(undefined), getFormattedSearchResults: vi.fn().mockReturnValue("None."),vi.mock("./textGenerationUtilities", async (importOriginal) => (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock({ getDefaultChatCompletionCreateParamsStreaming: vi.fn().mockReturnValue({ max_tokens: 1000, temperature: 0.35, }), };}); })(importOriginal),);
const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);18 unmodified lines}
/** * A response whose stream sends `chunks` and then stays open, as a stalled * upstream does, with a spy on the stream's cancel. * A response whose stream sends `chunks`, with a spy on the stream's cancel. * `close` ends the stream, as a completed upstream does; leaving it open * stands in for a stalled one. */function openStreamResponse(chunks: string[]) {function streamBody(chunks: string[], close: boolean) { const cancel = vi.fn(); const encoder = new TextEncoder(); const body = new ReadableStream({ start(controller) { for (const chunk of chunks) controller.enqueue(encoder.encode(chunk)); if (close) controller.close(); }, cancel, }); return { response: new Response(body), cancel };}
function openStreamResponse(chunks: string[]) { return streamBody(chunks, false);}
/** A closed stream, with a spy on its cancel. */function closedStreamResponse(chunks: string[]) { const cancel = vi.fn(); const encoder = new TextEncoder(); const body = new ReadableStream({ start(controller) { for (const chunk of chunks) controller.enqueue(encoder.encode(chunk)); controller.close(); }, cancel, }); return { response: new Response(body), cancel }; return streamBody(chunks, true);}
/** Makes the first publish abort the generation, and returns its controller. */function abortOnFirstPublish() { const controller = new AbortController(); vi.mocked(updateResponse).mockImplementationOnce(() => controller.abort()); return controller;}
function fetchSignal(): AbortSignal {130 unmodified lines ]), ), ); const controller = new AbortController(); vi.mocked(updateResponse).mockImplementationOnce(() => controller.abort(), ); const controller = abortOnFirstPublish();
await expect( generateTextWithInternalApi(controller.signal),108 unmodified lines 'data: {"choices":[{"delta":{"content":"partial"}}]}\n', ]); mockFetch.mockResolvedValueOnce(stream.response); const controller = new AbortController(); vi.mocked(updateResponse).mockImplementationOnce(() => controller.abort(), ); const controller = abortOnFirstPublish();
await expect( generateTextWithInternalApi(controller.signal),47 unmodified lines484950515253545556575859515253545556575847 unmodified lines getSystemPrompt: vi.fn().mockReturnValue("system"),}));
vi.mock("./textGenerationUtilities", async (importOriginal) => { const actual = await importOriginal<typeof import("./textGenerationUtilities")>(); return { ...actual, canStartResponding: vi.fn().mockResolvedValue(undefined), getFormattedSearchResults: vi.fn().mockReturnValue("None."), };});vi.mock("./textGenerationUtilities", async (importOriginal) => (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock()( importOriginal, ),);
vi.mock("./webGpu", () => ({ webGpuSupport: Promise.resolve(false) }));
129 unmodified lines130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202103 unmodified lines3063073082422432442452463093103113123133143152532542552563163173183193205 unmodified lines32632732826826927027127232933027427527633133233333420 unmodified lines3553563573033043583593603612 unmodified lines3643653663133143673683693703 unmodified lines3743753763243253263273283293303313323333343353363773783383793803813823433443453463473483493503513523533543553563573583833843853603613623633643653663863873883893903913923933733743753763773943953793803813823963973983994002 unmodified lines4034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464473983994004014484494504514054064074084094104114124134524534154164174544554564204574584594604614624634 unmodified lines46846947043143247147247347411 unmodified lines4864874884504514524534544894564904914924934944614624954644654664674964974984995004724734744754765014785025035045055064834845074864874884895085095105115125134954964974984995145015155165175185195201 unmodified line5225235245095105115125135255155265275285295305315215225235245255325275335345355365375385395345355405375385395405415425415425435445455465475483 unmodified lines55255355455255355555555655755855655755855911 unmodified lines5715725735765775785795805745755765776 unmodified lines5845855865935945875885895909 unmodified lines600601602610611603604605606129 unmodified lines return worker;}
type FakeWorker = ReturnType<typeof createFakeWorker>;
/** Installs a fake worker as the local engine. */function installFakeWorker(): FakeWorker { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker); return worker;}
/** Starts reading `text` with the local engine and waits for its request. */async function startLocalSpeech(text: string) { const worker = installFakeWorker(); const speaking = tts.speak(text); await vi.waitFor(() => expect(worker.sent).toHaveLength(1)); return { worker, speaking };}
/** The local voice the engine asks for when reading `text`. */async function localVoiceFor(text: string): Promise<string> { return (await startLocalSpeech(text)).worker.sent[0].voiceId;}
/** Reads `text` locally; the worker sends one chunk, then fails. */async function speakUntilWorkerFailsAfterFirstChunk(text: string) { const { worker, speaking } = await startLocalSpeech(text); sendAudioChunk(worker); await vi.waitFor(() => expect(createdObjectUrls).toBe(1)); sendError(worker, "synthesis died halfway"); await speaking;}
function sendAudioChunk(worker: FakeWorker) { worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, });}
function sendDone(worker: FakeWorker) { worker.onmessage?.({ data: { type: "done" } });}
function sendError(worker: FakeWorker, message: string) { worker.onmessage?.({ data: { type: "error", message } });}
/** An Audio element whose playback is always refused. */function stubUnplayableAudio() { vi.stubGlobal( "Audio", class { onended: (() => void) | null = null; onerror: (() => void) | null = null; pause = vi.fn(); removeAttribute = vi.fn(); src = ""; play() { return Promise.reject(new Error("autoplay blocked")); } }, );}
function removeSystemVoices() { vi.stubGlobal("speechSynthesis", undefined); self.speechSynthesis = undefined as unknown as SpeechSynthesis;}
let spoken: string[] = [];let spokenLanguages: string[] = [];let createdObjectUrls = 0;103 unmodified lines
describe("speak", () => { it("reads the answer with the local engine when it works", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1)); const { worker, speaking } = await startLocalSpeech("Hello there.");
expect(worker.sent[0]).toEqual({ sentences: ["Hello there."], voiceId: "en_US-lessac-high", });
worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, }); worker.onmessage?.({ data: { type: "done" } }); sendAudioChunk(worker); sendDone(worker);
await speaking; expect(createdObjectUrls).toBe(1);5 unmodified lines });
it("falls back to the system voice when the local engine cannot load", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1)); const { worker, speaking } = await startLocalSpeech("Hello there.");
worker.onmessage?.({ data: { type: "error", message: "model download failed" }, }); sendError(worker, "model download failed");
await speaking; expect(spoken).toEqual(["Hello there."]);20 unmodified lines
it("uses the system engine directly when it is selected", async () => { settings.textToSpeechEngine = "system"; const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker); const worker = installFakeWorker();
await tts.speak("Hello there.");
2 unmodified lines });
it("creates no utterance and never enters the speaking state for an open reasoning block", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker); const worker = installFakeWorker();
await tts.speak("<think>The user wants the capital. Maybe Paris?");
3 unmodified lines });
it("does not fall back after audio has started", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("One. Two."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, }); await vi.waitFor(() => expect(createdObjectUrls).toBe(1)); worker.onmessage?.({ data: { type: "error", message: "synthesis died halfway" }, }); await speakUntilWorkerFailsAfterFirstChunk("One. Two.");
await speaking; expect(spoken).toEqual([]); });
it("falls back when every synthesized chunk fails to play", async () => { vi.stubGlobal( "Audio", class { onended: (() => void) | null = null; onerror: (() => void) | null = null; pause = vi.fn(); removeAttribute = vi.fn(); src = ""; play() { return Promise.reject(new Error("autoplay blocked")); } }, );
const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker); stubUnplayableAudio(); const { worker, speaking } = await startLocalSpeech("Hello there.");
const speaking = tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, }); worker.onmessage?.({ data: { type: "done" } }); sendAudioChunk(worker); sendDone(worker);
await speaking; expect(spoken).toEqual(["Hello there."]); });
it("detaches the audio handlers before clearing the source", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1)); const { worker, speaking } = await startLocalSpeech("Hello there.");
worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, }); worker.onmessage?.({ data: { type: "done" } }); sendAudioChunk(worker); sendDone(worker); await speaking;
// A real element can still fire `error` during teardown; a still-attached2 unmodified lines });
it("falls back when the worker fails and no chunk was ever audible", async () => { stubUnplayableAudio(); await speakUntilWorkerFailsAfterFirstChunk("One. Two.");
expect(spoken).toEqual(["One. Two."]); });
it("falls back to the system voice when the worker errors before any audio starts", async () => { const { worker, speaking } = await startLocalSpeech("One. Two.");
worker.onerror?.();
await speaking; expect(spoken).toEqual(["One. Two."]); expect(mockAddLogEntry).toHaveBeenCalledWith( "Local text-to-speech unavailable, using the system voices: The local text-to-speech worker failed to start", ); });
it("does not fall back when the worker errors after the first chunk started playing", async () => { const { worker, speaking } = await startLocalSpeech("One. Two.");
sendAudioChunk(worker); await vi.waitFor(() => expect(createdObjectUrls).toBe(1)); worker.onerror?.();
await speaking; expect(spoken).toEqual([]); expect(mockAddLogEntry).not.toHaveBeenCalledWith( expect.stringContaining("Local text-to-speech unavailable"), ); });
it("treats a chunk as audible once play() resolves, even without onended firing", async () => { vi.stubGlobal( "Audio", class { onended: (() => void) | null = null; onerror: (() => void) | null = null; src = ""; play = () => Promise.resolve(); pause = vi.fn(); removeAttribute = vi.fn(); src = ""; play() { return Promise.reject(new Error("autoplay blocked")); } }, ); const { worker, speaking } = await startLocalSpeech("One. Two.");
const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("One. Two."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
worker.onmessage?.({ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) }, }); sendAudioChunk(worker); await vi.waitFor(() => expect(createdObjectUrls).toBe(1)); worker.onmessage?.({ data: { type: "error", message: "synthesis died halfway" }, }); sendError(worker, "synthesis died halfway");
await speaking; expect(spoken).toEqual(["One. Two."]); expect(spoken).toEqual([]); expect(mockAddLogEntry).toHaveBeenCalledWith( "Local text-to-speech stopped early: synthesis died halfway", ); });
it("honours a stop pressed while the voice catalogue is still loading", async () => {4 unmodified lines }), );
const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker); const worker = installFakeWorker();
const speaking = tts.speak("Hello there."); await vi.waitFor(() =>11 unmodified lines
it("picks the local voice for the answer's language, not the browser's", async () => { mockVoices.mockResolvedValue([englishVoice, portugueseVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak(portugueseAnswer); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("pt_BR-faber-medium"); expect(await localVoiceFor(portugueseAnswer)).toBe("pt_BR-faber-medium"); });
it("prefers a medium voice over a low one of the same language", async () => { mockVoices.mockResolvedValue([englishLowVoice, englishMediumVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium"); expect(await localVoiceFor("Hello there.")).toBe("en_GB-alan-medium"); });
it("prefers a medium voice over a high one, which is a bigger download", async () => { mockVoices.mockResolvedValue([englishVoice, englishMediumVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium"); expect(await localVoiceFor("Hello there.")).toBe("en_GB-alan-medium"); });
it("prefers the browser's region among voices of the same quality", async () => { mockVoices.mockResolvedValue([englishMediumVoice, americanMediumVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("en_US-amy-medium"); expect(await localVoiceFor("Hello there.")).toBe("en_US-amy-medium"); });
it("prefers a low voice over an x-low one of the same language", async () => { vi.stubGlobal("navigator", { language: "vi-VN" }); mockVoices.mockResolvedValue([vietnameseXLowVoice, vietnameseLowVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak(vietnameseAnswer); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("vi_VN-25hours_single-low"); expect(await localVoiceFor(vietnameseAnswer)).toBe( "vi_VN-25hours_single-low", ); });
it("keeps the catalogue order when the answer's language has no region", async () => {1 unmodified line portugueseFromPortugalVoice, portugueseVoice, ]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak(portugueseAnswer); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("pt_PT-tugรฃo-medium"); expect(await localVoiceFor(portugueseAnswer)).toBe("pt_PT-tugรฃo-medium"); });
it("keeps a chosen voice whatever the answer's language", async () => { mockVoices.mockResolvedValue([englishVoice, portugueseVoice]); settings.selectedVoiceId = "piper:en_US-lessac-high"; const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak(portugueseAnswer); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("en_US-lessac-high"); expect(await localVoiceFor(portugueseAnswer)).toBe("en_US-lessac-high"); });
it("keeps the browser language when the detector cannot recognize it", async () => { // franc-min has no Danish and reads this sentence as Swedish. vi.stubGlobal("navigator", { language: "da-DK" }); mockVoices.mockResolvedValue([swedishVoice, danishVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak( "Eiffeltรฅrnet blev bygget i 1889 til verdensudstillingen i Paris og er omkring 330 meter hรธjt.", ); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("da_DK-talesyntese-medium"); expect( await localVoiceFor( "Eiffeltรฅrnet blev bygget i 1889 til verdensudstillingen i Paris og er omkring 330 meter hรธjt.", ), ).toBe("da_DK-talesyntese-medium"); });
it("uses the browser language when the detector fails to load", async () => {3 unmodified lines try { tts = await import("./textToSpeech"); mockVoices.mockResolvedValue([englishVoice, portugueseVoice]); const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
void tts.speak(portugueseAnswer); await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
expect(worker.sent[0].voiceId).toBe("en_US-lessac-high"); expect(await localVoiceFor(portugueseAnswer)).toBe("en_US-lessac-high"); expect(mockAddLogEntry).toHaveBeenCalledWith( expect.stringContaining("Could not detect the answer's language"), );11 unmodified lines });
it("stops playback without falling back to the system voice", async () => { const worker = createFakeWorker(); tts.setWorkerFactory(() => worker as unknown as Worker);
const speaking = tts.speak("Hello there."); await vi.waitFor(() => expect(worker.sent).toHaveLength(1)); const { worker, speaking } = await startLocalSpeech("Hello there.");
tts.stopSpeaking(); await speaking;6 unmodified linesdescribe("no speech engine at all", () => { it("resolves and logs when the local engine failed and there are no OS voices", async () => { mockVoices.mockRejectedValue(new Error("offline")); vi.stubGlobal("speechSynthesis", undefined); self.speechSynthesis = undefined as unknown as SpeechSynthesis; removeSystemVoices();
await tts.speak("Hello there.");
9 unmodified lines
it("lists no voices instead of throwing", async () => { mockVoices.mockRejectedValue(new Error("offline")); vi.stubGlobal("speechSynthesis", undefined); self.speechSynthesis = undefined as unknown as SpeechSynthesis; removeSystemVoices();
await expect(tts.listVoices("en-US", "system")).resolves.toEqual([]); });3 unmodified lines4567891010111213141516171819111213143 unmodified linesimport "fake-indexeddb/auto";import "@testing-library/jest-dom/vitest";import { vi } from "vitest";import { matchMediaStub } from "./matchMediaStub";
Object.defineProperty(window, "matchMedia", { writable: true, value: vi.fn().mockImplementation((query) => ({ matches: false, media: query, onchange: null, addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(), removeEventListener: vi.fn(), dispatchEvent: vi.fn(), })), value: vi.fn().mockImplementation((query) => matchMediaStub(query)),});
class ResizeObserverMock {12345678910111213141516171819202122232425262728293031323334353637383940import { useSyncExternalStore } from "react";
/** * The `speechToText` mock the dictation component tests share. Each file calls * it from its own `vi.mock`, because those calls are hoisted above the * imports and only run their factory later. */export async function speechToTextMock() { const { DictationError: RealDictationError } = await import( "@/modules/speechToText" ); return { DictationError: RealDictationError, getDictationEngine: vi.fn(() => "wasm" as const), startDictation: vi.fn(), };}
/** A `notifications` stub that only records what was shown. */export function notificationsStub() { return { notifications: { show: vi.fn() } };}
/** * `create-pubsub/react` subscribing for real, so a channel written mid-test * re-renders the component the way it does in the app. */export function pubSubReactMock() { return { usePubSub: (pubSub: [unknown, unknown, unknown]) => { const [publish, subscribe, get] = pubSub as [ unknown, (listener: () => void) => () => void, () => unknown, ]; const value = useSyncExternalStore(subscribe, get, get); return [value, publish]; }, };}424 unmodified lines425426427428429430431432433434435436437438439428429430431432433434435436437438439440441442443443444445446424 unmodified lines
### Build-Time vs Runtime Configuration
| Value | Resolved At | Notes || ---------------------------------- | ----------- | ----------------------------------------------------------------------------------- || `VITE_BUILD_DATE_TIME` | Build time | Epoch milliseconds when the build occurred || `VITE_COMMIT_SHORT_HASH` | Build time | Git commit hash at build time (if available) || `ACCESS_KEYS` | Runtime | Read from `/api/config` || `ACCESS_KEY_TIMEOUT_HOURS` | Runtime | Read from `/api/config` || `WLLAMA_DEFAULT_MODEL_ID` | Runtime | Read from `/api/config` || `WLLAMA_DEFAULT_GPU_MODEL_ID` | Runtime | Read from `/api/config` || `INTERNAL_OPENAI_COMPATIBLE_API_*` | Runtime | Read from `/api/config` (except `API_KEY` which is server-only) || `DEFAULT_INFERENCE_TYPE` | Runtime | Read from `/api/config` || `PARENT_WINDOW_ORIGINS` | Runtime | Read from `/api/config` || Search token | Runtime | Read from `/api/config`, so a reload picks up the token of whichever server answers || Value | Resolved At | Notes || ---------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- || `VITE_BUILD_DATE_TIME` | Build time | Epoch milliseconds when the build occurred || `VITE_COMMIT_SHORT_HASH` | Build time | The commit the build reports: the source commit the Hugging Face deploy workflow wrote into `.source-commit`, or, when that file is not there, the build's own git hash || `ACCESS_KEYS` | Runtime | Read from `/api/config` || `ACCESS_KEY_TIMEOUT_HOURS` | Runtime | Read from `/api/config` || `WLLAMA_DEFAULT_MODEL_ID` | Runtime | Read from `/api/config` || `WLLAMA_DEFAULT_GPU_MODEL_ID` | Runtime | Read from `/api/config` || `INTERNAL_OPENAI_COMPATIBLE_API_*` | Runtime | Read from `/api/config` (except `API_KEY` which is server-only) || `DEFAULT_INFERENCE_TYPE` | Runtime | Read from `/api/config` || `PARENT_WINDOW_ORIGINS` | Runtime | Read from `/api/config` || Search token | Runtime | Read from `/api/config`, so a reload picks up the token of whichever server answers |
### Security Considerations
- `VITE_BUILD_DATE_TIME` and `VITE_COMMIT_SHORT_HASH` are bundled into the client JavaScript as build-time constants (build metadata only)- `VITE_BUILD_DATE_TIME` and `VITE_COMMIT_SHORT_HASH` are bundled into the client JavaScript as build-time constants (build metadata only). A Hugging Face Space is built from a copy of the repository, so its git hash belongs to the Space; the deploy workflow writes the source commit into `.source-commit` beside that copy, and `shared/buildSourceCommit.ts` prefers it, which is what `/status` and the app version string then report- The CSRF token is served at runtime like the rest of the config. It reaches any caller that can reach `/api/config`, which is the same exposure it had while it was compiled into the bundle- All other configuration is fetched at runtime from `/api/config` and never appears in the bundled JavaScript- Server-only variables like `INTERNAL_OPENAI_COMPATIBLE_API_KEY` are never exposed to the client105 unmodified lines106107108109109110111112105 unmodified lines| `on-pull-request-to-main.yml` | PR opened/synced/reopened to `main` | Delegates to `reusable-check-docker.yml`; skippable via `skip-check-docker` label || `publish-docker-image.yml` | Manual (`workflow_dispatch`), `main` only | Cuts a CalVer release: validates the optional `version` input (empty auto-computes today's date in UTC plus the next free same-day sequence), builds the multi-platform Docker image (linux/amd64, linux/arm64) and pushes it to `ghcr.io` as that version plus `latest` (build job, `contents: read` + `packages: write`), then a second job holding `contents: write` pushes the git tag and publishes the GitHub Release. The release job is idempotent: when a run pushed the tag but failed before publishing the Release, re-running that job alone finishes it without rebuilding || `scan-docker-image.yml` | Weekly (Monday 06:00 UTC) or manual | Trivy scan of the published image, reporting fixable HIGH/CRITICAL findings to code scanning || `deploy-to-hugging-face.yml` | Manual (`workflow_dispatch`) | Syncs the repository to a Hugging Face Space with the `hf` CLI over OIDC Trusted Publishers || `deploy-to-hugging-face.yml` | Manual (`workflow_dispatch`) | Syncs the repository to a Hugging Face Space with the `hf` CLI over OIDC Trusted Publishers, writing the source commit into `.source-commit` first so the Space build can report the commit that is actually running || `stale.yml` | Daily (01:30 UTC) or manual | Marks and closes inactive issues and labels stale pull requests || `reusable-check-docker.yml` | Called by other workflows | Docker compose production build + health check via `curl localhost:7860` (lint/format/test are covered by `ci.yml`) |
.github/workflows/deploy-to-hugging-face.yml+18
.source-commitAdded+1
Dockerfile+2-2
changelog.md+4
client/components/AiResponse/ChatInputArea.test.tsx+16-34
client/components/AiResponse/ChatInterface.test.tsx+121-85
client/components/AiResponse/MessageList.test.tsx+15-11
client/components/DictationButton.test.tsx+66-100
client/components/Pages/Main/MainPage.test.tsx+10-12
client/components/Pages/Main/Menu/ClearDataButton.test.tsx+11-24
client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx+12-12
client/components/Search/Form/SearchForm.test.tsx+2-6
client/components/Search/History/HistoryDrawer.test.tsx+17-18
client/components/Search/Results/Graphical/ImageResultsList.test.tsx+11-8
client/components/Search/Results/Graphical/ImageSearchResults.test.tsxAdded+67
client/components/Search/Results/Graphical/ImageSearchResults.tsx+6
client/components/Search/Results/testUtils.ts+3-12
client/enterToSubmitCases.tsAdded+10
client/hooks/useSearchHistory.test.ts+14-20
client/matchMediaStub.tsAdded+22
client/modules/accessKey.test.ts+9-6
client/modules/chatHelpers.test.ts+55-34
client/modules/chatHelpers.ts+5-11
client/modules/history.test.ts+52-67
client/modules/pubSub.test.ts+28-14
client/modules/pubSub.throttle.test.ts+17-10
client/modules/search.test.ts+17-36
client/modules/speechToText.test.ts+23-44
client/modules/speechToText.ts+1-1
client/modules/textGeneration.chatBudget.test.ts+90-118
client/modules/textGeneration.degradation.test.ts+86-125
client/modules/textGeneration.inference.test.ts+17-39
client/modules/textGeneration.responsePersistence.test.ts+11-22
client/modules/textGenerationTestUtils.tsAdded+121
client/modules/textGenerationUtilities.test.ts+15-18
client/modules/textGenerationWithHorde.test.ts+122-220
client/modules/textGenerationWithInternalApi.test.ts+23-33
client/modules/textGenerationWithWllama.test.ts+5-9
client/modules/textToSpeech.test.ts+143-151
client/setupTests.ts+2-10
client/testMocks.tsAdded+40
docs/configuration.md+13-13
docs/development-commands.md+1-1