system HF Staff commited on
Commit
0a1e948
ยท
verified ยท
1 Parent(s): 0ae4889

Sync from felladrin/MiniSearch@7e8885e

Browse files
Files changed (43) hide show
  1. .github/workflows/deploy-to-hugging-face.yml +18 -0
  2. .source-commit +1 -0
  3. Dockerfile +2 -2
  4. changelog.md +4 -0
  5. client/components/AiResponse/ChatInputArea.test.tsx +16 -34
  6. client/components/AiResponse/ChatInterface.test.tsx +121 -85
  7. client/components/AiResponse/MessageList.test.tsx +15 -11
  8. client/components/DictationButton.test.tsx +66 -100
  9. client/components/Pages/Main/MainPage.test.tsx +10 -12
  10. client/components/Pages/Main/Menu/ClearDataButton.test.tsx +11 -24
  11. client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx +12 -12
  12. client/components/Search/Form/SearchForm.test.tsx +2 -6
  13. client/components/Search/History/HistoryDrawer.test.tsx +17 -18
  14. client/components/Search/Results/Graphical/ImageResultsList.test.tsx +11 -8
  15. client/components/Search/Results/Graphical/ImageSearchResults.test.tsx +67 -0
  16. client/components/Search/Results/Graphical/ImageSearchResults.tsx +6 -0
  17. client/components/Search/Results/testUtils.ts +3 -12
  18. client/enterToSubmitCases.ts +10 -0
  19. client/hooks/useSearchHistory.test.ts +14 -20
  20. client/matchMediaStub.ts +22 -0
  21. client/modules/accessKey.test.ts +9 -6
  22. client/modules/chatHelpers.test.ts +55 -34
  23. client/modules/chatHelpers.ts +5 -11
  24. client/modules/history.test.ts +52 -67
  25. client/modules/pubSub.test.ts +28 -14
  26. client/modules/pubSub.throttle.test.ts +17 -10
  27. client/modules/search.test.ts +17 -36
  28. client/modules/speechToText.test.ts +23 -44
  29. client/modules/speechToText.ts +1 -1
  30. client/modules/textGeneration.chatBudget.test.ts +90 -118
  31. client/modules/textGeneration.degradation.test.ts +86 -125
  32. client/modules/textGeneration.inference.test.ts +17 -39
  33. client/modules/textGeneration.responsePersistence.test.ts +11 -22
  34. client/modules/textGenerationTestUtils.ts +121 -0
  35. client/modules/textGenerationUtilities.test.ts +15 -18
  36. client/modules/textGenerationWithHorde.test.ts +122 -220
  37. client/modules/textGenerationWithInternalApi.test.ts +23 -33
  38. client/modules/textGenerationWithWllama.test.ts +5 -9
  39. client/modules/textToSpeech.test.ts +143 -151
  40. client/setupTests.ts +2 -10
  41. client/testMocks.ts +40 -0
  42. docs/configuration.md +13 -13
  43. docs/development-commands.md +1 -1
.github/workflows/deploy-to-hugging-face.yml CHANGED
@@ -26,6 +26,24 @@ jobs:
26
  { echo '---'; cat .github/hf-space-config.yml; echo '---'; echo; cat README.md; } > README.space.md
27
  mv README.space.md README.md
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  - name: Sync to the Space
30
  run: |
31
  hf upload "$HF_SPACE" . . \
 
26
  { echo '---'; cat .github/hf-space-config.yml; echo '---'; echo; cat README.md; } > README.space.md
27
  mv README.space.md README.md
28
 
29
+ # The file is generated here and must never be committed to the source
30
+ # repository: a committed copy would freeze the reported commit for every
31
+ # later build. It is not in .gitignore on purpose, because the upload has
32
+ # to carry it and whether `hf upload` honours .gitignore is not something
33
+ # this project should depend on.
34
+ - name: Refuse a source commit file committed to the repository
35
+ run: |
36
+ if [ -e .source-commit ]; then
37
+ echo "::error::.source-commit is written by this workflow; remove it from the repository."
38
+ exit 1
39
+ fi
40
+
41
+ # The Space builds from this copy, so its own git history is the Space's,
42
+ # not the source's. The build reads this file instead of its git history
43
+ # to report which commit is running (shared/buildSourceCommit.ts).
44
+ - name: Record the source commit for the Space build
45
+ run: git rev-parse --short "$GITHUB_SHA" > .source-commit
46
+
47
  - name: Sync to the Space
48
  run: |
49
  hf upload "$HF_SPACE" . . \
.source-commit ADDED
@@ -0,0 +1 @@
 
 
1
+ 7e8885e
Dockerfile CHANGED
@@ -125,8 +125,8 @@ COPY --chown=${USERNAME}:${USERNAME} . .
125
  # at preview time stay because `npm start` runs `vite preview` and the server
126
  # hooks load with the config.
127
  RUN git config --global --add safe.directory ${APP_DIR} 2>/dev/null || true; \
128
- git rev-parse --short HEAD >/dev/null 2>&1 || \
129
- echo "WARNING: no usable git repository in the build context, so the app will report an empty commit hash."; \
130
  npm run build && \
131
  npm prune --omit=dev
132
 
 
125
  # at preview time stay because `npm start` runs `vite preview` and the server
126
  # hooks load with the config.
127
  RUN git config --global --add safe.directory ${APP_DIR} 2>/dev/null || true; \
128
+ { git rev-parse --short HEAD >/dev/null 2>&1 || [ -f .source-commit ]; } || \
129
+ echo "WARNING: no usable git repository and no .source-commit in the build context, so the app will report an empty commit hash."; \
130
  npm run build && \
131
  npm prune --omit=dev
132
 
changelog.md CHANGED
@@ -4,6 +4,10 @@ Notable changes, grouped by date, most recent first.
4
 
5
  ## 2026-11-27
6
 
 
 
 
 
7
  - 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.
8
 
9
  ## 2026-11-26
 
4
 
5
  ## 2026-11-27
6
 
7
+ - `/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.
8
+ - `/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.
9
+ - 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.
10
+ - 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.
11
  - 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.
12
 
13
  ## 2026-11-26
client/components/AiResponse/ChatInputArea.test.tsx CHANGED
@@ -1,8 +1,8 @@
1
  import { MantineProvider } from "@mantine/core";
2
  import { render, screen, waitFor } from "@testing-library/react";
3
  import userEvent from "@testing-library/user-event";
4
- import { useSyncExternalStore } from "react";
5
  import ChatInputArea from "@/components/AiResponse/ChatInputArea";
 
