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 lines26272829303125 unmodified lines{ echo '---'; cat .github/hf-space-config.yml; echo '---'; echo; cat README.md; } > README.space.mdmv README.space.md README.md- name: Sync to the Spacerun: |hf upload "$HF_SPACE" . . \25 unmodified lines26272829303132333435363738394041424344454647484925 unmodified lines{ echo '---'; cat .github/hf-space-config.yml; echo '---'; echo; cat README.md; } > README.space.mdmv 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 repositoryrun: |if [ -e .source-commit ]; thenecho "::error::.source-commit is written by this workflow; remove it from the repository."exit 1fi# 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 buildrun: git rev-parse --short "$GITHUB_SHA" > .source-commit- name: Sync to the Spacerun: |hf upload "$HF_SPACE" . . \
17e8885e124 unmodified lines125126127128129130131132124 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."; \npm run build && \npm prune --omit=dev124 unmodified lines125126127128129130131132124 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 || [ -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 lines4567893 unmodified lines## 2026-11-27- 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-263 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-26
123456783 unmodified lines121314151617181920212223242526272829303132333435363738394041424344113 unmodified lines158159160161162163164165166167168169import { 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 {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];},}));const stopFn = vi.fn();const cancelFn = vi.fn();113 unmodified linessettingsPubSub[0]({ ...defaultSettings });});it.each([[true, "{Enter}", true],[true, "{Shift>}{Enter}{/Shift}", false],[false, "{Shift>}{Enter}{/Shift}", true],[false, "{Enter}", false],])("with enterToSubmit %s, pressing %s sends it: %s",async (enterToSubmit, keys, sends) => {settingsPubSub[0]({ ...defaultSettings, enterToSubmit });123456783 unmodified lines1213141516171819202122232425262728293031113 unmodified lines145146147148149150151import { MantineProvider } from "@mantine/core";import { render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";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";// 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-endconst stopFn = vi.fn();const cancelFn = vi.fn();113 unmodified linessettingsPubSub[0]({ ...defaultSettings });});it.each(ENTER_TO_SUBMIT_CASES)("with enterToSubmit %s, pressing %s sends it: %s",async (enterToSubmit, keys, sends) => {settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
121 unmodified lines12212312412512612734 unmodified lines16216316416516616716816917017117217317417517617726 unmodified lines204205206207208209210211212213214215216143 unmodified lines3603613623633643653663673683693703713723733743758 unmodified lines38438538638738838939039139239339439539639739839940040140240340440540640740848 unmodified lines4574584594604614624634644654664674684694704714724734744752 unmodified lines47847948048148248348448548648776 unmodified lines5645655665675685695705715725735745755765775785795805815825834 unmodified lines58858959059159259359459559659759859915 unmodified lines6156166176186196206216226236246256266276286296306316326336342 unmodified lines637638639640641642643644645646647648121 unmodified lines);}function stubWakeLockApi() {const release = vi.fn(() => Promise.resolve());const request = vi.fn(() =>34 unmodified linesdescribe("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);await act(async () => {await sendMessage("And how do I use it?");26 unmodified linessend = 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 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);let send: Promise<void> = Promise.resolve();await act(async () => {8 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);expect(getFollowUpQuestion()).toBe("");await act(async () => {newerQuestion.resolve("The newest question?");await 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);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?");});// The orphaned call fails. Its catch must not blank the newer one's work.await act(async () => {2 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);await act(async () => {newerQuestion.resolve("The newest question?");await send;});expect(getFollowUpQuestion()).toBe("The newest question?");expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);76 unmodified linesfirstSend = sendMessage("And how do I use it?");});await act(async () => {first.unmount();});renderChatInterface();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);// 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 linesexpect(getChatGenerationState().isGeneratingResponse).toBe(true);await act(async () => {secondResponse.resolve("The live answer.");await secondSend;});expect(getChatGenerationState().isGeneratingResponse).toBe(false);});it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {15 unmodified linesfirstRegenerate = regenerateResponse();});await act(async () => {first.unmount();});renderChatInterface();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);await act(async () => {firstResponse.resolve("The orphaned regeneration.");2 unmodified linesexpect(getChatGenerationState().isGeneratingResponse).toBe(true);await act(async () => {secondResponse.resolve("The live answer.");await secondSend;});expect(getChatGenerationState().isGeneratingResponse).toBe(false);});it("starts one re-generation when two regenerates land in the same task", async () => {121 unmodified lines12212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123234 unmodified lines26726826927027127227326 unmodified lines300301302303304305306143 unmodified lines4504514524534544554564578 unmodified lines46646746846947047147247347447547647747847948048 unmodified lines5295305315325335345355362 unmodified lines53954054154254354454576 unmodified lines6226236246256266276286296306316326336346354 unmodified lines64064164264364464564615 unmodified lines6626636646656666676686696706716726736746752 unmodified lines678679680681682683684121 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 linesdescribe("ChatInterface generation state", () => {it("leaves the follow-up question flag off after sending during its generation", async () => {const { question: earlierQuestion } = await mountWithFollowUpInFlight();await act(async () => {await sendMessage("And how do I use it?");26 unmodified linessend = sendMessage("And how do I use it?");});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, newerQuestion } =await mountWithTwoFollowUpsInFlight();let send: Promise<void> = Promise.resolve();await act(async () => {8 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);expect(getFollowUpQuestion()).toBe("");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 { 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, newerQuestion, send } =await sendDuringTwoFollowUpsInFlight();// The orphaned call fails. Its catch must not blank the newer one's work.await act(async () => {2 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);await settleNewestQuestion(newerQuestion, send);expect(getFollowUpQuestion()).toBe("The newest question?");expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);76 unmodified linesfirstSend = sendMessage("And how do I use it?");});await remountChatMidGeneration(first);let secondSend: Promise<void> = Promise.resolve();await act(async () => {secondSend = sendMessage("Does it work offline?");});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 linesexpect(getChatGenerationState().isGeneratingResponse).toBe(true);await settleLiveAnswer(secondResponse, secondSend);});it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {15 unmodified linesfirstRegenerate = regenerateResponse();});await remountChatMidGeneration(first);let secondSend: Promise<void> = Promise.resolve();await act(async () => {secondSend = sendMessage("Does it work offline?");});expectLiveGenerationStarted(3);await act(async () => {firstResponse.resolve("The orphaned regeneration.");2 unmodified linesexpect(getChatGenerationState().isGeneratingResponse).toBe(true);await settleLiveAnswer(secondResponse, secondSend);});it("starts one re-generation when two regenerates land in the same task", async () => {
28 unmodified lines29303132333422 unmodified lines575859606162636465666768697071727328 unmodified lines);}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[] = [{ 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();28 unmodified lines293031323334353637383940414243444546474822 unmodified lines7172737475767728 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", () => {const messages: ChatMessage[] = chatWithEmptyAnswers();it("edits each question at its position in the chat", () => {const onEditMessage = vi.fn();
1 unmodified line23456781 unmodified line10111213141516171819202122232425262728293031323334353637383940414243444546 unmodified lines92939495969798991001011022 unmodified lines1051061071081091101111121131149 unmodified lines124125126127128129130131132133134135136106 unmodified lines243244245246247248249250251252253254255256257258279 unmodified lines5385395405415425435442 unmodified lines5475485495505515525535545555565575585595604 unmodified lines56556656756856957057157257357414 unmodified lines5895905915925935945952 unmodified lines5985996006016026036046056066076086096106116126136146156166176186196206216226236246256266272 unmodified lines6306316326336346356366376386396406416426436446456466476486496507 unmodified lines6586596606616626636646656666671 unmodified line66967067167267367467567667767813 unmodified lines6926936946956966976986997007011 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 linestartDictation,} 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 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];},}));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,});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,});}});9 unmodified linesawait user.click(screen.getByRole("button", { name: "Dictate the search query" }),);await waitFor(() =>expect(startDictation).toHaveBeenCalledWith(expect.anything(),false,expect.any(AbortSignal),),);expect(getDictationEngine).toHaveBeenCalledWith(false);} finally {settingsPubSub[0]({106 unmodified lines"transcribing",);view.rerender(<MantineProvider><DictationButtongetValue={() => ""}setValue={() => {}}labelScope="the search query"disabled/></MantineProvider>,);// The transcript would otherwise land in a field that went read-only.await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));279 unmodified linesit("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));try {settingsPubSub[0]({...(settingsPubSub[2]?.() ?? {}),enableDictation: 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,});}});14 unmodified linesit("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));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,});release?.(session);await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));} finally {settingsPubSub[0]({...(settingsPubSub[2]?.() ?? {}),enableDictation: 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));try {settingsPubSub[0]({...(settingsPubSub[2]?.() ?? {}),enableDictation: false,});await waitFor(() =>expect(screen.queryByRole("button")).not.toBeInTheDocument(),);settingsPubSub[0]({...(settingsPubSub[2]?.() ?? {}),enableDictation: true,});await user.click(await screen.findByRole("button"));await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(2));7 unmodified linesawait waitFor(() => expect(first.cancel).toHaveBeenCalledTimes(1));expect(second.cancel).not.toHaveBeenCalled();} finally {settingsPubSub[0]({...(settingsPubSub[2]?.() ?? {}),enableDictation: true,});}});1 unmodified lineconst 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];act(() => onEnd?.());// The engine ending by itself is not a failure, but the button has to13 unmodified linesconst 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];act(() => onError?.(new DictationError("engine", "the transcriber died")));await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));1 unmodified line2345671 unmodified line910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656646 unmodified lines1131141151161171181192 unmodified lines1221231241251261271289 unmodified lines138139140141142143144106 unmodified lines251252253254255256257279 unmodified lines5375385395405415422 unmodified lines5455465475485495505515525535544 unmodified lines55956056156256356456514 unmodified lines5805815825835845852 unmodified lines5885895905915925935945955965975985996006016026036046056066076086092 unmodified lines6126136146156166176186196206216226236246257 unmodified lines6336346356366376386391 unmodified line64164264364464564664713 unmodified lines6616626636646656666671 unmodified lineimport { notifications } from "@mantine/notifications";import { act, render, screen, waitFor } from "@testing-library/react";import userEvent from "@testing-library/user-event";import DictationButton from "@/components/DictationButton";import {DictationError,1 unmodified linestartDictation,} from "@/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><DictationButtongetValue={() => ""}setValue={() => {}}labelScope="the search query"disabled/></MantineProvider>,);}/** 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 () => {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.await setDictationSetting(true);}});9 unmodified linesawait user.click(screen.getByRole("button", { name: "Dictate the search query" }),);await expectEngineStartedWith(false);expect(getDictationEngine).toHaveBeenCalledWith(false);} finally {settingsPubSub[0]({106 unmodified lines"transcribing",);renderDisabledButton(view);// The transcript would otherwise land in a field that went read-only.await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));279 unmodified linesit("stays quiet when a load abandoned by the setting fails", async () => {const user = userEvent.setup();let fail: ((error: Error) => void) | undefined;vi.mocked(startDictation).mockReturnValue(new Promise((_resolve, reject) => {2 unmodified lines);renderButton();await pressAndWaitForEngine(user);try {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 {await setDictationSetting(true);}});14 unmodified linesit("discards a session that arrives after the setting was turned off", async () => {const user = userEvent.setup();let release: ((value: typeof session) => void) | undefined;vi.mocked(startDictation).mockReturnValue(new Promise((resolve) => {2 unmodified lines);renderButton();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.await setDictationSetting(false);release?.(session);await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));} finally {await setDictationSetting(true);}});it("does not adopt a load an earlier press abandoned", async () => {const user = userEvent.setup();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 pressAndWaitForEngine(user);try {await setDictationSetting(false);await waitFor(() =>expect(screen.queryByRole("button")).not.toBeInTheDocument(),);await setDictationSetting(true);await user.click(await screen.findByRole("button"));await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(2));7 unmodified linesawait waitFor(() => expect(first.cancel).toHaveBeenCalledTimes(1));expect(second.cancel).not.toHaveBeenCalled();} finally {await setDictationSetting(true);}});1 unmodified lineconst user = userEvent.setup();renderButton();const { onEnd } = await pressAndWaitForEngine(user);act(() => onEnd?.());// The engine ending by itself is not a failure, but the button has to13 unmodified linesconst user = userEvent.setup();renderButton();const { onError } = await pressAndWaitForEngine(user);act(() => onError?.(new DictationError("engine", "the transcriber died")));await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
103 unmodified lines10410510610710810973 unmodified lines1831841851861871881891901911921931946 unmodified lines201202203204205206207208209210211212103 unmodified linesreturn { ...utils, ...handlers };}describe("MainPage", () => {beforeEach(() => {vi.clearAllMocks();73 unmodified linesit("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 },}),);await user.click(await screen.findByRole("button", { name: "Accept" }));6 unmodified linesit("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 },}),);await user.click(await screen.findByRole("button", { name: "Decline" }));103 unmodified lines10410510610710810911011111211311411511611773 unmodified lines1911921931941951961976 unmodified lines204205206207208209210103 unmodified linesreturn { ...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 linesit("enables AI response and triggers a search when the prompt is accepted", async () => {const user = userEvent.setup();const { setSettings } = await renderMainPage(promptPageState());await user.click(await screen.findByRole("button", { name: "Accept" }));6 unmodified linesit("disables AI response without triggering a search when the prompt is declined", async () => {const user = userEvent.setup();const { setSettings } = await renderMainPage(promptPageState());await user.click(await screen.findByRole("button", { name: "Decline" }));
29 unmodified lines30313233343535 unmodified lines717273747576777879808182838414 unmodified lines9910010110210310410510610710810911011111222 unmodified lines13513613713813914014114214314414514614714829 unmodified lines}describe("ClearDataButton", () => {const originalLocation = self.location;const originalCachesDescriptor = Object.getOwnPropertyDescriptor(self,35 unmodified linesvalue: undefined,});const user = userEvent.setup();renderClearDataButton();await user.click(screen.getByRole("button", { name: "Clear all data" }));await waitFor(() => {expect(reloadMock).toHaveBeenCalledTimes(1);});expect(localStorage.getItem("sample-key")).toBeNull();expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");14 unmodified linesnew Error("OPFS unavailable"),);const user = userEvent.setup();renderClearDataButton();await user.click(screen.getByRole("button", { name: "Clear all data" }));await waitFor(() => {expect(reloadMock).toHaveBeenCalledTimes(1);});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);});expect(keysMock).toHaveBeenCalledTimes(1);expect(deleteMock).toHaveBeenCalledWith("cache-a");29 unmodified lines303132333435363738394041424335 unmodified lines7980818283848514 unmodified lines10010110210310410510622 unmodified lines12913013113213313413529 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 linesvalue: undefined,});await pressClearAllData();expect(localStorage.getItem("sample-key")).toBeNull();expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");14 unmodified linesnew Error("OPFS unavailable"),);await pressClearAllData();expect(addLogEntry).toHaveBeenCalledWith("Error clearing data: OPFS unavailable",22 unmodified lines},});await pressClearAllData();expect(keysMock).toHaveBeenCalledTimes(1);expect(deleteMock).toHaveBeenCalledWith("cache-a");
93 unmodified lines94959697989910010110210310410510610726 unmodified lines13413513613713813914014114214314414593 unmodified lines);});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,});expect(options.map((option) => option.textContent)).toEqual(["๐บ๐ธ lessac โข English (high)",26 unmodified linesit("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,});expect(options.map((option) => option.textContent)).toEqual(["๐บ๐ธ OS Voice โข en-US",93 unmodified lines94959697989910010110210310410510610710810911011111226 unmodified lines13914014114214314414593 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 () => {const options = await renderedVoiceOptions();expect(options.map((option) => option.textContent)).toEqual(["๐บ๐ธ lessac โข English (high)",26 unmodified linesit("lists only the system voices while the system engine is selected", async () => {settings.current.textToSpeechEngine = "system";const options = await renderedVoiceOptions();expect(options.map((option) => option.textContent)).toEqual(["๐บ๐ธ OS Voice โข en-US",
1 unmodified line234567141 unmodified lines1491501511521531541551561571581591601 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 { resetHandledQuery } from "@/modules/autoSearch";import { settingsPubSub } from "@/modules/pubSub";import { getRandomQuerySuggestion } from "@/modules/querySuggestions";141 unmodified linessettingsPubSub[0]({ ...defaultSettings });});it.each([[true, "{Enter}", true],[true, "{Shift>}{Enter}{/Shift}", false],[false, "{Shift>}{Enter}{/Shift}", true],[false, "{Enter}", false],])("with enterToSubmit %s, pressing %s submits: %s",async (enterToSubmit, keys, submits) => {settingsPubSub[0]({ ...defaultSettings, enterToSubmit });1 unmodified line2345678141 unmodified lines1501511521531541551561 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 linessettingsPubSub[0]({ ...defaultSettings });});it.each(ENTER_TO_SUBMIT_CASES)("with enterToSubmit %s, pressing %s submits: %s",async (enterToSubmit, keys, submits) => {settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
77 unmodified lines78798081828353 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591603 unmodified lines16416516616716816917017117217317417577 unmodified lines});};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);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);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 queryButton = await screen.findByRole("button", {name: /quantum tunneling/,});77 unmodified lines787980818283848586878889909192939495969753 unmodified lines1511521531541551561571581591601611621631643 unmodified lines16816917017117217317477 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 { 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 { 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 { user, onSearchSelect, entry } = drawerWithOneEntry();const queryButton = await screen.findByRole("button", {name: /quantum tunneling/,});
66 unmodified lines67686970717240 unmodified lines1131141151161171181191201211221233 unmodified lines12712812913013113213313413566 unmodified lines);}describe("ImageResultsList", () => {it("renders thumbnails as named buttons", async () => {renderImageResultsList();40 unmodified linesit("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));expect(screen.getByRole("button", { name: "Open image preview: First image" }),).toHaveTextContent("example.com");3 unmodified linesconst user = userEvent.setup();renderImageResultsList();const [img] = await screen.findAllByRole("img");img.dispatchEvent(new Event("error"));await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1));await user.click(screen.getByRole("button", { name: "Open image preview: First image" }),66 unmodified lines67686970717273747576777879808140 unmodified lines1221231241251261271283 unmodified lines13213313413513613713866 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 linesit("shows the host name when a thumbnail fails to load", async () => {renderImageResultsList();await breakFirstThumbnail();expect(screen.getByRole("button", { name: "Open image preview: First image" }),).toHaveTextContent("example.com");3 unmodified linesconst user = userEvent.setup();renderImageResultsList();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 lines35363738394034 unmodified lines}if (searchState === "failed") {return (<Alertvariant="light"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 (<Alertvariant="light"
12341 unmodified line678910111213141516171819202122import { vi } from "vitest";/*** 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,);}123451 unmodified line78910111213import { 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) =>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 lines1211221231241251261271281291301311321331341351361375 unmodified lines1431441451461471481491501511521536 unmodified lines1601611621631641651661671681691706 unmodified lines177178179180181182183184185186187120 unmodified lines}}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);expect(queriesOf(result.current.filteredSearches)).toEqual(["newer search 4",5 unmodified linesit("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);expect(queriesOf(result.current.filteredSearches)).toEqual(["rust async tutorial",6 unmodified linesawait pinOldestEntry();await addNewerSearches(4);const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);act(() => result.current.searchHistory("lisbon"));await settle();6 unmodified linesawait pinOldestEntry();const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);expect(pinnedReadSpy).toHaveBeenCalledTimes(1);for (const query of ["w", "we", "wea"]) {120 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421435 unmodified lines1491501511521531541556 unmodified lines1621631641651661671686 unmodified lines175176177178179180181120 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 = await renderPinnedAwareHistory();expect(queriesOf(result.current.filteredSearches)).toEqual(["newer search 4",5 unmodified linesit("keeps a pinned search inside the window but past the limit", async () => {await pinOldestEntry();const result = await renderPinnedAwareHistory();expect(queriesOf(result.current.filteredSearches)).toEqual(["rust async tutorial",6 unmodified linesawait pinOldestEntry();await addNewerSearches(4);const result = await renderPinnedAwareHistory();act(() => result.current.searchHistory("lisbon"));await settle();6 unmodified linesawait pinOldestEntry();const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");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 lines363738394041154 unmodified lines1961971981992002012022032042 unmodified lines20720820921021121221321421535 unmodified linesconst TIMEOUT_HOURS = 24;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();});it("deletes a stored value that is not JSON without asking the server", async () => {2 unmodified linesconst result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);expect(localStorage.getItem("accessKeyHash")).toBeNull();expect(mockFetch).not.toHaveBeenCalled();});it("keeps the stored hash on a 429 instead of deleting it", async () => {35 unmodified lines36373839404142434445464748154 unmodified lines2032042052062072082092 unmodified lines21221321421521621721835 unmodified linesconst 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);expectStoredKeyDiscarded(result);});it("deletes a stored value that is not JSON without asking the server", async () => {2 unmodified linesconst result = await verifyStoredAccessKey(TIMEOUT_HOURS);expectStoredKeyDiscarded(result);});it("keeps the stored hash on a 429 instead of deleting it", async () => {
1234493 unmodified lines49849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154230 unmodified lines5735745755765775785795805815825835845855865872 unmodified lines590591592593594595596597598599import { beforeEach, describe, expect, it, vi } from "vitest";beforeEach(() => vi.clearAllMocks());493 unmodified linesmockGetCurrentSearchRunId.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 = () => {};mockSearchImages.mockReturnValueOnce(new Promise((resolve) => {releaseFirst = resolve;}),);const existingA: ImageSearchResults = [["Initial", "https://initial.com", "thumb-0", "src-0"],];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,];mockSearchImages.mockResolvedValueOnce({results: [["B1", "https://b1.com", "thumb-b1", "src-b1"]],stale: false,});await refreshImageSearchResults("second", 10, existingB);releaseFirst({results: [["Late A", "https://a.com", "thumb-a", "src-a"]],stale: false,});await first;expect(mockUpdateImage).toHaveBeenCalledTimes(1);expect(mockUpdateImage).toHaveBeenCalledWith([["B1", "https://b1.com", "thumb-b1", "src-b1"],...existingB,]);expect(mergeSearchImageResults).toHaveBeenCalledTimes(1);});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 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,});await refresh;expect(mockUpdateImage).not.toHaveBeenCalled();1234493 unmodified lines49849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357430 unmodified lines6056066076086096106112 unmodified lines614615616617618619620import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";beforeEach(() => vi.clearAllMocks());493 unmodified linesmockGetCurrentSearchRunId.mockReturnValue("run-1");});/** Holds the next image search until the returned function releases it. */function holdNextImageSearch() {let release: (results: ImageSearchResults) => void = () => {};mockSearchImages.mockReturnValueOnce(new Promise((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));// 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, existingA);releaseFirst([["Late A", "https://a.com", "thumb-a", "src-a"]]);await first;const both: ImageSearchResults = [["Late A", "https://a.com", "thumb-a", "src-a"],["B1", "https://b1.com", "thumb-b1", "src-b1"],...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 () => {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([["Fresh", "https://fresh.com", "thumb-f", "src-f"]]);await refresh;expect(mockUpdateImage).not.toHaveBeenCalled();
42 unmodified lines4344454647484950515268 unmodified lines12112212312412512612712812913013113213313413513625 unmodified lines16216316416516616716842 unmodified linesreturn () => 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 linesexistingResults: ImageSearchResults,searchRunId = getCurrentSearchRunId(),): Promise<void> {const invocation = ++imageRefreshInvocation;latestImageRefreshByRunId.set(searchRunId, invocation);const isSameAttempt = sameSearchAttempt(searchRunId);const isCurrent = () =>invocation === imageRefreshInvocation &&searchRunId === getCurrentSearchRunId() &&isSameAttempt();const isRunCurrent = () =>latestImageRefreshByRunId.get(searchRunId) === invocation &&isSameAttempt();const { results: imageResults } = await searchImages(searchQuery,25 unmodified linesupdateImageSearchResults(updatedImageResults);}if (isRunCurrent()) {mergeSearchImageResults(searchRunId, {type: "image",items: updatedImageResults.map(42 unmodified lines434445464748495068 unmodified lines11912012112212312412512612712812913025 unmodified lines15615715815916016116242 unmodified linesreturn () => getLatestSearchAttempt(searchRunId) === attempt;}let textRefreshInvocation = 0;let pageContentsReadInvocation = 0;const latestTextRefreshByRunId = new Map<string, number>();/*** Returns the fresh results the answer is grounded on (empty when nothing came68 unmodified linesexistingResults: ImageSearchResults,searchRunId = getCurrentSearchRunId(),): Promise<void> {// 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 = () =>searchRunId === getCurrentSearchRunId() && isSameAttempt();const { results: imageResults } = await searchImages(searchQuery,25 unmodified linesupdateImageSearchResults(updatedImageResults);}if (isSameAttempt()) {mergeSearchImageResults(searchRunId, {type: "image",items: updatedImageResults.map(
18 unmodified lines192021222324163 unmodified lines18818919019119219319419519619728 unmodified lines22622722822923023123223323423511 unmodified lines2472482492502512522532542552567 unmodified lines2642652662672682692702712722738 unmodified lines28228328428528628728828929029121 unmodified lines3133143153163173183193203213226 unmodified lines32933033133233333433533633733836 unmodified lines37537637737837938055 unmodified lines4364374384394404414424434444457 unmodified lines45345445545645745845946046146230 unmodified lines4934944954964974984995005015026 unmodified lines50951051151251351451551651751810 unmodified lines52953053153253353453553653753896 unmodified lines63563663763863964064164264364464564664764864965065165265365438 unmodified lines69369469569669769869970070170271 unmodified lines77477577677777877978078178218 unmodified lines...overrides,});describe("History Module - Search Run ID Management", () => {beforeEach(async () => {vi.resetModules();163 unmodified linesdescribe("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 id = await addSearchToHistory("test query", results);expect(id).toBeDefined();expect(typeof id).toBe("number");28 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};// Insert "second" with the earlier timestamp so it proves sorting by timestamp, not ID.vi.setSystemTime(new Date(2000, 0, 2));11 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};for (let i = 0; i < 5; i++) {await addSearchToHistory(`query ${i}`, results);7 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};for (let i = 0; i < 12; i++) {await addSearchToHistory(`query ${i}`, results);8 unmodified linesit("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" }],};vi.setSystemTime(new Date(2000, 0, 1));const oldest = await addSearchToHistory("pinned long ago", results);21 unmodified linesconst { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =await import("./history");const runId = getCurrentSearchRunId();const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};await addSearchToHistory("round trip query", results, "user");const [entry] = await getRecentSearches();6 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};await addSearchToHistory("fields test", results);const [entry] = await getRecentSearches();36 unmodified lines});describe("mergeSearchImageResults", () => {const image = (title: string, url: string) => ({title,url,55 unmodified linestype: "image",items: [image("Fresh", "https://fresh.com")],});expect(await storedItems()).toEqual([image("Fresh", "https://fresh.com"),image("First", "https://first.com"),]);// 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"),]);// A retry on the run clears the list before its own images arrive.await updateSearchResults(runId, { type: "image", items: [] });30 unmodified linessaveLlmResponseForQuery,getLatestLlmResponseForEntry,} = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};await addSearchToHistory("llm test", results);await saveLlmResponseForQuery("llm test", "AI answer", "model-x");6 unmodified linesit("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 id = await addSearchToHistory("llm link test", results);await saveLlmResponseForQuery("llm link test", "answer", "m");10 unmodified linessaveLlmResponseForQuery,getLatestLlmResponseForEntry,} = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};await addSearchToHistory("multi llm", results);vi.setSystemTime(new Date(2000, 0, 2));96 unmodified linesdescribe("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,});const { addSearchToHistory, historyDatabase } = await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};// Cleanup must run after the add transaction completes: inside it, the// async import causes a TransactionInactiveError.38 unmodified linesvi.spyOn(historyDatabase.searches, "add").mockRejectedValue(new Error("boom"),);const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};const id = await addSearchToHistory("q", results);expect(id).toBeUndefined();});71 unmodified linesawait clearAllHistory();expect(await historyDatabase.searches.count()).toBe(0);expect(await historyDatabase.llmResponses.count()).toBe(0);expect(await historyDatabase.chatHistory.count()).toBe(0);});});});18 unmodified lines19202122232425262728293031323334353637383940414243444546474849505152163 unmodified lines21621721821922022122228 unmodified lines25125225325425525625711 unmodified lines2692702712722732742757 unmodified lines2832842852862872882898 unmodified lines29829930030130230330421 unmodified lines3263273283293303313326 unmodified lines33934034134234334434536 unmodified lines38238338438538638738838939039139239339439555 unmodified lines4514524534544554564577 unmodified lines46546646746846947047130 unmodified lines5025035045055065075086 unmodified lines51551651751851952052110 unmodified lines53253353453553653753896 unmodified lines63563663763863964064164264364438 unmodified lines68368468568668768868971 unmodified lines76176276376476576676718 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 linesdescribe("addSearchToHistory", () => {it("should add a text search entry and return an ID", async () => {const { addSearchToHistory } = await import("./history");const results = oneTextResult();const id = await addSearchToHistory("test query", results);expect(id).toBeDefined();expect(typeof id).toBe("number");28 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");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 linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = oneTextResult();for (let i = 0; i < 5; i++) {await addSearchToHistory(`query ${i}`, results);7 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");const results = oneTextResult();for (let i = 0; i < 12; i++) {await addSearchToHistory(`query ${i}`, results);8 unmodified linesit("returns only pinned entries, newest first, however old", async () => {const { addSearchToHistory, getPinnedSearches, historyDatabase } =await import("./history");const results = oneTextResult();vi.setSystemTime(new Date(2000, 0, 1));const oldest = await addSearchToHistory("pinned long ago", results);21 unmodified linesconst { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =await import("./history");const runId = getCurrentSearchRunId();const results = oneTextResult();await addSearchToHistory("round trip query", results, "user");const [entry] = await getRecentSearches();6 unmodified linesconst { addSearchToHistory, getRecentSearches } = await import("./history");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 linestype: "image",items: [image("Fresh", "https://fresh.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(freshAndFirstImages());// A retry on the run clears the list before its own images arrive.await updateSearchResults(runId, { type: "image", items: [] });30 unmodified linessaveLlmResponseForQuery,getLatestLlmResponseForEntry,} = await import("./history");const results = oneTextResult();await addSearchToHistory("llm test", results);await saveLlmResponseForQuery("llm test", "AI answer", "model-x");6 unmodified linesit("should store searchId back-link from llmResponses to the search row", async () => {const { addSearchToHistory, historyDatabase, saveLlmResponseForQuery } =await import("./history");const results = oneTextResult();const id = await addSearchToHistory("llm link test", results);await saveLlmResponseForQuery("llm link test", "answer", "m");10 unmodified linessaveLlmResponseForQuery,getLatestLlmResponseForEntry,} = await import("./history");const results = oneTextResult();await addSearchToHistory("multi llm", results);vi.setSystemTime(new Date(2000, 0, 2));96 unmodified linesdescribe("cleanup after add", () => {it("should not throw TransactionInactiveError when auto-cleanup is enabled", async () => {await enableAutoCleanup();const { addSearchToHistory, historyDatabase } = await import("./history");const results = oneTextResult();// Cleanup must run after the add transaction completes: inside it, the// async import causes a TransactionInactiveError.38 unmodified linesvi.spyOn(historyDatabase.searches, "add").mockRejectedValue(new Error("boom"),);const results = oneTextResult();const id = await addSearchToHistory("q", results);expect(id).toBeUndefined();});71 unmodified linesawait clearAllHistory();await expectStoresEmpty(historyDatabase);});});});
22 unmodified lines23242526272825 unmodified lines545556575859606162636465666768697071727374757677787980818283848522 unmodified linesvi.resetModules();});describe("PubSub localStorage persistence", () => {it("updates query suggestions and persists to localStorage", async () => {const { updateQuerySuggestions, getQuerySuggestions } = await import(25 unmodified linesit("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'",);});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'",);});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'",);});});22 unmodified lines2324252627282930313233343536373839404142434425 unmodified lines70717273747576777879808182838485868788899091929394959697989922 unmodified linesvi.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 linesit("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");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");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");expectUnusableStoredValue("menuExpandedAccordions",() => menuExpandedAccordionsPubSub[2](),[],);});});
8 unmodified lines910111213145 unmodified lines202122232425262728293015 unmodified lines46474849505152535455568 unmodified linesreturn await import("./pubSub");}describe("response publishing", () => {beforeEach(() => {vi.useFakeTimers();5 unmodified linesit("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);});updateResponse("Hello");updateResponse("Hello world");15 unmodified linesupdateResponse,updateResponseImmediately,} = await loadResponseChannel();const published: string[] = [];const [, onResponseChange] = responsePubSub;const unsubscribe = onResponseChange((value) => {published.push(value);});updateResponse("Hello");updateResponse("Hello world, but truncated");8 unmodified lines910111213141516171819202122232425262728295 unmodified lines3536373839404115 unmodified lines575859606162638 unmodified linesreturn 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 linesit("publishes one leading and one trailing value per throttle window", async () => {const { responsePubSub, updateResponse } = await loadResponseChannel();const { published, unsubscribe } = collectPublished(responsePubSub);updateResponse("Hello");updateResponse("Hello world");15 unmodified linesupdateResponse,updateResponseImmediately,} = await loadResponseChannel();const { published, unsubscribe } = collectPublished(responsePubSub);updateResponse("Hello");updateResponse("Hello world, but truncated");
16 unmodified lines171819202122422 unmodified lines44544644744844945045145245345414 unmodified lines46947047147247347447547647747816 unmodified lines4954964974984995005015025035044 unmodified lines5095105115125135145155165175184 unmodified lines5235245255265275285295305315329 unmodified lines5425435445455465475485495505516 unmodified lines55855956056156256356456556656711 unmodified lines57958058158258358458558658758824 unmodified lines61361461561661761861962062162216 unmodified lines}));const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);vi.stubGlobal("self", {location: new URL("http://localhost:3000"),422 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});const firstResults = await searchModule.searchText("cached query");expect(firstResults).toEqual({ results: mockResults, stale: false });14 unmodified linesconst mockResults: string[][] = [["Image", "Alt", "https://example.com/img.jpg"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});const firstResults = await searchModule.searchImages("cached images");expect(firstResults).toEqual({ results: mockResults, stale: false });16 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});await searchModule.searchText("query A");await searchModule.searchText("query B");4 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});await searchModule.searchText("same query", 5);await searchModule.searchText("same query", 10);4 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});await searchModule.searchText("ttl query");expect(mockFetch).toHaveBeenCalledTimes(1);9 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});searchModule.searchServiceInstance.updateCacheConfig({ enabled: false });6 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});await searchModule.searchText("cross-store query");expect(mockFetch).toHaveBeenCalledTimes(1);11 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});const first = await searchModule.searchText("stale query");expect(first).toEqual({ results: mockResults, stale: false });24 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue(mockResults),});try {// Cache an entry, then move past the 24-hour stale retention.16 unmodified lines1718192021222324252627282930422 unmodified lines45345445545645745845914 unmodified lines47447547647747847948016 unmodified lines4974984995005015025034 unmodified lines5085095105115125135144 unmodified lines5195205215225235245259 unmodified lines5355365375385395405416 unmodified lines54854955055155255355411 unmodified lines56656756856957057157224 unmodified lines59759859960060160260316 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 linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);const firstResults = await searchModule.searchText("cached query");expect(firstResults).toEqual({ results: mockResults, stale: false });14 unmodified linesconst mockResults: string[][] = [["Image", "Alt", "https://example.com/img.jpg"],];mockSearchResponse(mockResults);const firstResults = await searchModule.searchImages("cached images");expect(firstResults).toEqual({ results: mockResults, stale: false });16 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("query A");await searchModule.searchText("query B");4 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("same query", 5);await searchModule.searchText("same query", 10);4 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("ttl query");expect(mockFetch).toHaveBeenCalledTimes(1);9 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);searchModule.searchServiceInstance.updateCacheConfig({ enabled: false });6 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);await searchModule.searchText("cross-store query");expect(mockFetch).toHaveBeenCalledTimes(1);11 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);const first = await searchModule.searchText("stale query");expect(first).toEqual({ results: mockResults, stale: false });24 unmodified linesconst mockResults: string[][] = [["Title", "Snippet", "https://example.com"],];mockSearchResponse(mockResults);try {// Cache an entry, then move past the 24-hour stale retention.
4 unmodified lines5678910223 unmodified lines234235236237238239285 unmodified lines5255265275285295305315325335345355 unmodified lines54154254354454554654754854955055158 unmodified lines61061161261361461561661761861962062162262362462562662762862963063183 unmodified lines7157167177187197207217227237247257267277287297307317327335 unmodified lines7397407417427437447457467477487497507517527537547557564 unmodified linesgetDictationEngine,MAX_RECORDING_SECONDS,resampleTo16k,startDictation,stripLanguageTag,} from "@/modules/speechToText";223 unmodified lines});});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);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);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;}let instance: RecognitionFake | undefined;83 unmodified linesawait session.stop();});it("ends the session quietly when the recognizer stops on its own", async () => {installRecognitionFake();const onError = vi.fn();const onEnd = vi.fn();const session = await startDictation({onTranscript: vi.fn(),onEnd,onError,},true,);// 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,);await session.stop();instance?.onend?.();4 unmodified lines567891011223 unmodified lines235236237238239240241242243244245246247248249250285 unmodified lines5365375385395405415425 unmodified lines54854955055155255355458 unmodified lines61361461561661761861983 unmodified lines7037047057067077087097107117127137147157167177187197207217227235 unmodified lines7297307317327337347354 unmodified linesgetDictationEngine,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 { 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 { session, onTranscript } = await startWasmSession();await session.stop();expect(wllama.createTranscription).not.toHaveBeenCalled();58 unmodified lines});describe("startDictation with the web speech fallback", () => {type RecognitionFake = SpeechRecognitionLike & { stopped: boolean };let instance: RecognitionFake | undefined;83 unmodified linesawait session.stop();});/** 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 },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 () => {const { session, onEnd, onError } = await startRecognitionSession();await session.stop();instance?.onend?.();
50 unmodified lines5152535455565750 unmodified linesconst DICTATION_CONTEXT_SIZE = 4096;/** The minimum the app needs from `window.SpeechRecognition`. */interface SpeechRecognitionLike {continuous: boolean;interimResults: boolean;lang: string;50 unmodified lines5152535455565750 unmodified linesconst DICTATION_CONTEXT_SIZE = 4096;/** The minimum the app needs from `window.SpeechRecognition`. */export interface SpeechRecognitionLike {continuous: boolean;interimResults: boolean;lang: string;
12345 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515236 unmodified lines899091929394130 unmodified lines22522622722822923023123223323423523623723823924024124224327 unmodified lines2712722732742752762772782792807 unmodified lines28828929029129229329429529629729829930030110 unmodified lines3123133143153163173187 unmodified lines32632732832933033133233333433533633733833934034134234320 unmodified lines364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432import { beforeEach, describe, expect, it, vi } from "vitest";const state = vi.hoisted(() => ({settings: { inferenceType: "browser" } as {5 unmodified linessystemPrompt: "",}));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([])),}));// 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),}));vi.mock("./textGenerationUtilities", async (importOriginal) => ({...(await importOriginal<typeof import("./textGenerationUtilities")>()),getFormattedSearchResults: vi.fn(() => Promise.resolve("")),36 unmodified lines);}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",);await generateChatResponse(messages, () => {});const { answer, summarizer } = callsTo(generateChatWithWllama);const sentTokens = answer[0].reduce((total, message) => total + message.content.length,0,);expect(sentTokens).toBeLessThanOrEqual(3072);expect(answer[0].slice(2)).toEqual(messages.slice(4));for (const dropped of messages.slice(0, 4)) {27 unmodified linesawait generateChatResponse(messages, () => {});const { answer } = callsTo(generateChatWithWllama);const sentTokens = answer[0].reduce((total, message) => total + message.content.length,0,);expect(sentTokens).toBeLessThanOrEqual(3072);expect(answer[0][0].content).toContain("z");expect(answer[0].slice(2)).toEqual(messages.slice(2));7 unmodified linesit("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;});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);const turnTwo = [...firstExchange, ...secondExchange, question];await generateChatResponse(turnTwo, () => {});7 unmodified linesexpect(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);});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;});mockGenerateChat(generateChatWithWllama);state.systemPrompt = "s".repeat(2000);const question: ChatMessage = { role: "user", content: "c".repeat(300) };20 unmodified linesexpect(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);});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)) {throw new Error("summarizer unavailable");}return "the answer";});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");});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",);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");});});describe("reasoning in earlier assistant turns", () => {12345678910115 unmodified lines1718192021222324252627282930313233343536373836 unmodified lines75767778798081828384858687888990919293949596979899100101102103104105106107108109130 unmodified lines24024124224324424524624724824925025127 unmodified lines2792802812822832842857 unmodified lines29329429529629729829910 unmodified lines3103113123133143153167 unmodified lines32432532632732832933033133233333420 unmodified lines355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404import { 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 linessystemPrompt: "",}));// 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) },];mockSummarizerReturningTokens(summaryTokens);await generateChatResponse(messages, () => {});const { answer, summarizer } = callsTo(generateChatWithWllama);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 linesawait generateChatResponse(messages, () => {});const { answer } = callsTo(generateChatWithWllama);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 linesit("folds each dropped turn into the summary once across turns", async () => {// The summary slot persists between turns, as the pubsub store does.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.current.summarizedCount).toBe(2);const turnTwo = [...firstExchange, ...secondExchange, question];await generateChatResponse(turnTwo, () => {});7 unmodified linesexpect(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.current.summarizedCount).toBe(4);});it("folds again from the start once an edit reaches into the summary", async () => {const slot = stubPersistentSummarySlot();mockGenerateChat(generateChatWithWllama);state.systemPrompt = "s".repeat(2000);const question: ChatMessage = { role: "user", content: "c".repeat(300) };20 unmodified linesexpect(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.current.summarizedCount).toBe(2);});it.each([{title: "rejects",summarize: () => {throw new Error("summarizer unavailable");},},{ 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",});vi.mocked(generateChatWithWllama).mockImplementation(async (chat) =>chat[0].content.startsWith(summarizerInstruction)? summarize(): "the answer",);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");},);});describe("reasoning in earlier assistant turns", () => {
33 unmodified lines34353637383952 unmodified lines929394959697989910010110210310410510610710810911011111236 unmodified lines14915015115215315415515615715815 unmodified lines17417517617717817918018118218318418518618718818919019119219319471 unmodified lines2662672682692702712722732742752762775 unmodified lines28328428528628728828929029129229329489 unmodified lines3843853863873883893903913923933943953963973983994004014024034044059 unmodified lines4154164174184194204214224234244254264274284294304312 unmodified lines4344354364374384394404414424434444454464474484494504514524534545 unmodified lines46046146246346446546646746846947047147247347497 unmodified lines5725735745755765775785795805815825835845855866 unmodified lines59359459559659759859931 unmodified lines63163263363463563663763863964064164264364464564664764864965065165222 unmodified lines67567667767867968068169 unmodified lines7517527537547557567577587597607617622 unmodified lines76576676776876977077177277377477577677742 unmodified lines8208218228238248258268278288298308314 unmodified lines83683783883984084184284384484527 unmodified lines87387487587687787887988088188223 unmodified lines90690790890991091191235 unmodified lines94894995095195295395433 unmodified lines};});vi.mock("./pubSub", () => ({getImageSearchResults: () => harness.state.imageSearchResults,getConversationSummary: () => ({ conversationId: "", summary: "" }),52 unmodified linesgetConfig: 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("./logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));vi.mock("./pageContent", () => ({fetchPageContents: vi.fn(() => Promise.resolve({})),}));vi.mock("./search", () => ({searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),36 unmodified linesdefault: { encode: vi.fn(() => [1, 2, 3]) },}));vi.mock("./textGenerationWithWllama", () => ({generateTextWithWllama: vi.fn(() => Promise.resolve()),generateChatWithWllama: vi.fn(() => Promise.resolve("")),}));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();},}),{ status: 200 },);}function contentFrame(content: string) {return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;}describe("search degradation", () => {71 unmodified linesit("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 };});await searchAndRespond();await harness.state.searchPromise;5 unmodified linesit("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 };});await searchAndRespond();await harness.state.searchPromise;89 unmodified linesit("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 first = searchAndRespond();await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());9 unmodified linesawait 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,});// 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 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 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,});// 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 first;expect(harness.state.llmTextSearchResults).toEqual([97 unmodified linesconst 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,});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 first;expect(harness.state.textSearchResults).toEqual(resultsB);31 unmodified linesconst 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 second = searchAndRespond();await second;await harness.state.searchPromise;deferredA.fail(new Error("late failure"));await new Promise((resolve) => setTimeout(resolve, 0));await first;expect(harness.state.textSearchState).toBe("completed");22 unmodified linesreturn {finishImages: async (results: ImageSearchResults) => {deferredImages.release({ results, stale: false });await new Promise((resolve) => setTimeout(resolve, 0));await running;},};69 unmodified linesconst 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,});vi.mocked(searchImages).mockResolvedValueOnce({results: imagesB,stale: false,2 unmodified linesconst second = searchAndRespond();await second;await harness.state.searchPromise;await new Promise((resolve) => setTimeout(resolve, 0));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 first;expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith(42 unmodified linesconst 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,});vi.mocked(searchImages).mockResolvedValueOnce({results: [["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],4 unmodified linesconst second = searchAndRespond();await second;await harness.state.searchPromise;await new Promise((resolve) => setTimeout(resolve, 0));deferredImagesA.fail(new Error("late image error"));await new Promise((resolve) => setTimeout(resolve, 0));await first;expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(27 unmodified linesconst fourth = searchAndRespond();await fourth;await harness.state.searchPromise;await new Promise((resolve) => setTimeout(resolve, 0));deferredImagesC.fail(new Error("late fire-and-forget image error"));await new Promise((resolve) => setTimeout(resolve, 0));await third;expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(23 unmodified linesresults: [["Old", "Old snippet", "https://old.example"]],stale: true,});await new Promise((resolve) => setTimeout(resolve, 0));await first;expect(harness.state.textSearchResults).toEqual(retryResults);35 unmodified linesresults: [["Late A", "Late snippet", "https://late.example"]],stale: true,});await new Promise((resolve) => setTimeout(resolve, 0));await first;expect(harness.state.textSearchResults).toEqual(restoredResults);33 unmodified lines3435363738394041424344454647484952 unmodified lines10210310410510610710810911011111211311436 unmodified lines15115215315415515615715 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923071 unmodified lines3023033043053063073085 unmodified lines31431531631731831932089 unmodified lines4104114124134144154169 unmodified lines4264274284294304314324334344354364372 unmodified lines4404414424434444454465 unmodified lines45245345445545645745845946046197 unmodified lines5595605615625635645656 unmodified lines57257357457557657757831 unmodified lines61061161261361461561661761861962062162262322 unmodified lines64664764864965065165269 unmodified lines7227237247257267277282 unmodified lines73173273373473573673773873974074174274342 unmodified lines7867877887897907917924 unmodified lines79779879980080180280380480580627 unmodified lines83483583683783883984084184284323 unmodified lines86786886987087187287335 unmodified lines90991091191291391491533 unmodified lines};});import {contentFrame,historyMock,logEntriesMock,notificationsMock,pageContentMock,sseStream,wllamaMock,} from "./textGenerationTestUtils";vi.mock("./pubSub", () => ({getImageSearchResults: () => harness.state.imageSearchResults,getConversationSummary: () => ({ conversationId: "", summary: "" }),52 unmodified linesgetConfig: vi.fn(() => Promise.resolve({})),}));vi.mock("./history", () => historyMock(() => harness.state.searchRunId));vi.mock("./logEntries", () => logEntriesMock());vi.mock("./notifications", () => notificationsMock());vi.mock("./pageContent", () => pageContentMock());vi.mock("./search", () => ({searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),36 unmodified linesdefault: { encode: vi.fn(() => [1, 2, 3]) },}));vi.mock("./textGenerationWithWllama", () => wllamaMock());import {mergeSearchImageResults,15 unmodified linesconst mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);/** 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;}),);harness.state.settings.enableAiResponse = true;harness.state.settings.enableImageSearch = true;return () => release?.({ results: LATE_IMAGE_RESULTS, stale: false });}/** 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 linesit("completes with no results when a stopword-only query leaves no keywords to retry with", async () => {harness.state.query = "how about that";stubEmptyQueryRejection();await searchAndRespond();await harness.state.searchPromise;5 unmodified linesit("completes without searching when an over-long query has no keywords", async () => {harness.state.query = "that ".repeat(401);stubEmptyQueryRejection();await searchAndRespond();await harness.state.searchPromise;89 unmodified linesit("lets a newer search keep the grounding channel when an older image fallback resolves last", async () => {// Run 1: text fails, image in flight.const releaseLateImages = failTextAndHoldImages();const first = searchAndRespond();await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());9 unmodified linesawait harness.state.searchPromise;// Run 1's image search now lands, after run 2 already owns the channel.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 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 () => {const releaseLateImages = failTextAndHoldImages();const first = searchAndRespond();await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());5 unmodified lines["Restored", "snippet", "https://restored.example.com"],];releaseLateImages();// The publish sits behind the awaited image search; drain the// continuation before asserting, as in the cross-run test above.await drainContinuations();await first;expect(harness.state.llmTextSearchResults).toEqual([97 unmodified linesconst first = searchAndRespond();await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));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 drainContinuations();await first;expect(harness.state.textSearchResults).toEqual(resultsB);31 unmodified linesconst first = searchAndRespond();await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));const resultsB = queueSecondSearch();const second = searchAndRespond();await second;await harness.state.searchPromise;deferredA.fail(new Error("late failure"));await drainContinuations();await first;expect(harness.state.textSearchState).toBe("completed");22 unmodified linesreturn {finishImages: async (results: ImageSearchResults) => {deferredImages.release({ results, stale: false });await drainContinuations();await running;},};69 unmodified linesconst imagesB: ImageSearchResults = [["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],];queueSecondSearch();vi.mocked(searchImages).mockResolvedValueOnce({results: imagesB,stale: false,2 unmodified linesconst second = searchAndRespond();await second;await harness.state.searchPromise;await drainContinuations();const imagesA: ImageSearchResults = [["Img A", "https://a.example/img.png", "thumb-a", "https://a.example"],];deferredImagesA.release({ results: imagesA, stale: false });await drainContinuations();await first;expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith(42 unmodified linesconst first = searchAndRespond();await vi.waitFor(() => expect(searchImages).toHaveBeenCalledTimes(1));queueSecondSearch();vi.mocked(searchImages).mockResolvedValueOnce({results: [["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],4 unmodified linesconst second = searchAndRespond();await second;await harness.state.searchPromise;await drainContinuations();deferredImagesA.fail(new Error("late image error"));await drainContinuations();await first;expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(27 unmodified linesconst fourth = searchAndRespond();await fourth;await harness.state.searchPromise;await drainContinuations();deferredImagesC.fail(new Error("late fire-and-forget image error"));await drainContinuations();await third;expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(23 unmodified linesresults: [["Old", "Old snippet", "https://old.example"]],stale: true,});await drainContinuations();await first;expect(harness.state.textSearchResults).toEqual(retryResults);35 unmodified linesresults: [["Late A", "Late snippet", "https://late.example"]],stale: true,});await drainContinuations();await first;expect(harness.state.textSearchResults).toEqual(restoredResults);
123456789101 unmodified line12131415161718192021222324252627282930313233343536373839404142434445468 unmodified lines55565758596061626364import { beforeEach, describe, expect, it, vi } from "vitest";vi.mock("./pubSub", () => ({getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })),getQuery: vi.fn(() => ""),getResponse: vi.fn(() => ""),getSettings: vi.fn(() => ({inferenceType: "browser",enableAiResponse: true,enableTextSearch: true,1 unmodified linesearchResultsLimit: 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("./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("")),}));import gptTokenizer from "gpt-tokenizer";import {1234567891011121314151 unmodified line17181920212223242526278 unmodified lines36373839404142import { beforeEach, describe, expect, it, vi } from "vitest";import {historyMock,logEntriesMock,notificationsMock,pubSubMock,searchMock,wllamaMock,} from "./textGenerationTestUtils";vi.mock("./pubSub", () =>pubSubMock(() => ({inferenceType: "browser",enableAiResponse: true,enableTextSearch: true,1 unmodified linesearchResultsLimit: 10,allowAiModelDownload: true,})),);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", () => wllamaMock());import gptTokenizer from "gpt-tokenizer";import {
4 unmodified lines56789106 unmodified lines171819202122235 unmodified lines293031323334353637383923 unmodified lines63646566676869707172737475767778798081828384854 unmodified linesresponseAtCompletion: { current: null as string | null },}));vi.mock("./history", () => ({replaceChatConversation: vi.fn(() => Promise.resolve()),getCurrentSearchRunId: vi.fn(() => "run-1"),6 unmodified linesupdateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));// 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("./pageContent", () => ({fetchPageContents: vi.fn(() => Promise.resolve({})),}));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;4 unmodified lines567891011121314151617186 unmodified lines252627282930315 unmodified lines37383940414243444523 unmodified lines6970717273744 unmodified linesresponseAtCompletion: { 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 linesupdateSearchResults: vi.fn(() => Promise.resolve()),}));vi.mock("./logEntries", () => logEntriesMock());// The internal API sizes its budgets from /api/config; `fetch` below only// answers /inference.5 unmodified lines};});vi.mock("./notifications", () => notificationsMock());vi.mock("./pageContent", () => pageContentMock());vi.mock("./search", () => ({searchText: vi.fn(() =>23 unmodified linesconst mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);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 lines127128129130131132365 unmodified lines498499500501502503504505506507508509510511512513514515516517518519520521522523524525126 unmodified lines});});describe("getFormattedSearchResults", () => {beforeEach(() => {state.searchResults = results;365 unmodified linesdata: { 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();});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();});it("does not start a worker when no page content was read", async () => {126 unmodified lines127128129130131132133134135136137138139140141142143144145365 unmodified lines511512513514515516517518519520521522126 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 linesdata: { type: "error", message: "tokenization failed" },} as MessageEvent<WorkerResponse>),);await expectMainThreadFallback(worker);});it("falls back when the worker dies before answering", async () => {const worker = createFailingWorker((deadWorker) => deadWorker.onerror?.());await expectMainThreadFallback(worker);});it("does not start a worker when no page content was read", async () => {
23 unmodified lines24252627282930313233343536373839404142434413 unmodified lines5859606162634 unmodified lines68697071727374757626 unmodified lines1031041051061071081091101115 unmodified lines1171181191201211221231241257 unmodified lines13313413513613713813914014114214314414515 unmodified lines1611621631641651661671681697 unmodified lines1771781791801811821831841851861871881891901911921931941951965 unmodified lines2022032042052062072082092102112122132142152162172182192202 unmodified lines2232242252262272282292302316 unmodified lines2382392402412422432442452466 unmodified lines2532542552562572582592602619 unmodified lines27127227327427527627727827913 unmodified lines2932942952962972982993003018 unmodified lines31031131231331431531631731826 unmodified lines3453463473483493503513523537 unmodified lines3613623633643653663673683699 unmodified lines37938038138238338438538638716 unmodified lines4044054064074084094104114129 unmodified lines42242342442542642742842943010 unmodified lines44144244344444544644744844973 unmodified lines52352452552652752824 unmodified lines55355455555655755855956056156256356412 unmodified lines5775785795805815825835845858 unmodified lines5945955965975985996006016026036046054 unmodified lines61061161261361461561661761861962062162262362462513 unmodified lines6396406416426436446456466476486496506516526536541 unmodified line65665765865966066166266366466566666766866967067167267367467511 unmodified lines6876886896906916926936946956966976986997007017027037041 unmodified line7067077087097107117127137147151 unmodified line7177187197207217227237247257267271 unmodified line7297307317327337347357367377382 unmodified lines7417427437447457467477487497507512 unmodified lines75475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378413 unmodified lines7987998008018028038048058062 unmodified lines80981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586613 unmodified lines88088188288388488588688788888989089189289389412 unmodified lines90790890991091191291391491591691791891992092192223 unmodified linessleep: 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),getDefaultChatMessages: vi.fn().mockReturnValue([{ role: "user", content: "hi" }]),getFormattedSearchResults: vi.fn().mockReturnValue("None."),};});const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);13 unmodified linesvi.mocked(getSettings).mockReturnValue({ ...defaultSettings, ...overrides });}describe("textGenerationWithHorde", () => {beforeEach(() => {vi.clearAllMocks();4 unmodified linesdescribe("generateTextWithHorde", () => {it("starts a generation, polls until done, and streams the response", async () => {const { generateTextWithHorde } = await import("./textGenerationWithHorde");mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-1" }))26 unmodified lines});it("throws ChatGenerationError when the generation is faulted", async () => {const { generateTextWithHorde } = await import("./textGenerationWithHorde");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");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");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 controller = new AbortController();controller.abort();7 unmodified linesit("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");mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-queued" })).mockResolvedValueOnce(jsonResponse({ done: false, is_possible: true, generations: [] }),).mockResolvedValueOnce(jsonResponse({}));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({}));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");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");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");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");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");mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-k" })).mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))8 unmodified linesit("includes the configured model in the generation request body", async () => {mockSettings({ hordeModel: "custom-model" });const { generateTextWithHorde } = await import("./textGenerationWithHorde");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");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");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");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");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");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");mockFetch.mockResolvedValueOnce(jsonResponse({ message: "Invalid API key" }, 401),);73 unmodified lines);}function generationRequestBodies() {return mockFetch.mock.calls.filter(([url]) => String(url).includes("/generate/text/async"))24 unmodified linesstatusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();const bodies = generationRequestBodies();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 linesstatusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();for (const body of generationRequestBodies()) {8 unmodified linesstatusResponder: () => doneResponse,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();const bodies = generationRequestBodies();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,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");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");await expect(generateTextWithHorde()).rejects.toThrow("Too many requests",);1 unmodified line});it("does not retry when the generation faults", 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",);expect(generationRequestBodies()).toHaveLength(2);});/** Answers each job's polls from its own script, by the job id in the URL. */function perJobResponder(11 unmodified linesconst 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({"gen-1": () => ({ done: true, faulted: true }),"gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");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({// 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");await expect(generateTextWithHorde()).resolves.toBe("Top model answer");expect(generationRequestBodies()).toHaveLength(4);1 unmodified lineit("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({"gen-1": () => ({ done: true, is_possible: false }),"gen-2": (poll) => {// The user presses Stop while this job is still queued, after its2 unmodified linesreturn pendingResponse;},}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");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({"gen-1": () => doneResponse,"gen-2": () => pendingResponse,}),});const { generateTextWithHorde } = await import("./textGenerationWithHorde");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({"gen-1": () => doneResponse,"gen-2": () => pendingResponse,}),});const routed = mockFetch.getMockImplementation();let submits = 0;let releaseSecondSubmit: () => void = () => {};13 unmodified lines},);const { generateTextWithHorde } = await import("./textGenerationWithHorde");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({"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");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",);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({"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");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,});const { generateTextWithHorde } = await import("./textGenerationWithHorde");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,});const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);const { generateTextWithHorde } = await import("./textGenerationWithHorde");await generateTextWithHorde();nowSpy.mockReturnValue(5 * 60 * 1000 + 1);await generateTextWithHorde();23 unmodified lines2425262728293031323334353613 unmodified lines50515253545556575859606162636465666768697071727374757677784 unmodified lines8384858687888926 unmodified lines1161171181191201211225 unmodified lines1281291301311321331347 unmodified lines14214314414514614714814915 unmodified lines1651661671681691701717 unmodified lines1791801811821831841851861871885 unmodified lines1941951961971981992002012022 unmodified lines2052062072082092102116 unmodified lines2182192202212222232246 unmodified lines2312322332342352362379 unmodified lines24724824925025125225313 unmodified lines2672682692702712722738 unmodified lines28228328428528628728826 unmodified lines3153163173183193203217 unmodified lines3293303313323333343359 unmodified lines34534634734834935035116 unmodified lines3683693703713723733749 unmodified lines38438538638738838939010 unmodified lines40140240340440540640773 unmodified lines48148248348448548648748848949049149249349449549649749849950050150250324 unmodified lines52852953053153253353412 unmodified lines5475485495505515525538 unmodified lines5625635645655665675684 unmodified lines57357457557657757857958058158258313 unmodified lines5975985996006016026036046056066071 unmodified line60961061161261361461561661761861962062162262362462562662762811 unmodified lines6406416426436446456466476486496506516526531 unmodified line6556566576586596606616621 unmodified line6646656666676686696706716721 unmodified line6746756766776786796806812 unmodified lines6846856866876886896906916922 unmodified lines69569669769869970070170270370470570670770870971071171271371471571671771871913 unmodified lines7337347357367377387392 unmodified lines74274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978013 unmodified lines79479579679779879980080180212 unmodified lines81581681781881982082182282382423 unmodified linessleep: vi.fn().mockResolvedValue(undefined),}));vi.mock("./textGenerationUtilities", async (importOriginal) =>(await import("./textGenerationTestUtils")).textGenerationUtilitiesMock({getDefaultChatMessages: vi.fn().mockReturnValue([{ role: "user", content: "hi" }]),})(importOriginal),);const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);13 unmodified linesvi.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 linesdescribe("generateTextWithHorde", () => {it("starts a generation, polls until done, and streams the response", async () => {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 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 loadHordeGenerator();mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-3" }))7 unmodified lines});it("stops polling and publishes nothing once the user interrupts generation", async () => {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 loadHordeGenerator();const controller = new AbortController();controller.abort();7 unmodified linesit("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 = abortWhenGenerating();const generateTextWithHorde = await loadHordeGenerator();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 = 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 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 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 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 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 loadHordeGenerator();mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-k" })).mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))8 unmodified linesit("includes the configured model in the generation request body", async () => {mockSettings({ hordeModel: "custom-model" });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 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 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 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 loadHordeGenerator();mockFetch.mockResolvedValueOnce(jsonResponse({ id: "gen-gone" })).mockResolvedValueOnce(9 unmodified lines});it("rejects a finished generation that carries no text", async () => {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 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 linesstatusResponder: () => doneResponse,});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 linesstatusResponder: () => doneResponse,});const generateTextWithHorde = await loadHordeGenerator();await generateTextWithHorde();for (const body of generationRequestBodies()) {8 unmodified linesstatusResponder: () => doneResponse,});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 () => {routeSingleWorker((pollIndex) =>pollIndex < 2 ? { done: true, is_possible: false } : doneResponse,);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 () => {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,});}/** Answers each job's polls from its own script, by the job id in the URL. */function perJobResponder(11 unmodified linesconst pendingResponse = { done: false, is_possible: true, generations: [] };it("serves the healthy job when its sibling faults first", async () => {routeSingleWorker(perJobResponder({"gen-1": () => ({ done: true, faulted: true }),"gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),}),);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 () => {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 loadHordeGenerator();await expect(generateTextWithHorde()).resolves.toBe("Top model answer");expect(generationRequestBodies()).toHaveLength(4);1 unmodified lineit("reports an interrupt during the race and submits no retry", async () => {const controller = new AbortController();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 linesreturn pendingResponse;},}),);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 () => {routeSingleWorker(perJobResponder({"gen-1": () => doneResponse,"gen-2": () => pendingResponse,}),);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 () => {routeSingleWorker(perJobResponder({"gen-1": () => doneResponse,"gen-2": () => pendingResponse,}),);const routed = mockFetch.getMockImplementation();let submits = 0;let releaseSecondSubmit: () => void = () => {};13 unmodified lines},);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 () => {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 loadHordeGenerator();await expect(generateTextWithHorde()).resolves.toBe("Top model answer");expect(cancelledIds()).toEqual(["gen-2"]);});it("cancels both jobs when the race fails", async () => {await expectFaultedGenerationRejects();expect(cancelledIds().sort()).toEqual(["gen-1", "gen-2"]);});it("cancels the first round before submitting the fallback round", async () => {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 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 () => {routeSingleWorker(() => doneResponse);const generateTextWithHorde = await loadHordeGenerator();await generateTextWithHorde();await generateTextWithHorde();12 unmodified lines});it("refetches the ranking after the cache expires", async () => {routeSingleWorker(() => doneResponse);const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);const generateTextWithHorde = await loadHordeGenerator();await generateTextWithHorde();nowSpy.mockReturnValue(5 * 60 * 1000 + 1);await generateTextWithHorde();
22 unmodified lines2324252627282930313233343536373839404142434418 unmodified lines636465666768697071727374757677787980818283848586878889909192939495130 unmodified lines226227228229230231232233234235108 unmodified lines34434534634734834935035135235322 unmodified linesgetSystemPrompt: 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."),getDefaultChatCompletionCreateParamsStreaming: vi.fn().mockReturnValue({max_tokens: 1000,temperature: 0.35,}),};});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.*/function openStreamResponse(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));},cancel,});return { response: new Response(body), cancel };}/** 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 };}function fetchSignal(): AbortSignal {130 unmodified lines]),),);const controller = new AbortController();vi.mocked(updateResponse).mockImplementationOnce(() =>controller.abort(),);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(),);await expect(generateTextWithInternalApi(controller.signal),22 unmodified lines232425262728293031323334353618 unmodified lines55565758596061626364656667686970717273747576777879808182838485868788899091130 unmodified lines222223224225226227228108 unmodified lines33733833934034134234322 unmodified linesgetSystemPrompt: vi.fn().mockReturnValue("system prompt"),}));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`, 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 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[]) {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 = abortOnFirstPublish();await expect(generateTextWithInternalApi(controller.signal),108 unmodified lines'data: {"choices":[{"delta":{"content":"partial"}}]}\n',]);mockFetch.mockResolvedValueOnce(stream.response);const controller = abortOnFirstPublish();await expect(generateTextWithInternalApi(controller.signal),
47 unmodified lines48495051525354555657585960616247 unmodified linesgetSystemPrompt: 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("./webGpu", () => ({ webGpuSupport: Promise.resolve(false) }));47 unmodified lines484950515253545556575847 unmodified linesgetSystemPrompt: vi.fn().mockReturnValue("system"),}));vi.mock("./textGenerationUtilities", async (importOriginal) =>(await import("./textGenerationTestUtils")).textGenerationUtilitiesMock()(importOriginal,),);vi.mock("./webGpu", () => ({ webGpuSupport: Promise.resolve(false) }));
129 unmodified lines130131132133134135103 unmodified lines2392402412422432442452462472482492502512522532542552562572582595 unmodified lines26526626726826927027127227327427527627727827920 unmodified lines3003013023033043053063072 unmodified lines3103113123133143153163173 unmodified lines3213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843852 unmodified lines3883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234 unmodified lines42842943043143243343443511 unmodified lines4474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035041 unmodified line5065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445453 unmodified lines54955055155255355455555655755855956056111 unmodified lines5735745755765775785795805815825836 unmodified lines5905915925935945955965979 unmodified lines607608609610611612613614129 unmodified linesreturn worker;}let spoken: string[] = [];let spokenLanguages: string[] = [];let createdObjectUrls = 0;103 unmodified linesdescribe("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));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" } });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));worker.onmessage?.({data: { type: "error", message: "model download failed" },});await speaking;expect(spoken).toEqual(["Hello there."]);20 unmodified linesit("uses the system engine directly when it is selected", async () => {settings.textToSpeechEngine = "system";const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);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);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 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);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" } });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));worker.onmessage?.({data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },});worker.onmessage?.({ data: { type: "done" } });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 () => {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);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 speaking;expect(spoken).toEqual(["One. Two."]);});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 speaking = tts.speak("Hello there.");await vi.waitFor(() =>11 unmodified linesit("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");});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");});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");});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");});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");});it("keeps the catalogue order when the answer's language has no region", async () => {1 unmodified lineportugueseFromPortugalVoice,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");});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");});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");});it("uses the browser language when the detector fails to load", async () => {3 unmodified linestry {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(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));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;await tts.speak("Hello there.");9 unmodified linesit("lists no voices instead of throwing", async () => {mockVoices.mockRejectedValue(new Error("offline"));vi.stubGlobal("speechSynthesis", undefined);self.speechSynthesis = undefined as unknown as SpeechSynthesis;await expect(tts.listVoices("en-US", "system")).resolves.toEqual([]);});129 unmodified lines130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202103 unmodified lines3063073083093103113123133143153163173183193205 unmodified lines32632732832933033133233333420 unmodified lines3553563573583593603612 unmodified lines3643653663673683693703 unmodified lines3743753763773783793803813823833843853863873883893903913923933943953963973983994002 unmodified lines4034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634 unmodified lines46846947047147247347411 unmodified lines4864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195201 unmodified line5225235245255265275285295305315325335345355365375385395405415425435445455465475483 unmodified lines55255355455555655755855911 unmodified lines5715725735745755765776 unmodified lines5845855865875885895909 unmodified lines600601602603604605606129 unmodified linesreturn 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 linesdescribe("speak", () => {it("reads the answer with the local engine when it works", async () => {const { worker, speaking } = await startLocalSpeech("Hello there.");expect(worker.sent[0]).toEqual({sentences: ["Hello there."],voiceId: "en_US-lessac-high",});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, speaking } = await startLocalSpeech("Hello there.");sendError(worker, "model download failed");await speaking;expect(spoken).toEqual(["Hello there."]);20 unmodified linesit("uses the system engine directly when it is selected", async () => {settings.textToSpeechEngine = "system";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 = 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 () => {await speakUntilWorkerFailsAfterFirstChunk("One. Two.");expect(spoken).toEqual([]);});it("falls back when every synthesized chunk fails to play", async () => {stubUnplayableAudio();const { worker, speaking } = await startLocalSpeech("Hello there.");sendAudioChunk(worker);sendDone(worker);await speaking;expect(spoken).toEqual(["Hello there."]);});it("detaches the audio handlers before clearing the source", async () => {const { worker, speaking } = await startLocalSpeech("Hello there.");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();},);const { worker, speaking } = await startLocalSpeech("One. Two.");sendAudioChunk(worker);await vi.waitFor(() => expect(createdObjectUrls).toBe(1));sendError(worker, "synthesis died halfway");await speaking;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 = installFakeWorker();const speaking = tts.speak("Hello there.");await vi.waitFor(() =>11 unmodified linesit("picks the local voice for the answer's language, not the browser's", async () => {mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);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]);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]);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]);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]);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 lineportugueseFromPortugalVoice,portugueseVoice,]);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";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]);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 linestry {tts = await import("./textToSpeech");mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);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, 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"));removeSystemVoices();await tts.speak("Hello there.");9 unmodified linesit("lists no voices instead of throwing", async () => {mockVoices.mockRejectedValue(new Error("offline"));removeSystemVoices();await expect(tts.listVoices("en-US", "system")).resolves.toEqual([]);});
3 unmodified lines456789101112131415161718192021223 unmodified linesimport "fake-indexeddb/auto";import "@testing-library/jest-dom/vitest";import { vi } from "vitest";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(),})),});class ResizeObserverMock {3 unmodified lines45678910111213143 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) => 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 lines425426427428429430431432433434435436437438439440441442443444445446424 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 |### Security Considerations- `VITE_BUILD_DATE_TIME` and `VITE_COMMIT_SHORT_HASH` are bundled into the client JavaScript as build-time constants (build metadata only)- 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 client424 unmodified lines425426427428429430431432433434435436437438439440441442443444445446424 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 | 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). 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 client
105 unmodified lines106107108109110111112105 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 || `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`) |105 unmodified lines106107108109110111112105 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, 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