6
  import {
7
  chatGenerationStatePubSub,
8
  chatInputPubSub,
@@ -12,33 +12,20 @@ import {
12
  import { defaultSettings } from "@/modules/settings";
13
  import { getDictationEngine, startDictation } from "@/modules/speechToText";
14
 
15
- vi.mock("@/modules/speechToText", async () => {
16
- const { DictationError: RealDictationError } = await import(
17
- "@/modules/speechToText"
18
- );
19
- return {
20
- DictationError: RealDictationError,
21
- getDictationEngine: vi.fn(() => "wasm" as const),
22
- startDictation: vi.fn(),
23
- };
24
- });
25
-
26
- vi.mock("@mantine/notifications", () => ({
27
- notifications: { show: vi.fn() },
28
- }));
29
-
30
- /** Subscribes for real, so a channel written mid-test re-renders the area. */
31
- vi.mock("create-pubsub/react", () => ({
32
- usePubSub: (pubSub: [unknown, unknown, unknown]) => {
33
- const [publish, subscribe, get] = pubSub as [
34
- unknown,
35
- (listener: () => void) => () => void,
36
- () => unknown,
37
- ];
38
- const value = useSyncExternalStore(subscribe, get, get);
39
- return [value, publish];
40
- },
41
- }));
42
 
43
  const stopFn = vi.fn();
44
  const cancelFn = vi.fn();
@@ -158,12 +145,7 @@ describe("sending the suggested follow-up question", () => {
158
  settingsPubSub[0]({ ...defaultSettings });
159
  });
160
 
161
- it.each([
162
- [true, "{Enter}", true],
163
- [true, "{Shift>}{Enter}{/Shift}", false],
164
- [false, "{Shift>}{Enter}{/Shift}", true],
165
- [false, "{Enter}", false],
166
- ])(
167
  "with enterToSubmit %s, pressing %s sends it: %s",
168
  async (enterToSubmit, keys, sends) => {
169
  settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
 
1
  import { MantineProvider } from "@mantine/core";
2
  import { render, screen, waitFor } from "@testing-library/react";
3
  import userEvent from "@testing-library/user-event";
 
4
  import ChatInputArea from "@/components/AiResponse/ChatInputArea";
5
+ import { ENTER_TO_SUBMIT_CASES } from "@/enterToSubmitCases";
6
  import {
7
  chatGenerationStatePubSub,
8
  chatInputPubSub,
 
12
  import { defaultSettings } from "@/modules/settings";
13
  import { getDictationEngine, startDictation } from "@/modules/speechToText";
14
 
15
+ // jscpd:ignore-start
16
+ // Vitest hoists every vi.mock call above the imports, so the registration has
17
+ // to be written out in each file; only the factory body can be shared, and it
18
+ // is. The duplication is the framework's, not the tests'.
19
+ vi.mock("@/modules/speechToText", async () =>
20
+ (await import("@/testMocks")).speechToTextMock(),
21
+ );
22
+ vi.mock("@mantine/notifications", async () =>
23
+ (await import("@/testMocks")).notificationsStub(),
24
+ );
25
+ vi.mock("create-pubsub/react", async () =>
26
+ (await import("@/testMocks")).pubSubReactMock(),
27
+ );
28
+ // jscpd:ignore-end
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
  const stopFn = vi.fn();
31
  const cancelFn = vi.fn();
 
145
  settingsPubSub[0]({ ...defaultSettings });
146
  });
147
 
148
+ it.each(ENTER_TO_SUBMIT_CASES)(
 
 
 
 
 
149
  "with enterToSubmit %s, pressing %s sends it: %s",
150
  async (enterToSubmit, keys, sends) => {
151
  settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
client/components/AiResponse/ChatInterface.test.tsx CHANGED
@@ -122,6 +122,111 @@ function renderChatInterface({ suppressInitialFollowUp = true } = {}) {
122
  );
123
  }
124
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
125
  function stubWakeLockApi() {
126
  const release = vi.fn(() => Promise.resolve());
127
  const request = vi.fn(() =>
@@ -162,16 +267,7 @@ afterEach(() => {
162
 
163
  describe("ChatInterface generation state", () => {
164
  it("leaves the follow-up question flag off after sending during its generation", async () => {
165
- const earlierQuestion = deferred<string>();
166
- vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
167
- earlierQuestion.promise,
168
- );
169
-
170
- renderChatInterface({ suppressInitialFollowUp: false });
171
-
172
- await act(async () => {});
173
-
174
- expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
175
 
176
  await act(async () => {
177
  await sendMessage("And how do I use it?");
@@ -204,13 +300,7 @@ describe("ChatInterface generation state", () => {
204
  send = sendMessage("And how do I use it?");
205
  });
206
 
207
- expect(getChatGenerationState().isGeneratingResponse).toBe(true);
208
-
209
- await act(async () => {
210
- followUpQuestion.resolve("An earlier question?");
211
- });
212
-
213
- expect(getChatGenerationState().isGeneratingResponse).toBe(true);
214
 
215
  await act(async () => {
216
  chatResponse.resolve("An answer.");
@@ -360,16 +450,8 @@ describe("ChatInterface generation state", () => {
360
  });
361
 
362
  it("keeps the follow-up question flag on until the newest call finishes", async () => {
363
- const earlierQuestion = deferred<string>();
364
- const newerQuestion = deferred<string>();
365
- vi.mocked(generateFollowUpQuestion)
366
- .mockReturnValueOnce(earlierQuestion.promise)
367
- .mockReturnValueOnce(newerQuestion.promise);
368
-
369
- renderChatInterface({ suppressInitialFollowUp: false });
370
- await act(async () => {});
371
-
372
- expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
373
 
374
  let send: Promise<void> = Promise.resolve();
375
  await act(async () => {
@@ -384,25 +466,15 @@ describe("ChatInterface generation state", () => {
384
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
385
  expect(getFollowUpQuestion()).toBe("");
386
 
387
- await act(async () => {
388
- newerQuestion.resolve("The newest question?");
389
- await send;
390
- });
391
 
392
  expect(getFollowUpQuestion()).toBe("The newest question?");
393
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
394
  });
395
 
396
  it("leaves both generation flags off after unmounting mid-generation", async () => {
397
- const heldQuestion = deferred<string>();
398
- vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
399
- heldQuestion.promise,
400
- );
401
-
402
- const { unmount } = renderChatInterface({ suppressInitialFollowUp: false });
403
- await act(async () => {});
404
-
405
- expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
406
 
407
  await act(async () => {
408
  unmount();
@@ -457,19 +529,8 @@ describe("ChatInterface generation state", () => {
457
  });
458
 
459
  it("blanks nothing when an orphaned call rejects after a newer one started", async () => {
460
- const earlierQuestion = deferred<string>();
461
- const newerQuestion = deferred<string>();
462
- vi.mocked(generateFollowUpQuestion)
463
- .mockReturnValueOnce(earlierQuestion.promise)
464
- .mockReturnValueOnce(newerQuestion.promise);
465
-
466
- renderChatInterface({ suppressInitialFollowUp: false });
467
- await act(async () => {});
468
-
469
- let send: Promise<void> = Promise.resolve();
470
- await act(async () => {
471
- send = sendMessage("And how do I use it?");
472
- });
473
 
474
  // The orphaned call fails. Its catch must not blank the newer one's work.
475
  await act(async () => {
@@ -478,10 +539,7 @@ describe("ChatInterface generation state", () => {
478
 
479
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
480
 
481
- await act(async () => {
482
- newerQuestion.resolve("The newest question?");
483
- await send;
484
- });
485
 
486
  expect(getFollowUpQuestion()).toBe("The newest question?");
487
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
@@ -564,20 +622,14 @@ describe("ChatInterface generation state", () => {
564
  firstSend = sendMessage("And how do I use it?");
565
  });
566
 
567
- await act(async () => {
568
- first.unmount();
569
- });
570
-
571
- renderChatInterface();
572
 
573
  let secondSend: Promise<void> = Promise.resolve();
574
  await act(async () => {
575
  secondSend = sendMessage("Does it work offline?");
576
  });
577
 
578
- expect(getChatGenerationState().isGeneratingResponse).toBe(true);
579
- // The live generation really started, rather than the flag being stale.
580
- expect(generateChatResponse).toHaveBeenCalledTimes(2);
581
 
582
  // The orphan's `finally` must not clear the live generation's flag, which
583
  // would drop the spinner and let a third send start alongside it.
@@ -588,12 +640,7 @@ describe("ChatInterface generation state", () => {
588
 
589
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
590
 
591
- await act(async () => {
592
- secondResponse.resolve("The live answer.");
593
- await secondSend;
594
- });
595
-
596
- expect(getChatGenerationState().isGeneratingResponse).toBe(false);
597
  });
598
 
599
  it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {
@@ -615,20 +662,14 @@ describe("ChatInterface generation state", () => {
615
  firstRegenerate = regenerateResponse();
616
  });
617
 
618
- await act(async () => {
619
- first.unmount();
620
- });
621
-
622
- renderChatInterface();
623
 
624
  let secondSend: Promise<void> = Promise.resolve();
625
  await act(async () => {
626
  secondSend = sendMessage("Does it work offline?");
627
  });
628
 
629
- expect(getChatGenerationState().isGeneratingResponse).toBe(true);
630
- // The live generation really started, rather than the flag being stale.
631
- expect(generateChatResponse).toHaveBeenCalledTimes(3);
632
 
633
  await act(async () => {
634
  firstResponse.resolve("The orphaned regeneration.");
@@ -637,12 +678,7 @@ describe("ChatInterface generation state", () => {
637
 
638
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
639
 
640
- await act(async () => {
641
- secondResponse.resolve("The live answer.");
642
- await secondSend;
643
- });
644
-
645
- expect(getChatGenerationState().isGeneratingResponse).toBe(false);
646
  });
647
 
648
  it("starts one re-generation when two regenerates land in the same task", async () => {
 
122
  );
123
  }
124
 
125
+ /**
126
+ * Mounts the chat with one follow-up question in flight. Returns the deferred
127
+ * that settles the question, plus the render's `unmount`.
128
+ */
129
+ async function mountWithFollowUpInFlight() {
130
+ const question = deferred<string>();
131
+ vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(question.promise);
132
+
133
+ const view = renderChatInterface({ suppressInitialFollowUp: false });
134
+
135
+ await act(async () => {});
136
+
137
+ expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
138
+ return { question, unmount: view.unmount };
139
+ }
140
+
141
+ /**
142
+ * Mounts the chat with two follow-up questions in flight, oldest first, and
143
+ * returns both deferreds.
144
+ */
145
+ async function mountWithTwoFollowUpsInFlight() {
146
+ const earlierQuestion = deferred<string>();
147
+ const newerQuestion = deferred<string>();
148
+ vi.mocked(generateFollowUpQuestion)
149
+ .mockReturnValueOnce(earlierQuestion.promise)
150
+ .mockReturnValueOnce(newerQuestion.promise);
151
+
152
+ renderChatInterface({ suppressInitialFollowUp: false });
153
+ await act(async () => {});
154
+
155
+ expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
156
+ return { earlierQuestion, newerQuestion };
157
+ }
158
+
159
+ /**
160
+ * Mounts the chat with two follow-up questions in flight, then sends a message,
161
+ * which orphans the older call. Returns both deferreds and the send promise.
162
+ */
163
+ async function sendDuringTwoFollowUpsInFlight() {
164
+ const { earlierQuestion, newerQuestion } =
165
+ await mountWithTwoFollowUpsInFlight();
166
+
167
+ let send: Promise<void> = Promise.resolve();
168
+ await act(async () => {
169
+ send = sendMessage("And how do I use it?");
170
+ });
171
+ return { earlierQuestion, newerQuestion, send };
172
+ }
173
+
174
+ /** Settles the newer question and waits for the send still running beside it. */
175
+ async function settleNewestQuestion(
176
+ newerQuestion: ReturnType<typeof deferred<string>>,
177
+ send: Promise<void>,
178
+ ) {
179
+ await act(async () => {
180
+ newerQuestion.resolve("The newest question?");
181
+ await send;
182
+ });
183
+ }
184
+
185
+ /**
186
+ * Unmounts the first chat inside `act`, then mounts the second one with no
187
+ * `act` around the render. The caller sends the second chat's own message
188
+ * right after, in its own `act`.
189
+ */
190
+ async function remountChatMidGeneration(first: { unmount: () => void }) {
191
+ await act(async () => {
192
+ first.unmount();
193
+ });
194
+
195
+ renderChatInterface();
196
+ }
197
+
198
+ /** Settles the live answer and expects the response flag to clear with it. */
199
+ async function settleLiveAnswer(
200
+ secondResponse: ReturnType<typeof deferred<string>>,
201
+ secondSend: Promise<void>,
202
+ ) {
203
+ await act(async () => {
204
+ secondResponse.resolve("The live answer.");
205
+ await secondSend;
206
+ });
207
+
208
+ expect(getChatGenerationState().isGeneratingResponse).toBe(false);
209
+ }
210
+
211
+ /** Lets an earlier follow-up question land while the answer is still running. */
212
+ async function settleEarlierQuestionMidResponse(
213
+ followUpQuestion: ReturnType<typeof deferred<string>>,
214
+ ) {
215
+ expect(getChatGenerationState().isGeneratingResponse).toBe(true);
216
+
217
+ await act(async () => {
218
+ followUpQuestion.resolve("An earlier question?");
219
+ });
220
+
221
+ expect(getChatGenerationState().isGeneratingResponse).toBe(true);
222
+ }
223
+
224
+ /** Checks the second mount's own generation started, and is not a stale flag. */
225
+ function expectLiveGenerationStarted(calls: number) {
226
+ expect(getChatGenerationState().isGeneratingResponse).toBe(true);
227
+ expect(generateChatResponse).toHaveBeenCalledTimes(calls);
228
+ }
229
+
230
  function stubWakeLockApi() {
231
  const release = vi.fn(() => Promise.resolve());
232
  const request = vi.fn(() =>
 
267
 
268
  describe("ChatInterface generation state", () => {
269
  it("leaves the follow-up question flag off after sending during its generation", async () => {
270
+ const { question: earlierQuestion } = await mountWithFollowUpInFlight();
 
 
 
 
 
 
 
 
 
271
 
272
  await act(async () => {
273
  await sendMessage("And how do I use it?");
 
300
  send = sendMessage("And how do I use it?");
301
  });
302
 
303
+ await settleEarlierQuestionMidResponse(followUpQuestion);
 
 
 
 
 
 
304
 
305
  await act(async () => {
306
  chatResponse.resolve("An answer.");
 
450
  });
451
 
452
  it("keeps the follow-up question flag on until the newest call finishes", async () => {
453
+ const { earlierQuestion, newerQuestion } =
454
+ await mountWithTwoFollowUpsInFlight();
 
 
 
 
 
 
 
 
455
 
456
  let send: Promise<void> = Promise.resolve();
457
  await act(async () => {
 
466
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
467
  expect(getFollowUpQuestion()).toBe("");
468
 
469
+ await settleNewestQuestion(newerQuestion, send);
 
 
 
470
 
471
  expect(getFollowUpQuestion()).toBe("The newest question?");
472
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
473
  });
474
 
475
  it("leaves both generation flags off after unmounting mid-generation", async () => {
476
+ const { question: heldQuestion, unmount } =
477
+ await mountWithFollowUpInFlight();
 
 
 
 
 
 
 
478
 
479
  await act(async () => {
480
  unmount();
 
529
  });
530
 
531
  it("blanks nothing when an orphaned call rejects after a newer one started", async () => {
532
+ const { earlierQuestion, newerQuestion, send } =
533
+ await sendDuringTwoFollowUpsInFlight();
 
 
 
 
 
 
 
 
 
 
 
534
 
535
  // The orphaned call fails. Its catch must not blank the newer one's work.
536
  await act(async () => {
 
539
 
540
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
541
 
542
+ await settleNewestQuestion(newerQuestion, send);
 
 
 
543
 
544
  expect(getFollowUpQuestion()).toBe("The newest question?");
545
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
 
622
  firstSend = sendMessage("And how do I use it?");
623
  });
624
 
625
+ await remountChatMidGeneration(first);
 
 
 
 
626
 
627
  let secondSend: Promise<void> = Promise.resolve();
628
  await act(async () => {
629
  secondSend = sendMessage("Does it work offline?");
630
  });
631
 
632
+ expectLiveGenerationStarted(2);
 
 
633
 
634
  // The orphan's `finally` must not clear the live generation's flag, which
635
  // would drop the spinner and let a third send start alongside it.
 
640
 
641
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
642
 
643
+ await settleLiveAnswer(secondResponse, secondSend);
 
 
 
 
 
644
  });
645
 
646
  it("leaves the next mount's response flag alone when an orphaned regenerate settles", async () => {
 
662
  firstRegenerate = regenerateResponse();
663
  });
664
 
665
+ await remountChatMidGeneration(first);
 
 
 
 
666
 
667
  let secondSend: Promise<void> = Promise.resolve();
668
  await act(async () => {
669
  secondSend = sendMessage("Does it work offline?");
670
  });
671
 
672
+ expectLiveGenerationStarted(3);
 
 
673
 
674
  await act(async () => {
675
  firstResponse.resolve("The orphaned regeneration.");
 
678
 
679
  expect(getChatGenerationState().isGeneratingResponse).toBe(true);
680
 
681
+ await settleLiveAnswer(secondResponse, secondSend);
 
 
 
 
 
682
  });
683
 
684
  it("starts one re-generation when two regenerates land in the same task", async () => {
client/components/AiResponse/MessageList.test.tsx CHANGED
@@ -29,6 +29,20 @@ function renderMessageList(props: {
29
  );
30
  }
31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  describe("MessageList", () => {
33
  it("renders nothing when there are no follow-up messages", () => {
34
  const messages: ChatMessage[] = [
@@ -57,17 +71,7 @@ describe("MessageList", () => {
57
  });
58
 
59
  describe("an empty answer earlier in the chat", () => {
60
- // An empty answer is saved when the stream ends with no content.
61
- const messages: ChatMessage[] = [
62
- { role: "user", content: "system instructions" },
63
- { role: "assistant", content: "Ok!" },
64
- { role: "user", content: "Q1" },
65
- { role: "assistant", content: "" },
66
- { role: "user", content: "Q2" },
67
- { role: "assistant", content: "" },
68
- { role: "user", content: "Q3" },
69
- { role: "assistant", content: "A3" },
70
- ];
71
 
72
  it("edits each question at its position in the chat", () => {
73
  const onEditMessage = vi.fn();
 
29
  );
30
  }
31
 
32
+ // An empty answer is saved when the stream ends with no content.
33
+ function chatWithEmptyAnswers(): ChatMessage[] {
34
+ return [
35
+ { role: "user", content: "system instructions" },
36
+ { role: "assistant", content: "Ok!" },
37
+ { role: "user", content: "Q1" },
38
+ { role: "assistant", content: "" },
39
+ { role: "user", content: "Q2" },
40
+ { role: "assistant", content: "" },
41
+ { role: "user", content: "Q3" },
42
+ { role: "assistant", content: "A3" },
43
+ ];
44
+ }
45
+
46
  describe("MessageList", () => {
47
  it("renders nothing when there are no follow-up messages", () => {
48
  const messages: ChatMessage[] = [
 
71
  });
72
 
73
  describe("an empty answer earlier in the chat", () => {
74
+ const messages: ChatMessage[] = chatWithEmptyAnswers();
 
 
 
 
 
 
 
 
 
 
75
 
76
  it("edits each question at its position in the chat", () => {
77
  const onEditMessage = vi.fn();
client/components/DictationButton.test.tsx CHANGED
@@ -2,7 +2,6 @@ import { MantineProvider } from "@mantine/core";
2
  import { notifications } from "@mantine/notifications";
3
  import { act, render, screen, waitFor } from "@testing-library/react";
4
  import userEvent from "@testing-library/user-event";
5
- import { useSyncExternalStore } from "react";
6
  import DictationButton from "@/components/DictationButton";
7
  import {
8
  DictationError,
@@ -10,36 +9,58 @@ import {
10
  startDictation,
11
  } from "@/modules/speechToText";
12
 
13
- vi.mock("@/modules/speechToText", async () => {
14
- const { DictationError: RealDictationError } = await import(
15
- "@/modules/speechToText"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  );
17
- return {
18
- DictationError: RealDictationError,
19
- getDictationEngine: vi.fn(() => "wasm" as const),
20
- startDictation: vi.fn(),
21
- };
22
- });
23
 
24
- vi.mock("@mantine/notifications", () => ({
25
- notifications: { show: vi.fn() },
26
- }));
27
-
28
- /**
29
- * Subscribes for real rather than reading a snapshot, so a settings change
30
- * during a test re-renders the button the way it does in the app.
31
- */
32
- vi.mock("create-pubsub/react", () => ({
33
- usePubSub: (pubSub: [unknown, unknown, unknown]) => {
34
- const [publish, subscribe, get] = pubSub as [
35
- unknown,
36
- (listener: () => void) => () => void,
37
- () => unknown,
38
- ];
39
- const value = useSyncExternalStore(subscribe, get, get);
40
- return [value, publish];
41
- },
42
- }));
43
 
44
  function renderButton({
45
  getValue = () => "",
@@ -92,11 +113,7 @@ it("hides when no dictation engine is available", () => {
92
  });
93
 
94
  it("hides when the setting is off", async () => {
95
- const { settingsPubSub } = await import("@/modules/pubSub");
96
- settingsPubSub[0]({
97
- ...(settingsPubSub[2]?.() ?? {}),
98
- enableDictation: false,
99
- });
100
  try {
101
  renderButton();
102
  expect(
@@ -105,10 +122,7 @@ it("hides when the setting is off", async () => {
105
  } finally {
106
  // Restored even on a failure: this channel is module state, so leaking
107
  // `false` would hide the button in every later test in this file.
108
- settingsPubSub[0]({
109
- ...(settingsPubSub[2]?.() ?? {}),
110
- enableDictation: true,
111
- });
112
  }
113
  });
114
 
@@ -124,13 +138,7 @@ it("passes the local-model preference through to the engine", async () => {
124
  await user.click(
125
  screen.getByRole("button", { name: "Dictate the search query" }),
126
  );
127
- await waitFor(() =>
128
- expect(startDictation).toHaveBeenCalledWith(
129
- expect.anything(),
130
- false,
131
- expect.any(AbortSignal),
132
- ),
133
- );
134
  expect(getDictationEngine).toHaveBeenCalledWith(false);
135
  } finally {
136
  settingsPubSub[0]({
@@ -243,16 +251,7 @@ describe("the transcribing phase", () => {
243
  "transcribing",
244
  );
245
 
246
- view.rerender(
247
- <MantineProvider>
248
- <DictationButton
249
- getValue={() => ""}
250
- setValue={() => {}}
251
- labelScope="the search query"
252
- disabled
253
- />
254
- </MantineProvider>,
255
- );
256
 
257
  // The transcript would otherwise land in a field that went read-only.
258
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
@@ -538,7 +537,6 @@ describe("teardown", () => {
538
 
539
  it("stays quiet when a load abandoned by the setting fails", async () => {
540
  const user = userEvent.setup();
541
- const { settingsPubSub } = await import("@/modules/pubSub");
542
  let fail: ((error: Error) => void) | undefined;
543
  vi.mocked(startDictation).mockReturnValue(
544
  new Promise((_resolve, reject) => {
@@ -547,14 +545,10 @@ describe("teardown", () => {
547
  );
548
 
549
  renderButton();
550
- await user.click(screen.getByRole("button"));
551
- await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
552
 
553
  try {
554
- settingsPubSub[0]({
555
- ...(settingsPubSub[2]?.() ?? {}),
556
- enableDictation: false,
557
- });
558
  await waitFor(() =>
559
  expect(vi.mocked(startDictation).mock.calls[0][2]?.aborted).toBe(true),
560
  );
@@ -565,10 +559,7 @@ describe("teardown", () => {
565
  // The button is gone, so there is nothing for the failure to explain.
566
  expect(notifications.show).not.toHaveBeenCalled();
567
  } finally {
568
- settingsPubSub[0]({
569
- ...(settingsPubSub[2]?.() ?? {}),
570
- enableDictation: true,
571
- });
572
  }
573
  });
574
 
@@ -589,7 +580,6 @@ describe("teardown", () => {
589
 
590
  it("discards a session that arrives after the setting was turned off", async () => {
591
  const user = userEvent.setup();
592
- const { settingsPubSub } = await import("@/modules/pubSub");
593
  let release: ((value: typeof session) => void) | undefined;
594
  vi.mocked(startDictation).mockReturnValue(
595
  new Promise((resolve) => {
@@ -598,30 +588,22 @@ describe("teardown", () => {
598
  );
599
 
600
  renderButton();
601
- await user.click(screen.getByRole("button"));
602
- await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
603
 
604
  try {
605
  // Mid-load, with the session not yet in the ref: the button disappears,
606
  // and the microphone would otherwise open with nothing to stop it.
607
- settingsPubSub[0]({
608
- ...(settingsPubSub[2]?.() ?? {}),
609
- enableDictation: false,
610
- });
611
  release?.(session);
612
 
613
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
614
  } finally {
615
- settingsPubSub[0]({
616
- ...(settingsPubSub[2]?.() ?? {}),
617
- enableDictation: true,
618
- });
619
  }
620
  });
621
 
622
  it("does not adopt a load an earlier press abandoned", async () => {
623
  const user = userEvent.setup();
624
- const { settingsPubSub } = await import("@/modules/pubSub");
625
  const first = { stop: vi.fn(), cancel: vi.fn() };
626
  const second = { stop: vi.fn(), cancel: vi.fn() };
627
  const releases: ((value: typeof session) => void)[] = [];
@@ -630,21 +612,14 @@ describe("teardown", () => {
630
  );
631
 
632
  renderButton();
633
- await user.click(screen.getByRole("button"));
634
- await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
635
 
636
  try {
637
- settingsPubSub[0]({
638
- ...(settingsPubSub[2]?.() ?? {}),
639
- enableDictation: false,
640
- });
641
  await waitFor(() =>
642
  expect(screen.queryByRole("button")).not.toBeInTheDocument(),
643
  );
644
- settingsPubSub[0]({
645
- ...(settingsPubSub[2]?.() ?? {}),
646
- enableDictation: true,
647
- });
648
 
649
  await user.click(await screen.findByRole("button"));
650
  await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(2));
@@ -658,10 +633,7 @@ describe("teardown", () => {
658
  await waitFor(() => expect(first.cancel).toHaveBeenCalledTimes(1));
659
  expect(second.cancel).not.toHaveBeenCalled();
660
  } finally {
661
- settingsPubSub[0]({
662
- ...(settingsPubSub[2]?.() ?? {}),
663
- enableDictation: true,
664
- });
665
  }
666
  });
667
 
@@ -669,10 +641,7 @@ describe("teardown", () => {
669
  const user = userEvent.setup();
670
  renderButton();
671
 
672
- await user.click(screen.getByRole("button"));
673
- await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
674
-
675
- const { onEnd } = vi.mocked(startDictation).mock.calls[0][0];
676
  act(() => onEnd?.());
677
 
678
  // The engine ending by itself is not a failure, but the button has to
@@ -692,10 +661,7 @@ describe("teardown", () => {
692
  const user = userEvent.setup();
693
  renderButton();
694
 
695
- await user.click(screen.getByRole("button"));
696
- await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
697
-
698
- const { onError } = vi.mocked(startDictation).mock.calls[0][0];
699
  act(() => onError?.(new DictationError("engine", "the transcriber died")));
700
 
701
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
 
2
  import { notifications } from "@mantine/notifications";
3
  import { act, render, screen, waitFor } from "@testing-library/react";
4
  import userEvent from "@testing-library/user-event";
 
5
  import DictationButton from "@/components/DictationButton";
6
  import {
7
  DictationError,
 
9
  startDictation,
10
  } from "@/modules/speechToText";
11
 
12
+ // jscpd:ignore-start
13
+ // Vitest hoists every vi.mock call above the imports, so the registration has
14
+ // to be written out in each file; only the factory body can be shared, and it
15
+ // is. The duplication is the framework's, not the tests'.
16
+ vi.mock("@/modules/speechToText", async () =>
17
+ (await import("@/testMocks")).speechToTextMock(),
18
+ );
19
+ vi.mock("@mantine/notifications", async () =>
20
+ (await import("@/testMocks")).notificationsStub(),
21
+ );
22
+ vi.mock("create-pubsub/react", async () =>
23
+ (await import("@/testMocks")).pubSubReactMock(),
24
+ );
25
+ // jscpd:ignore-end
26
+
27
+ /** Turns dictation on or off in the settings the button subscribes to. */
28
+ async function setDictationSetting(enableDictation: boolean) {
29
+ const { settingsPubSub } = await import("@/modules/pubSub");
30
+ settingsPubSub[0]({ ...(settingsPubSub[2]?.() ?? {}), enableDictation });
31
+ }
32
+
33
+ /** Presses the button and returns the callbacks it handed the engine. */
34
+ async function pressAndWaitForEngine(user: ReturnType<typeof userEvent.setup>) {
35
+ await user.click(screen.getByRole("button"));
36
+ await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(1));
37
+ return vi.mocked(startDictation).mock.calls[0][0];
38
+ }
39
+
40
+ /** Re-renders the button as a field that went read-only mid-transcription. */
41
+ function renderDisabledButton(view: ReturnType<typeof render>) {
42
+ view.rerender(
43
+ <MantineProvider>
44
+ <DictationButton
45
+ getValue={() => ""}
46
+ setValue={() => {}}
47
+ labelScope="the search query"
48
+ disabled
49
+ />
50
+ </MantineProvider>,
51
  );
52
+ }
 
 
 
 
 
53
 
54
+ /** Waits for the engine to have been started with this local-model preference. */
55
+ async function expectEngineStartedWith(localModel: boolean) {
56
+ await waitFor(() =>
57
+ expect(startDictation).toHaveBeenCalledWith(
58
+ expect.anything(),
59
+ localModel,
60
+ expect.any(AbortSignal),
61
+ ),
62
+ );
63
+ }
 
 
 
 
 
 
 
 
 
64
 
65
  function renderButton({
66
  getValue = () => "",
 
113
  });
114
 
115
  it("hides when the setting is off", async () => {
116
+ await setDictationSetting(false);
 
 
 
 
117
  try {
118
  renderButton();
119
  expect(
 
122
  } finally {
123
  // Restored even on a failure: this channel is module state, so leaking
124
  // `false` would hide the button in every later test in this file.
125
+ await setDictationSetting(true);
 
 
 
126
  }
127
  });
128
 
 
138
  await user.click(
139
  screen.getByRole("button", { name: "Dictate the search query" }),
140
  );
141
+ await expectEngineStartedWith(false);
 
 
 
 
 
 
142
  expect(getDictationEngine).toHaveBeenCalledWith(false);
143
  } finally {
144
  settingsPubSub[0]({
 
251
  "transcribing",
252
  );
253
 
254
+ renderDisabledButton(view);
 
 
 
 
 
 
 
 
 
255
 
256
  // The transcript would otherwise land in a field that went read-only.
257
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
 
537
 
538
  it("stays quiet when a load abandoned by the setting fails", async () => {
539
  const user = userEvent.setup();
 
540
  let fail: ((error: Error) => void) | undefined;
541
  vi.mocked(startDictation).mockReturnValue(
542
  new Promise((_resolve, reject) => {
 
545
  );
546
 
547
  renderButton();
548
+ await pressAndWaitForEngine(user);
 
549
 
550
  try {
551
+ await setDictationSetting(false);
 
 
 
552
  await waitFor(() =>
553
  expect(vi.mocked(startDictation).mock.calls[0][2]?.aborted).toBe(true),
554
  );
 
559
  // The button is gone, so there is nothing for the failure to explain.
560
  expect(notifications.show).not.toHaveBeenCalled();
561
  } finally {
562
+ await setDictationSetting(true);
 
 
 
563
  }
564
  });
565
 
 
580
 
581
  it("discards a session that arrives after the setting was turned off", async () => {
582
  const user = userEvent.setup();
 
583
  let release: ((value: typeof session) => void) | undefined;
584
  vi.mocked(startDictation).mockReturnValue(
585
  new Promise((resolve) => {
 
588
  );
589
 
590
  renderButton();
591
+ await pressAndWaitForEngine(user);
 
592
 
593
  try {
594
  // Mid-load, with the session not yet in the ref: the button disappears,
595
  // and the microphone would otherwise open with nothing to stop it.
596
+ await setDictationSetting(false);
 
 
 
597
  release?.(session);
598
 
599
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
600
  } finally {
601
+ await setDictationSetting(true);
 
 
 
602
  }
603
  });
604
 
605
  it("does not adopt a load an earlier press abandoned", async () => {
606
  const user = userEvent.setup();
 
607
  const first = { stop: vi.fn(), cancel: vi.fn() };
608
  const second = { stop: vi.fn(), cancel: vi.fn() };
609
  const releases: ((value: typeof session) => void)[] = [];
 
612
  );
613
 
614
  renderButton();
615
+ await pressAndWaitForEngine(user);
 
616
 
617
  try {
618
+ await setDictationSetting(false);
 
 
 
619
  await waitFor(() =>
620
  expect(screen.queryByRole("button")).not.toBeInTheDocument(),
621
  );
622
+ await setDictationSetting(true);
 
 
 
623
 
624
  await user.click(await screen.findByRole("button"));
625
  await waitFor(() => expect(startDictation).toHaveBeenCalledTimes(2));
 
633
  await waitFor(() => expect(first.cancel).toHaveBeenCalledTimes(1));
634
  expect(second.cancel).not.toHaveBeenCalled();
635
  } finally {
636
+ await setDictationSetting(true);
 
 
 
637
  }
638
  });
639
 
 
641
  const user = userEvent.setup();
642
  renderButton();
643
 
644
+ const { onEnd } = await pressAndWaitForEngine(user);
 
 
 
645
  act(() => onEnd?.());
646
 
647
  // The engine ending by itself is not a failure, but the button has to
 
661
  const user = userEvent.setup();
662
  renderButton();
663
 
664
+ const { onError } = await pressAndWaitForEngine(user);
 
 
 
665
  act(() => onError?.(new DictationError("engine", "the transcriber died")));
666
 
667
  await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
client/components/Pages/Main/MainPage.test.tsx CHANGED
@@ -104,6 +104,14 @@ async function renderMainPage(state: PageState) {
104
  return { ...utils, ...handlers };
105
  }
106
 
 
 
 
 
 
 
 
 
107
  describe("MainPage", () => {
108
  beforeEach(() => {
109
  vi.clearAllMocks();
@@ -183,12 +191,7 @@ describe("MainPage", () => {
183
 
184
  it("enables AI response and triggers a search when the prompt is accepted", async () => {
185
  const user = userEvent.setup();
186
- const { setSettings } = await renderMainPage(
187
- createPageState({
188
- query: "cats",
189
- settings: { showEnableAiResponsePrompt: true },
190
- }),
191
- );
192
 
193
  await user.click(await screen.findByRole("button", { name: "Accept" }));
194
 
@@ -201,12 +204,7 @@ describe("MainPage", () => {
201
 
202
  it("disables AI response without triggering a search when the prompt is declined", async () => {
203
  const user = userEvent.setup();
204
- const { setSettings } = await renderMainPage(
205
- createPageState({
206
- query: "cats",
207
- settings: { showEnableAiResponsePrompt: true },
208
- }),
209
- );
210
 
211
  await user.click(await screen.findByRole("button", { name: "Decline" }));
212
 
 
104
  return { ...utils, ...handlers };
105
  }
106
 
107
+ /** Renders the page with the AI-response prompt showing. */
108
+ function promptPageState() {
109
+ return createPageState({
110
+ query: "cats",
111
+ settings: { showEnableAiResponsePrompt: true },
112
+ });
113
+ }
114
+
115
  describe("MainPage", () => {
116
  beforeEach(() => {
117
  vi.clearAllMocks();
 
191
 
192
  it("enables AI response and triggers a search when the prompt is accepted", async () => {
193
  const user = userEvent.setup();
194
+ const { setSettings } = await renderMainPage(promptPageState());
 
 
 
 
 
195
 
196
  await user.click(await screen.findByRole("button", { name: "Accept" }));
197
 
 
204
 
205
  it("disables AI response without triggering a search when the prompt is declined", async () => {
206
  const user = userEvent.setup();
207
+ const { setSettings } = await renderMainPage(promptPageState());
 
 
 
 
 
208
 
209
  await user.click(await screen.findByRole("button", { name: "Decline" }));
210
 
client/components/Pages/Main/Menu/ClearDataButton.test.tsx CHANGED
@@ -30,6 +30,14 @@ function renderClearDataButton() {
30
  }
31
 
32
  describe("ClearDataButton", () => {
 
 
 
 
 
 
 
 
33
  const originalLocation = self.location;
34
  const originalCachesDescriptor = Object.getOwnPropertyDescriptor(
35
  self,
@@ -71,14 +79,7 @@ describe("ClearDataButton", () => {
71
  value: undefined,
72
  });
73
 
74
- const user = userEvent.setup();
75
- renderClearDataButton();
76
-
77
- await user.click(screen.getByRole("button", { name: "Clear all data" }));
78
-
79
- await waitFor(() => {
80
- expect(reloadMock).toHaveBeenCalledTimes(1);
81
- });
82
 
83
  expect(localStorage.getItem("sample-key")).toBeNull();
84
  expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");
@@ -99,14 +100,7 @@ describe("ClearDataButton", () => {
99
  new Error("OPFS unavailable"),
100
  );
101
 
102
- const user = userEvent.setup();
103
- renderClearDataButton();
104
-
105
- await user.click(screen.getByRole("button", { name: "Clear all data" }));
106
-
107
- await waitFor(() => {
108
- expect(reloadMock).toHaveBeenCalledTimes(1);
109
- });
110
 
111
  expect(addLogEntry).toHaveBeenCalledWith(
112
  "Error clearing data: OPFS unavailable",
@@ -135,14 +129,7 @@ describe("ClearDataButton", () => {
135
  },
136
  });
137
 
138
- const user = userEvent.setup();
139
- renderClearDataButton();
140
-
141
- await user.click(screen.getByRole("button", { name: "Clear all data" }));
142
-
143
- await waitFor(() => {
144
- expect(reloadMock).toHaveBeenCalledTimes(1);
145
- });
146
 
147
  expect(keysMock).toHaveBeenCalledTimes(1);
148
  expect(deleteMock).toHaveBeenCalledWith("cache-a");
 
30
  }
31
 
32
  describe("ClearDataButton", () => {
33
+ /** Presses the button and waits for the teardown to reload the page. */
34
+ async function pressClearAllData() {
35
+ const user = userEvent.setup();
36
+ renderClearDataButton();
37
+ await user.click(screen.getByRole("button", { name: "Clear all data" }));
38
+ await waitFor(() => expect(reloadMock).toHaveBeenCalledTimes(1));
39
+ }
40
+
41
  const originalLocation = self.location;
42
  const originalCachesDescriptor = Object.getOwnPropertyDescriptor(
43
  self,
 
79
  value: undefined,
80
  });
81
 
82
+ await pressClearAllData();
 
 
 
 
 
 
 
83
 
84
  expect(localStorage.getItem("sample-key")).toBeNull();
85
  expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");
 
100
  new Error("OPFS unavailable"),
101
  );
102
 
103
+ await pressClearAllData();
 
 
 
 
 
 
 
104
 
105
  expect(addLogEntry).toHaveBeenCalledWith(
106
  "Error clearing data: OPFS unavailable",
 
129
  },
130
  });
131
 
132
+ await pressClearAllData();
 
 
 
 
 
 
 
133
 
134
  expect(keysMock).toHaveBeenCalledTimes(1);
135
  expect(deleteMock).toHaveBeenCalledWith("cache-a");
client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx CHANGED
@@ -94,14 +94,19 @@ beforeEach(() => {
94
  );
95
  });
96
 
 
 
 
 
 
 
 
 
 
 
97
  describe("VoiceSettingsForm", () => {
98
  it("lists only the local voices while the local engine is selected", async () => {
99
- renderForm();
100
- await screen.findByText("Voice Selection");
101
-
102
- const options = openSelect(voiceInput()).getAllByRole("option", {
103
- hidden: true,
104
- });
105
 
106
  expect(options.map((option) => option.textContent)).toEqual([
107
  "๐Ÿ‡บ๐Ÿ‡ธ lessac โ€ข English (high)",
@@ -134,12 +139,7 @@ describe("VoiceSettingsForm", () => {
134
 
135
  it("lists only the system voices while the system engine is selected", async () => {
136
  settings.current.textToSpeechEngine = "system";
137
- renderForm();
138
- await screen.findByText("Voice Selection");
139
-
140
- const options = openSelect(voiceInput()).getAllByRole("option", {
141
- hidden: true,
142
- });
143
 
144
  expect(options.map((option) => option.textContent)).toEqual([
145
  "๐Ÿ‡บ๐Ÿ‡ธ OS Voice โ€ข en-US",
 
94
  );
95
  });
96
 
97
+ /** Renders the form, opens the voice select, and returns its options. */
98
+ async function renderedVoiceOptions() {
99
+ renderForm();
100
+ await screen.findByText("Voice Selection");
101
+
102
+ return openSelect(voiceInput()).getAllByRole("option", {
103
+ hidden: true,
104
+ });
105
+ }
106
+
107
  describe("VoiceSettingsForm", () => {
108
  it("lists only the local voices while the local engine is selected", async () => {
109
+ const options = await renderedVoiceOptions();
 
 
 
 
 
110
 
111
  expect(options.map((option) => option.textContent)).toEqual([
112
  "๐Ÿ‡บ๐Ÿ‡ธ lessac โ€ข English (high)",
 
139
 
140
  it("lists only the system voices while the system engine is selected", async () => {
141
  settings.current.textToSpeechEngine = "system";
142
+ const options = await renderedVoiceOptions();
 
 
 
 
 
143
 
144
  expect(options.map((option) => option.textContent)).toEqual([
145
  "๐Ÿ‡บ๐Ÿ‡ธ OS Voice โ€ข en-US",
client/components/Search/Form/SearchForm.test.tsx CHANGED
@@ -2,6 +2,7 @@ import { MantineProvider } from "@mantine/core";
2
  import { act, render, screen, waitFor } from "@testing-library/react";
3
  import userEvent from "@testing-library/user-event";
4
  import SearchForm from "@/components/Search/Form/SearchForm";
 
5
  import { resetHandledQuery } from "@/modules/autoSearch";
6
  import { settingsPubSub } from "@/modules/pubSub";
7
  import { getRandomQuerySuggestion } from "@/modules/querySuggestions";
@@ -149,12 +150,7 @@ describe("SearchForm component", () => {
149
  settingsPubSub[0]({ ...defaultSettings });
150
  });
151
 
152
- it.each([
153
- [true, "{Enter}", true],
154
- [true, "{Shift>}{Enter}{/Shift}", false],
155
- [false, "{Shift>}{Enter}{/Shift}", true],
156
- [false, "{Enter}", false],
157
- ])(
158
  "with enterToSubmit %s, pressing %s submits: %s",
159
  async (enterToSubmit, keys, submits) => {
160
  settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
 
2
  import { act, render, screen, waitFor } from "@testing-library/react";
3
  import userEvent from "@testing-library/user-event";
4
  import SearchForm from "@/components/Search/Form/SearchForm";
5
+ import { ENTER_TO_SUBMIT_CASES } from "@/enterToSubmitCases";
6
  import { resetHandledQuery } from "@/modules/autoSearch";
7
  import { settingsPubSub } from "@/modules/pubSub";
8
  import { getRandomQuerySuggestion } from "@/modules/querySuggestions";
 
150
  settingsPubSub[0]({ ...defaultSettings });
151
  });
152
 
153
+ it.each(ENTER_TO_SUBMIT_CASES)(
 
 
 
 
 
154
  "with enterToSubmit %s, pressing %s submits: %s",
155
  async (enterToSubmit, keys, submits) => {
156
  settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
client/components/Search/History/HistoryDrawer.test.tsx CHANGED
@@ -78,6 +78,20 @@ const mockHistory = (overrides: SearchHistoryOverrides = {}) => {
78
  });
79
  };
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  describe("HistoryDrawer component", () => {
82
  beforeEach(() => {
83
  mockSettings(true);
@@ -137,24 +151,14 @@ describe("HistoryDrawer component", () => {
137
  });
138
 
139
  it("selects an entry when its card is clicked", async () => {
140
- const onSearchSelect = vi.fn();
141
- const entry = makeEntry(1, "quantum tunneling");
142
- mockHistory({ filteredSearches: [entry] });
143
-
144
- const user = userEvent.setup();
145
- renderDrawer(onSearchSelect);
146
  await user.click(await screen.findByText("quantum tunneling"));
147
 
148
  expect(onSearchSelect).toHaveBeenCalledWith(entry);
149
  });
150
 
151
  it("selects an entry once when its query is clicked", async () => {
152
- const onSearchSelect = vi.fn();
153
- const entry = makeEntry(1, "quantum tunneling");
154
- mockHistory({ filteredSearches: [entry] });
155
-
156
- const user = userEvent.setup();
157
- renderDrawer(onSearchSelect);
158
  await user.click(
159
  await screen.findByRole("button", { name: /quantum tunneling/ }),
160
  );
@@ -164,12 +168,7 @@ describe("HistoryDrawer component", () => {
164
  });
165
 
166
  it("selects an entry from the keyboard", async () => {
167
- const onSearchSelect = vi.fn();
168
- const entry = makeEntry(1, "quantum tunneling");
169
- mockHistory({ filteredSearches: [entry] });
170
-
171
- const user = userEvent.setup();
172
- renderDrawer(onSearchSelect);
173
  const queryButton = await screen.findByRole("button", {
174
  name: /quantum tunneling/,
175
  });
 
78
  });
79
  };
80
 
81
+ /**
82
+ * Renders the drawer with one stored search and returns the select spy, the
83
+ * entry, and the user for the click that follows.
84
+ */
85
+ function drawerWithOneEntry() {
86
+ const onSearchSelect = vi.fn();
87
+ const entry = makeEntry(1, "quantum tunneling");
88
+ mockHistory({ filteredSearches: [entry] });
89
+
90
+ const user = userEvent.setup();
91
+ renderDrawer(onSearchSelect);
92
+ return { user, onSearchSelect, entry };
93
+ }
94
+
95
  describe("HistoryDrawer component", () => {
96
  beforeEach(() => {
97
  mockSettings(true);
 
151
  });
152
 
153
  it("selects an entry when its card is clicked", async () => {
154
+ const { user, onSearchSelect, entry } = drawerWithOneEntry();
 
 
 
 
 
155
  await user.click(await screen.findByText("quantum tunneling"));
156
 
157
  expect(onSearchSelect).toHaveBeenCalledWith(entry);
158
  });
159
 
160
  it("selects an entry once when its query is clicked", async () => {
161
+ const { user, onSearchSelect, entry } = drawerWithOneEntry();
 
 
 
 
 
162
  await user.click(
163
  await screen.findByRole("button", { name: /quantum tunneling/ }),
164
  );
 
168
  });
169
 
170
  it("selects an entry from the keyboard", async () => {
171
+ const { user, onSearchSelect, entry } = drawerWithOneEntry();
 
 
 
 
 
172
  const queryButton = await screen.findByRole("button", {
173
  name: /quantum tunneling/,
174
  });
client/components/Search/Results/Graphical/ImageResultsList.test.tsx CHANGED
@@ -67,6 +67,15 @@ function renderImageResultsList() {
67
  );
68
  }
69
 
 
 
 
 
 
 
 
 
 
70
  describe("ImageResultsList", () => {
71
  it("renders thumbnails as named buttons", async () => {
72
  renderImageResultsList();
@@ -113,11 +122,7 @@ describe("ImageResultsList", () => {
113
  it("shows the host name when a thumbnail fails to load", async () => {
114
  renderImageResultsList();
115
 
116
- const [img] = await screen.findAllByRole("img");
117
- img.dispatchEvent(new Event("error"));
118
-
119
- // The second tile still loads, so exactly one img survives the failure.
120
- await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1));
121
  expect(
122
  screen.getByRole("button", { name: "Open image preview: First image" }),
123
  ).toHaveTextContent("example.com");
@@ -127,9 +132,7 @@ describe("ImageResultsList", () => {
127
  const user = userEvent.setup();
128
  renderImageResultsList();
129
 
130
- const [img] = await screen.findAllByRole("img");
131
- img.dispatchEvent(new Event("error"));
132
- await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1));
133
 
134
  await user.click(
135
  screen.getByRole("button", { name: "Open image preview: First image" }),
 
67
  );
68
  }
69
 
70
+ /** Breaks the first thumbnail and waits for its tile to fall back. */
71
+ async function breakFirstThumbnail() {
72
+ const [img] = await screen.findAllByRole("img");
73
+ img.dispatchEvent(new Event("error"));
74
+
75
+ // The second tile still loads, so exactly one img survives the failure.
76
+ await waitFor(() => expect(screen.getAllByRole("img")).toHaveLength(1));
77
+ }
78
+
79
  describe("ImageResultsList", () => {
80
  it("renders thumbnails as named buttons", async () => {
81
  renderImageResultsList();
 
122
  it("shows the host name when a thumbnail fails to load", async () => {
123
  renderImageResultsList();
124
 
125
+ await breakFirstThumbnail();
 
 
 
 
126
  expect(
127
  screen.getByRole("button", { name: "Open image preview: First image" }),
128
  ).toHaveTextContent("example.com");
 
132
  const user = userEvent.setup();
133
  renderImageResultsList();
134
 
135
+ await breakFirstThumbnail();
 
 
136
 
137
  await user.click(
138
  screen.getByRole("button", { name: "Open image preview: First image" }),
client/components/Search/Results/Graphical/ImageSearchResults.test.tsx ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { MantineProvider } from "@mantine/core";
2
+ import { act, render, screen } from "@testing-library/react";
3
+ import { afterEach, describe, expect, it, vi } from "vitest";
4
+ import {
5
+ imageSearchResultsPubSub,
6
+ imageSearchStatePubSub,
7
+ } from "@/modules/pubSub";
8
+ import type { ImageSearchResult } from "@/modules/types";
9
+ import ImageSearchResults from "./ImageSearchResults";
10
+
11
+ vi.mock("./ImageResultsList", () => ({
12
+ default: ({ imageResults }: { imageResults: ImageSearchResult[] }) => (
13
+ <ul aria-label="Image results">
14
+ {imageResults.map(([title]) => (
15
+ <li key={title}>{title}</li>
16
+ ))}
17
+ </ul>
18
+ ),
19
+ }));
20
+
21
+ const [setImageSearchState] = imageSearchStatePubSub;
22
+ const [setImageSearchResults] = imageSearchResultsPubSub;
23
+
24
+ const followUpImage: ImageSearchResult = [
25
+ "Follow-up image",
26
+ "https://example.com/follow-up",
27
+ "https://example.com/follow-up.jpg",
28
+ "https://source.example.com/follow-up",
29
+ ];
30
+
31
+ function renderImageSearchResults() {
32
+ return render(
33
+ <MantineProvider>
34
+ <ImageSearchResults />
35
+ </MantineProvider>,
36
+ );
37
+ }
38
+
39
+ afterEach(() => {
40
+ act(() => {
41
+ setImageSearchState("idle");
42
+ setImageSearchResults([]);
43
+ });
44
+ });
45
+
46
+ describe("ImageSearchResults", () => {
47
+ it("shows a follow-up's images after the first image search failed", () => {
48
+ setImageSearchState("failed");
49
+ renderImageSearchResults();
50
+ expect(screen.getByText("Failed to search for images")).toBeInTheDocument();
51
+
52
+ act(() => setImageSearchResults([followUpImage]));
53
+
54
+ expect(screen.getByText("Follow-up image")).toBeInTheDocument();
55
+ expect(
56
+ screen.queryByText("Failed to search for images"),
57
+ ).not.toBeInTheDocument();
58
+ });
59
+
60
+ it("keeps the failure alert when no images were added", () => {
61
+ setImageSearchState("failed");
62
+ renderImageSearchResults();
63
+
64
+ expect(screen.getByText("Failed to search for images")).toBeInTheDocument();
65
+ expect(screen.queryByLabelText("Image results")).not.toBeInTheDocument();
66
+ });
67
+ });
client/components/Search/Results/Graphical/ImageSearchResults.tsx CHANGED
@@ -35,6 +35,12 @@ export default function ImageSearchResults() {
35
  }
36
 
37
  if (searchState === "failed") {
 
 
 
 
 
 
38
  return (
39
  <Alert
40
  variant="light"
 
35
  }
36
 
37
  if (searchState === "failed") {
38
+ // A follow-up's image search can still add images after the first one
39
+ // failed, and it does not change this state.
40
+ if (results.length > 0) {
41
+ return <ImageResultsList imageResults={results} />;
42
+ }
43
+
44
  return (
45
  <Alert
46
  variant="light"
client/components/Search/Results/testUtils.ts CHANGED
@@ -1,4 +1,5 @@
1
  import { vi } from "vitest";
 
2
 
3
  /**
4
  * Overrides the global `matchMedia` mock from `setupTests.ts`. Only
@@ -6,17 +7,7 @@ import { vi } from "vitest";
6
  * queries the result components rely on keep returning false.
7
  */
8
  export function setReducedMotionPreference(matches: boolean) {
9
- vi.mocked(window.matchMedia).mockImplementation(
10
- (query) =>
11
- ({
12
- matches: matches && query === "(prefers-reduced-motion: reduce)",
13
- media: query,
14
- onchange: null,
15
- addListener: vi.fn(),
16
- removeListener: vi.fn(),
17
- addEventListener: vi.fn(),
18
- removeEventListener: vi.fn(),
19
- dispatchEvent: vi.fn(),
20
- }) as MediaQueryList,
21
  );
22
  }
 
1
  import { vi } from "vitest";
2
+ import { matchMediaStub, REDUCED_MOTION_QUERY } from "@/matchMediaStub";
3
 
4
  /**
5
  * Overrides the global `matchMedia` mock from `setupTests.ts`. Only
 
7
  * queries the result components rely on keep returning false.
8
  */
9
  export function setReducedMotionPreference(matches: boolean) {
10
+ vi.mocked(window.matchMedia).mockImplementation((query) =>
11
+ matchMediaStub(query, matches && query === REDUCED_MOTION_QUERY),
 
 
 
 
 
 
 
 
 
 
12
  );
13
  }
client/enterToSubmitCases.ts ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * The `enterToSubmit` matrix: the setting, the key, and whether the key sends.
3
+ * Shared by the search form and the chat input, which read the same setting.
4
+ */
5
+ export const ENTER_TO_SUBMIT_CASES: [boolean, string, boolean][] = [
6
+ [true, "{Enter}", true],
7
+ [true, "{Shift>}{Enter}{/Shift}", false],
8
+ [false, "{Shift>}{Enter}{/Shift}", true],
9
+ [false, "{Enter}", false],
10
+ ];
client/hooks/useSearchHistory.test.ts CHANGED
@@ -121,17 +121,23 @@ async function addNewerSearches(count: number) {
121
  }
122
  }
123
 
 
 
 
 
 
 
 
 
 
 
124
  describe("useSearchHistory with includeAllPinned", () => {
125
  it("keeps a pinned search older than the whole recent window", async () => {
126
  await pinOldestEntry();
127
  // limit 2 reads the newest 4: the pinned entry is the 7th newest.
128
  await addNewerSearches(4);
129
 
130
- const { result } = renderHook(() =>
131
- useSearchHistory({ limit: 2, includeAllPinned: true }),
132
- );
133
- await settle();
134
- await untilLoaded(result);
135
 
136
  expect(queriesOf(result.current.filteredSearches)).toEqual([
137
  "newer search 4",
@@ -143,11 +149,7 @@ describe("useSearchHistory with includeAllPinned", () => {
143
  it("keeps a pinned search inside the window but past the limit", async () => {
144
  await pinOldestEntry();
145
 
146
- const { result } = renderHook(() =>
147
- useSearchHistory({ limit: 2, includeAllPinned: true }),
148
- );
149
- await settle();
150
- await untilLoaded(result);
151
 
152
  expect(queriesOf(result.current.filteredSearches)).toEqual([
153
  "rust async tutorial",
@@ -160,11 +162,7 @@ describe("useSearchHistory with includeAllPinned", () => {
160
  await pinOldestEntry();
161
  await addNewerSearches(4);
162
 
163
- const { result } = renderHook(() =>
164
- useSearchHistory({ limit: 2, includeAllPinned: true }),
165
- );
166
- await settle();
167
- await untilLoaded(result);
168
  act(() => result.current.searchHistory("lisbon"));
169
  await settle();
170
 
@@ -177,11 +175,7 @@ describe("useSearchHistory with includeAllPinned", () => {
177
  await pinOldestEntry();
178
  const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");
179
 
180
- const { result } = renderHook(() =>
181
- useSearchHistory({ limit: 2, includeAllPinned: true }),
182
- );
183
- await settle();
184
- await untilLoaded(result);
185
  expect(pinnedReadSpy).toHaveBeenCalledTimes(1);
186
 
187
  for (const query of ["w", "we", "wea"]) {
 
121
  }
122
  }
123
 
124
+ /** Renders the pinned-aware two-entry window and waits for the first load. */
125
+ async function renderPinnedAwareHistory() {
126
+ const { result } = renderHook(() =>
127
+ useSearchHistory({ limit: 2, includeAllPinned: true }),
128
+ );
129
+ await settle();
130
+ await untilLoaded(result);
131
+ return result;
132
+ }
133
+
134
  describe("useSearchHistory with includeAllPinned", () => {
135
  it("keeps a pinned search older than the whole recent window", async () => {
136
  await pinOldestEntry();
137
  // limit 2 reads the newest 4: the pinned entry is the 7th newest.
138
  await addNewerSearches(4);
139
 
140
+ const result = await renderPinnedAwareHistory();
 
 
 
 
141
 
142
  expect(queriesOf(result.current.filteredSearches)).toEqual([
143
  "newer search 4",
 
149
  it("keeps a pinned search inside the window but past the limit", async () => {
150
  await pinOldestEntry();
151
 
152
+ const result = await renderPinnedAwareHistory();
 
 
 
 
153
 
154
  expect(queriesOf(result.current.filteredSearches)).toEqual([
155
  "rust async tutorial",
 
162
  await pinOldestEntry();
163
  await addNewerSearches(4);
164
 
165
+ const result = await renderPinnedAwareHistory();
 
 
 
 
166
  act(() => result.current.searchHistory("lisbon"));
167
  await settle();
168
 
 
175
  await pinOldestEntry();
176
  const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");
177
 
178
+ const result = await renderPinnedAwareHistory();
 
 
 
 
179
  expect(pinnedReadSpy).toHaveBeenCalledTimes(1);
180
 
181
  for (const query of ["w", "we", "wea"]) {
client/matchMediaStub.ts ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { vi } from "vitest";
2
+
3
+ /** The only media query the app's components ask about by name. */
4
+ export const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)";
5
+
6
+ /**
7
+ * A `MediaQueryList` for `query`, matching or not. `setupTests.ts` installs it
8
+ * as the global `matchMedia` mock and the result tests override that mock with
9
+ * it to toggle the reduced-motion preference.
10
+ */
11
+ export function matchMediaStub(query: string, matches = false) {
12
+ return {
13
+ matches,
14
+ media: query,
15
+ onchange: null,
16
+ addListener: vi.fn(),
17
+ removeListener: vi.fn(),
18
+ addEventListener: vi.fn(),
19
+ removeEventListener: vi.fn(),
20
+ dispatchEvent: vi.fn(),
21
+ } as MediaQueryList;
22
+ }
client/modules/accessKey.test.ts CHANGED
@@ -36,6 +36,13 @@ vi.mock("@mantine/notifications", () => ({
36
 
37
  const TIMEOUT_HOURS = 24;
38
 
 
 
 
 
 
 
 
39
  describe("Access Key Module", () => {
40
  beforeEach(() => {
41
  vi.clearAllMocks();
@@ -196,9 +203,7 @@ describe("Access Key Module", () => {
196
  );
197
 
198
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
199
- expect(result).toBe(false);
200
- expect(localStorage.getItem("accessKeyHash")).toBeNull();
201
- expect(mockFetch).not.toHaveBeenCalled();
202
  });
203
 
204
  it("deletes a stored value that is not JSON without asking the server", async () => {
@@ -207,9 +212,7 @@ describe("Access Key Module", () => {
207
 
208
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
209
 
210
- expect(result).toBe(false);
211
- expect(localStorage.getItem("accessKeyHash")).toBeNull();
212
- expect(mockFetch).not.toHaveBeenCalled();
213
  });
214
 
215
  it("keeps the stored hash on a 429 instead of deleting it", async () => {
 
36
 
37
  const TIMEOUT_HOURS = 24;
38
 
39
+ /** Checks that a stored key was dropped without a call to the server. */
40
+ function expectStoredKeyDiscarded(result: unknown) {
41
+ expect(result).toBe(false);
42
+ expect(localStorage.getItem("accessKeyHash")).toBeNull();
43
+ expect(mockFetch).not.toHaveBeenCalled();
44
+ }
45
+
46
  describe("Access Key Module", () => {
47
  beforeEach(() => {
48
  vi.clearAllMocks();
 
203
  );
204
 
205
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
206
+ expectStoredKeyDiscarded(result);
 
 
207
  });
208
 
209
  it("deletes a stored value that is not JSON without asking the server", async () => {
 
212
 
213
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
214
 
215
+ expectStoredKeyDiscarded(result);
 
 
216
  });
217
 
218
  it("keeps the stored hash on a 429 instead of deleting it", async () => {
client/modules/chatHelpers.test.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { beforeEach, describe, expect, it, vi } from "vitest";
2
 
3
  beforeEach(() => vi.clearAllMocks());
4
 
@@ -498,45 +498,77 @@ describe("follow-up supersession ownership", () => {
498
  mockGetCurrentSearchRunId.mockReturnValue("run-1");
499
  });
500
 
501
- it("drops a stale image refresh that resolves after a newer image refresh on the same run", async () => {
502
- let releaseFirst: (value: {
503
- results: ImageSearchResults;
504
- stale: boolean;
505
- }) => void = () => {};
506
  mockSearchImages.mockReturnValueOnce(
507
  new Promise((resolve) => {
508
- releaseFirst = resolve;
509
  }),
510
  );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
511
 
512
  const existingA: ImageSearchResults = [
513
  ["Initial", "https://initial.com", "thumb-0", "src-0"],
514
  ];
 
515
  const first = refreshImageSearchResults("first", 10, existingA);
516
  await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalledTimes(1));
517
 
518
- const existingB: ImageSearchResults = [
519
- ["B0", "https://b0.com", "thumb-b0", "src-b0"],
520
- ...existingA,
521
- ];
522
  mockSearchImages.mockResolvedValueOnce({
523
  results: [["B1", "https://b1.com", "thumb-b1", "src-b1"]],
524
  stale: false,
525
  });
526
- await refreshImageSearchResults("second", 10, existingB);
527
 
528
- releaseFirst({
529
- results: [["Late A", "https://a.com", "thumb-a", "src-a"]],
530
- stale: false,
531
- });
532
  await first;
533
 
534
- expect(mockUpdateImage).toHaveBeenCalledTimes(1);
535
- expect(mockUpdateImage).toHaveBeenCalledWith([
536
  ["B1", "https://b1.com", "thumb-b1", "src-b1"],
537
- ...existingB,
538
- ]);
539
- expect(mergeSearchImageResults).toHaveBeenCalledTimes(1);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
540
  });
541
 
542
  it("drops a stale text refresh that resolves after a newer text refresh on the same run", async () => {
@@ -573,15 +605,7 @@ describe("follow-up supersession ownership", () => {
573
  });
574
 
575
  it("adds a late image refresh to its own run's stored images after leaving the search", async () => {
576
- let releaseImages: (value: {
577
- results: ImageSearchResults;
578
- stale: boolean;
579
- }) => void = () => {};
580
- mockSearchImages.mockReturnValueOnce(
581
- new Promise((resolve) => {
582
- releaseImages = resolve;
583
- }),
584
- );
585
  const handed: ImageSearchResults = [
586
  ["Shown", "https://shown.com", "thumb-s", "src-s"],
587
  ];
@@ -590,10 +614,7 @@ describe("follow-up supersession ownership", () => {
590
 
591
  // The user restored or started another search meanwhile.
592
  mockGetCurrentSearchRunId.mockReturnValue("run-2");
593
- releaseImages({
594
- results: [["Fresh", "https://fresh.com", "thumb-f", "src-f"]],
595
- stale: false,
596
- });
597
  await refresh;
598
 
599
  expect(mockUpdateImage).not.toHaveBeenCalled();
 
1
+ import { beforeEach, describe, expect, it, onTestFinished, vi } from "vitest";
2
 
3
  beforeEach(() => vi.clearAllMocks());
4
 
 
498
  mockGetCurrentSearchRunId.mockReturnValue("run-1");
499
  });
500
 
501
+ /** Holds the next image search until the returned function releases it. */
502
+ function holdNextImageSearch() {
503
+ let release: (results: ImageSearchResults) => void = () => {};
 
 
504
  mockSearchImages.mockReturnValueOnce(
505
  new Promise((resolve) => {
506
+ release = (results) => resolve({ results, stale: false });
507
  }),
508
  );
509
+ return (results: ImageSearchResults) => release(results);
510
+ }
511
+
512
+ it("keeps both follow-ups' images when their refreshes land in reverse order", async () => {
513
+ let shown: ImageSearchResults = [];
514
+ vi.mocked(getImageSearchResults).mockImplementation(() => shown);
515
+ mockUpdateImage.mockImplementation((results) => {
516
+ shown = results;
517
+ });
518
+ onTestFinished(() => {
519
+ vi.mocked(getImageSearchResults).mockImplementation(() => []);
520
+ mockUpdateImage.mockImplementation(() => {});
521
+ });
522
+
523
+ const releaseFirst = holdNextImageSearch();
524
 
525
  const existingA: ImageSearchResults = [
526
  ["Initial", "https://initial.com", "thumb-0", "src-0"],
527
  ];
528
+ shown = existingA;
529
  const first = refreshImageSearchResults("first", 10, existingA);
530
  await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalledTimes(1));
531
 
532
+ // The second follow-up is sent before the first one's images land, so
533
+ // the list it is handed does not have them.
 
 
534
  mockSearchImages.mockResolvedValueOnce({
535
  results: [["B1", "https://b1.com", "thumb-b1", "src-b1"]],
536
  stale: false,
537
  });
538
+ await refreshImageSearchResults("second", 10, existingA);
539
 
540
+ releaseFirst([["Late A", "https://a.com", "thumb-a", "src-a"]]);
 
 
 
541
  await first;
542
 
543
+ const both: ImageSearchResults = [
544
+ ["Late A", "https://a.com", "thumb-a", "src-a"],
545
  ["B1", "https://b1.com", "thumb-b1", "src-b1"],
546
+ ...existingA,
547
+ ];
548
+ expect(mockUpdateImage).toHaveBeenLastCalledWith(both);
549
+ expect(mergeSearchImageResults).toHaveBeenCalledTimes(2);
550
+ expect(mergeSearchImageResults).toHaveBeenLastCalledWith("run-1", {
551
+ type: "image",
552
+ items: both.map(([title, url, thumbnail, sourceUrl]) => ({
553
+ title,
554
+ url,
555
+ thumbnail,
556
+ sourceUrl,
557
+ })),
558
+ });
559
+ });
560
+
561
+ it("drops an image refresh that lands after a retry on the same run", async () => {
562
+ const releaseImages = holdNextImageSearch();
563
+ const refresh = refreshImageSearchResults("query", 10, [], "run-1");
564
+ await vi.waitFor(() => expect(mockSearchImages).toHaveBeenCalledTimes(1));
565
+
566
+ recordSearchAttempt("run-1", (getLatestSearchAttempt("run-1") ?? 0) + 1);
567
+ releaseImages([["Old", "https://old.com", "thumb-o", "src-o"]]);
568
+ await refresh;
569
+
570
+ expect(mockUpdateImage).not.toHaveBeenCalled();
571
+ expect(mergeSearchImageResults).not.toHaveBeenCalled();
572
  });
573
 
574
  it("drops a stale text refresh that resolves after a newer text refresh on the same run", async () => {
 
605
  });
606
 
607
  it("adds a late image refresh to its own run's stored images after leaving the search", async () => {
608
+ const releaseImages = holdNextImageSearch();
 
 
 
 
 
 
 
 
609
  const handed: ImageSearchResults = [
610
  ["Shown", "https://shown.com", "thumb-s", "src-s"],
611
  ];
 
614
 
615
  // The user restored or started another search meanwhile.
616
  mockGetCurrentSearchRunId.mockReturnValue("run-2");
617
+ releaseImages([["Fresh", "https://fresh.com", "thumb-f", "src-f"]]);
 
 
 
618
  await refresh;
619
 
620
  expect(mockUpdateImage).not.toHaveBeenCalled();
client/modules/chatHelpers.ts CHANGED
@@ -43,10 +43,8 @@ function sameSearchAttempt(searchRunId: string): () => boolean {
43
  return () => getLatestSearchAttempt(searchRunId) === attempt;
44
  }
45
  let textRefreshInvocation = 0;
46
- let imageRefreshInvocation = 0;
47
  let pageContentsReadInvocation = 0;
48
  const latestTextRefreshByRunId = new Map<string, number>();
49
- const latestImageRefreshByRunId = new Map<string, number>();
50
 
51
  /**
52
  * Returns the fresh results the answer is grounded on (empty when nothing came
@@ -121,16 +119,12 @@ export async function refreshImageSearchResults(
121
  existingResults: ImageSearchResults,
122
  searchRunId = getCurrentSearchRunId(),
123
  ): Promise<void> {
124
- const invocation = ++imageRefreshInvocation;
125
- latestImageRefreshByRunId.set(searchRunId, invocation);
 
126
  const isSameAttempt = sameSearchAttempt(searchRunId);
127
  const isCurrent = () =>
128
- invocation === imageRefreshInvocation &&
129
- searchRunId === getCurrentSearchRunId() &&
130
- isSameAttempt();
131
- const isRunCurrent = () =>
132
- latestImageRefreshByRunId.get(searchRunId) === invocation &&
133
- isSameAttempt();
134
 
135
  const { results: imageResults } = await searchImages(
136
  searchQuery,
@@ -162,7 +156,7 @@ export async function refreshImageSearchResults(
162
  updateImageSearchResults(updatedImageResults);
163
  }
164
 
165
- if (isRunCurrent()) {
166
  mergeSearchImageResults(searchRunId, {
167
  type: "image",
168
  items: updatedImageResults.map(
 
43
  return () => getLatestSearchAttempt(searchRunId) === attempt;
44
  }
45
  let textRefreshInvocation = 0;
 
46
  let pageContentsReadInvocation = 0;
47
  const latestTextRefreshByRunId = new Map<string, number>();
 
48
 
49
  /**
50
  * Returns the fresh results the answer is grounded on (empty when nothing came
 
119
  existingResults: ImageSearchResults,
120
  searchRunId = getCurrentSearchRunId(),
121
  ): Promise<void> {
122
+ // No newest-refresh check, unlike text: image refreshes merge into the list
123
+ // on screen and into history, so an older one landing after a newer one
124
+ // adds its images instead of overwriting the newer ones.
125
  const isSameAttempt = sameSearchAttempt(searchRunId);
126
  const isCurrent = () =>
127
+ searchRunId === getCurrentSearchRunId() && isSameAttempt();
 
 
 
 
 
128
 
129
  const { results: imageResults } = await searchImages(
130
  searchQuery,
 
156
  updateImageSearchResults(updatedImageResults);
157
  }
158
 
159
+ if (isSameAttempt()) {
160
  mergeSearchImageResults(searchRunId, {
161
  type: "image",
162
  items: updatedImageResults.map(
client/modules/history.test.ts CHANGED
@@ -19,6 +19,34 @@ const createTestEntry = (overrides: Record<string, unknown> = {}) => ({
19
  ...overrides,
20
  });
21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  describe("History Module - Search Run ID Management", () => {
23
  beforeEach(async () => {
24
  vi.resetModules();
@@ -188,10 +216,7 @@ describe("History Module - Dexie CRUD", () => {
188
  describe("addSearchToHistory", () => {
189
  it("should add a text search entry and return an ID", async () => {
190
  const { addSearchToHistory } = await import("./history");
191
- const results = {
192
- type: "text" as const,
193
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
194
- };
195
  const id = await addSearchToHistory("test query", results);
196
  expect(id).toBeDefined();
197
  expect(typeof id).toBe("number");
@@ -226,10 +251,7 @@ describe("History Module - Dexie CRUD", () => {
226
  const { addSearchToHistory, getRecentSearches } = await import(
227
  "./history"
228
  );
229
- const results = {
230
- type: "text" as const,
231
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
232
- };
233
 
234
  // Insert "second" with the earlier timestamp so it proves sorting by timestamp, not ID.
235
  vi.setSystemTime(new Date(2000, 0, 2));
@@ -247,10 +269,7 @@ describe("History Module - Dexie CRUD", () => {
247
  const { addSearchToHistory, getRecentSearches } = await import(
248
  "./history"
249
  );
250
- const results = {
251
- type: "text" as const,
252
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
253
- };
254
 
255
  for (let i = 0; i < 5; i++) {
256
  await addSearchToHistory(`query ${i}`, results);
@@ -264,10 +283,7 @@ describe("History Module - Dexie CRUD", () => {
264
  const { addSearchToHistory, getRecentSearches } = await import(
265
  "./history"
266
  );
267
- const results = {
268
- type: "text" as const,
269
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
270
- };
271
 
272
  for (let i = 0; i < 12; i++) {
273
  await addSearchToHistory(`query ${i}`, results);
@@ -282,10 +298,7 @@ describe("History Module - Dexie CRUD", () => {
282
  it("returns only pinned entries, newest first, however old", async () => {
283
  const { addSearchToHistory, getPinnedSearches, historyDatabase } =
284
  await import("./history");
285
- const results = {
286
- type: "text" as const,
287
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
288
- };
289
 
290
  vi.setSystemTime(new Date(2000, 0, 1));
291
  const oldest = await addSearchToHistory("pinned long ago", results);
@@ -313,10 +326,7 @@ describe("History Module - Dexie CRUD", () => {
313
  const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =
314
  await import("./history");
315
  const runId = getCurrentSearchRunId();
316
- const results = {
317
- type: "text" as const,
318
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
319
- };
320
 
321
  await addSearchToHistory("round trip query", results, "user");
322
  const [entry] = await getRecentSearches();
@@ -329,10 +339,7 @@ describe("History Module - Dexie CRUD", () => {
329
  const { addSearchToHistory, getRecentSearches } = await import(
330
  "./history"
331
  );
332
- const results = {
333
- type: "text" as const,
334
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
335
- };
336
 
337
  await addSearchToHistory("fields test", results);
338
  const [entry] = await getRecentSearches();
@@ -375,6 +382,14 @@ describe("History Module - Dexie CRUD", () => {
375
  });
376
 
377
  describe("mergeSearchImageResults", () => {
 
 
 
 
 
 
 
 
378
  const image = (title: string, url: string) => ({
379
  title,
380
  url,
@@ -436,10 +451,7 @@ describe("History Module - Dexie CRUD", () => {
436
  type: "image",
437
  items: [image("Fresh", "https://fresh.com")],
438
  });
439
- expect(await storedItems()).toEqual([
440
- image("Fresh", "https://fresh.com"),
441
- image("First", "https://first.com"),
442
- ]);
443
 
444
  // The reverse order: a follow-up stored first, the first search lands
445
  // after it. Its images go after the follow-up's, as on screen.
@@ -453,10 +465,7 @@ describe("History Module - Dexie CRUD", () => {
453
  { type: "image", items: [image("First", "https://first.com")] },
454
  { newFirst: false },
455
  );
456
- expect(await storedItems()).toEqual([
457
- image("Fresh", "https://fresh.com"),
458
- image("First", "https://first.com"),
459
- ]);
460
 
461
  // A retry on the run clears the list before its own images arrive.
462
  await updateSearchResults(runId, { type: "image", items: [] });
@@ -493,10 +502,7 @@ describe("History Module - Dexie CRUD", () => {
493
  saveLlmResponseForQuery,
494
  getLatestLlmResponseForEntry,
495
  } = await import("./history");
496
- const results = {
497
- type: "text" as const,
498
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
499
- };
500
 
501
  await addSearchToHistory("llm test", results);
502
  await saveLlmResponseForQuery("llm test", "AI answer", "model-x");
@@ -509,10 +515,7 @@ describe("History Module - Dexie CRUD", () => {
509
  it("should store searchId back-link from llmResponses to the search row", async () => {
510
  const { addSearchToHistory, historyDatabase, saveLlmResponseForQuery } =
511
  await import("./history");
512
- const results = {
513
- type: "text" as const,
514
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
515
- };
516
 
517
  const id = await addSearchToHistory("llm link test", results);
518
  await saveLlmResponseForQuery("llm link test", "answer", "m");
@@ -529,10 +532,7 @@ describe("History Module - Dexie CRUD", () => {
529
  saveLlmResponseForQuery,
530
  getLatestLlmResponseForEntry,
531
  } = await import("./history");
532
- const results = {
533
- type: "text" as const,
534
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
535
- };
536
 
537
  await addSearchToHistory("multi llm", results);
538
  vi.setSystemTime(new Date(2000, 0, 2));
@@ -635,20 +635,10 @@ describe("History Module - Dexie CRUD", () => {
635
 
636
  describe("cleanup after add", () => {
637
  it("should not throw TransactionInactiveError when auto-cleanup is enabled", async () => {
638
- const { getSettings } = await import("./pubSub");
639
- const { defaultSettings } = await import("./settings");
640
- vi.mocked(getSettings).mockReturnValue({
641
- ...defaultSettings,
642
- historyAutoCleanup: true,
643
- historyRetentionDays: 0,
644
- historyMaxEntries: 5,
645
- });
646
 
647
  const { addSearchToHistory, historyDatabase } = await import("./history");
648
- const results = {
649
- type: "text" as const,
650
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
651
- };
652
 
653
  // Cleanup must run after the add transaction completes: inside it, the
654
  // async import causes a TransactionInactiveError.
@@ -693,10 +683,7 @@ describe("History Module - Dexie CRUD", () => {
693
  vi.spyOn(historyDatabase.searches, "add").mockRejectedValue(
694
  new Error("boom"),
695
  );
696
- const results = {
697
- type: "text" as const,
698
- items: [{ title: "T", url: "https://t.com", snippet: "S" }],
699
- };
700
  const id = await addSearchToHistory("q", results);
701
  expect(id).toBeUndefined();
702
  });
@@ -774,9 +761,7 @@ describe("History Module - Dexie CRUD", () => {
774
 
775
  await clearAllHistory();
776
 
777
- expect(await historyDatabase.searches.count()).toBe(0);
778
- expect(await historyDatabase.llmResponses.count()).toBe(0);
779
- expect(await historyDatabase.chatHistory.count()).toBe(0);
780
  });
781
  });
782
  });
 
19
  ...overrides,
20
  });
21
 
22
+ /** A one-item text result set, the shape most of these tests store. */
23
+ function oneTextResult() {
24
+ return {
25
+ type: "text" as const,
26
+ items: [{ title: "T", url: "https://t.com", snippet: "S" }],
27
+ };
28
+ }
29
+ /** Turns auto-cleanup on with a five-entry window and no retention. */
30
+ async function enableAutoCleanup() {
31
+ const { getSettings } = await import("./pubSub");
32
+ const { defaultSettings } = await import("./settings");
33
+ vi.mocked(getSettings).mockReturnValue({
34
+ ...defaultSettings,
35
+ historyAutoCleanup: true,
36
+ historyRetentionDays: 0,
37
+ historyMaxEntries: 5,
38
+ });
39
+ }
40
+
41
+ /** Checks that every history store came back empty. */
42
+ async function expectStoresEmpty(
43
+ db: typeof import("./history")["historyDatabase"],
44
+ ) {
45
+ expect(await db.searches.count()).toBe(0);
46
+ expect(await db.llmResponses.count()).toBe(0);
47
+ expect(await db.chatHistory.count()).toBe(0);
48
+ }
49
+
50
  describe("History Module - Search Run ID Management", () => {
51
  beforeEach(async () => {
52
  vi.resetModules();
 
216
  describe("addSearchToHistory", () => {
217
  it("should add a text search entry and return an ID", async () => {
218
  const { addSearchToHistory } = await import("./history");
219
+ const results = oneTextResult();
 
 
 
220
  const id = await addSearchToHistory("test query", results);
221
  expect(id).toBeDefined();
222
  expect(typeof id).toBe("number");
 
251
  const { addSearchToHistory, getRecentSearches } = await import(
252
  "./history"
253
  );
254
+ const results = oneTextResult();
 
 
 
255
 
256
  // Insert "second" with the earlier timestamp so it proves sorting by timestamp, not ID.
257
  vi.setSystemTime(new Date(2000, 0, 2));
 
269
  const { addSearchToHistory, getRecentSearches } = await import(
270
  "./history"
271
  );
272
+ const results = oneTextResult();
 
 
 
273
 
274
  for (let i = 0; i < 5; i++) {
275
  await addSearchToHistory(`query ${i}`, results);
 
283
  const { addSearchToHistory, getRecentSearches } = await import(
284
  "./history"
285
  );
286
+ const results = oneTextResult();
 
 
 
287
 
288
  for (let i = 0; i < 12; i++) {
289
  await addSearchToHistory(`query ${i}`, results);
 
298
  it("returns only pinned entries, newest first, however old", async () => {
299
  const { addSearchToHistory, getPinnedSearches, historyDatabase } =
300
  await import("./history");
301
+ const results = oneTextResult();
 
 
 
302
 
303
  vi.setSystemTime(new Date(2000, 0, 1));
304
  const oldest = await addSearchToHistory("pinned long ago", results);
 
326
  const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =
327
  await import("./history");
328
  const runId = getCurrentSearchRunId();
329
+ const results = oneTextResult();
 
 
 
330
 
331
  await addSearchToHistory("round trip query", results, "user");
332
  const [entry] = await getRecentSearches();
 
339
  const { addSearchToHistory, getRecentSearches } = await import(
340
  "./history"
341
  );
342
+ const results = oneTextResult();
 
 
 
343
 
344
  await addSearchToHistory("fields test", results);
345
  const [entry] = await getRecentSearches();
 
382
  });
383
 
384
  describe("mergeSearchImageResults", () => {
385
+ /** The two image results these tests merge, in the order the screen shows. */
386
+ function freshAndFirstImages() {
387
+ return [
388
+ image("Fresh", "https://fresh.com"),
389
+ image("First", "https://first.com"),
390
+ ];
391
+ }
392
+
393
  const image = (title: string, url: string) => ({
394
  title,
395
  url,
 
451
  type: "image",
452
  items: [image("Fresh", "https://fresh.com")],
453
  });
454
+ expect(await storedItems()).toEqual(freshAndFirstImages());
 
 
 
455
 
456
  // The reverse order: a follow-up stored first, the first search lands
457
  // after it. Its images go after the follow-up's, as on screen.
 
465
  { type: "image", items: [image("First", "https://first.com")] },
466
  { newFirst: false },
467
  );
468
+ expect(await storedItems()).toEqual(freshAndFirstImages());
 
 
 
469
 
470
  // A retry on the run clears the list before its own images arrive.
471
  await updateSearchResults(runId, { type: "image", items: [] });
 
502
  saveLlmResponseForQuery,
503
  getLatestLlmResponseForEntry,
504
  } = await import("./history");
505
+ const results = oneTextResult();
 
 
 
506
 
507
  await addSearchToHistory("llm test", results);
508
  await saveLlmResponseForQuery("llm test", "AI answer", "model-x");
 
515
  it("should store searchId back-link from llmResponses to the search row", async () => {
516
  const { addSearchToHistory, historyDatabase, saveLlmResponseForQuery } =
517
  await import("./history");
518
+ const results = oneTextResult();
 
 
 
519
 
520
  const id = await addSearchToHistory("llm link test", results);
521
  await saveLlmResponseForQuery("llm link test", "answer", "m");
 
532
  saveLlmResponseForQuery,
533
  getLatestLlmResponseForEntry,
534
  } = await import("./history");
535
+ const results = oneTextResult();
 
 
 
536
 
537
  await addSearchToHistory("multi llm", results);
538
  vi.setSystemTime(new Date(2000, 0, 2));
 
635
 
636
  describe("cleanup after add", () => {
637
  it("should not throw TransactionInactiveError when auto-cleanup is enabled", async () => {
638
+ await enableAutoCleanup();
 
 
 
 
 
 
 
639
 
640
  const { addSearchToHistory, historyDatabase } = await import("./history");
641
+ const results = oneTextResult();
 
 
 
642
 
643
  // Cleanup must run after the add transaction completes: inside it, the
644
  // async import causes a TransactionInactiveError.
 
683
  vi.spyOn(historyDatabase.searches, "add").mockRejectedValue(
684
  new Error("boom"),
685
  );
686
+ const results = oneTextResult();
 
 
 
687
  const id = await addSearchToHistory("q", results);
688
  expect(id).toBeUndefined();
689
  });
 
761
 
762
  await clearAllHistory();
763
 
764
+ await expectStoresEmpty(historyDatabase);
 
 
765
  });
766
  });
767
  });
client/modules/pubSub.test.ts CHANGED
@@ -23,6 +23,22 @@ beforeEach(() => {
23
  vi.resetModules();
24
  });
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  describe("PubSub localStorage persistence", () => {
27
  it("updates query suggestions and persists to localStorage", async () => {
28
  const { updateQuerySuggestions, getQuerySuggestions } = await import(
@@ -54,32 +70,30 @@ describe("PubSub localStorage persistence", () => {
54
  it("falls back to the default and drops the value when the stored JSON is corrupted", async () => {
55
  localStorage.setItem("menuExpandedAccordions", "{not valid json");
56
  const { menuExpandedAccordionsPubSub } = await import("./pubSub");
57
- const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub;
58
- expect(getMenuExpandedAccordions()).toEqual([]);
59
- expect(localStorage.getItem("menuExpandedAccordions")).toBeNull();
60
- expect(addLogEntry).toHaveBeenCalledWith(
61
- "Discarded an unusable stored value for 'menuExpandedAccordions'",
62
  );
63
  });
64
 
65
  it("falls back to the default and drops the value when the stored JSON has the wrong type", async () => {
66
  localStorage.setItem("lastSearchTokenHash", "123");
67
  const { getLastSearchTokenHash } = await import("./pubSub");
68
- expect(getLastSearchTokenHash()).toBe("");
69
- expect(localStorage.getItem("lastSearchTokenHash")).toBeNull();
70
- expect(addLogEntry).toHaveBeenCalledWith(
71
- "Discarded an unusable stored value for 'lastSearchTokenHash'",
72
  );
73
  });
74
 
75
  it("falls back to the default and drops the value when the stored value is empty", async () => {
76
  localStorage.setItem("menuExpandedAccordions", "");
77
  const { menuExpandedAccordionsPubSub } = await import("./pubSub");
78
- const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub;
79
- expect(getMenuExpandedAccordions()).toEqual([]);
80
- expect(localStorage.getItem("menuExpandedAccordions")).toBeNull();
81
- expect(addLogEntry).toHaveBeenCalledWith(
82
- "Discarded an unusable stored value for 'menuExpandedAccordions'",
83
  );
84
  });
85
  });
 
23
  vi.resetModules();
24
  });
25
 
26
+ /**
27
+ * Checks that a stored value the module cannot use fell back to its default,
28
+ * was dropped from storage, and was logged.
29
+ */
30
+ function expectUnusableStoredValue(
31
+ key: string,
32
+ read: () => unknown,
33
+ fallback: unknown,
34
+ ) {
35
+ expect(read()).toEqual(fallback);
36
+ expect(localStorage.getItem(key)).toBeNull();
37
+ expect(addLogEntry).toHaveBeenCalledWith(
38
+ `Discarded an unusable stored value for '${key}'`,
39
+ );
40
+ }
41
+
42
  describe("PubSub localStorage persistence", () => {
43
  it("updates query suggestions and persists to localStorage", async () => {
44
  const { updateQuerySuggestions, getQuerySuggestions } = await import(
 
70
  it("falls back to the default and drops the value when the stored JSON is corrupted", async () => {
71
  localStorage.setItem("menuExpandedAccordions", "{not valid json");
72
  const { menuExpandedAccordionsPubSub } = await import("./pubSub");
73
+ expectUnusableStoredValue(
74
+ "menuExpandedAccordions",
75
+ () => menuExpandedAccordionsPubSub[2](),
76
+ [],
 
77
  );
78
  });
79
 
80
  it("falls back to the default and drops the value when the stored JSON has the wrong type", async () => {
81
  localStorage.setItem("lastSearchTokenHash", "123");
82
  const { getLastSearchTokenHash } = await import("./pubSub");
83
+ expectUnusableStoredValue(
84
+ "lastSearchTokenHash",
85
+ () => getLastSearchTokenHash(),
86
+ "",
87
  );
88
  });
89
 
90
  it("falls back to the default and drops the value when the stored value is empty", async () => {
91
  localStorage.setItem("menuExpandedAccordions", "");
92
  const { menuExpandedAccordionsPubSub } = await import("./pubSub");
93
+ expectUnusableStoredValue(
94
+ "menuExpandedAccordions",
95
+ () => menuExpandedAccordionsPubSub[2](),
96
+ [],
 
97
  );
98
  });
99
  });
client/modules/pubSub.throttle.test.ts CHANGED
@@ -9,6 +9,21 @@ async function loadResponseChannel() {
9
  return await import("./pubSub");
10
  }
11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  describe("response publishing", () => {
13
  beforeEach(() => {
14
  vi.useFakeTimers();
@@ -20,11 +35,7 @@ describe("response publishing", () => {
20
 
21
  it("publishes one leading and one trailing value per throttle window", async () => {
22
  const { responsePubSub, updateResponse } = await loadResponseChannel();
23
- const published: string[] = [];
24
- const [, onResponseChange] = responsePubSub;
25
- const unsubscribe = onResponseChange((value) => {
26
- published.push(value);
27
- });
28
 
29
  updateResponse("Hello");
30
  updateResponse("Hello world");
@@ -46,11 +57,7 @@ describe("response publishing", () => {
46
  updateResponse,
47
  updateResponseImmediately,
48
  } = await loadResponseChannel();
49
- const published: string[] = [];
50
- const [, onResponseChange] = responsePubSub;
51
- const unsubscribe = onResponseChange((value) => {
52
- published.push(value);
53
- });
54
 
55
  updateResponse("Hello");
56
  updateResponse("Hello world, but truncated");
 
9
  return await import("./pubSub");
10
  }
11
 
12
+ /** Subscribes to the response channel and records each published value. */
13
+ function collectPublished(
14
+ responsePubSub: [
15
+ unknown,
16
+ (listener: (value: string) => void) => () => void,
17
+ unknown,
18
+ ],
19
+ ) {
20
+ const published: string[] = [];
21
+ const unsubscribe = responsePubSub[1]((value) => {
22
+ published.push(value);
23
+ });
24
+ return { published, unsubscribe };
25
+ }
26
+
27
  describe("response publishing", () => {
28
  beforeEach(() => {
29
  vi.useFakeTimers();
 
35
 
36
  it("publishes one leading and one trailing value per throttle window", async () => {
37
  const { responsePubSub, updateResponse } = await loadResponseChannel();
38
+ const { published, unsubscribe } = collectPublished(responsePubSub);
 
 
 
 
39
 
40
  updateResponse("Hello");
41
  updateResponse("Hello world");
 
57
  updateResponse,
58
  updateResponseImmediately,
59
  } = await loadResponseChannel();
60
+ const { published, unsubscribe } = collectPublished(responsePubSub);
 
 
 
 
61
 
62
  updateResponse("Hello");
63
  updateResponse("Hello world, but truncated");
client/modules/search.test.ts CHANGED
@@ -17,6 +17,14 @@ vi.mock("./searchTokenHash", () => ({
17
  }));
18
 
19
  const mockFetch = vi.fn();
 
 
 
 
 
 
 
 
20
  vi.stubGlobal("fetch", mockFetch);
21
  vi.stubGlobal("self", {
22
  location: new URL("http://localhost:3000"),
@@ -445,10 +453,7 @@ describe("Search Module", () => {
445
  const mockResults: string[][] = [
446
  ["Title", "Snippet", "https://example.com"],
447
  ];
448
- mockFetch.mockResolvedValue({
449
- ok: true,
450
- json: vi.fn().mockResolvedValue(mockResults),
451
- });
452
 
453
  const firstResults = await searchModule.searchText("cached query");
454
  expect(firstResults).toEqual({ results: mockResults, stale: false });
@@ -469,10 +474,7 @@ describe("Search Module", () => {
469
  const mockResults: string[][] = [
470
  ["Image", "Alt", "https://example.com/img.jpg"],
471
  ];
472
- mockFetch.mockResolvedValue({
473
- ok: true,
474
- json: vi.fn().mockResolvedValue(mockResults),
475
- });
476
 
477
  const firstResults = await searchModule.searchImages("cached images");
478
  expect(firstResults).toEqual({ results: mockResults, stale: false });
@@ -495,10 +497,7 @@ describe("Search Module", () => {
495
  const mockResults: string[][] = [
496
  ["Title", "Snippet", "https://example.com"],
497
  ];
498
- mockFetch.mockResolvedValue({
499
- ok: true,
500
- json: vi.fn().mockResolvedValue(mockResults),
501
- });
502
 
503
  await searchModule.searchText("query A");
504
  await searchModule.searchText("query B");
@@ -509,10 +508,7 @@ describe("Search Module", () => {
509
  const mockResults: string[][] = [
510
  ["Title", "Snippet", "https://example.com"],
511
  ];
512
- mockFetch.mockResolvedValue({
513
- ok: true,
514
- json: vi.fn().mockResolvedValue(mockResults),
515
- });
516
 
517
  await searchModule.searchText("same query", 5);
518
  await searchModule.searchText("same query", 10);
@@ -523,10 +519,7 @@ describe("Search Module", () => {
523
  const mockResults: string[][] = [
524
  ["Title", "Snippet", "https://example.com"],
525
  ];
526
- mockFetch.mockResolvedValue({
527
- ok: true,
528
- json: vi.fn().mockResolvedValue(mockResults),
529
- });
530
 
531
  await searchModule.searchText("ttl query");
532
  expect(mockFetch).toHaveBeenCalledTimes(1);
@@ -542,10 +535,7 @@ describe("Search Module", () => {
542
  const mockResults: string[][] = [
543
  ["Title", "Snippet", "https://example.com"],
544
  ];
545
- mockFetch.mockResolvedValue({
546
- ok: true,
547
- json: vi.fn().mockResolvedValue(mockResults),
548
- });
549
 
550
  searchModule.searchServiceInstance.updateCacheConfig({ enabled: false });
551
 
@@ -558,10 +548,7 @@ describe("Search Module", () => {
558
  const mockResults: string[][] = [
559
  ["Title", "Snippet", "https://example.com"],
560
  ];
561
- mockFetch.mockResolvedValue({
562
- ok: true,
563
- json: vi.fn().mockResolvedValue(mockResults),
564
- });
565
 
566
  await searchModule.searchText("cross-store query");
567
  expect(mockFetch).toHaveBeenCalledTimes(1);
@@ -579,10 +566,7 @@ describe("Search Module", () => {
579
  const mockResults: string[][] = [
580
  ["Title", "Snippet", "https://example.com"],
581
  ];
582
- mockFetch.mockResolvedValue({
583
- ok: true,
584
- json: vi.fn().mockResolvedValue(mockResults),
585
- });
586
 
587
  const first = await searchModule.searchText("stale query");
588
  expect(first).toEqual({ results: mockResults, stale: false });
@@ -613,10 +597,7 @@ describe("Search Module", () => {
613
  const mockResults: string[][] = [
614
  ["Title", "Snippet", "https://example.com"],
615
  ];
616
- mockFetch.mockResolvedValue({
617
- ok: true,
618
- json: vi.fn().mockResolvedValue(mockResults),
619
- });
620
 
621
  try {
622
  // Cache an entry, then move past the 24-hour stale retention.
 
17
  }));
18
 
19
  const mockFetch = vi.fn();
20
+
21
+ /** Answers every following `/search` fetch with `results`. */
22
+ function mockSearchResponse(results: string[][]) {
23
+ mockFetch.mockResolvedValue({
24
+ ok: true,
25
+ json: vi.fn().mockResolvedValue(results),
26
+ });
27
+ }
28
  vi.stubGlobal("fetch", mockFetch);
29
  vi.stubGlobal("self", {
30
  location: new URL("http://localhost:3000"),
 
453
  const mockResults: string[][] = [
454
  ["Title", "Snippet", "https://example.com"],
455
  ];
456
+ mockSearchResponse(mockResults);
 
 
 
457
 
458
  const firstResults = await searchModule.searchText("cached query");
459
  expect(firstResults).toEqual({ results: mockResults, stale: false });
 
474
  const mockResults: string[][] = [
475
  ["Image", "Alt", "https://example.com/img.jpg"],
476
  ];
477
+ mockSearchResponse(mockResults);
 
 
 
478
 
479
  const firstResults = await searchModule.searchImages("cached images");
480
  expect(firstResults).toEqual({ results: mockResults, stale: false });
 
497
  const mockResults: string[][] = [
498
  ["Title", "Snippet", "https://example.com"],
499
  ];
500
+ mockSearchResponse(mockResults);
 
 
 
501
 
502
  await searchModule.searchText("query A");
503
  await searchModule.searchText("query B");
 
508
  const mockResults: string[][] = [
509
  ["Title", "Snippet", "https://example.com"],
510
  ];
511
+ mockSearchResponse(mockResults);
 
 
 
512
 
513
  await searchModule.searchText("same query", 5);
514
  await searchModule.searchText("same query", 10);
 
519
  const mockResults: string[][] = [
520
  ["Title", "Snippet", "https://example.com"],
521
  ];
522
+ mockSearchResponse(mockResults);
 
 
 
523
 
524
  await searchModule.searchText("ttl query");
525
  expect(mockFetch).toHaveBeenCalledTimes(1);
 
535
  const mockResults: string[][] = [
536
  ["Title", "Snippet", "https://example.com"],
537
  ];
538
+ mockSearchResponse(mockResults);
 
 
 
539
 
540
  searchModule.searchServiceInstance.updateCacheConfig({ enabled: false });
541
 
 
548
  const mockResults: string[][] = [
549
  ["Title", "Snippet", "https://example.com"],
550
  ];
551
+ mockSearchResponse(mockResults);
 
 
 
552
 
553
  await searchModule.searchText("cross-store query");
554
  expect(mockFetch).toHaveBeenCalledTimes(1);
 
566
  const mockResults: string[][] = [
567
  ["Title", "Snippet", "https://example.com"],
568
  ];
569
+ mockSearchResponse(mockResults);
 
 
 
570
 
571
  const first = await searchModule.searchText("stale query");
572
  expect(first).toEqual({ results: mockResults, stale: false });
 
597
  const mockResults: string[][] = [
598
  ["Title", "Snippet", "https://example.com"],
599
  ];
600
+ mockSearchResponse(mockResults);
 
 
 
601
 
602
  try {
603
  // Cache an entry, then move past the 24-hour stale retention.
client/modules/speechToText.test.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
  getDictationEngine,
6
  MAX_RECORDING_SECONDS,
7
  resampleTo16k,
 
8
  startDictation,
9
  stripLanguageTag,
10
  } from "@/modules/speechToText";
@@ -234,6 +235,16 @@ describe("stripLanguageTag", () => {
234
  });
235
  });
236
 
 
 
 
 
 
 
 
 
 
 
237
  describe("startDictation with the wasm engine", () => {
238
  /** Minimal `SpeechRecognition` stand-in; reports whether it was started. */
239
  function installLocalRecognitionFake() {
@@ -525,11 +536,7 @@ describe("startDictation with the wasm engine", () => {
525
  });
526
 
527
  it("gives a second stop the same transcript instead of resolving early", async () => {
528
- const { stream } = makeMediaStream();
529
- stubWasmSupport(vi.fn().mockResolvedValue(stream));
530
- const onTranscript = vi.fn();
531
-
532
- const session = await startDictation({ onTranscript }, true);
533
  capture(4800);
534
  const first = session.stop();
535
  const second = session.stop();
@@ -541,11 +548,7 @@ describe("startDictation with the wasm engine", () => {
541
  });
542
 
543
  it("skips the transcription when nothing was recorded", async () => {
544
- const { stream } = makeMediaStream();
545
- stubWasmSupport(vi.fn().mockResolvedValue(stream));
546
- const onTranscript = vi.fn();
547
-
548
- const session = await startDictation({ onTranscript }, true);
549
  await session.stop();
550
 
551
  expect(wllama.createTranscription).not.toHaveBeenCalled();
@@ -610,22 +613,7 @@ describe("startDictation with the local model preference off", () => {
610
  });
611
 
612
  describe("startDictation with the web speech fallback", () => {
613
- interface RecognitionFake {
614
- continuous: boolean;
615
- interimResults: boolean;
616
- lang: string;
617
- onresult:
618
- | ((event: {
619
- resultIndex: number;
620
- results: ArrayLike<{ isFinal: boolean; 0: { transcript: string } }>;
621
- }) => void)
622
- | null;
623
- onerror: ((event: { error: string }) => void) | null;
624
- onend: (() => void) | null;
625
- start: () => void;
626
- stop: () => void;
627
- stopped: boolean;
628
- }
629
 
630
  let instance: RecognitionFake | undefined;
631
 
@@ -715,19 +703,21 @@ describe("startDictation with the web speech fallback", () => {
715
  await session.stop();
716
  });
717
 
718
- it("ends the session quietly when the recognizer stops on its own", async () => {
 
719
  installRecognitionFake();
720
  const onError = vi.fn();
721
  const onEnd = vi.fn();
722
 
723
  const session = await startDictation(
724
- {
725
- onTranscript: vi.fn(),
726
- onEnd,
727
- onError,
728
- },
729
  true,
730
  );
 
 
 
 
 
731
 
732
  // Chrome ends after silence even with `continuous`. The session is over,
733
  // but there is nothing the user needs told about.
@@ -739,18 +729,7 @@ describe("startDictation with the web speech fallback", () => {
739
  });
740
 
741
  it("says nothing when the recognizer ends because it was stopped", async () => {
742
- installRecognitionFake();
743
- const onError = vi.fn();
744
- const onEnd = vi.fn();
745
-
746
- const session = await startDictation(
747
- {
748
- onTranscript: vi.fn(),
749
- onEnd,
750
- onError,
751
- },
752
- true,
753
- );
754
 
755
  await session.stop();
756
  instance?.onend?.();
 
5
  getDictationEngine,
6
  MAX_RECORDING_SECONDS,
7
  resampleTo16k,
8
+ type SpeechRecognitionLike,
9
  startDictation,
10
  stripLanguageTag,
11
  } from "@/modules/speechToText";
 
235
  });
236
  });
237
 
238
+ /** Starts a wasm-engine session with a fresh transcript spy. */
239
+ async function startWasmSession() {
240
+ const { stream } = makeMediaStream();
241
+ stubWasmSupport(vi.fn().mockResolvedValue(stream));
242
+ const onTranscript = vi.fn();
243
+
244
+ const session = await startDictation({ onTranscript }, true);
245
+ return { session, onTranscript };
246
+ }
247
+
248
  describe("startDictation with the wasm engine", () => {
249
  /** Minimal `SpeechRecognition` stand-in; reports whether it was started. */
250
  function installLocalRecognitionFake() {
 
536
  });
537
 
538
  it("gives a second stop the same transcript instead of resolving early", async () => {
539
+ const { session, onTranscript } = await startWasmSession();
 
 
 
 
540
  capture(4800);
541
  const first = session.stop();
542
  const second = session.stop();
 
548
  });
549
 
550
  it("skips the transcription when nothing was recorded", async () => {
551
+ const { session, onTranscript } = await startWasmSession();
 
 
 
 
552
  await session.stop();
553
 
554
  expect(wllama.createTranscription).not.toHaveBeenCalled();
 
613
  });
614
 
615
  describe("startDictation with the web speech fallback", () => {
616
+ type RecognitionFake = SpeechRecognitionLike & { stopped: boolean };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617
 
618
  let instance: RecognitionFake | undefined;
619
 
 
703
  await session.stop();
704
  });
705
 
706
+ /** Starts a web-speech session with fresh `onEnd` and `onError` spies. */
707
+ async function startRecognitionSession() {
708
  installRecognitionFake();
709
  const onError = vi.fn();
710
  const onEnd = vi.fn();
711
 
712
  const session = await startDictation(
713
+ { onTranscript: vi.fn(), onEnd, onError },
 
 
 
 
714
  true,
715
  );
716
+ return { session, onEnd, onError };
717
+ }
718
+
719
+ it("ends the session quietly when the recognizer stops on its own", async () => {
720
+ const { session, onEnd, onError } = await startRecognitionSession();
721
 
722
  // Chrome ends after silence even with `continuous`. The session is over,
723
  // but there is nothing the user needs told about.
 
729
  });
730
 
731
  it("says nothing when the recognizer ends because it was stopped", async () => {
732
+ const { session, onEnd, onError } = await startRecognitionSession();
 
 
 
 
 
 
 
 
 
 
 
733
 
734
  await session.stop();
735
  instance?.onend?.();
client/modules/speechToText.ts CHANGED
@@ -51,7 +51,7 @@ export const MAX_RECORDING_SECONDS = 120;
51
  const DICTATION_CONTEXT_SIZE = 4096;
52
 
53
  /** The minimum the app needs from `window.SpeechRecognition`. */
54
- interface SpeechRecognitionLike {
55
  continuous: boolean;
56
  interimResults: boolean;
57
  lang: string;
 
51
  const DICTATION_CONTEXT_SIZE = 4096;
52
 
53
  /** The minimum the app needs from `window.SpeechRecognition`. */
54
+ export interface SpeechRecognitionLike {
55
  continuous: boolean;
56
  interimResults: boolean;
57
  lang: string;
client/modules/textGeneration.chatBudget.test.ts CHANGED
@@ -1,4 +1,11 @@
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
 
 
 
 
 
 
 
2
 
3
  const state = vi.hoisted(() => ({
4
  settings: { inferenceType: "browser" } as {
@@ -10,43 +17,22 @@ const state = vi.hoisted(() => ({
10
  systemPrompt: "",
11
  }));
12
 
13
- vi.mock("./pubSub", () => ({
14
- getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })),
15
- getQuery: vi.fn(() => ""),
16
- getResponse: vi.fn(() => ""),
17
- getSettings: vi.fn(() => state.settings),
18
- getTextGenerationState: vi.fn(() => "idle"),
19
- listenToSettingsChanges: vi.fn(() => vi.fn()),
20
- updateChatMessages: vi.fn(),
21
- updateConversationSummary: vi.fn(),
22
- updateImageSearchResults: vi.fn(),
23
- updateImageSearchState: vi.fn(),
24
- updateLlmTextSearchResults: vi.fn(),
25
- updateResponse: vi.fn(),
26
- updateResponseImmediately: vi.fn(),
27
- updateSearchPromise: vi.fn(),
28
- updateTextGenerationState: vi.fn(),
29
- updateTextSearchResults: vi.fn(),
30
- updateTextSearchState: vi.fn(),
31
- }));
32
- vi.mock("./history", () => ({
33
- replaceChatConversation: vi.fn(() => Promise.resolve()),
34
- getCurrentSearchRunId: vi.fn(() => "run-1"),
35
- saveLlmResponseForQuery: vi.fn(() => Promise.resolve()),
36
- updateSearchResults: vi.fn(() => Promise.resolve()),
37
- }));
38
- vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
39
- vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
40
- vi.mock("./search", () => ({
41
- searchImages: vi.fn(() => Promise.resolve([])),
42
- searchText: vi.fn(() => Promise.resolve([])),
43
- }));
44
  // The system prompt stands in for everything that fills it (instructions,
45
  // search results, page excerpts), so its length sets how much of the window
46
  // is left for the conversation.
47
  vi.mock("./systemPrompt", () => ({
48
  getSystemPrompt: vi.fn(() => state.systemPrompt),
49
  }));
 
50
  vi.mock("./textGenerationUtilities", async (importOriginal) => ({
51
  ...(await importOriginal<typeof import("./textGenerationUtilities")>()),
52
  getFormattedSearchResults: vi.fn(() => Promise.resolve("")),
@@ -89,6 +75,35 @@ function mockGenerateChat(generateChat: typeof generateChatWithWllama) {
89
  );
90
  }
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  function callsTo(generateChat: typeof generateChatWithWllama) {
93
  const calls = vi
94
  .mocked(generateChat)
@@ -225,19 +240,12 @@ describe("generateChatResponse context budget", () => {
225
  { role: "assistant", content: "d".repeat(400) },
226
  { role: "user", content: "q".repeat(300) },
227
  ];
228
- vi.mocked(generateChatWithWllama).mockImplementation(async (chat) =>
229
- chat[0].content.startsWith(summarizerInstruction)
230
- ? "z".repeat(summaryTokens)
231
- : "the answer",
232
- );
233
 
234
  await generateChatResponse(messages, () => {});
235
 
236
  const { answer, summarizer } = callsTo(generateChatWithWllama);
237
- const sentTokens = answer[0].reduce(
238
- (total, message) => total + message.content.length,
239
- 0,
240
- );
241
  expect(sentTokens).toBeLessThanOrEqual(3072);
242
  expect(answer[0].slice(2)).toEqual(messages.slice(4));
243
  for (const dropped of messages.slice(0, 4)) {
@@ -271,10 +279,7 @@ describe("generateChatResponse context budget", () => {
271
  await generateChatResponse(messages, () => {});
272
 
273
  const { answer } = callsTo(generateChatWithWllama);
274
- const sentTokens = answer[0].reduce(
275
- (total, message) => total + message.content.length,
276
- 0,
277
- );
278
  expect(sentTokens).toBeLessThanOrEqual(3072);
279
  expect(answer[0][0].content).toContain("z");
280
  expect(answer[0].slice(2)).toEqual(messages.slice(2));
@@ -288,14 +293,7 @@ describe("generateChatResponse context budget", () => {
288
 
289
  it("folds each dropped turn into the summary once across turns", async () => {
290
  // The summary slot persists between turns, as the pubsub store does.
291
- let slot: ReturnType<typeof getConversationSummary> = {
292
- conversationId: "",
293
- summary: "",
294
- };
295
- vi.mocked(getConversationSummary).mockImplementation(() => slot);
296
- vi.mocked(updateConversationSummary).mockImplementation((next) => {
297
- slot = next;
298
- });
299
  mockGenerateChat(generateChatWithWllama);
300
  state.systemPrompt = "s".repeat(2000);
301
  const firstExchange: ChatMessage[] = [
@@ -312,7 +310,7 @@ describe("generateChatResponse context budget", () => {
312
  [...firstExchange, { role: "user", content: "c".repeat(300) }],
313
  () => {},
314
  );
315
- expect(slot.summarizedCount).toBe(2);
316
 
317
  const turnTwo = [...firstExchange, ...secondExchange, question];
318
  await generateChatResponse(turnTwo, () => {});
@@ -326,18 +324,11 @@ describe("generateChatResponse context budget", () => {
326
  expect(summarizer[1][0].content).toContain("d".repeat(300));
327
  expect(summarizer[1][0].content).not.toContain("a".repeat(500));
328
  expect(summarizer[1][0].content).not.toContain("b".repeat(500));
329
- expect(slot.summarizedCount).toBe(4);
330
  });
331
 
332
  it("folds again from the start once an edit reaches into the summary", async () => {
333
- let slot: ReturnType<typeof getConversationSummary> = {
334
- conversationId: "",
335
- summary: "",
336
- };
337
- vi.mocked(getConversationSummary).mockImplementation(() => slot);
338
- vi.mocked(updateConversationSummary).mockImplementation((next) => {
339
- slot = next;
340
- });
341
  mockGenerateChat(generateChatWithWllama);
342
  state.systemPrompt = "s".repeat(2000);
343
  const question: ChatMessage = { role: "user", content: "c".repeat(300) };
@@ -364,69 +355,50 @@ describe("generateChatResponse context budget", () => {
364
  expect(summarizer[1][0].content).toContain("a".repeat(500));
365
  expect(summarizer[1][0].content).toContain("x".repeat(500));
366
  expect(summarizer[1][0].content).toContain("Previous summary:\n(none)");
367
- expect(slot.summarizedCount).toBe(2);
368
  });
369
 
370
- it("keeps the stored summary when the summarizer rejects and the fallback returns empty", async () => {
371
- state.systemPrompt = "s".repeat(2000);
372
- const messages: ChatMessage[] = [
373
- { role: "user", content: "first question" },
374
- { role: "assistant", content: "x".repeat(1500) },
375
- { role: "user", content: "follow-up question" },
376
- ];
377
- vi.mocked(getConversationSummary).mockReturnValue({
378
- conversationId: "first question",
379
- summary: "S1",
380
- });
381
- vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => {
382
- if (chat[0].content.startsWith(summarizerInstruction)) {
383
  throw new Error("summarizer unavailable");
384
- }
385
- return "the answer";
386
- });
387
-
388
- await generateChatResponse(messages, () => {});
389
-
390
- expect(updateConversationSummary).toHaveBeenCalledWith(
391
- expect.objectContaining({
 
 
 
 
 
392
  conversationId: "first question",
393
  summary: "S1",
394
- summarizedCount: 0,
395
- }),
396
- );
397
- const { answer } = callsTo(generateChatWithWllama);
398
- expect(answer).toHaveLength(1);
399
- expect(answer[0][0].content).toContain("S1");
400
- });
401
-
402
- it("keeps the stored summary when the summarizer resolves to an empty string", async () => {
403
- state.systemPrompt = "s".repeat(2000);
404
- const messages: ChatMessage[] = [
405
- { role: "user", content: "first question" },
406
- { role: "assistant", content: "x".repeat(1500) },
407
- { role: "user", content: "follow-up question" },
408
- ];
409
- vi.mocked(getConversationSummary).mockReturnValue({
410
- conversationId: "first question",
411
- summary: "S1",
412
- });
413
- vi.mocked(generateChatWithWllama).mockImplementation(async (chat) =>
414
- chat[0].content.startsWith(summarizerInstruction) ? "" : "the answer",
415
- );
416
 
417
- await generateChatResponse(messages, () => {});
418
 
419
- expect(updateConversationSummary).toHaveBeenCalledWith(
420
- expect.objectContaining({
421
- conversationId: "first question",
422
- summary: "S1",
423
- summarizedCount: 0,
424
- }),
425
- );
426
- const { answer } = callsTo(generateChatWithWllama);
427
- expect(answer).toHaveLength(1);
428
- expect(answer[0][0].content).toContain("S1");
429
- });
 
430
  });
431
 
432
  describe("reasoning in earlier assistant turns", () => {
 
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import {
3
+ historyMock,
4
+ logEntriesMock,
5
+ notificationsMock,
6
+ pubSubMock,
7
+ searchMock,
8
+ } from "./textGenerationTestUtils";
9
 
10
  const state = vi.hoisted(() => ({
11
  settings: { inferenceType: "browser" } as {
 
17
  systemPrompt: "",
18
  }));
19
 
20
+ // jscpd:ignore-start
21
+ // Vitest hoists every vi.mock call above the imports, so the registration has
22
+ // to be written out in each file; only the factory body can be shared, and it
23
+ // is. The duplication is the framework's, not the tests'.
24
+ vi.mock("./pubSub", () => pubSubMock(() => state.settings));
25
+ vi.mock("./history", () => historyMock(() => "run-1"));
26
+ vi.mock("./logEntries", () => logEntriesMock());
27
+ vi.mock("./notifications", () => notificationsMock());
28
+ vi.mock("./search", () => searchMock());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  // The system prompt stands in for everything that fills it (instructions,
30
  // search results, page excerpts), so its length sets how much of the window
31
  // is left for the conversation.
32
  vi.mock("./systemPrompt", () => ({
33
  getSystemPrompt: vi.fn(() => state.systemPrompt),
34
  }));
35
+ // jscpd:ignore-end
36
  vi.mock("./textGenerationUtilities", async (importOriginal) => ({
37
  ...(await importOriginal<typeof import("./textGenerationUtilities")>()),
38
  getFormattedSearchResults: vi.fn(() => Promise.resolve("")),
 
75
  );
76
  }
77
 
78
+ /** Total characters in a chat, which is its token count under this tokenizer. */
79
+ function contentLength(chat: ChatMessage[]) {
80
+ return chat.reduce((total, message) => total + message.content.length, 0);
81
+ }
82
+
83
+ /**
84
+ * A summary slot that survives between turns, as the pubsub store does. The
85
+ * mock reads and writes it, so a test can watch what the turns folded in.
86
+ */
87
+ function stubPersistentSummarySlot() {
88
+ const slot: { current: ReturnType<typeof getConversationSummary> } = {
89
+ current: { conversationId: "", summary: "" },
90
+ };
91
+ vi.mocked(getConversationSummary).mockImplementation(() => slot.current);
92
+ vi.mocked(updateConversationSummary).mockImplementation((next) => {
93
+ slot.current = next;
94
+ });
95
+ return slot;
96
+ }
97
+
98
+ /** Answers the summarizer with a summary of exactly this many tokens. */
99
+ function mockSummarizerReturningTokens(tokens: number) {
100
+ vi.mocked(generateChatWithWllama).mockImplementation(async (chat) =>
101
+ chat[0].content.startsWith(summarizerInstruction)
102
+ ? "z".repeat(tokens)
103
+ : "the answer",
104
+ );
105
+ }
106
+
107
  function callsTo(generateChat: typeof generateChatWithWllama) {
108
  const calls = vi
109
  .mocked(generateChat)
 
240
  { role: "assistant", content: "d".repeat(400) },
241
  { role: "user", content: "q".repeat(300) },
242
  ];
243
+ mockSummarizerReturningTokens(summaryTokens);
 
 
 
 
244
 
245
  await generateChatResponse(messages, () => {});
246
 
247
  const { answer, summarizer } = callsTo(generateChatWithWllama);
248
+ const sentTokens = contentLength(answer[0]);
 
 
 
249
  expect(sentTokens).toBeLessThanOrEqual(3072);
250
  expect(answer[0].slice(2)).toEqual(messages.slice(4));
251
  for (const dropped of messages.slice(0, 4)) {
 
279
  await generateChatResponse(messages, () => {});
280
 
281
  const { answer } = callsTo(generateChatWithWllama);
282
+ const sentTokens = contentLength(answer[0]);
 
 
 
283
  expect(sentTokens).toBeLessThanOrEqual(3072);
284
  expect(answer[0][0].content).toContain("z");
285
  expect(answer[0].slice(2)).toEqual(messages.slice(2));
 
293
 
294
  it("folds each dropped turn into the summary once across turns", async () => {
295
  // The summary slot persists between turns, as the pubsub store does.
296
+ const slot = stubPersistentSummarySlot();
 
 
 
 
 
 
 
297
  mockGenerateChat(generateChatWithWllama);
298
  state.systemPrompt = "s".repeat(2000);
299
  const firstExchange: ChatMessage[] = [
 
310
  [...firstExchange, { role: "user", content: "c".repeat(300) }],
311
  () => {},
312
  );
313
+ expect(slot.current.summarizedCount).toBe(2);
314
 
315
  const turnTwo = [...firstExchange, ...secondExchange, question];
316
  await generateChatResponse(turnTwo, () => {});
 
324
  expect(summarizer[1][0].content).toContain("d".repeat(300));
325
  expect(summarizer[1][0].content).not.toContain("a".repeat(500));
326
  expect(summarizer[1][0].content).not.toContain("b".repeat(500));
327
+ expect(slot.current.summarizedCount).toBe(4);
328
  });
329
 
330
  it("folds again from the start once an edit reaches into the summary", async () => {
331
+ const slot = stubPersistentSummarySlot();
 
 
 
 
 
 
 
332
  mockGenerateChat(generateChatWithWllama);
333
  state.systemPrompt = "s".repeat(2000);
334
  const question: ChatMessage = { role: "user", content: "c".repeat(300) };
 
355
  expect(summarizer[1][0].content).toContain("a".repeat(500));
356
  expect(summarizer[1][0].content).toContain("x".repeat(500));
357
  expect(summarizer[1][0].content).toContain("Previous summary:\n(none)");
358
+ expect(slot.current.summarizedCount).toBe(2);
359
  });
360
 
361
+ it.each([
362
+ {
363
+ title: "rejects",
364
+ summarize: () => {
 
 
 
 
 
 
 
 
 
365
  throw new Error("summarizer unavailable");
366
+ },
367
+ },
368
+ { title: "resolves to an empty string", summarize: () => "" },
369
+ ])(
370
+ "keeps the stored summary when the summarizer $title",
371
+ async ({ summarize }) => {
372
+ state.systemPrompt = "s".repeat(2000);
373
+ const messages: ChatMessage[] = [
374
+ { role: "user", content: "first question" },
375
+ { role: "assistant", content: "x".repeat(1500) },
376
+ { role: "user", content: "follow-up question" },
377
+ ];
378
+ vi.mocked(getConversationSummary).mockReturnValue({
379
  conversationId: "first question",
380
  summary: "S1",
381
+ });
382
+ vi.mocked(generateChatWithWllama).mockImplementation(async (chat) =>
383
+ chat[0].content.startsWith(summarizerInstruction)
384
+ ? summarize()
385
+ : "the answer",
386
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
387
 
388
+ await generateChatResponse(messages, () => {});
389
 
390
+ expect(updateConversationSummary).toHaveBeenCalledWith(
391
+ expect.objectContaining({
392
+ conversationId: "first question",
393
+ summary: "S1",
394
+ summarizedCount: 0,
395
+ }),
396
+ );
397
+ const { answer } = callsTo(generateChatWithWllama);
398
+ expect(answer).toHaveLength(1);
399
+ expect(answer[0][0].content).toContain("S1");
400
+ },
401
+ );
402
  });
403
 
404
  describe("reasoning in earlier assistant turns", () => {
client/modules/textGeneration.degradation.test.ts CHANGED
@@ -34,6 +34,16 @@ const harness = vi.hoisted(() => {
34
  };
35
  });
36
 
 
 
 
 
 
 
 
 
 
 
37
  vi.mock("./pubSub", () => ({
38
  getImageSearchResults: () => harness.state.imageSearchResults,
39
  getConversationSummary: () => ({ conversationId: "", summary: "" }),
@@ -92,21 +102,13 @@ vi.mock("./config", () => ({
92
  getConfig: vi.fn(() => Promise.resolve({})),
93
  }));
94
 
95
- vi.mock("./history", () => ({
96
- replaceChatConversation: vi.fn(() => Promise.resolve()),
97
- getCurrentSearchRunId: vi.fn(() => harness.state.searchRunId),
98
- saveLlmResponseForQuery: vi.fn(() => Promise.resolve()),
99
- updateSearchResults: vi.fn(() => Promise.resolve()),
100
- mergeSearchImageResults: vi.fn(() => Promise.resolve()),
101
- }));
102
 
103
- vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
104
 
105
- vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
106
 
107
- vi.mock("./pageContent", () => ({
108
- fetchPageContents: vi.fn(() => Promise.resolve({})),
109
- }));
110
 
111
  vi.mock("./search", () => ({
112
  searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),
@@ -149,10 +151,7 @@ vi.mock("gpt-tokenizer", () => ({
149
  default: { encode: vi.fn(() => [1, 2, 3]) },
150
  }));
151
 
152
- vi.mock("./textGenerationWithWllama", () => ({
153
- generateTextWithWllama: vi.fn(() => Promise.resolve()),
154
- generateChatWithWllama: vi.fn(() => Promise.resolve("")),
155
- }));
156
 
157
  import {
158
  mergeSearchImageResults,
@@ -174,21 +173,58 @@ import type { ImageSearchResults, TextSearchResults } from "./types";
174
  const mockFetch = vi.fn();
175
  vi.stubGlobal("fetch", mockFetch);
176
 
177
- function sseStream(frames: string[]) {
178
- const encoder = new TextEncoder();
179
- return new Response(
180
- new ReadableStream({
181
- start(controller) {
182
- for (const frame of frames) controller.enqueue(encoder.encode(frame));
183
- controller.close();
184
- },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  }),
186
- { status: 200 },
187
  );
 
 
 
188
  }
189
 
190
- function contentFrame(content: string) {
191
- return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  }
193
 
194
  describe("search degradation", () => {
@@ -266,12 +302,7 @@ describe("search degradation", () => {
266
 
267
  it("completes with no results when a stopword-only query leaves no keywords to retry with", async () => {
268
  harness.state.query = "how about that";
269
- vi.mocked(searchText).mockImplementation(async (query) => {
270
- if (!query.trim()) {
271
- throw new Error("Query cannot be empty or whitespace only");
272
- }
273
- return { results: [], stale: false };
274
- });
275
 
276
  await searchAndRespond();
277
  await harness.state.searchPromise;
@@ -283,12 +314,7 @@ describe("search degradation", () => {
283
 
284
  it("completes without searching when an over-long query has no keywords", async () => {
285
  harness.state.query = "that ".repeat(401);
286
- vi.mocked(searchText).mockImplementation(async (query) => {
287
- if (!query.trim()) {
288
- throw new Error("Query cannot be empty or whitespace only");
289
- }
290
- return { results: [], stale: false };
291
- });
292
 
293
  await searchAndRespond();
294
  await harness.state.searchPromise;
@@ -384,22 +410,7 @@ describe("search degradation", () => {
384
 
385
  it("lets a newer search keep the grounding channel when an older image fallback resolves last", async () => {
386
  // Run 1: text fails, image in flight.
387
- vi.mocked(searchText).mockRejectedValueOnce(
388
- new Error("HTTP error! status: 502"),
389
- );
390
- let releaseImages: (value: {
391
- results: ImageSearchResults;
392
- stale: boolean;
393
- }) => void = () => {};
394
- vi.mocked(searchImages).mockReturnValueOnce(
395
- new Promise<{ results: ImageSearchResults; stale: boolean }>(
396
- (resolve) => {
397
- releaseImages = resolve;
398
- },
399
- ),
400
- );
401
- harness.state.settings.enableAiResponse = true;
402
- harness.state.settings.enableImageSearch = true;
403
 
404
  const first = searchAndRespond();
405
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());
@@ -415,17 +426,12 @@ describe("search degradation", () => {
415
  await harness.state.searchPromise;
416
 
417
  // Run 1's image search now lands, after run 2 already owns the channel.
418
- releaseImages({
419
- results: [
420
- ["Late", "https://late.example.com", "t", "https://late.example.com"],
421
- ],
422
- stale: false,
423
- });
424
  // Let run 1's in-flight continuation fully drain: without the guard its
425
  // publish lands on later microtasks, after the test's own `await` has
426
  // resumed, so asserting without draining would race the very write the
427
  // guard blocks.
428
- await new Promise((resolve) => setTimeout(resolve, 0));
429
  await first;
430
 
431
  expect(harness.state.llmTextSearchResults).toEqual([
@@ -434,21 +440,7 @@ describe("search degradation", () => {
434
  });
435
 
436
  it("keeps restored grounding when an older image fallback resolves after a restore", async () => {
437
- vi.mocked(searchText).mockRejectedValueOnce(
438
- new Error("HTTP error! status: 502"),
439
- );
440
- let releaseImages:
441
- | ((value: { results: ImageSearchResults; stale: boolean }) => void)
442
- | undefined;
443
- vi.mocked(searchImages).mockReturnValueOnce(
444
- new Promise<{ results: ImageSearchResults; stale: boolean }>(
445
- (resolve) => {
446
- releaseImages = resolve;
447
- },
448
- ),
449
- );
450
- harness.state.settings.enableAiResponse = true;
451
- harness.state.settings.enableImageSearch = true;
452
 
453
  const first = searchAndRespond();
454
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());
@@ -460,15 +452,10 @@ describe("search degradation", () => {
460
  ["Restored", "snippet", "https://restored.example.com"],
461
  ];
462
 
463
- releaseImages?.({
464
- results: [
465
- ["Late", "https://late.example.com", "t", "https://late.example.com"],
466
- ],
467
- stale: false,
468
- });
469
  // The publish sits behind the awaited image search; drain the
470
  // continuation before asserting, as in the cross-run test above.
471
- await new Promise((resolve) => setTimeout(resolve, 0));
472
  await first;
473
 
474
  expect(harness.state.llmTextSearchResults).toEqual([
@@ -572,15 +559,7 @@ describe("search supersession ownership", () => {
572
  const first = searchAndRespond();
573
  await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
574
 
575
- const resultsB: TextSearchResults = [
576
- ["B title", "B snippet", "https://b.example"],
577
- ];
578
- harness.state.query = "search b";
579
- harness.state.searchRunId = "run-b";
580
- vi.mocked(searchText).mockResolvedValueOnce({
581
- results: resultsB,
582
- stale: false,
583
- });
584
  vi.mocked(fetchPageContents).mockResolvedValueOnce({
585
  "https://b.example": "B page excerpt",
586
  });
@@ -593,7 +572,7 @@ describe("search supersession ownership", () => {
593
  ["A title", "A snippet", "https://a.example"],
594
  ];
595
  deferredA.release({ results: resultsA, stale: true });
596
- await new Promise((resolve) => setTimeout(resolve, 0));
597
  await first;
598
 
599
  expect(harness.state.textSearchResults).toEqual(resultsB);
@@ -631,22 +610,14 @@ describe("search supersession ownership", () => {
631
  const first = searchAndRespond();
632
  await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
633
 
634
- const resultsB: TextSearchResults = [
635
- ["B title", "B snippet", "https://b.example"],
636
- ];
637
- harness.state.query = "search b";
638
- harness.state.searchRunId = "run-b";
639
- vi.mocked(searchText).mockResolvedValueOnce({
640
- results: resultsB,
641
- stale: false,
642
- });
643
 
644
  const second = searchAndRespond();
645
  await second;
646
  await harness.state.searchPromise;
647
 
648
  deferredA.fail(new Error("late failure"));
649
- await new Promise((resolve) => setTimeout(resolve, 0));
650
  await first;
651
 
652
  expect(harness.state.textSearchState).toBe("completed");
@@ -675,7 +646,7 @@ describe("search supersession ownership", () => {
675
  return {
676
  finishImages: async (results: ImageSearchResults) => {
677
  deferredImages.release({ results, stale: false });
678
- await new Promise((resolve) => setTimeout(resolve, 0));
679
  await running;
680
  },
681
  };
@@ -751,12 +722,7 @@ describe("search supersession ownership", () => {
751
  const imagesB: ImageSearchResults = [
752
  ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],
753
  ];
754
- harness.state.query = "search b";
755
- harness.state.searchRunId = "run-b";
756
- vi.mocked(searchText).mockResolvedValueOnce({
757
- results: [["B title", "B snippet", "https://b.example"]],
758
- stale: false,
759
- });
760
  vi.mocked(searchImages).mockResolvedValueOnce({
761
  results: imagesB,
762
  stale: false,
@@ -765,13 +731,13 @@ describe("search supersession ownership", () => {
765
  const second = searchAndRespond();
766
  await second;
767
  await harness.state.searchPromise;
768
- await new Promise((resolve) => setTimeout(resolve, 0));
769
 
770
  const imagesA: ImageSearchResults = [
771
  ["Img A", "https://a.example/img.png", "thumb-a", "https://a.example"],
772
  ];
773
  deferredImagesA.release({ results: imagesA, stale: false });
774
- await new Promise((resolve) => setTimeout(resolve, 0));
775
  await first;
776
 
777
  expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith(
@@ -820,12 +786,7 @@ describe("search supersession ownership", () => {
820
  const first = searchAndRespond();
821
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalledTimes(1));
822
 
823
- harness.state.query = "search b";
824
- harness.state.searchRunId = "run-b";
825
- vi.mocked(searchText).mockResolvedValueOnce({
826
- results: [["B title", "B snippet", "https://b.example"]],
827
- stale: false,
828
- });
829
  vi.mocked(searchImages).mockResolvedValueOnce({
830
  results: [
831
  ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],
@@ -836,10 +797,10 @@ describe("search supersession ownership", () => {
836
  const second = searchAndRespond();
837
  await second;
838
  await harness.state.searchPromise;
839
- await new Promise((resolve) => setTimeout(resolve, 0));
840
 
841
  deferredImagesA.fail(new Error("late image error"));
842
- await new Promise((resolve) => setTimeout(resolve, 0));
843
  await first;
844
 
845
  expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(
@@ -873,10 +834,10 @@ describe("search supersession ownership", () => {
873
  const fourth = searchAndRespond();
874
  await fourth;
875
  await harness.state.searchPromise;
876
- await new Promise((resolve) => setTimeout(resolve, 0));
877
 
878
  deferredImagesC.fail(new Error("late fire-and-forget image error"));
879
- await new Promise((resolve) => setTimeout(resolve, 0));
880
  await third;
881
 
882
  expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(
@@ -906,7 +867,7 @@ describe("search supersession ownership", () => {
906
  results: [["Old", "Old snippet", "https://old.example"]],
907
  stale: true,
908
  });
909
- await new Promise((resolve) => setTimeout(resolve, 0));
910
  await first;
911
 
912
  expect(harness.state.textSearchResults).toEqual(retryResults);
@@ -948,7 +909,7 @@ describe("search supersession ownership", () => {
948
  results: [["Late A", "Late snippet", "https://late.example"]],
949
  stale: true,
950
  });
951
- await new Promise((resolve) => setTimeout(resolve, 0));
952
  await first;
953
 
954
  expect(harness.state.textSearchResults).toEqual(restoredResults);
 
34
  };
35
  });
36
 
37
+ import {
38
+ contentFrame,
39
+ historyMock,
40
+ logEntriesMock,
41
+ notificationsMock,
42
+ pageContentMock,
43
+ sseStream,
44
+ wllamaMock,
45
+ } from "./textGenerationTestUtils";
46
+
47
  vi.mock("./pubSub", () => ({
48
  getImageSearchResults: () => harness.state.imageSearchResults,
49
  getConversationSummary: () => ({ conversationId: "", summary: "" }),
 
102
  getConfig: vi.fn(() => Promise.resolve({})),
103
  }));
104
 
105
+ vi.mock("./history", () => historyMock(() => harness.state.searchRunId));
 
 
 
 
 
 
106
 
107
+ vi.mock("./logEntries", () => logEntriesMock());
108
 
109
+ vi.mock("./notifications", () => notificationsMock());
110
 
111
+ vi.mock("./pageContent", () => pageContentMock());
 
 
112
 
113
  vi.mock("./search", () => ({
114
  searchImages: vi.fn(() => Promise.resolve({ results: [], stale: false })),
 
151
  default: { encode: vi.fn(() => [1, 2, 3]) },
152
  }));
153
 
154
+ vi.mock("./textGenerationWithWllama", () => wllamaMock());
 
 
 
155
 
156
  import {
157
  mergeSearchImageResults,
 
173
  const mockFetch = vi.fn();
174
  vi.stubGlobal("fetch", mockFetch);
175
 
176
+ /** Makes the search endpoint reject a blank query, as the real one does. */
177
+ function stubEmptyQueryRejection() {
178
+ vi.mocked(searchText).mockImplementation(async (query) => {
179
+ if (!query.trim()) {
180
+ throw new Error("Query cannot be empty or whitespace only");
181
+ }
182
+ return { results: [], stale: false };
183
+ });
184
+ }
185
+
186
+ const LATE_IMAGE_RESULTS: ImageSearchResults = [
187
+ ["Late", "https://late.example.com", "t", "https://late.example.com"],
188
+ ];
189
+
190
+ /**
191
+ * Fails the text search and holds the image search open, with the AI response
192
+ * and the image search on. Returns the function that releases the held search.
193
+ */
194
+ function failTextAndHoldImages() {
195
+ vi.mocked(searchText).mockRejectedValueOnce(
196
+ new Error("HTTP error! status: 502"),
197
+ );
198
+ let release:
199
+ | ((value: { results: ImageSearchResults; stale: boolean }) => void)
200
+ | undefined;
201
+ vi.mocked(searchImages).mockReturnValueOnce(
202
+ new Promise<{ results: ImageSearchResults; stale: boolean }>((resolve) => {
203
+ release = resolve;
204
  }),
 
205
  );
206
+ harness.state.settings.enableAiResponse = true;
207
+ harness.state.settings.enableImageSearch = true;
208
+ return () => release?.({ results: LATE_IMAGE_RESULTS, stale: false });
209
  }
210
 
211
+ /** Lets an in-flight continuation drain before the next assertion. */
212
+ async function drainContinuations() {
213
+ await new Promise((resolve) => setTimeout(resolve, 0));
214
+ }
215
+
216
+ /** Queues run B: its own query, run id and text results. */
217
+ function queueSecondSearch() {
218
+ const resultsB: TextSearchResults = [
219
+ ["B title", "B snippet", "https://b.example"],
220
+ ];
221
+ harness.state.query = "search b";
222
+ harness.state.searchRunId = "run-b";
223
+ vi.mocked(searchText).mockResolvedValueOnce({
224
+ results: resultsB,
225
+ stale: false,
226
+ });
227
+ return resultsB;
228
  }
229
 
230
  describe("search degradation", () => {
 
302
 
303
  it("completes with no results when a stopword-only query leaves no keywords to retry with", async () => {
304
  harness.state.query = "how about that";
305
+ stubEmptyQueryRejection();
 
 
 
 
 
306
 
307
  await searchAndRespond();
308
  await harness.state.searchPromise;
 
314
 
315
  it("completes without searching when an over-long query has no keywords", async () => {
316
  harness.state.query = "that ".repeat(401);
317
+ stubEmptyQueryRejection();
 
 
 
 
 
318
 
319
  await searchAndRespond();
320
  await harness.state.searchPromise;
 
410
 
411
  it("lets a newer search keep the grounding channel when an older image fallback resolves last", async () => {
412
  // Run 1: text fails, image in flight.
413
+ const releaseLateImages = failTextAndHoldImages();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
 
415
  const first = searchAndRespond();
416
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());
 
426
  await harness.state.searchPromise;
427
 
428
  // Run 1's image search now lands, after run 2 already owns the channel.
429
+ releaseLateImages();
 
 
 
 
 
430
  // Let run 1's in-flight continuation fully drain: without the guard its
431
  // publish lands on later microtasks, after the test's own `await` has
432
  // resumed, so asserting without draining would race the very write the
433
  // guard blocks.
434
+ await drainContinuations();
435
  await first;
436
 
437
  expect(harness.state.llmTextSearchResults).toEqual([
 
440
  });
441
 
442
  it("keeps restored grounding when an older image fallback resolves after a restore", async () => {
443
+ const releaseLateImages = failTextAndHoldImages();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
444
 
445
  const first = searchAndRespond();
446
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalled());
 
452
  ["Restored", "snippet", "https://restored.example.com"],
453
  ];
454
 
455
+ releaseLateImages();
 
 
 
 
 
456
  // The publish sits behind the awaited image search; drain the
457
  // continuation before asserting, as in the cross-run test above.
458
+ await drainContinuations();
459
  await first;
460
 
461
  expect(harness.state.llmTextSearchResults).toEqual([
 
559
  const first = searchAndRespond();
560
  await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
561
 
562
+ const resultsB = queueSecondSearch();
 
 
 
 
 
 
 
 
563
  vi.mocked(fetchPageContents).mockResolvedValueOnce({
564
  "https://b.example": "B page excerpt",
565
  });
 
572
  ["A title", "A snippet", "https://a.example"],
573
  ];
574
  deferredA.release({ results: resultsA, stale: true });
575
+ await drainContinuations();
576
  await first;
577
 
578
  expect(harness.state.textSearchResults).toEqual(resultsB);
 
610
  const first = searchAndRespond();
611
  await vi.waitFor(() => expect(searchText).toHaveBeenCalledTimes(1));
612
 
613
+ const resultsB = queueSecondSearch();
 
 
 
 
 
 
 
 
614
 
615
  const second = searchAndRespond();
616
  await second;
617
  await harness.state.searchPromise;
618
 
619
  deferredA.fail(new Error("late failure"));
620
+ await drainContinuations();
621
  await first;
622
 
623
  expect(harness.state.textSearchState).toBe("completed");
 
646
  return {
647
  finishImages: async (results: ImageSearchResults) => {
648
  deferredImages.release({ results, stale: false });
649
+ await drainContinuations();
650
  await running;
651
  },
652
  };
 
722
  const imagesB: ImageSearchResults = [
723
  ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],
724
  ];
725
+ queueSecondSearch();
 
 
 
 
 
726
  vi.mocked(searchImages).mockResolvedValueOnce({
727
  results: imagesB,
728
  stale: false,
 
731
  const second = searchAndRespond();
732
  await second;
733
  await harness.state.searchPromise;
734
+ await drainContinuations();
735
 
736
  const imagesA: ImageSearchResults = [
737
  ["Img A", "https://a.example/img.png", "thumb-a", "https://a.example"],
738
  ];
739
  deferredImagesA.release({ results: imagesA, stale: false });
740
+ await drainContinuations();
741
  await first;
742
 
743
  expect(vi.mocked(updateImageSearchResults)).toHaveBeenLastCalledWith(
 
786
  const first = searchAndRespond();
787
  await vi.waitFor(() => expect(searchImages).toHaveBeenCalledTimes(1));
788
 
789
+ queueSecondSearch();
 
 
 
 
 
790
  vi.mocked(searchImages).mockResolvedValueOnce({
791
  results: [
792
  ["Img B", "https://b.example/img.png", "thumb-b", "https://b.example"],
 
797
  const second = searchAndRespond();
798
  await second;
799
  await harness.state.searchPromise;
800
+ await drainContinuations();
801
 
802
  deferredImagesA.fail(new Error("late image error"));
803
+ await drainContinuations();
804
  await first;
805
 
806
  expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(
 
834
  const fourth = searchAndRespond();
835
  await fourth;
836
  await harness.state.searchPromise;
837
+ await drainContinuations();
838
 
839
  deferredImagesC.fail(new Error("late fire-and-forget image error"));
840
+ await drainContinuations();
841
  await third;
842
 
843
  expect(vi.mocked(updateImageSearchState)).not.toHaveBeenCalledWith(
 
867
  results: [["Old", "Old snippet", "https://old.example"]],
868
  stale: true,
869
  });
870
+ await drainContinuations();
871
  await first;
872
 
873
  expect(harness.state.textSearchResults).toEqual(retryResults);
 
909
  results: [["Late A", "Late snippet", "https://late.example"]],
910
  stale: true,
911
  });
912
+ await drainContinuations();
913
  await first;
914
 
915
  expect(harness.state.textSearchResults).toEqual(restoredResults);
client/modules/textGeneration.inference.test.ts CHANGED
@@ -1,10 +1,15 @@
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
-
3
- vi.mock("./pubSub", () => ({
4
- getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })),
5
- getQuery: vi.fn(() => ""),
6
- getResponse: vi.fn(() => ""),
7
- getSettings: vi.fn(() => ({
 
 
 
 
 
8
  inferenceType: "browser",
9
  enableAiResponse: true,
10
  enableTextSearch: true,
@@ -12,35 +17,11 @@ vi.mock("./pubSub", () => ({
12
  searchResultsLimit: 10,
13
  allowAiModelDownload: true,
14
  })),
15
- getTextGenerationState: vi.fn(() => "idle"),
16
- listenToSettingsChanges: vi.fn(() => vi.fn()),
17
- updateChatMessages: vi.fn(),
18
- updateConversationSummary: vi.fn(),
19
- updateImageSearchResults: vi.fn(),
20
- updateImageSearchState: vi.fn(),
21
- updateLlmTextSearchResults: vi.fn(),
22
- updateResponse: vi.fn(),
23
- updateResponseImmediately: vi.fn(),
24
- updateSearchPromise: vi.fn(),
25
- updateTextGenerationState: vi.fn(),
26
- updateTextSearchResults: vi.fn(),
27
- updateTextSearchState: vi.fn(),
28
- updateTextSearchStale: vi.fn(),
29
- updateSuppressNextFollowUp: vi.fn(),
30
- updatePageContents: vi.fn(),
31
- }));
32
- vi.mock("./history", () => ({
33
- replaceChatConversation: vi.fn(() => Promise.resolve()),
34
- getCurrentSearchRunId: vi.fn(() => "run-1"),
35
- saveLlmResponseForQuery: vi.fn(() => Promise.resolve()),
36
- updateSearchResults: vi.fn(() => Promise.resolve()),
37
- }));
38
- vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
39
- vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
40
- vi.mock("./search", () => ({
41
- searchImages: vi.fn(() => Promise.resolve([])),
42
- searchText: vi.fn(() => Promise.resolve([])),
43
- }));
44
  vi.mock("./systemPrompt", () => ({ getSystemPrompt: vi.fn(() => "") }));
45
  vi.mock("./textGenerationUtilities", () => ({
46
  ChatGenerationError: class ChatGenerationError extends Error {},
@@ -55,10 +36,7 @@ vi.mock("gpt-tokenizer", () => ({
55
  vi.mock("pretty-ms", () => ({
56
  default: vi.fn(() => "100ms"),
57
  }));
58
- vi.mock("./textGenerationWithWllama", () => ({
59
- generateTextWithWllama: vi.fn(() => Promise.resolve()),
60
- generateChatWithWllama: vi.fn(() => Promise.resolve("")),
61
- }));
62
 
63
  import gptTokenizer from "gpt-tokenizer";
64
  import {
 
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import {
3
+ historyMock,
4
+ logEntriesMock,
5
+ notificationsMock,
6
+ pubSubMock,
7
+ searchMock,
8
+ wllamaMock,
9
+ } from "./textGenerationTestUtils";
10
+
11
+ vi.mock("./pubSub", () =>
12
+ pubSubMock(() => ({
13
  inferenceType: "browser",
14
  enableAiResponse: true,
15
  enableTextSearch: true,
 
17
  searchResultsLimit: 10,
18
  allowAiModelDownload: true,
19
  })),
20
+ );
21
+ vi.mock("./history", () => historyMock(() => "run-1"));
22
+ vi.mock("./logEntries", () => logEntriesMock());
23
+ vi.mock("./notifications", () => notificationsMock());
24
+ vi.mock("./search", () => searchMock());
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  vi.mock("./systemPrompt", () => ({ getSystemPrompt: vi.fn(() => "") }));
26
  vi.mock("./textGenerationUtilities", () => ({
27
  ChatGenerationError: class ChatGenerationError extends Error {},
 
36
  vi.mock("pretty-ms", () => ({
37
  default: vi.fn(() => "100ms"),
38
  }));
39
+ vi.mock("./textGenerationWithWllama", () => wllamaMock());
 
 
 
40
 
41
  import gptTokenizer from "gpt-tokenizer";
42
  import {
client/modules/textGeneration.responsePersistence.test.ts CHANGED
@@ -5,6 +5,14 @@ const harness = vi.hoisted(() => ({
5
  responseAtCompletion: { current: null as string | null },
6
  }));
7
 
 
 
 
 
 
 
 
 
8
  vi.mock("./history", () => ({
9
  replaceChatConversation: vi.fn(() => Promise.resolve()),
10
  getCurrentSearchRunId: vi.fn(() => "run-1"),
@@ -17,7 +25,7 @@ vi.mock("./history", () => ({
17
  updateSearchResults: vi.fn(() => Promise.resolve()),
18
  }));
19
 
20
- vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() }));
21
 
22
  // The internal API sizes its budgets from /api/config; `fetch` below only
23
  // answers /inference.
@@ -29,11 +37,9 @@ vi.mock("./config", async (importOriginal) => {
29
  };
30
  });
31
 
32
- vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() }));
33
 
34
- vi.mock("./pageContent", () => ({
35
- fetchPageContents: vi.fn(() => Promise.resolve({})),
36
- }));
37
 
38
  vi.mock("./search", () => ({
39
  searchText: vi.fn(() =>
@@ -63,23 +69,6 @@ const throttleInterval = 1000 / 12;
63
  const mockFetch = vi.fn();
64
  vi.stubGlobal("fetch", mockFetch);
65
 
66
- function sseStream(frames: string[]) {
67
- const encoder = new TextEncoder();
68
- return new Response(
69
- new ReadableStream({
70
- start(controller) {
71
- for (const frame of frames) controller.enqueue(encoder.encode(frame));
72
- controller.close();
73
- },
74
- }),
75
- { status: 200 },
76
- );
77
- }
78
-
79
- function contentFrame(content: string) {
80
- return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;
81
- }
82
-
83
  describe("response persistence", () => {
84
  beforeEach(() => {
85
  harness.saved.length = 0;
 
5
  responseAtCompletion: { current: null as string | null },
6
  }));
7
 
8
+ import {
9
+ contentFrame,
10
+ logEntriesMock,
11
+ notificationsMock,
12
+ pageContentMock,
13
+ sseStream,
14
+ } from "./textGenerationTestUtils";
15
+
16
  vi.mock("./history", () => ({
17
  replaceChatConversation: vi.fn(() => Promise.resolve()),
18
  getCurrentSearchRunId: vi.fn(() => "run-1"),
 
25
  updateSearchResults: vi.fn(() => Promise.resolve()),
26
  }));
27
 
28
+ vi.mock("./logEntries", () => logEntriesMock());
29
 
30
  // The internal API sizes its budgets from /api/config; `fetch` below only
31
  // answers /inference.
 
37
  };
38
  });
39
 
40
+ vi.mock("./notifications", () => notificationsMock());
41
 
42
+ vi.mock("./pageContent", () => pageContentMock());
 
 
43
 
44
  vi.mock("./search", () => ({
45
  searchText: vi.fn(() =>
 
69
  const mockFetch = vi.fn();
70
  vi.stubGlobal("fetch", mockFetch);
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  describe("response persistence", () => {
73
  beforeEach(() => {
74
  harness.saved.length = 0;
client/modules/textGenerationTestUtils.ts ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { vi } from "vitest";
2
+
3
+ /**
4
+ * The `./textGenerationUtilities` override shared by the per-engine generation
5
+ * tests. The helpers that read pubSub state become mocks, so a generation test
6
+ * does not have to drive the UI channels; everything else (`ChatGenerationError`,
7
+ * `defaultContextSize`) stays real, so `instanceof` checks still work.
8
+ *
9
+ * Returns the factory rather than the object so a `vi.mock` call can stay a
10
+ * one-liner. Call it from inside a `vi.mock` factory that loads this module with
11
+ * `await import(...)`: vitest hoists the registration above the imports, so a
12
+ * static import here would only be initialised in time by accident of the import
13
+ * order.
14
+ */
15
+ export function textGenerationUtilitiesMock(
16
+ overrides: Record<string, unknown> = {},
17
+ ) {
18
+ return async (
19
+ importOriginal: () => Promise<typeof import("./textGenerationUtilities")>,
20
+ ) => ({
21
+ ...(await importOriginal()),
22
+ canStartResponding: vi.fn().mockResolvedValue(undefined),
23
+ getFormattedSearchResults: vi.fn().mockReturnValue("None."),
24
+ ...overrides,
25
+ });
26
+ }
27
+
28
+ /** The `./textGenerationWithWllama` override: both generators answer nothing. */
29
+ export function wllamaMock() {
30
+ return {
31
+ generateTextWithWllama: vi.fn(() => Promise.resolve()),
32
+ generateChatWithWllama: vi.fn(() => Promise.resolve("")),
33
+ };
34
+ }
35
+
36
+ /**
37
+ * A `Response` that streams `frames` as SSE, the shape the OpenAI-compatible
38
+ * and internal-API paths produce.
39
+ */
40
+ export function sseStream(frames: string[]) {
41
+ const encoder = new TextEncoder();
42
+ return new Response(
43
+ new ReadableStream({
44
+ start(controller) {
45
+ for (const frame of frames) controller.enqueue(encoder.encode(frame));
46
+ controller.close();
47
+ },
48
+ }),
49
+ { status: 200 },
50
+ );
51
+ }
52
+
53
+ /** One `chat.completion.chunk` delta frame carrying `content`. */
54
+ export function contentFrame(content: string) {
55
+ return `data: ${JSON.stringify({ choices: [{ delta: { content } }] })}\n`;
56
+ }
57
+
58
+ /**
59
+ * The `./history` override shared by the textGeneration tests: every write is
60
+ * a resolved mock, and the run id is fixed so the supersede guards pass.
61
+ */
62
+ export function historyMock(getCurrentSearchRunId: () => string) {
63
+ return {
64
+ replaceChatConversation: vi.fn(() => Promise.resolve()),
65
+ getCurrentSearchRunId: vi.fn(getCurrentSearchRunId),
66
+ saveLlmResponseForQuery: vi.fn(() => Promise.resolve()),
67
+ updateSearchResults: vi.fn(() => Promise.resolve()),
68
+ mergeSearchImageResults: vi.fn(() => Promise.resolve()),
69
+ };
70
+ }
71
+
72
+ /** The `./logEntries` and `./notifications` overrides, with no behaviour. */
73
+ export function logEntriesMock() {
74
+ return { addLogEntry: vi.fn() };
75
+ }
76
+
77
+ export function notificationsMock() {
78
+ return { showAiCompleteNotification: vi.fn() };
79
+ }
80
+
81
+ /** The `./pageContent` override: every read comes back empty. */
82
+ export function pageContentMock() {
83
+ return { fetchPageContents: vi.fn(() => Promise.resolve({})) };
84
+ }
85
+
86
+ /** The `./search` override: both searches answer with nothing. */
87
+ export function searchMock() {
88
+ return {
89
+ searchImages: vi.fn(() => Promise.resolve([])),
90
+ searchText: vi.fn(() => Promise.resolve([])),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * The pubsub surface `textGeneration` reads. `getSettings` is the one part
96
+ * tests rewrite per case, so it is passed in as a getter.
97
+ */
98
+ export function pubSubMock(getSettings: () => unknown) {
99
+ return {
100
+ getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })),
101
+ getQuery: vi.fn(() => ""),
102
+ getResponse: vi.fn(() => ""),
103
+ getSettings: vi.fn(getSettings),
104
+ getTextGenerationState: vi.fn(() => "idle"),
105
+ listenToSettingsChanges: vi.fn(() => vi.fn()),
106
+ updateChatMessages: vi.fn(),
107
+ updateConversationSummary: vi.fn(),
108
+ updateImageSearchResults: vi.fn(),
109
+ updateImageSearchState: vi.fn(),
110
+ updateLlmTextSearchResults: vi.fn(),
111
+ updatePageContents: vi.fn(),
112
+ updateResponse: vi.fn(),
113
+ updateResponseImmediately: vi.fn(),
114
+ updateSearchPromise: vi.fn(),
115
+ updateSuppressNextFollowUp: vi.fn(),
116
+ updateTextGenerationState: vi.fn(),
117
+ updateTextSearchResults: vi.fn(),
118
+ updateTextSearchStale: vi.fn(),
119
+ updateTextSearchState: vi.fn(),
120
+ };
121
+ }
client/modules/textGenerationUtilities.test.ts CHANGED
@@ -127,6 +127,19 @@ beforeEach(() => {
127
  });
128
  });
129
 
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  describe("getFormattedSearchResults", () => {
131
  beforeEach(() => {
132
  state.searchResults = results;
@@ -498,28 +511,12 @@ describe("worker handoff", () => {
498
  data: { type: "error", message: "tokenization failed" },
499
  } as MessageEvent<WorkerResponse>),
500
  );
501
- setWorkerFactory(() => worker as unknown as Worker);
502
- setPageContents({
503
- "https://a.example/": "sentence about cats. ".repeat(500),
504
- });
505
-
506
- const formatted = await getFormattedSearchResults(true);
507
-
508
- expect(formatted).toContain("โ€ฆ");
509
- expect(worker.terminate).toHaveBeenCalled();
510
  });
511
 
512
  it("falls back when the worker dies before answering", async () => {
513
  const worker = createFailingWorker((deadWorker) => deadWorker.onerror?.());
514
- setWorkerFactory(() => worker as unknown as Worker);
515
- setPageContents({
516
- "https://a.example/": "sentence about cats. ".repeat(500),
517
- });
518
-
519
- const formatted = await getFormattedSearchResults(true);
520
-
521
- expect(formatted).toContain("โ€ฆ");
522
- expect(worker.terminate).toHaveBeenCalled();
523
  });
524
 
525
  it("does not start a worker when no page content was read", async () => {
 
127
  });
128
  });
129
 
130
+ /** Points the formatter at a worker that fails, and expects the fallback. */
131
+ async function expectMainThreadFallback(worker: { terminate: () => void }) {
132
+ setWorkerFactory(() => worker as unknown as Worker);
133
+ setPageContents({
134
+ "https://a.example/": "sentence about cats. ".repeat(500),
135
+ });
136
+
137
+ const formatted = await getFormattedSearchResults(true);
138
+
139
+ expect(formatted).toContain("โ€ฆ");
140
+ expect(worker.terminate).toHaveBeenCalled();
141
+ }
142
+
143
  describe("getFormattedSearchResults", () => {
144
  beforeEach(() => {
145
  state.searchResults = results;
 
511
  data: { type: "error", message: "tokenization failed" },
512
  } as MessageEvent<WorkerResponse>),
513
  );
514
+ await expectMainThreadFallback(worker);
 
 
 
 
 
 
 
 
515
  });
516
 
517
  it("falls back when the worker dies before answering", async () => {
518
  const worker = createFailingWorker((deadWorker) => deadWorker.onerror?.());
519
+ await expectMainThreadFallback(worker);
 
 
 
 
 
 
 
 
520
  });
521
 
522
  it("does not start a worker when no page content was read", async () => {
client/modules/textGenerationWithHorde.test.ts CHANGED
@@ -24,21 +24,13 @@ vi.mock("./sleep", () => ({
24
  sleep: vi.fn().mockResolvedValue(undefined),
25
  }));
26
 
27
- // canStartResponding/getDefaultChatMessages/getFormattedSearchResults depend
28
- // on pubSub state we don't want to drive here; ChatGenerationError and
29
- // defaultContextSize have no such dependency, so keep them real.
30
- vi.mock("./textGenerationUtilities", async (importOriginal) => {
31
- const actual =
32
- await importOriginal<typeof import("./textGenerationUtilities")>();
33
- return {
34
- ...actual,
35
- canStartResponding: vi.fn().mockResolvedValue(undefined),
36
  getDefaultChatMessages: vi
37
  .fn()
38
  .mockReturnValue([{ role: "user", content: "hi" }]),
39
- getFormattedSearchResults: vi.fn().mockReturnValue("None."),
40
- };
41
- });
42
 
43
  const mockFetch = vi.fn();
44
  vi.stubGlobal("fetch", mockFetch);
@@ -58,6 +50,29 @@ function mockSettings(overrides: Partial<typeof defaultSettings> = {}) {
58
  vi.mocked(getSettings).mockReturnValue({ ...defaultSettings, ...overrides });
59
  }
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  describe("textGenerationWithHorde", () => {
62
  beforeEach(() => {
63
  vi.clearAllMocks();
@@ -68,9 +83,7 @@ describe("textGenerationWithHorde", () => {
68
 
69
  describe("generateTextWithHorde", () => {
70
  it("starts a generation, polls until done, and streams the response", async () => {
71
- const { generateTextWithHorde } = await import(
72
- "./textGenerationWithHorde"
73
- );
74
 
75
  mockFetch
76
  .mockResolvedValueOnce(jsonResponse({ id: "gen-1" }))
@@ -103,9 +116,7 @@ describe("textGenerationWithHorde", () => {
103
  });
104
 
105
  it("throws ChatGenerationError when the generation is faulted", async () => {
106
- const { generateTextWithHorde } = await import(
107
- "./textGenerationWithHorde"
108
- );
109
 
110
  mockFetch
111
  .mockResolvedValueOnce(jsonResponse({ id: "gen-2" }))
@@ -117,9 +128,7 @@ describe("textGenerationWithHorde", () => {
117
  });
118
 
119
  it("throws ChatGenerationError when the model reports generation is not possible", async () => {
120
- const { generateTextWithHorde } = await import(
121
- "./textGenerationWithHorde"
122
- );
123
 
124
  mockFetch
125
  .mockResolvedValueOnce(jsonResponse({ id: "gen-3" }))
@@ -133,13 +142,8 @@ describe("textGenerationWithHorde", () => {
133
  });
134
 
135
  it("stops polling and publishes nothing once the user interrupts generation", async () => {
136
- const controller = new AbortController();
137
- vi.mocked(updateTextGenerationState).mockImplementation((next) => {
138
- if (next === "generating") controller.abort();
139
- });
140
- const { generateTextWithHorde } = await import(
141
- "./textGenerationWithHorde"
142
- );
143
 
144
  mockFetch
145
  .mockResolvedValueOnce(jsonResponse({ id: "gen-4" }))
@@ -161,9 +165,7 @@ describe("textGenerationWithHorde", () => {
161
  });
162
 
163
  it('submits nothing and never enters "generating" once a newer search aborted it', async () => {
164
- const { generateTextWithHorde } = await import(
165
- "./textGenerationWithHorde"
166
- );
167
  const controller = new AbortController();
168
  controller.abort();
169
 
@@ -177,20 +179,10 @@ describe("textGenerationWithHorde", () => {
177
  it("can be interrupted once it is generating, and cancels the queued job", async () => {
178
  // The UI only offers Stop while the state is "generating", so the
179
  // interrupt can only happen after the engine has entered it.
180
- const controller = new AbortController();
181
- vi.mocked(updateTextGenerationState).mockImplementation((next) => {
182
- if (next === "generating") controller.abort();
183
- });
184
- const { generateTextWithHorde } = await import(
185
- "./textGenerationWithHorde"
186
- );
187
 
188
- mockFetch
189
- .mockResolvedValueOnce(jsonResponse({ id: "gen-queued" }))
190
- .mockResolvedValueOnce(
191
- jsonResponse({ done: false, is_possible: true, generations: [] }),
192
- )
193
- .mockResolvedValueOnce(jsonResponse({}));
194
 
195
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
196
  "Generation interrupted",
@@ -202,19 +194,9 @@ describe("textGenerationWithHorde", () => {
202
  });
203
 
204
  it("cancels the job exactly once when the user interrupts", async () => {
205
- const controller = new AbortController();
206
- vi.mocked(updateTextGenerationState).mockImplementation((next) => {
207
- if (next === "generating") controller.abort();
208
- });
209
- const { generateTextWithHorde } = await import(
210
- "./textGenerationWithHorde"
211
- );
212
- mockFetch
213
- .mockResolvedValueOnce(jsonResponse({ id: "gen-stop" }))
214
- .mockResolvedValueOnce(
215
- jsonResponse({ done: false, is_possible: true, generations: [] }),
216
- )
217
- .mockResolvedValueOnce(jsonResponse({}));
218
 
219
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
220
  "Generation interrupted",
@@ -223,9 +205,7 @@ describe("textGenerationWithHorde", () => {
223
  });
224
 
225
  it("cancels a pinned-model job that faults", async () => {
226
- const { generateTextWithHorde } = await import(
227
- "./textGenerationWithHorde"
228
- );
229
  mockFetch
230
  .mockResolvedValueOnce(jsonResponse({ id: "gen-fault" }))
231
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
@@ -238,9 +218,7 @@ describe("textGenerationWithHorde", () => {
238
  });
239
 
240
  it("cancels a pinned-model job that the model cannot take", async () => {
241
- const { generateTextWithHorde } = await import(
242
- "./textGenerationWithHorde"
243
- );
244
  mockFetch
245
  .mockResolvedValueOnce(jsonResponse({ id: "gen-offline" }))
246
  .mockResolvedValueOnce(jsonResponse({ done: true, is_possible: false }))
@@ -253,9 +231,7 @@ describe("textGenerationWithHorde", () => {
253
  });
254
 
255
  it("does not cancel a job whose answer was returned", async () => {
256
- const { generateTextWithHorde } = await import(
257
- "./textGenerationWithHorde"
258
- );
259
  mockFetch
260
  .mockResolvedValueOnce(jsonResponse({ id: "gen-ok" }))
261
  .mockResolvedValueOnce(
@@ -271,9 +247,7 @@ describe("textGenerationWithHorde", () => {
271
  });
272
 
273
  it("keeps the original error and logs once when the cancel fails", async () => {
274
- const { generateTextWithHorde } = await import(
275
- "./textGenerationWithHorde"
276
- );
277
  mockFetch
278
  .mockResolvedValueOnce(jsonResponse({ id: "gen-x" }))
279
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
@@ -293,9 +267,7 @@ describe("textGenerationWithHorde", () => {
293
  });
294
 
295
  it("sends the cancel with a timeout and keepalive", async () => {
296
- const { generateTextWithHorde } = await import(
297
- "./textGenerationWithHorde"
298
- );
299
  mockFetch
300
  .mockResolvedValueOnce(jsonResponse({ id: "gen-k" }))
301
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
@@ -310,9 +282,7 @@ describe("textGenerationWithHorde", () => {
310
 
311
  it("includes the configured model in the generation request body", async () => {
312
  mockSettings({ hordeModel: "custom-model" });
313
- const { generateTextWithHorde } = await import(
314
- "./textGenerationWithHorde"
315
- );
316
 
317
  mockFetch
318
  .mockResolvedValueOnce(jsonResponse({ id: "gen-5" }))
@@ -345,9 +315,7 @@ describe("textGenerationWithHorde", () => {
345
  });
346
 
347
  it("keeps polling through a rate limit and finishes the generation", async () => {
348
- const { generateTextWithHorde } = await import(
349
- "./textGenerationWithHorde"
350
- );
351
  mockFetch
352
  .mockResolvedValueOnce(jsonResponse({ id: "gen-rate" }))
353
  .mockResolvedValueOnce(
@@ -361,9 +329,7 @@ describe("textGenerationWithHorde", () => {
361
  });
362
 
363
  it("recovers when a gateway answers a poll with an HTML error page", async () => {
364
- const { generateTextWithHorde } = await import(
365
- "./textGenerationWithHorde"
366
- );
367
  mockFetch
368
  .mockResolvedValueOnce(jsonResponse({ id: "gen-gateway" }))
369
  .mockResolvedValueOnce(
@@ -379,9 +345,7 @@ describe("textGenerationWithHorde", () => {
379
  });
380
 
381
  it("gives up on a status check that keeps failing without calling the model impossible", async () => {
382
- const { generateTextWithHorde } = await import(
383
- "./textGenerationWithHorde"
384
- );
385
  mockFetch
386
  .mockResolvedValueOnce(jsonResponse({ id: "gen-down" }))
387
  .mockImplementation(async () =>
@@ -404,9 +368,7 @@ describe("textGenerationWithHorde", () => {
404
  });
405
 
406
  it("stops at once when the job is gone, with the server's message", async () => {
407
- const { generateTextWithHorde } = await import(
408
- "./textGenerationWithHorde"
409
- );
410
  mockFetch
411
  .mockResolvedValueOnce(jsonResponse({ id: "gen-gone" }))
412
  .mockResolvedValueOnce(
@@ -422,9 +384,7 @@ describe("textGenerationWithHorde", () => {
422
  });
423
 
424
  it("rejects a finished generation that carries no text", async () => {
425
- const { generateTextWithHorde } = await import(
426
- "./textGenerationWithHorde"
427
- );
428
  mockFetch
429
  .mockResolvedValueOnce(jsonResponse({ id: "gen-empty" }))
430
  .mockResolvedValueOnce(
@@ -441,9 +401,7 @@ describe("textGenerationWithHorde", () => {
441
  });
442
 
443
  it("reports the server's reason when the job is refused at submit", async () => {
444
- const { generateTextWithHorde } = await import(
445
- "./textGenerationWithHorde"
446
- );
447
  mockFetch.mockResolvedValueOnce(
448
  jsonResponse({ message: "Invalid API key" }, 401),
449
  );
@@ -523,6 +481,23 @@ describe("textGenerationWithHorde", () => {
523
  );
524
  }
525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526
  function generationRequestBodies() {
527
  return mockFetch.mock.calls
528
  .filter(([url]) => String(url).includes("/generate/text/async"))
@@ -553,12 +528,7 @@ describe("textGenerationWithHorde", () => {
553
  statusResponder: () => doneResponse,
554
  });
555
 
556
- const { generateTextWithHorde } = await import(
557
- "./textGenerationWithHorde"
558
- );
559
- await generateTextWithHorde();
560
-
561
- const bodies = generationRequestBodies();
562
  expect(bodies).toHaveLength(2);
563
  for (const body of bodies) {
564
  expect(body.models).toEqual(["m-f", "m-e", "m-d", "m-c", "m-b"]);
@@ -577,9 +547,7 @@ describe("textGenerationWithHorde", () => {
577
  statusResponder: () => doneResponse,
578
  });
579
 
580
- const { generateTextWithHorde } = await import(
581
- "./textGenerationWithHorde"
582
- );
583
  await generateTextWithHorde();
584
 
585
  for (const body of generationRequestBodies()) {
@@ -594,12 +562,7 @@ describe("textGenerationWithHorde", () => {
594
  statusResponder: () => doneResponse,
595
  });
596
 
597
- const { generateTextWithHorde } = await import(
598
- "./textGenerationWithHorde"
599
- );
600
- await generateTextWithHorde();
601
-
602
- const bodies = generationRequestBodies();
603
  expect(bodies).toHaveLength(2);
604
  for (const body of bodies) {
605
  expect(body.models).toBeUndefined();
@@ -610,16 +573,11 @@ describe("textGenerationWithHorde", () => {
610
  });
611
 
612
  it("retries with any available model when the top models cannot take the job", async () => {
613
- routeHordeFetch({
614
- workers: [{ models: ["m-a"], max_length: 1024 }],
615
- monthStats: { "m-a": 10 },
616
- statusResponder: (pollIndex) =>
617
- pollIndex < 2 ? { done: true, is_possible: false } : doneResponse,
618
- });
619
-
620
- const { generateTextWithHorde } = await import(
621
- "./textGenerationWithHorde"
622
  );
 
 
623
  await generateTextWithHorde();
624
 
625
  expect(updateResponse).toHaveBeenCalledWith("Top model answer");
@@ -639,16 +597,11 @@ describe("textGenerationWithHorde", () => {
639
  });
640
 
641
  it("does not submit a second round when the status checks keep failing", async () => {
642
- routeHordeFetch({
643
- workers: [{ models: ["m-a"], max_length: 1024 }],
644
- monthStats: { "m-a": 10 },
645
- statusResponder: () =>
646
- jsonResponse({ message: "Too many requests" }, 429),
647
- });
648
-
649
- const { generateTextWithHorde } = await import(
650
- "./textGenerationWithHorde"
651
  );
 
 
652
  await expect(generateTextWithHorde()).rejects.toThrow(
653
  "Too many requests",
654
  );
@@ -656,20 +609,20 @@ describe("textGenerationWithHorde", () => {
656
  });
657
 
658
  it("does not retry when the generation faults", async () => {
 
 
 
 
 
 
 
 
659
  routeHordeFetch({
660
  workers: [{ models: ["m-a"], max_length: 1024 }],
661
  monthStats: { "m-a": 10 },
662
- statusResponder: () => ({ done: true, faulted: true }),
663
  });
664
-
665
- const { generateTextWithHorde } = await import(
666
- "./textGenerationWithHorde"
667
- );
668
- await expect(generateTextWithHorde()).rejects.toThrow(
669
- "Generation failed",
670
- );
671
- expect(generationRequestBodies()).toHaveLength(2);
672
- });
673
 
674
  /** Answers each job's polls from its own script, by the job id in the URL. */
675
  function perJobResponder(
@@ -687,18 +640,14 @@ describe("textGenerationWithHorde", () => {
687
  const pendingResponse = { done: false, is_possible: true, generations: [] };
688
 
689
  it("serves the healthy job when its sibling faults first", async () => {
690
- routeHordeFetch({
691
- workers: [{ models: ["m-a"], max_length: 1024 }],
692
- monthStats: { "m-a": 10 },
693
- statusResponder: perJobResponder({
694
  "gen-1": () => ({ done: true, faulted: true }),
695
  "gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),
696
  }),
697
- });
698
-
699
- const { generateTextWithHorde } = await import(
700
- "./textGenerationWithHorde"
701
  );
 
 
702
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
703
 
704
  expect(updateResponse).toHaveBeenCalledWith("Top model answer");
@@ -706,10 +655,8 @@ describe("textGenerationWithHorde", () => {
706
  });
707
 
708
  it("still retries with any model when one job faults and the other cannot take the job", async () => {
709
- routeHordeFetch({
710
- workers: [{ models: ["m-a"], max_length: 1024 }],
711
- monthStats: { "m-a": 10 },
712
- statusResponder: perJobResponder({
713
  // The faulted job is first in submission order, so picking the
714
  // first error would hide the "not possible" that the retry needs.
715
  "gen-1": () => ({ done: true, faulted: true }),
@@ -717,11 +664,9 @@ describe("textGenerationWithHorde", () => {
717
  "gen-3": () => doneResponse,
718
  "gen-4": () => doneResponse,
719
  }),
720
- });
721
-
722
- const { generateTextWithHorde } = await import(
723
- "./textGenerationWithHorde"
724
  );
 
 
725
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
726
 
727
  expect(generationRequestBodies()).toHaveLength(4);
@@ -729,10 +674,8 @@ describe("textGenerationWithHorde", () => {
729
 
730
  it("reports an interrupt during the race and submits no retry", async () => {
731
  const controller = new AbortController();
732
- routeHordeFetch({
733
- workers: [{ models: ["m-a"], max_length: 1024 }],
734
- monthStats: { "m-a": 10 },
735
- statusResponder: perJobResponder({
736
  "gen-1": () => ({ done: true, is_possible: false }),
737
  "gen-2": (poll) => {
738
  // The user presses Stop while this job is still queued, after its
@@ -741,11 +684,9 @@ describe("textGenerationWithHorde", () => {
741
  return pendingResponse;
742
  },
743
  }),
744
- });
745
-
746
- const { generateTextWithHorde } = await import(
747
- "./textGenerationWithHorde"
748
  );
 
 
749
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
750
  "Generation interrupted",
751
  );
@@ -754,31 +695,25 @@ describe("textGenerationWithHorde", () => {
754
  });
755
 
756
  it("cancels the losing job and not the winner", async () => {
757
- routeHordeFetch({
758
- workers: [{ models: ["m-a"], max_length: 1024 }],
759
- monthStats: { "m-a": 10 },
760
- statusResponder: perJobResponder({
761
  "gen-1": () => doneResponse,
762
  "gen-2": () => pendingResponse,
763
  }),
764
- });
765
-
766
- const { generateTextWithHorde } = await import(
767
- "./textGenerationWithHorde"
768
  );
 
 
769
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
770
  expect(cancelledIds()).toEqual(["gen-2"]);
771
  });
772
 
773
  it("cancels the loser whose submit was still in flight when the race ended", async () => {
774
- routeHordeFetch({
775
- workers: [{ models: ["m-a"], max_length: 1024 }],
776
- monthStats: { "m-a": 10 },
777
- statusResponder: perJobResponder({
778
  "gen-1": () => doneResponse,
779
  "gen-2": () => pendingResponse,
780
  }),
781
- });
782
  const routed = mockFetch.getMockImplementation();
783
  let submits = 0;
784
  let releaseSecondSubmit: () => void = () => {};
@@ -798,9 +733,7 @@ describe("textGenerationWithHorde", () => {
798
  },
799
  );
800
 
801
- const { generateTextWithHorde } = await import(
802
- "./textGenerationWithHorde"
803
- );
804
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
805
  expect(cancelledIds()).toEqual([]);
806
 
@@ -809,58 +742,39 @@ describe("textGenerationWithHorde", () => {
809
  });
810
 
811
  it("returns the winner's answer without waiting for the loser's cancel", async () => {
812
- routeHordeFetch({
813
- workers: [{ models: ["m-a"], max_length: 1024 }],
814
- monthStats: { "m-a": 10 },
815
- statusResponder: perJobResponder({
816
  "gen-1": () => doneResponse,
817
  "gen-2": () => pendingResponse,
818
  }),
819
- });
820
  const routed = mockFetch.getMockImplementation();
821
  // A Horde that never answers the DELETE.
822
  mockFetch.mockImplementation((url: string, init?: { method?: string }) =>
823
  init?.method === "DELETE" ? new Promise(() => {}) : routed?.(url, init),
824
  );
825
 
826
- const { generateTextWithHorde } = await import(
827
- "./textGenerationWithHorde"
828
- );
829
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
830
  expect(cancelledIds()).toEqual(["gen-2"]);
831
  });
832
 
833
  it("cancels both jobs when the race fails", async () => {
834
- routeHordeFetch({
835
- workers: [{ models: ["m-a"], max_length: 1024 }],
836
- monthStats: { "m-a": 10 },
837
- statusResponder: () => ({ done: true, faulted: true }),
838
- });
839
-
840
- const { generateTextWithHorde } = await import(
841
- "./textGenerationWithHorde"
842
- );
843
- await expect(generateTextWithHorde()).rejects.toThrow(
844
- "Generation failed",
845
- );
846
  expect(cancelledIds().sort()).toEqual(["gen-1", "gen-2"]);
847
  });
848
 
849
  it("cancels the first round before submitting the fallback round", async () => {
850
- routeHordeFetch({
851
- workers: [{ models: ["m-a"], max_length: 1024 }],
852
- monthStats: { "m-a": 10 },
853
- statusResponder: perJobResponder({
854
  "gen-1": () => ({ done: true, is_possible: false }),
855
  "gen-2": () => ({ done: true, is_possible: false }),
856
  "gen-3": () => doneResponse,
857
  "gen-4": () => pendingResponse,
858
  }),
859
- });
860
-
861
- const { generateTextWithHorde } = await import(
862
- "./textGenerationWithHorde"
863
  );
 
 
864
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
865
 
866
  const calls = mockFetch.mock.calls.map(([url, init]) =>
@@ -880,15 +794,9 @@ describe("textGenerationWithHorde", () => {
880
  });
881
 
882
  it("reuses the cached ranking for the next generation", async () => {
883
- routeHordeFetch({
884
- workers: [{ models: ["m-a"], max_length: 1024 }],
885
- monthStats: { "m-a": 10 },
886
- statusResponder: () => doneResponse,
887
- });
888
 
889
- const { generateTextWithHorde } = await import(
890
- "./textGenerationWithHorde"
891
- );
892
  await generateTextWithHorde();
893
  await generateTextWithHorde();
894
 
@@ -907,16 +815,10 @@ describe("textGenerationWithHorde", () => {
907
  });
908
 
909
  it("refetches the ranking after the cache expires", async () => {
910
- routeHordeFetch({
911
- workers: [{ models: ["m-a"], max_length: 1024 }],
912
- monthStats: { "m-a": 10 },
913
- statusResponder: () => doneResponse,
914
- });
915
  const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);
916
 
917
- const { generateTextWithHorde } = await import(
918
- "./textGenerationWithHorde"
919
- );
920
  await generateTextWithHorde();
921
  nowSpy.mockReturnValue(5 * 60 * 1000 + 1);
922
  await generateTextWithHorde();
 
24
  sleep: vi.fn().mockResolvedValue(undefined),
25
  }));
26
 
27
+ vi.mock("./textGenerationUtilities", async (importOriginal) =>
28
+ (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock({
 
 
 
 
 
 
 
29
  getDefaultChatMessages: vi
30
  .fn()
31
  .mockReturnValue([{ role: "user", content: "hi" }]),
32
+ })(importOriginal),
33
+ );
 
34
 
35
  const mockFetch = vi.fn();
36
  vi.stubGlobal("fetch", mockFetch);
 
50
  vi.mocked(getSettings).mockReturnValue({ ...defaultSettings, ...overrides });
51
  }
52
 
53
+ /** Queues a submit, one in-progress poll, and a final empty reply. */
54
+ function queueInterruptedPolling(id: string) {
55
+ mockFetch
56
+ .mockResolvedValueOnce(jsonResponse({ id }))
57
+ .mockResolvedValueOnce(
58
+ jsonResponse({ done: false, is_possible: true, generations: [] }),
59
+ )
60
+ .mockResolvedValueOnce(jsonResponse({}));
61
+ }
62
+
63
+ function abortWhenGenerating() {
64
+ const controller = new AbortController();
65
+ vi.mocked(updateTextGenerationState).mockImplementation((next) => {
66
+ if (next === "generating") controller.abort();
67
+ });
68
+ return controller;
69
+ }
70
+
71
+ /** Loads the generator under test, after the fetch routes are in place. */
72
+ async function loadHordeGenerator() {
73
+ return (await import("./textGenerationWithHorde")).generateTextWithHorde;
74
+ }
75
+
76
  describe("textGenerationWithHorde", () => {
77
  beforeEach(() => {
78
  vi.clearAllMocks();
 
83
 
84
  describe("generateTextWithHorde", () => {
85
  it("starts a generation, polls until done, and streams the response", async () => {
86
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
87
 
88
  mockFetch
89
  .mockResolvedValueOnce(jsonResponse({ id: "gen-1" }))
 
116
  });
117
 
118
  it("throws ChatGenerationError when the generation is faulted", async () => {
119
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
120
 
121
  mockFetch
122
  .mockResolvedValueOnce(jsonResponse({ id: "gen-2" }))
 
128
  });
129
 
130
  it("throws ChatGenerationError when the model reports generation is not possible", async () => {
131
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
132
 
133
  mockFetch
134
  .mockResolvedValueOnce(jsonResponse({ id: "gen-3" }))
 
142
  });
143
 
144
  it("stops polling and publishes nothing once the user interrupts generation", async () => {
145
+ const controller = abortWhenGenerating();
146
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
 
 
 
147
 
148
  mockFetch
149
  .mockResolvedValueOnce(jsonResponse({ id: "gen-4" }))
 
165
  });
166
 
167
  it('submits nothing and never enters "generating" once a newer search aborted it', async () => {
168
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
169
  const controller = new AbortController();
170
  controller.abort();
171
 
 
179
  it("can be interrupted once it is generating, and cancels the queued job", async () => {
180
  // The UI only offers Stop while the state is "generating", so the
181
  // interrupt can only happen after the engine has entered it.
182
+ const controller = abortWhenGenerating();
183
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
 
 
 
184
 
185
+ queueInterruptedPolling("gen-queued");
 
 
 
 
 
186
 
187
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
188
  "Generation interrupted",
 
194
  });
195
 
196
  it("cancels the job exactly once when the user interrupts", async () => {
197
+ const controller = abortWhenGenerating();
198
+ const generateTextWithHorde = await loadHordeGenerator();
199
+ queueInterruptedPolling("gen-stop");
 
 
 
 
 
 
 
 
 
 
200
 
201
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
202
  "Generation interrupted",
 
205
  });
206
 
207
  it("cancels a pinned-model job that faults", async () => {
208
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
209
  mockFetch
210
  .mockResolvedValueOnce(jsonResponse({ id: "gen-fault" }))
211
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
 
218
  });
219
 
220
  it("cancels a pinned-model job that the model cannot take", async () => {
221
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
222
  mockFetch
223
  .mockResolvedValueOnce(jsonResponse({ id: "gen-offline" }))
224
  .mockResolvedValueOnce(jsonResponse({ done: true, is_possible: false }))
 
231
  });
232
 
233
  it("does not cancel a job whose answer was returned", async () => {
234
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
235
  mockFetch
236
  .mockResolvedValueOnce(jsonResponse({ id: "gen-ok" }))
237
  .mockResolvedValueOnce(
 
247
  });
248
 
249
  it("keeps the original error and logs once when the cancel fails", async () => {
250
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
251
  mockFetch
252
  .mockResolvedValueOnce(jsonResponse({ id: "gen-x" }))
253
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
 
267
  });
268
 
269
  it("sends the cancel with a timeout and keepalive", async () => {
270
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
271
  mockFetch
272
  .mockResolvedValueOnce(jsonResponse({ id: "gen-k" }))
273
  .mockResolvedValueOnce(jsonResponse({ done: true, faulted: true }))
 
282
 
283
  it("includes the configured model in the generation request body", async () => {
284
  mockSettings({ hordeModel: "custom-model" });
285
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
286
 
287
  mockFetch
288
  .mockResolvedValueOnce(jsonResponse({ id: "gen-5" }))
 
315
  });
316
 
317
  it("keeps polling through a rate limit and finishes the generation", async () => {
318
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
319
  mockFetch
320
  .mockResolvedValueOnce(jsonResponse({ id: "gen-rate" }))
321
  .mockResolvedValueOnce(
 
329
  });
330
 
331
  it("recovers when a gateway answers a poll with an HTML error page", async () => {
332
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
333
  mockFetch
334
  .mockResolvedValueOnce(jsonResponse({ id: "gen-gateway" }))
335
  .mockResolvedValueOnce(
 
345
  });
346
 
347
  it("gives up on a status check that keeps failing without calling the model impossible", async () => {
348
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
349
  mockFetch
350
  .mockResolvedValueOnce(jsonResponse({ id: "gen-down" }))
351
  .mockImplementation(async () =>
 
368
  });
369
 
370
  it("stops at once when the job is gone, with the server's message", async () => {
371
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
372
  mockFetch
373
  .mockResolvedValueOnce(jsonResponse({ id: "gen-gone" }))
374
  .mockResolvedValueOnce(
 
384
  });
385
 
386
  it("rejects a finished generation that carries no text", async () => {
387
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
388
  mockFetch
389
  .mockResolvedValueOnce(jsonResponse({ id: "gen-empty" }))
390
  .mockResolvedValueOnce(
 
401
  });
402
 
403
  it("reports the server's reason when the job is refused at submit", async () => {
404
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
405
  mockFetch.mockResolvedValueOnce(
406
  jsonResponse({ message: "Invalid API key" }, 401),
407
  );
 
481
  );
482
  }
483
 
484
+ /** Routes a worker whose job faults and expects the generation to reject. */
485
+ async function expectFaultedGenerationRejects() {
486
+ routeSingleWorker(() => ({ done: true, faulted: true }));
487
+
488
+ const generateTextWithHorde = await loadHordeGenerator();
489
+ await expect(generateTextWithHorde()).rejects.toThrow(
490
+ "Generation failed",
491
+ );
492
+ }
493
+
494
+ /** Runs one generation to its end and returns the generation request bodies. */
495
+ async function generationBodiesAfterOneRun() {
496
+ const generateTextWithHorde = await loadHordeGenerator();
497
+ await generateTextWithHorde();
498
+ return generationRequestBodies();
499
+ }
500
+
501
  function generationRequestBodies() {
502
  return mockFetch.mock.calls
503
  .filter(([url]) => String(url).includes("/generate/text/async"))
 
528
  statusResponder: () => doneResponse,
529
  });
530
 
531
+ const bodies = await generationBodiesAfterOneRun();
 
 
 
 
 
532
  expect(bodies).toHaveLength(2);
533
  for (const body of bodies) {
534
  expect(body.models).toEqual(["m-f", "m-e", "m-d", "m-c", "m-b"]);
 
547
  statusResponder: () => doneResponse,
548
  });
549
 
550
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
551
  await generateTextWithHorde();
552
 
553
  for (const body of generationRequestBodies()) {
 
562
  statusResponder: () => doneResponse,
563
  });
564
 
565
+ const bodies = await generationBodiesAfterOneRun();
 
 
 
 
 
566
  expect(bodies).toHaveLength(2);
567
  for (const body of bodies) {
568
  expect(body.models).toBeUndefined();
 
573
  });
574
 
575
  it("retries with any available model when the top models cannot take the job", async () => {
576
+ routeSingleWorker((pollIndex) =>
577
+ pollIndex < 2 ? { done: true, is_possible: false } : doneResponse,
 
 
 
 
 
 
 
578
  );
579
+
580
+ const generateTextWithHorde = await loadHordeGenerator();
581
  await generateTextWithHorde();
582
 
583
  expect(updateResponse).toHaveBeenCalledWith("Top model answer");
 
597
  });
598
 
599
  it("does not submit a second round when the status checks keep failing", async () => {
600
+ routeSingleWorker(() =>
601
+ jsonResponse({ message: "Too many requests" }, 429),
 
 
 
 
 
 
 
602
  );
603
+
604
+ const generateTextWithHorde = await loadHordeGenerator();
605
  await expect(generateTextWithHorde()).rejects.toThrow(
606
  "Too many requests",
607
  );
 
609
  });
610
 
611
  it("does not retry when the generation faults", async () => {
612
+ await expectFaultedGenerationRejects();
613
+ expect(generationRequestBodies()).toHaveLength(2);
614
+ });
615
+
616
+ /** One worker with ten monthly generations, the shape most tests need. */
617
+ function routeSingleWorker(
618
+ statusResponder: (pollIndex: number, url: string) => unknown,
619
+ ) {
620
  routeHordeFetch({
621
  workers: [{ models: ["m-a"], max_length: 1024 }],
622
  monthStats: { "m-a": 10 },
623
+ statusResponder,
624
  });
625
+ }
 
 
 
 
 
 
 
 
626
 
627
  /** Answers each job's polls from its own script, by the job id in the URL. */
628
  function perJobResponder(
 
640
  const pendingResponse = { done: false, is_possible: true, generations: [] };
641
 
642
  it("serves the healthy job when its sibling faults first", async () => {
643
+ routeSingleWorker(
644
+ perJobResponder({
 
 
645
  "gen-1": () => ({ done: true, faulted: true }),
646
  "gen-2": (poll) => (poll === 0 ? pendingResponse : doneResponse),
647
  }),
 
 
 
 
648
  );
649
+
650
+ const generateTextWithHorde = await loadHordeGenerator();
651
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
652
 
653
  expect(updateResponse).toHaveBeenCalledWith("Top model answer");
 
655
  });
656
 
657
  it("still retries with any model when one job faults and the other cannot take the job", async () => {
658
+ routeSingleWorker(
659
+ perJobResponder({
 
 
660
  // The faulted job is first in submission order, so picking the
661
  // first error would hide the "not possible" that the retry needs.
662
  "gen-1": () => ({ done: true, faulted: true }),
 
664
  "gen-3": () => doneResponse,
665
  "gen-4": () => doneResponse,
666
  }),
 
 
 
 
667
  );
668
+
669
+ const generateTextWithHorde = await loadHordeGenerator();
670
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
671
 
672
  expect(generationRequestBodies()).toHaveLength(4);
 
674
 
675
  it("reports an interrupt during the race and submits no retry", async () => {
676
  const controller = new AbortController();
677
+ routeSingleWorker(
678
+ perJobResponder({
 
 
679
  "gen-1": () => ({ done: true, is_possible: false }),
680
  "gen-2": (poll) => {
681
  // The user presses Stop while this job is still queued, after its
 
684
  return pendingResponse;
685
  },
686
  }),
 
 
 
 
687
  );
688
+
689
+ const generateTextWithHorde = await loadHordeGenerator();
690
  await expect(generateTextWithHorde(controller.signal)).rejects.toThrow(
691
  "Generation interrupted",
692
  );
 
695
  });
696
 
697
  it("cancels the losing job and not the winner", async () => {
698
+ routeSingleWorker(
699
+ perJobResponder({
 
 
700
  "gen-1": () => doneResponse,
701
  "gen-2": () => pendingResponse,
702
  }),
 
 
 
 
703
  );
704
+
705
+ const generateTextWithHorde = await loadHordeGenerator();
706
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
707
  expect(cancelledIds()).toEqual(["gen-2"]);
708
  });
709
 
710
  it("cancels the loser whose submit was still in flight when the race ended", async () => {
711
+ routeSingleWorker(
712
+ perJobResponder({
 
 
713
  "gen-1": () => doneResponse,
714
  "gen-2": () => pendingResponse,
715
  }),
716
+ );
717
  const routed = mockFetch.getMockImplementation();
718
  let submits = 0;
719
  let releaseSecondSubmit: () => void = () => {};
 
733
  },
734
  );
735
 
736
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
737
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
738
  expect(cancelledIds()).toEqual([]);
739
 
 
742
  });
743
 
744
  it("returns the winner's answer without waiting for the loser's cancel", async () => {
745
+ routeSingleWorker(
746
+ perJobResponder({
 
 
747
  "gen-1": () => doneResponse,
748
  "gen-2": () => pendingResponse,
749
  }),
750
+ );
751
  const routed = mockFetch.getMockImplementation();
752
  // A Horde that never answers the DELETE.
753
  mockFetch.mockImplementation((url: string, init?: { method?: string }) =>
754
  init?.method === "DELETE" ? new Promise(() => {}) : routed?.(url, init),
755
  );
756
 
757
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
758
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
759
  expect(cancelledIds()).toEqual(["gen-2"]);
760
  });
761
 
762
  it("cancels both jobs when the race fails", async () => {
763
+ await expectFaultedGenerationRejects();
 
 
 
 
 
 
 
 
 
 
 
764
  expect(cancelledIds().sort()).toEqual(["gen-1", "gen-2"]);
765
  });
766
 
767
  it("cancels the first round before submitting the fallback round", async () => {
768
+ routeSingleWorker(
769
+ perJobResponder({
 
 
770
  "gen-1": () => ({ done: true, is_possible: false }),
771
  "gen-2": () => ({ done: true, is_possible: false }),
772
  "gen-3": () => doneResponse,
773
  "gen-4": () => pendingResponse,
774
  }),
 
 
 
 
775
  );
776
+
777
+ const generateTextWithHorde = await loadHordeGenerator();
778
  await expect(generateTextWithHorde()).resolves.toBe("Top model answer");
779
 
780
  const calls = mockFetch.mock.calls.map(([url, init]) =>
 
794
  });
795
 
796
  it("reuses the cached ranking for the next generation", async () => {
797
+ routeSingleWorker(() => doneResponse);
 
 
 
 
798
 
799
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
800
  await generateTextWithHorde();
801
  await generateTextWithHorde();
802
 
 
815
  });
816
 
817
  it("refetches the ranking after the cache expires", async () => {
818
+ routeSingleWorker(() => doneResponse);
 
 
 
 
819
  const nowSpy = vi.spyOn(Date, "now").mockReturnValue(0);
820
 
821
+ const generateTextWithHorde = await loadHordeGenerator();
 
 
822
  await generateTextWithHorde();
823
  nowSpy.mockReturnValue(5 * 60 * 1000 + 1);
824
  await generateTextWithHorde();
client/modules/textGenerationWithInternalApi.test.ts CHANGED
@@ -23,22 +23,14 @@ vi.mock("./systemPrompt", () => ({
23
  getSystemPrompt: vi.fn().mockReturnValue("system prompt"),
24
  }));
25
 
26
- // canStartResponding/getFormattedSearchResults depend on pubSub state we
27
- // don't want to drive here; ChatGenerationError has no such dependency, so
28
- // keep it real so `instanceof` checks against it still work.
29
- vi.mock("./textGenerationUtilities", async (importOriginal) => {
30
- const actual =
31
- await importOriginal<typeof import("./textGenerationUtilities")>();
32
- return {
33
- ...actual,
34
- canStartResponding: vi.fn().mockResolvedValue(undefined),
35
- getFormattedSearchResults: vi.fn().mockReturnValue("None."),
36
  getDefaultChatCompletionCreateParamsStreaming: vi.fn().mockReturnValue({
37
  max_tokens: 1000,
38
  temperature: 0.35,
39
  }),
40
- };
41
- });
42
 
43
  const mockFetch = vi.fn();
44
  vi.stubGlobal("fetch", mockFetch);
@@ -63,33 +55,37 @@ function streamResponse(chunks: Array<string | Uint8Array>, status = 200) {
63
  }
64
 
65
  /**
66
- * A response whose stream sends `chunks` and then stays open, as a stalled
67
- * upstream does, with a spy on the stream's cancel.
 
68
  */
69
- function openStreamResponse(chunks: string[]) {
70
  const cancel = vi.fn();
71
  const encoder = new TextEncoder();
72
  const body = new ReadableStream({
73
  start(controller) {
74
  for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
 
75
  },
76
  cancel,
77
  });
78
  return { response: new Response(body), cancel };
79
  }
80
 
 
 
 
 
81
  /** A closed stream, with a spy on its cancel. */
82
  function closedStreamResponse(chunks: string[]) {
83
- const cancel = vi.fn();
84
- const encoder = new TextEncoder();
85
- const body = new ReadableStream({
86
- start(controller) {
87
- for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
88
- controller.close();
89
- },
90
- cancel,
91
- });
92
- return { response: new Response(body), cancel };
93
  }
94
 
95
  function fetchSignal(): AbortSignal {
@@ -226,10 +222,7 @@ describe("textGenerationWithInternalApi", () => {
226
  ]),
227
  ),
228
  );
229
- const controller = new AbortController();
230
- vi.mocked(updateResponse).mockImplementationOnce(() =>
231
- controller.abort(),
232
- );
233
 
234
  await expect(
235
  generateTextWithInternalApi(controller.signal),
@@ -344,10 +337,7 @@ describe("textGenerationWithInternalApi", () => {
344
  'data: {"choices":[{"delta":{"content":"partial"}}]}\n',
345
  ]);
346
  mockFetch.mockResolvedValueOnce(stream.response);
347
- const controller = new AbortController();
348
- vi.mocked(updateResponse).mockImplementationOnce(() =>
349
- controller.abort(),
350
- );
351
 
352
  await expect(
353
  generateTextWithInternalApi(controller.signal),
 
23
  getSystemPrompt: vi.fn().mockReturnValue("system prompt"),
24
  }));
25
 
26
+ vi.mock("./textGenerationUtilities", async (importOriginal) =>
27
+ (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock({
 
 
 
 
 
 
 
 
28
  getDefaultChatCompletionCreateParamsStreaming: vi.fn().mockReturnValue({
29
  max_tokens: 1000,
30
  temperature: 0.35,
31
  }),
32
+ })(importOriginal),
33
+ );
34
 
35
  const mockFetch = vi.fn();
36
  vi.stubGlobal("fetch", mockFetch);
 
55
  }
56
 
57
  /**
58
+ * A response whose stream sends `chunks`, with a spy on the stream's cancel.
59
+ * `close` ends the stream, as a completed upstream does; leaving it open
60
+ * stands in for a stalled one.
61
  */
62
+ function streamBody(chunks: string[], close: boolean) {
63
  const cancel = vi.fn();
64
  const encoder = new TextEncoder();
65
  const body = new ReadableStream({
66
  start(controller) {
67
  for (const chunk of chunks) controller.enqueue(encoder.encode(chunk));
68
+ if (close) controller.close();
69
  },
70
  cancel,
71
  });
72
  return { response: new Response(body), cancel };
73
  }
74
 
75
+ function openStreamResponse(chunks: string[]) {
76
+ return streamBody(chunks, false);
77
+ }
78
+
79
  /** A closed stream, with a spy on its cancel. */
80
  function closedStreamResponse(chunks: string[]) {
81
+ return streamBody(chunks, true);
82
+ }
83
+
84
+ /** Makes the first publish abort the generation, and returns its controller. */
85
+ function abortOnFirstPublish() {
86
+ const controller = new AbortController();
87
+ vi.mocked(updateResponse).mockImplementationOnce(() => controller.abort());
88
+ return controller;
 
 
89
  }
90
 
91
  function fetchSignal(): AbortSignal {
 
222
  ]),
223
  ),
224
  );
225
+ const controller = abortOnFirstPublish();
 
 
 
226
 
227
  await expect(
228
  generateTextWithInternalApi(controller.signal),
 
337
  'data: {"choices":[{"delta":{"content":"partial"}}]}\n',
338
  ]);
339
  mockFetch.mockResolvedValueOnce(stream.response);
340
+ const controller = abortOnFirstPublish();
 
 
 
341
 
342
  await expect(
343
  generateTextWithInternalApi(controller.signal),
client/modules/textGenerationWithWllama.test.ts CHANGED
@@ -48,15 +48,11 @@ vi.mock("./systemPrompt", () => ({
48
  getSystemPrompt: vi.fn().mockReturnValue("system"),
49
  }));
50
 
51
- vi.mock("./textGenerationUtilities", async (importOriginal) => {
52
- const actual =
53
- await importOriginal<typeof import("./textGenerationUtilities")>();
54
- return {
55
- ...actual,
56
- canStartResponding: vi.fn().mockResolvedValue(undefined),
57
- getFormattedSearchResults: vi.fn().mockReturnValue("None."),
58
- };
59
- });
60
 
61
  vi.mock("./webGpu", () => ({ webGpuSupport: Promise.resolve(false) }));
62
 
 
48
  getSystemPrompt: vi.fn().mockReturnValue("system"),
49
  }));
50
 
51
+ vi.mock("./textGenerationUtilities", async (importOriginal) =>
52
+ (await import("./textGenerationTestUtils")).textGenerationUtilitiesMock()(
53
+ importOriginal,
54
+ ),
55
+ );
 
 
 
 
56
 
57
  vi.mock("./webGpu", () => ({ webGpuSupport: Promise.resolve(false) }));
58
 
client/modules/textToSpeech.test.ts CHANGED
@@ -130,6 +130,73 @@ function createFakeWorker() {
130
  return worker;
131
  }
132
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  let spoken: string[] = [];
134
  let spokenLanguages: string[] = [];
135
  let createdObjectUrls = 0;
@@ -239,21 +306,15 @@ describe("splitIntoSentences", () => {
239
 
240
  describe("speak", () => {
241
  it("reads the answer with the local engine when it works", async () => {
242
- const worker = createFakeWorker();
243
- tts.setWorkerFactory(() => worker as unknown as Worker);
244
-
245
- const speaking = tts.speak("Hello there.");
246
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
247
 
248
  expect(worker.sent[0]).toEqual({
249
  sentences: ["Hello there."],
250
  voiceId: "en_US-lessac-high",
251
  });
252
 
253
- worker.onmessage?.({
254
- data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
255
- });
256
- worker.onmessage?.({ data: { type: "done" } });
257
 
258
  await speaking;
259
  expect(createdObjectUrls).toBe(1);
@@ -265,15 +326,9 @@ describe("speak", () => {
265
  });
266
 
267
  it("falls back to the system voice when the local engine cannot load", async () => {
268
- const worker = createFakeWorker();
269
- tts.setWorkerFactory(() => worker as unknown as Worker);
270
-
271
- const speaking = tts.speak("Hello there.");
272
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
273
 
274
- worker.onmessage?.({
275
- data: { type: "error", message: "model download failed" },
276
- });
277
 
278
  await speaking;
279
  expect(spoken).toEqual(["Hello there."]);
@@ -300,8 +355,7 @@ describe("speak", () => {
300
 
301
  it("uses the system engine directly when it is selected", async () => {
302
  settings.textToSpeechEngine = "system";
303
- const worker = createFakeWorker();
304
- tts.setWorkerFactory(() => worker as unknown as Worker);
305
 
306
  await tts.speak("Hello there.");
307
 
@@ -310,8 +364,7 @@ describe("speak", () => {
310
  });
311
 
312
  it("creates no utterance and never enters the speaking state for an open reasoning block", async () => {
313
- const worker = createFakeWorker();
314
- tts.setWorkerFactory(() => worker as unknown as Worker);
315
 
316
  await tts.speak("<think>The user wants the capital. Maybe Paris?");
317
 
@@ -321,65 +374,27 @@ describe("speak", () => {
321
  });
322
 
323
  it("does not fall back after audio has started", async () => {
324
- const worker = createFakeWorker();
325
- tts.setWorkerFactory(() => worker as unknown as Worker);
326
-
327
- const speaking = tts.speak("One. Two.");
328
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
329
-
330
- worker.onmessage?.({
331
- data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
332
- });
333
- await vi.waitFor(() => expect(createdObjectUrls).toBe(1));
334
- worker.onmessage?.({
335
- data: { type: "error", message: "synthesis died halfway" },
336
- });
337
 
338
- await speaking;
339
  expect(spoken).toEqual([]);
340
  });
341
 
342
  it("falls back when every synthesized chunk fails to play", async () => {
343
- vi.stubGlobal(
344
- "Audio",
345
- class {
346
- onended: (() => void) | null = null;
347
- onerror: (() => void) | null = null;
348
- pause = vi.fn();
349
- removeAttribute = vi.fn();
350
- src = "";
351
- play() {
352
- return Promise.reject(new Error("autoplay blocked"));
353
- }
354
- },
355
- );
356
-
357
- const worker = createFakeWorker();
358
- tts.setWorkerFactory(() => worker as unknown as Worker);
359
 
360
- const speaking = tts.speak("Hello there.");
361
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
362
-
363
- worker.onmessage?.({
364
- data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
365
- });
366
- worker.onmessage?.({ data: { type: "done" } });
367
 
368
  await speaking;
369
  expect(spoken).toEqual(["Hello there."]);
370
  });
371
 
372
  it("detaches the audio handlers before clearing the source", async () => {
373
- const worker = createFakeWorker();
374
- tts.setWorkerFactory(() => worker as unknown as Worker);
375
-
376
- const speaking = tts.speak("Hello there.");
377
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
378
 
379
- worker.onmessage?.({
380
- data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
381
- });
382
- worker.onmessage?.({ data: { type: "done" } });
383
  await speaking;
384
 
385
  // A real element can still fire `error` during teardown; a still-attached
@@ -388,36 +403,61 @@ describe("speak", () => {
388
  });
389
 
390
  it("falls back when the worker fails and no chunk was ever audible", async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
391
  vi.stubGlobal(
392
  "Audio",
393
  class {
394
  onended: (() => void) | null = null;
395
  onerror: (() => void) | null = null;
 
 
396
  pause = vi.fn();
397
  removeAttribute = vi.fn();
398
- src = "";
399
- play() {
400
- return Promise.reject(new Error("autoplay blocked"));
401
- }
402
  },
403
  );
 
404
 
405
- const worker = createFakeWorker();
406
- tts.setWorkerFactory(() => worker as unknown as Worker);
407
-
408
- const speaking = tts.speak("One. Two.");
409
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
410
-
411
- worker.onmessage?.({
412
- data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
413
- });
414
  await vi.waitFor(() => expect(createdObjectUrls).toBe(1));
415
- worker.onmessage?.({
416
- data: { type: "error", message: "synthesis died halfway" },
417
- });
418
 
419
  await speaking;
420
- expect(spoken).toEqual(["One. Two."]);
 
 
 
421
  });
422
 
423
  it("honours a stop pressed while the voice catalogue is still loading", async () => {
@@ -428,8 +468,7 @@ describe("speak", () => {
428
  }),
429
  );
430
 
431
- const worker = createFakeWorker();
432
- tts.setWorkerFactory(() => worker as unknown as Worker);
433
 
434
  const speaking = tts.speak("Hello there.");
435
  await vi.waitFor(() =>
@@ -447,58 +486,35 @@ describe("speak", () => {
447
 
448
  it("picks the local voice for the answer's language, not the browser's", async () => {
449
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
450
- const worker = createFakeWorker();
451
- tts.setWorkerFactory(() => worker as unknown as Worker);
452
-
453
- void tts.speak(portugueseAnswer);
454
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
455
 
456
- expect(worker.sent[0].voiceId).toBe("pt_BR-faber-medium");
457
  });
458
 
459
  it("prefers a medium voice over a low one of the same language", async () => {
460
  mockVoices.mockResolvedValue([englishLowVoice, englishMediumVoice]);
461
- const worker = createFakeWorker();
462
- tts.setWorkerFactory(() => worker as unknown as Worker);
463
 
464
- void tts.speak("Hello there.");
465
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
466
-
467
- expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium");
468
  });
469
 
470
  it("prefers a medium voice over a high one, which is a bigger download", async () => {
471
  mockVoices.mockResolvedValue([englishVoice, englishMediumVoice]);
472
- const worker = createFakeWorker();
473
- tts.setWorkerFactory(() => worker as unknown as Worker);
474
-
475
- void tts.speak("Hello there.");
476
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
477
 
478
- expect(worker.sent[0].voiceId).toBe("en_GB-alan-medium");
479
  });
480
 
481
  it("prefers the browser's region among voices of the same quality", async () => {
482
  mockVoices.mockResolvedValue([englishMediumVoice, americanMediumVoice]);
483
- const worker = createFakeWorker();
484
- tts.setWorkerFactory(() => worker as unknown as Worker);
485
 
486
- void tts.speak("Hello there.");
487
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
488
-
489
- expect(worker.sent[0].voiceId).toBe("en_US-amy-medium");
490
  });
491
 
492
  it("prefers a low voice over an x-low one of the same language", async () => {
493
  vi.stubGlobal("navigator", { language: "vi-VN" });
494
  mockVoices.mockResolvedValue([vietnameseXLowVoice, vietnameseLowVoice]);
495
- const worker = createFakeWorker();
496
- tts.setWorkerFactory(() => worker as unknown as Worker);
497
-
498
- void tts.speak(vietnameseAnswer);
499
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
500
 
501
- expect(worker.sent[0].voiceId).toBe("vi_VN-25hours_single-low");
 
 
502
  });
503
 
504
  it("keeps the catalogue order when the answer's language has no region", async () => {
@@ -506,40 +522,27 @@ describe("speak", () => {
506
  portugueseFromPortugalVoice,
507
  portugueseVoice,
508
  ]);
509
- const worker = createFakeWorker();
510
- tts.setWorkerFactory(() => worker as unknown as Worker);
511
-
512
- void tts.speak(portugueseAnswer);
513
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
514
 
515
- expect(worker.sent[0].voiceId).toBe("pt_PT-tugรฃo-medium");
516
  });
517
 
518
  it("keeps a chosen voice whatever the answer's language", async () => {
519
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
520
  settings.selectedVoiceId = "piper:en_US-lessac-high";
521
- const worker = createFakeWorker();
522
- tts.setWorkerFactory(() => worker as unknown as Worker);
523
-
524
- void tts.speak(portugueseAnswer);
525
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
526
 
527
- expect(worker.sent[0].voiceId).toBe("en_US-lessac-high");
528
  });
529
 
530
  it("keeps the browser language when the detector cannot recognize it", async () => {
531
  // franc-min has no Danish and reads this sentence as Swedish.
532
  vi.stubGlobal("navigator", { language: "da-DK" });
533
  mockVoices.mockResolvedValue([swedishVoice, danishVoice]);
534
- const worker = createFakeWorker();
535
- tts.setWorkerFactory(() => worker as unknown as Worker);
536
 
537
- void tts.speak(
538
- "Eiffeltรฅrnet blev bygget i 1889 til verdensudstillingen i Paris og er omkring 330 meter hรธjt.",
539
- );
540
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
541
-
542
- expect(worker.sent[0].voiceId).toBe("da_DK-talesyntese-medium");
543
  });
544
 
545
  it("uses the browser language when the detector fails to load", async () => {
@@ -549,13 +552,8 @@ describe("speak", () => {
549
  try {
550
  tts = await import("./textToSpeech");
551
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
552
- const worker = createFakeWorker();
553
- tts.setWorkerFactory(() => worker as unknown as Worker);
554
 
555
- void tts.speak(portugueseAnswer);
556
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
557
-
558
- expect(worker.sent[0].voiceId).toBe("en_US-lessac-high");
559
  expect(mockAddLogEntry).toHaveBeenCalledWith(
560
  expect.stringContaining("Could not detect the answer's language"),
561
  );
@@ -573,11 +571,7 @@ describe("speak", () => {
573
  });
574
 
575
  it("stops playback without falling back to the system voice", async () => {
576
- const worker = createFakeWorker();
577
- tts.setWorkerFactory(() => worker as unknown as Worker);
578
-
579
- const speaking = tts.speak("Hello there.");
580
- await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
581
 
582
  tts.stopSpeaking();
583
  await speaking;
@@ -590,8 +584,7 @@ describe("speak", () => {
590
  describe("no speech engine at all", () => {
591
  it("resolves and logs when the local engine failed and there are no OS voices", async () => {
592
  mockVoices.mockRejectedValue(new Error("offline"));
593
- vi.stubGlobal("speechSynthesis", undefined);
594
- self.speechSynthesis = undefined as unknown as SpeechSynthesis;
595
 
596
  await tts.speak("Hello there.");
597
 
@@ -607,8 +600,7 @@ describe("no speech engine at all", () => {
607
 
608
  it("lists no voices instead of throwing", async () => {
609
  mockVoices.mockRejectedValue(new Error("offline"));
610
- vi.stubGlobal("speechSynthesis", undefined);
611
- self.speechSynthesis = undefined as unknown as SpeechSynthesis;
612
 
613
  await expect(tts.listVoices("en-US", "system")).resolves.toEqual([]);
614
  });
 
130
  return worker;
131
  }
132
 
133
+ type FakeWorker = ReturnType<typeof createFakeWorker>;
134
+
135
+ /** Installs a fake worker as the local engine. */
136
+ function installFakeWorker(): FakeWorker {
137
+ const worker = createFakeWorker();
138
+ tts.setWorkerFactory(() => worker as unknown as Worker);
139
+ return worker;
140
+ }
141
+
142
+ /** Starts reading `text` with the local engine and waits for its request. */
143
+ async function startLocalSpeech(text: string) {
144
+ const worker = installFakeWorker();
145
+ const speaking = tts.speak(text);
146
+ await vi.waitFor(() => expect(worker.sent).toHaveLength(1));
147
+ return { worker, speaking };
148
+ }
149
+
150
+ /** The local voice the engine asks for when reading `text`. */
151
+ async function localVoiceFor(text: string): Promise<string> {
152
+ return (await startLocalSpeech(text)).worker.sent[0].voiceId;
153
+ }
154
+
155
+ /** Reads `text` locally; the worker sends one chunk, then fails. */
156
+ async function speakUntilWorkerFailsAfterFirstChunk(text: string) {
157
+ const { worker, speaking } = await startLocalSpeech(text);
158
+ sendAudioChunk(worker);
159
+ await vi.waitFor(() => expect(createdObjectUrls).toBe(1));
160
+ sendError(worker, "synthesis died halfway");
161
+ await speaking;
162
+ }
163
+
164
+ function sendAudioChunk(worker: FakeWorker) {
165
+ worker.onmessage?.({
166
+ data: { type: "audio", index: 0, buffer: new ArrayBuffer(8) },
167
+ });
168
+ }
169
+
170
+ function sendDone(worker: FakeWorker) {
171
+ worker.onmessage?.({ data: { type: "done" } });
172
+ }
173
+
174
+ function sendError(worker: FakeWorker, message: string) {
175
+ worker.onmessage?.({ data: { type: "error", message } });
176
+ }
177
+
178
+ /** An Audio element whose playback is always refused. */
179
+ function stubUnplayableAudio() {
180
+ vi.stubGlobal(
181
+ "Audio",
182
+ class {
183
+ onended: (() => void) | null = null;
184
+ onerror: (() => void) | null = null;
185
+ pause = vi.fn();
186
+ removeAttribute = vi.fn();
187
+ src = "";
188
+ play() {
189
+ return Promise.reject(new Error("autoplay blocked"));
190
+ }
191
+ },
192
+ );
193
+ }
194
+
195
+ function removeSystemVoices() {
196
+ vi.stubGlobal("speechSynthesis", undefined);
197
+ self.speechSynthesis = undefined as unknown as SpeechSynthesis;
198
+ }
199
+
200
  let spoken: string[] = [];
201
  let spokenLanguages: string[] = [];
202
  let createdObjectUrls = 0;
 
306
 
307
  describe("speak", () => {
308
  it("reads the answer with the local engine when it works", async () => {
309
+ const { worker, speaking } = await startLocalSpeech("Hello there.");
 
 
 
 
310
 
311
  expect(worker.sent[0]).toEqual({
312
  sentences: ["Hello there."],
313
  voiceId: "en_US-lessac-high",
314
  });
315
 
316
+ sendAudioChunk(worker);
317
+ sendDone(worker);
 
 
318
 
319
  await speaking;
320
  expect(createdObjectUrls).toBe(1);
 
326
  });
327
 
328
  it("falls back to the system voice when the local engine cannot load", async () => {
329
+ const { worker, speaking } = await startLocalSpeech("Hello there.");
 
 
 
 
330
 
331
+ sendError(worker, "model download failed");
 
 
332
 
333
  await speaking;
334
  expect(spoken).toEqual(["Hello there."]);
 
355
 
356
  it("uses the system engine directly when it is selected", async () => {
357
  settings.textToSpeechEngine = "system";
358
+ const worker = installFakeWorker();
 
359
 
360
  await tts.speak("Hello there.");
361
 
 
364
  });
365
 
366
  it("creates no utterance and never enters the speaking state for an open reasoning block", async () => {
367
+ const worker = installFakeWorker();
 
368
 
369
  await tts.speak("<think>The user wants the capital. Maybe Paris?");
370
 
 
374
  });
375
 
376
  it("does not fall back after audio has started", async () => {
377
+ await speakUntilWorkerFailsAfterFirstChunk("One. Two.");
 
 
 
 
 
 
 
 
 
 
 
 
378
 
 
379
  expect(spoken).toEqual([]);
380
  });
381
 
382
  it("falls back when every synthesized chunk fails to play", async () => {
383
+ stubUnplayableAudio();
384
+ const { worker, speaking } = await startLocalSpeech("Hello there.");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
385
 
386
+ sendAudioChunk(worker);
387
+ sendDone(worker);
 
 
 
 
 
388
 
389
  await speaking;
390
  expect(spoken).toEqual(["Hello there."]);
391
  });
392
 
393
  it("detaches the audio handlers before clearing the source", async () => {
394
+ const { worker, speaking } = await startLocalSpeech("Hello there.");
 
 
 
 
395
 
396
+ sendAudioChunk(worker);
397
+ sendDone(worker);
 
 
398
  await speaking;
399
 
400
  // A real element can still fire `error` during teardown; a still-attached
 
403
  });
404
 
405
  it("falls back when the worker fails and no chunk was ever audible", async () => {
406
+ stubUnplayableAudio();
407
+ await speakUntilWorkerFailsAfterFirstChunk("One. Two.");
408
+
409
+ expect(spoken).toEqual(["One. Two."]);
410
+ });
411
+
412
+ it("falls back to the system voice when the worker errors before any audio starts", async () => {
413
+ const { worker, speaking } = await startLocalSpeech("One. Two.");
414
+
415
+ worker.onerror?.();
416
+
417
+ await speaking;
418
+ expect(spoken).toEqual(["One. Two."]);
419
+ expect(mockAddLogEntry).toHaveBeenCalledWith(
420
+ "Local text-to-speech unavailable, using the system voices: The local text-to-speech worker failed to start",
421
+ );
422
+ });
423
+
424
+ it("does not fall back when the worker errors after the first chunk started playing", async () => {
425
+ const { worker, speaking } = await startLocalSpeech("One. Two.");
426
+
427
+ sendAudioChunk(worker);
428
+ await vi.waitFor(() => expect(createdObjectUrls).toBe(1));
429
+ worker.onerror?.();
430
+
431
+ await speaking;
432
+ expect(spoken).toEqual([]);
433
+ expect(mockAddLogEntry).not.toHaveBeenCalledWith(
434
+ expect.stringContaining("Local text-to-speech unavailable"),
435
+ );
436
+ });
437
+
438
+ it("treats a chunk as audible once play() resolves, even without onended firing", async () => {
439
  vi.stubGlobal(
440
  "Audio",
441
  class {
442
  onended: (() => void) | null = null;
443
  onerror: (() => void) | null = null;
444
+ src = "";
445
+ play = () => Promise.resolve();
446
  pause = vi.fn();
447
  removeAttribute = vi.fn();
 
 
 
 
448
  },
449
  );
450
+ const { worker, speaking } = await startLocalSpeech("One. Two.");
451
 
452
+ sendAudioChunk(worker);
 
 
 
 
 
 
 
 
453
  await vi.waitFor(() => expect(createdObjectUrls).toBe(1));
454
+ sendError(worker, "synthesis died halfway");
 
 
455
 
456
  await speaking;
457
+ expect(spoken).toEqual([]);
458
+ expect(mockAddLogEntry).toHaveBeenCalledWith(
459
+ "Local text-to-speech stopped early: synthesis died halfway",
460
+ );
461
  });
462
 
463
  it("honours a stop pressed while the voice catalogue is still loading", async () => {
 
468
  }),
469
  );
470
 
471
+ const worker = installFakeWorker();
 
472
 
473
  const speaking = tts.speak("Hello there.");
474
  await vi.waitFor(() =>
 
486
 
487
  it("picks the local voice for the answer's language, not the browser's", async () => {
488
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
 
 
 
 
 
489
 
490
+ expect(await localVoiceFor(portugueseAnswer)).toBe("pt_BR-faber-medium");
491
  });
492
 
493
  it("prefers a medium voice over a low one of the same language", async () => {
494
  mockVoices.mockResolvedValue([englishLowVoice, englishMediumVoice]);
 
 
495
 
496
+ expect(await localVoiceFor("Hello there.")).toBe("en_GB-alan-medium");
 
 
 
497
  });
498
 
499
  it("prefers a medium voice over a high one, which is a bigger download", async () => {
500
  mockVoices.mockResolvedValue([englishVoice, englishMediumVoice]);
 
 
 
 
 
501
 
502
+ expect(await localVoiceFor("Hello there.")).toBe("en_GB-alan-medium");
503
  });
504
 
505
  it("prefers the browser's region among voices of the same quality", async () => {
506
  mockVoices.mockResolvedValue([englishMediumVoice, americanMediumVoice]);
 
 
507
 
508
+ expect(await localVoiceFor("Hello there.")).toBe("en_US-amy-medium");
 
 
 
509
  });
510
 
511
  it("prefers a low voice over an x-low one of the same language", async () => {
512
  vi.stubGlobal("navigator", { language: "vi-VN" });
513
  mockVoices.mockResolvedValue([vietnameseXLowVoice, vietnameseLowVoice]);
 
 
 
 
 
514
 
515
+ expect(await localVoiceFor(vietnameseAnswer)).toBe(
516
+ "vi_VN-25hours_single-low",
517
+ );
518
  });
519
 
520
  it("keeps the catalogue order when the answer's language has no region", async () => {
 
522
  portugueseFromPortugalVoice,
523
  portugueseVoice,
524
  ]);
 
 
 
 
 
525
 
526
+ expect(await localVoiceFor(portugueseAnswer)).toBe("pt_PT-tugรฃo-medium");
527
  });
528
 
529
  it("keeps a chosen voice whatever the answer's language", async () => {
530
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
531
  settings.selectedVoiceId = "piper:en_US-lessac-high";
 
 
 
 
 
532
 
533
+ expect(await localVoiceFor(portugueseAnswer)).toBe("en_US-lessac-high");
534
  });
535
 
536
  it("keeps the browser language when the detector cannot recognize it", async () => {
537
  // franc-min has no Danish and reads this sentence as Swedish.
538
  vi.stubGlobal("navigator", { language: "da-DK" });
539
  mockVoices.mockResolvedValue([swedishVoice, danishVoice]);
 
 
540
 
541
+ expect(
542
+ await localVoiceFor(
543
+ "Eiffeltรฅrnet blev bygget i 1889 til verdensudstillingen i Paris og er omkring 330 meter hรธjt.",
544
+ ),
545
+ ).toBe("da_DK-talesyntese-medium");
 
546
  });
547
 
548
  it("uses the browser language when the detector fails to load", async () => {
 
552
  try {
553
  tts = await import("./textToSpeech");
554
  mockVoices.mockResolvedValue([englishVoice, portugueseVoice]);
 
 
555
 
556
+ expect(await localVoiceFor(portugueseAnswer)).toBe("en_US-lessac-high");
 
 
 
557
  expect(mockAddLogEntry).toHaveBeenCalledWith(
558
  expect.stringContaining("Could not detect the answer's language"),
559
  );
 
571
  });
572
 
573
  it("stops playback without falling back to the system voice", async () => {
574
+ const { worker, speaking } = await startLocalSpeech("Hello there.");
 
 
 
 
575
 
576
  tts.stopSpeaking();
577
  await speaking;
 
584
  describe("no speech engine at all", () => {
585
  it("resolves and logs when the local engine failed and there are no OS voices", async () => {
586
  mockVoices.mockRejectedValue(new Error("offline"));
587
+ removeSystemVoices();
 
588
 
589
  await tts.speak("Hello there.");
590
 
 
600
 
601
  it("lists no voices instead of throwing", async () => {
602
  mockVoices.mockRejectedValue(new Error("offline"));
603
+ removeSystemVoices();
 
604
 
605
  await expect(tts.listVoices("en-US", "system")).resolves.toEqual([]);
606
  });
client/setupTests.ts CHANGED
@@ -4,19 +4,11 @@
4
  import "fake-indexeddb/auto";
5
  import "@testing-library/jest-dom/vitest";
6
  import { vi } from "vitest";
 
7
 
8
  Object.defineProperty(window, "matchMedia", {
9
  writable: true,
10
- value: vi.fn().mockImplementation((query) => ({
11
- matches: false,
12
- media: query,
13
- onchange: null,
14
- addListener: vi.fn(),
15
- removeListener: vi.fn(),
16
- addEventListener: vi.fn(),
17
- removeEventListener: vi.fn(),
18
- dispatchEvent: vi.fn(),
19
- })),
20
  });
21
 
22
  class ResizeObserverMock {
 
4
  import "fake-indexeddb/auto";
5
  import "@testing-library/jest-dom/vitest";
6
  import { vi } from "vitest";
7
+ import { matchMediaStub } from "./matchMediaStub";
8
 
9
  Object.defineProperty(window, "matchMedia", {
10
  writable: true,
11
+ value: vi.fn().mockImplementation((query) => matchMediaStub(query)),
 
 
 
 
 
 
 
 
 
12
  });
13
 
14
  class ResizeObserverMock {
client/testMocks.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { useSyncExternalStore } from "react";
2
+
3
+ /**
4
+ * The `speechToText` mock the dictation component tests share. Each file calls
5
+ * it from its own `vi.mock`, because those calls are hoisted above the
6
+ * imports and only run their factory later.
7
+ */
8
+ export async function speechToTextMock() {
9
+ const { DictationError: RealDictationError } = await import(
10
+ "@/modules/speechToText"
11
+ );
12
+ return {
13
+ DictationError: RealDictationError,
14
+ getDictationEngine: vi.fn(() => "wasm" as const),
15
+ startDictation: vi.fn(),
16
+ };
17
+ }
18
+
19
+ /** A `notifications` stub that only records what was shown. */
20
+ export function notificationsStub() {
21
+ return { notifications: { show: vi.fn() } };
22
+ }
23
+
24
+ /**
25
+ * `create-pubsub/react` subscribing for real, so a channel written mid-test
26
+ * re-renders the component the way it does in the app.
27
+ */
28
+ export function pubSubReactMock() {
29
+ return {
30
+ usePubSub: (pubSub: [unknown, unknown, unknown]) => {
31
+ const [publish, subscribe, get] = pubSub as [
32
+ unknown,
33
+ (listener: () => void) => () => void,
34
+ () => unknown,
35
+ ];
36
+ const value = useSyncExternalStore(subscribe, get, get);
37
+ return [value, publish];
38
+ },
39
+ };
40
+ }
docs/configuration.md CHANGED
@@ -425,22 +425,22 @@ Client-facing configuration (access keys, inference type, internal API settings)
425
 
426
  ### Build-Time vs Runtime Configuration
427
 
428
- | Value | Resolved At | Notes |
429
- | ---------------------------------- | ----------- | ----------------------------------------------------------------------------------- |
430
- | `VITE_BUILD_DATE_TIME` | Build time | Epoch milliseconds when the build occurred |
431
- | `VITE_COMMIT_SHORT_HASH` | Build time | Git commit hash at build time (if available) |
432
- | `ACCESS_KEYS` | Runtime | Read from `/api/config` |
433
- | `ACCESS_KEY_TIMEOUT_HOURS` | Runtime | Read from `/api/config` |
434
- | `WLLAMA_DEFAULT_MODEL_ID` | Runtime | Read from `/api/config` |
435
- | `WLLAMA_DEFAULT_GPU_MODEL_ID` | Runtime | Read from `/api/config` |
436
- | `INTERNAL_OPENAI_COMPATIBLE_API_*` | Runtime | Read from `/api/config` (except `API_KEY` which is server-only) |
437
- | `DEFAULT_INFERENCE_TYPE` | Runtime | Read from `/api/config` |
438
- | `PARENT_WINDOW_ORIGINS` | Runtime | Read from `/api/config` |
439
- | Search token | Runtime | Read from `/api/config`, so a reload picks up the token of whichever server answers |
440
 
441
  ### Security Considerations
442
 
443
- - `VITE_BUILD_DATE_TIME` and `VITE_COMMIT_SHORT_HASH` are bundled into the client JavaScript as build-time constants (build metadata only)
444
  - 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
445
  - All other configuration is fetched at runtime from `/api/config` and never appears in the bundled JavaScript
446
  - Server-only variables like `INTERNAL_OPENAI_COMPATIBLE_API_KEY` are never exposed to the client
 
425
 
426
  ### Build-Time vs Runtime Configuration
427
 
428
+ | Value | Resolved At | Notes |
429
+ | ---------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
430
+ | `VITE_BUILD_DATE_TIME` | Build time | Epoch milliseconds when the build occurred |
431
+ | `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 |
432
+ | `ACCESS_KEYS` | Runtime | Read from `/api/config` |
433
+ | `ACCESS_KEY_TIMEOUT_HOURS` | Runtime | Read from `/api/config` |
434
+ | `WLLAMA_DEFAULT_MODEL_ID` | Runtime | Read from `/api/config` |
435
+ | `WLLAMA_DEFAULT_GPU_MODEL_ID` | Runtime | Read from `/api/config` |
436
+ | `INTERNAL_OPENAI_COMPATIBLE_API_*` | Runtime | Read from `/api/config` (except `API_KEY` which is server-only) |
437
+ | `DEFAULT_INFERENCE_TYPE` | Runtime | Read from `/api/config` |
438
+ | `PARENT_WINDOW_ORIGINS` | Runtime | Read from `/api/config` |
439
+ | Search token | Runtime | Read from `/api/config`, so a reload picks up the token of whichever server answers |
440
 
441
  ### Security Considerations
442
 
443
+ - `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
444
  - 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
445
  - All other configuration is fetched at runtime from `/api/config` and never appears in the bundled JavaScript
446
  - Server-only variables like `INTERNAL_OPENAI_COMPATIBLE_API_KEY` are never exposed to the client
docs/development-commands.md CHANGED
@@ -106,7 +106,7 @@ The repository uses nine GitHub Actions workflows for continuous integration, de
106
  | `on-pull-request-to-main.yml` | PR opened/synced/reopened to `main` | Delegates to `reusable-check-docker.yml`; skippable via `skip-check-docker` label |
107
  | `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 |
108
  | `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 |
109
- | `deploy-to-hugging-face.yml` | Manual (`workflow_dispatch`) | Syncs the repository to a Hugging Face Space with the `hf` CLI over OIDC Trusted Publishers |
110
  | `stale.yml` | Daily (01:30 UTC) or manual | Marks and closes inactive issues and labels stale pull requests |
111
  | `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`) |
112
 
 
106
  | `on-pull-request-to-main.yml` | PR opened/synced/reopened to `main` | Delegates to `reusable-check-docker.yml`; skippable via `skip-check-docker` label |
107
  | `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 |
108
  | `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 |
109
+ | `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 |
110
  | `stale.yml` | Daily (01:30 UTC) or manual | Marks and closes inactive issues and labels stale pull requests |
111
  | `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`) |
112