system HF Staff commited on
Commit
d19ab4e
·
verified ·
1 Parent(s): e4dc8c3

Sync from felladrin/MiniSearch@43edeee

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.example +5 -2
  2. changelog.md +19 -0
  3. client/components/AiResponse/ChatInterface.test.tsx +24 -0
  4. client/components/AiResponse/ChatInterface.tsx +8 -3
  5. client/components/AiResponse/hooks/useReasoningContent.ts +9 -24
  6. client/components/Analytics/SearchStats.test.tsx +102 -39
  7. client/components/Analytics/SearchStats.tsx +36 -5
  8. client/components/App/App.test.tsx +61 -4
  9. client/components/App/App.tsx +8 -13
  10. client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.ts +207 -0
  11. client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts +22 -10
  12. client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts +30 -13
  13. client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts +21 -7
  14. client/components/Search/Form/SearchForm.suggestions.test.tsx +90 -0
  15. client/components/Search/Form/SearchForm.test.tsx +44 -0
  16. client/components/Search/Form/SearchForm.tsx +19 -27
  17. client/components/Search/History/HistoryDrawer.test.tsx +7 -0
  18. client/components/Search/History/HistoryDrawer.tsx +5 -1
  19. client/hooks/useHistoryRestore.test.ts +34 -0
  20. client/hooks/useSearchHistory.test.ts +154 -0
  21. client/hooks/useSearchHistory.ts +43 -11
  22. client/modules/accessKey.test.ts +84 -0
  23. client/modules/accessKey.ts +32 -16
  24. client/modules/config.test.ts +1 -0
  25. client/modules/config.ts +4 -1
  26. client/modules/followUpQuestions.test.ts +66 -8
  27. client/modules/followUpQuestions.ts +7 -3
  28. client/modules/history.test.ts +71 -0
  29. client/modules/history.ts +96 -0
  30. client/modules/parentWindow.test.ts +110 -0
  31. client/modules/parentWindow.ts +27 -3
  32. client/modules/pubSub.test.ts +82 -0
  33. client/modules/pubSub.ts +49 -1
  34. client/modules/querySuggestions.test.ts +36 -0
  35. client/modules/querySuggestions.ts +20 -11
  36. client/modules/reasoning.test.ts +81 -0
  37. client/modules/reasoning.ts +41 -0
  38. client/modules/settings.test.ts +1 -0
  39. client/modules/settings.ts +0 -9
  40. client/modules/textGeneration.chatBudget.test.ts +68 -1
  41. client/modules/textGeneration.inference.test.ts +1 -0
  42. client/modules/textGeneration.ts +4 -2
  43. client/modules/textGenerationUtilities.test.ts +41 -0
  44. client/modules/textGenerationUtilities.ts +24 -0
  45. client/modules/textGenerationWithHorde.ts +2 -0
  46. client/modules/textGenerationWithWllama.test.ts +26 -1
  47. client/modules/textGenerationWithWllama.ts +7 -3
  48. client/modules/textToSpeech.test.ts +23 -0
  49. client/modules/textToSpeech.ts +10 -17
  50. docs/ai-integration.md +3 -1
.env.example CHANGED
@@ -29,10 +29,13 @@ INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API"
29
  # "internal" -> $INTERNAL_OPENAI_COMPATIBLE_API_NAME
30
  DEFAULT_INFERENCE_TYPE="browser"
31
 
 
 
 
32
  # Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on.
33
  SEARCH_FALLBACK_ENABLED="false"
34
 
35
- # Comma-separated list of the second search providers to try: "parallel", "youcom", "keenable", or any mix. Empty means Parallel and You.com, plus Keenable when its key is set. With the fallback enabled, an unknown name stops the server at start.
36
  SEARCH_FALLBACK_PROVIDERS=""
37
 
38
  # The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.
@@ -41,7 +44,7 @@ SEARCH_FALLBACK_PARALLEL_API_KEY=""
41
  # The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.
42
  SEARCH_FALLBACK_YOUCOM_API_KEY=""
43
 
44
- # The API key for Keenable (api.keenable.ai), sent as X-API-Key. Keenable is opt-in: it joins the default list only when this key is set, or when SEARCH_FALLBACK_PROVIDERS names "keenable", in which case its keyless endpoint is used without a key.
45
  SEARCH_FALLBACK_KEENABLE_API_KEY=""
46
 
47
  # Whether a search that asks for an official page may run a second, "site:"-scoped query to reach the official site itself. Off by default, since it sends the engines a second request; only "true" or "1" turn it on.
 
29
  # "internal" -> $INTERNAL_OPENAI_COMPATIBLE_API_NAME
30
  DEFAULT_INFERENCE_TYPE="browser"
31
 
32
+ # Comma-separated list of the origins allowed to receive the search query when MiniSearch is embedded in an iframe, such as a Hugging Face Space. The query is posted to each one, and the browser delivers it only when the embedding page is on that origin. Leave blank to never post it.
33
+ PARENT_WINDOW_ORIGINS="https://huggingface.co"
34
+
35
  # Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on.
36
  SEARCH_FALLBACK_ENABLED="false"
37
 
38
+ # Comma-separated list of the second search providers to try: "parallel", "youcom", "keenable", or any mix. Empty means all three: Parallel, You.com and Keenable. With the fallback enabled, an unknown name stops the server at start.
39
  SEARCH_FALLBACK_PROVIDERS=""
40
 
41
  # The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.
 
44
  # The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.
45
  SEARCH_FALLBACK_YOUCOM_API_KEY=""
46
 
47
+ # The API key for Keenable (api.keenable.ai), sent as X-API-Key. Optional; without it Keenable uses the keyless "mcp-public" endpoint, like the other keyless tiers.
48
  SEARCH_FALLBACK_KEENABLE_API_KEY=""
49
 
50
  # Whether a search that asks for an official page may run a second, "site:"-scoped query to reach the official site itself. Off by default, since it sends the engines a second request; only "true" or "1" turn it on.
changelog.md CHANGED
@@ -2,8 +2,26 @@
2
 
3
  Notable changes, grouped by date, most recent first.
4
 
 
 
 
 
 
 
 
5
  ## 2026-11-24
6
 
 
 
 
 
 
 
 
 
 
 
 
7
  - Changing a setting in one section of the menu no longer undoes a change made in another. The AI, Search, Interface, History and Voice forms each kept a copy of every setting from the moment the menu opened and wrote the whole copy back on each change, so turning off Text Search and then switching Enter to Submit switched Text Search back on, and a model the app had fallen back to during a search was replaced by the one the menu opened with. Each form now writes only the settings it changed.
8
  - The search fallback can use Keenable as a third provider. It is opt-in: it joins the default list only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set, or when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, in which case its keyless endpoint is used without a key. Instances that already run the fallback keep Parallel and You.com as before.
9
  - Removing a search from the history now removes its AI answer and chat with it. Automatic cleanup, by age or by the entry limit, and deleting a single entry used to delete only the search, so its answer and chat stayed in the browser's storage for good, out of reach of the History drawer. Follow-up question suggestions also no longer write chat rows that nothing reads, and the rows that earlier versions left behind are removed once, the first time the app opens after this update. Pinned searches keep everything.
@@ -29,6 +47,7 @@ Notable changes, grouped by date, most recent first.
29
  - A missing file under `/assets/` is no longer sent with a one-year immutable cache header. During a partial deploy, or for an outdated link, the server answered such a request with the app page or a 404 marked immutable, so browsers could keep that wrong answer for the asset's URL for a year. Only files that exist in the build are now marked immutable; anything else under `/assets/` gets `no-cache`.
30
  - A search that found nothing is no longer reported as failed when the query has no keywords. A query made only of common words, such as "how about that", used to be retried with its keywords after finding no results; with none left, the retry sent an empty query, which was rejected, so the search showed as failed and, with AI answers on, ran the image fallback meant for outages. The retry is now skipped and the search completes with no results. A query over 2000 characters with no keywords is now searched without its surrounding spaces when that fits, and otherwise completes with no results instead of failing. A failed text search now also leaves a log entry with its error.
31
  - A relative date in a search query is now recognised the way people type it. "next year’s champion" with a curly apostrophe, the default on iPhone and Mac, no longer gets a year added, and a non-breaking or double space no longer hides "next year". A date the query already carries in another spelling ("2026 December", "Dec 2026", "2026-12") is not appended again, and a year inside a longer number such as "120265" is no longer taken for one. A follow-up search that is only a year no longer starts with a space, which gave the same search two cache entries.
 
32
 
33
  ## 2026-11-23
34
 
 
2
 
3
  Notable changes, grouped by date, most recent first.
4
 
5
+ ## 2026-11-25
6
+
7
+ - Earlier chat turns no longer send their thinking back to the model. Stored answers keep their reasoning block, and every prompt built from the conversation was sending it again: wasted tokens, and older turns dropped from the context sooner because of it. The reasoning is now stripped where the prompt is built, for the continuation, the rolling summary and the follow-up question suggestions. The chat and the History still show it.
8
+ - Fetches triggered by the settings are cancelled when superseded and give up after 10 seconds. Typing a base URL or a Horde key used to fire one request per character, and the slowest answer won: an old server's model list could replace the correct one, a cleared field could show the old user again, and an endpoint that never answers left the model dropdown stuck or delayed the start of an AI response indefinitely. Clearing the base URL now clears the model list too.
9
+ - Follow-up question suggestions are now written from the question prompt alone. The prompt went out the way a chat answer does, behind the system prompt with the search results, which buried the instructions for the question under unrelated text; it now goes out on its own, like the related search query. A reply with no question in it also no longer leaves a blank entry in the list of earlier suggestions the next prompt asks the model not to repeat, which pushed a real one out of that list.
10
+ - Searching from an embedded MiniSearch no longer depends on which frame comes first in the embedding page. The query was posted to an origin read from the parent's first child frame, so when that frame was another site (an ad, a chat widget, or a cross-origin frame of the app's own when not embedded), the browser refused the read and the search did nothing, and restoring a search from the history left the app stuck mid-restore. Browsers without `location.ancestorOrigins` never received the query at all. The query is now posted only to the origins in the new `PARENT_WINDOW_ORIGINS` setting, `https://huggingface.co` by default, and the browser delivers it only when the embedding page is on one of them.
11
+
12
  ## 2026-11-24
13
 
14
+ - Pinned searches now stay in the History drawer however many searches you make after them. The drawer only loaded your 200 most recent searches, and listed 100 of them, so an older pinned search disappeared from it, and from the filter, while it was still stored and protected from cleanup. Every pinned search is now shown in the Pinned section, and the filter finds it. Pinned searches are found through a new index, so this does not slow down as the history grows, and searches pinned before this update are picked up the first time the app opens after it.
15
+ - `/status` no longer names the internal models. Its `inference.byModel` was an object keyed by model id, and `/status` needs no token, so anyone probing an instance could read which upstream models it runs, or with the random pool the upstream's whole catalog. It is now an array: with `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` set, entry _i_ is the model at position _i_ of that list, zero-filled when untried, and with the random pool the entries follow first-seen order. The counters themselves are unchanged, so a dead member of the pool is still visible.
16
+ - Settings read from the browser now start from the shipped defaults with the stored values applied on top. A profile saved before a setting was added used to see that setting as undefined until initialization finished a moment later, and parts of the page read it before then. A stored settings value that could not be parsed now counts as no stored settings at all, so such a profile gets the server's defaults instead of being pinned to the shipped ones.
17
+ - `/status` no longer misreports two counters. The average search time (`searches.averageTextualMs`) divided SearXNG's response times by every text search served, fallback-served ones included, so during an outage it sank toward 0 while SearXNG answered nothing; it now averages only the searches SearXNG answered, as the docs say (image searches the same). And a PDF that cannot be parsed (password-protected or malformed), or a page whose text cannot be extracted, is counted as the new `pageReads.skipped.unparsable` instead of `failed`. `failed` counts as the host refusing the read, so three locked PDFs from one site used to make the server skip that site, its ordinary pages included, for five minutes.
18
+ - The History drawer's Analytics tab now counts every saved search. It read only the newest 1,000, so with a longer history (Maximum Entries goes up to 10,000) Total Searches stopped at 1,000, and Daily Average, Most Active Hour, Search Sources and the activity heatmap left out everything older. The tab now reads only the time and source of each search, never the saved results.
19
+ - Keenable is now one of the three default search fallback providers, alongside Parallel and You.com. When SearXNG fails, an instance that runs the fallback now tries Keenable too without any setup: with no key it uses Keenable's keyless endpoint, and setting `SEARCH_FALLBACK_KEENABLE_API_KEY` switches it to the authenticated one. To leave it out, name the providers you want with `SEARCH_FALLBACK_PROVIDERS`.
20
+ - An unknown path under `/search/` no longer runs a search. Any path there other than `/search/text` and `/search/images`, such as `/search/foo` or `/search/textual`, was served as a search: it checked the token and spent a rate-limit point, then queried SearXNG, as an image search unless the path began with `/search/text`, and was counted in the search counters. Such a request now gets a 404 with a JSON error, before the token is checked.
21
+ - A failed access key check on load no longer deletes the saved key. When the app had loaded its configuration but the check of the saved key then got no usable answer, such as a dropped connection, a proxy's error page on that request, or a server restarting between the two, the key was deleted and had to be entered again even though it had time left. It is now deleted only when the server says it is invalid, when it has expired, or when the saved value is unreadable. Otherwise it is kept and checked again on the next load.
22
+ - A page load where the server configuration could not be fetched no longer saves the shipped defaults as the browser's settings. On a first visit that failure used to lock in the built-in model and inference type, so the server's own defaults were never applied to that browser afterwards. The model the app switches to when the saved one has left the catalog follows the same rule: it is saved only when the server's configuration was available.
23
+ - The suggestion shown in an empty search box now uses up one stored suggestion each time the box is emptied, and the suggestions are drawn evenly from the whole list. Deleting the last character or pressing Clear used to use up two and show one, and when none were stored it fetched the list twice at the same moment. The shuffle also favoured entries near the top of the list, so some suggestions came up far more often than others.
24
+
25
  - Changing a setting in one section of the menu no longer undoes a change made in another. The AI, Search, Interface, History and Voice forms each kept a copy of every setting from the moment the menu opened and wrote the whole copy back on each change, so turning off Text Search and then switching Enter to Submit switched Text Search back on, and a model the app had fallen back to during a search was replaced by the one the menu opened with. Each form now writes only the settings it changed.
26
  - The search fallback can use Keenable as a third provider. It is opt-in: it joins the default list only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set, or when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, in which case its keyless endpoint is used without a key. Instances that already run the fallback keep Parallel and You.com as before.
27
  - Removing a search from the history now removes its AI answer and chat with it. Automatic cleanup, by age or by the entry limit, and deleting a single entry used to delete only the search, so its answer and chat stayed in the browser's storage for good, out of reach of the History drawer. Follow-up question suggestions also no longer write chat rows that nothing reads, and the rows that earlier versions left behind are removed once, the first time the app opens after this update. Pinned searches keep everything.
 
47
  - A missing file under `/assets/` is no longer sent with a one-year immutable cache header. During a partial deploy, or for an outdated link, the server answered such a request with the app page or a 404 marked immutable, so browsers could keep that wrong answer for the asset's URL for a year. Only files that exist in the build are now marked immutable; anything else under `/assets/` gets `no-cache`.
48
  - A search that found nothing is no longer reported as failed when the query has no keywords. A query made only of common words, such as "how about that", used to be retried with its keywords after finding no results; with none left, the retry sent an empty query, which was rejected, so the search showed as failed and, with AI answers on, ran the image fallback meant for outages. The retry is now skipped and the search completes with no results. A query over 2000 characters with no keywords is now searched without its surrounding spaces when that fits, and otherwise completes with no results instead of failing. A failed text search now also leaves a log entry with its error.
49
  - A relative date in a search query is now recognised the way people type it. "next year’s champion" with a curly apostrophe, the default on iPhone and Mac, no longer gets a year added, and a non-breaking or double space no longer hides "next year". A date the query already carries in another spelling ("2026 December", "Dec 2026", "2026-12") is not appended again, and a year inside a longer number such as "120265" is no longer taken for one. A follow-up search that is only a year no longer starts with a space, which gave the same search two cache entries.
50
+ - Reading an answer aloud no longer speaks unfinished reasoning. When a response's reasoning block never closed, such as after an interrupted generation or a reply that ended mid-thought, the Listen button used to read the whole thing, reasoning and literal marker text included, because text-to-speech only removed properly closed blocks. Reasoning is now split the same way the on-screen display splits it: an unterminated block has no answer to speak, so nothing is read, and a marker that only shows up mid-answer is left as ordinary text.
51
 
52
  ## 2026-11-23
53
 
client/components/AiResponse/ChatInterface.test.tsx CHANGED
@@ -737,3 +737,27 @@ describe("ChatInterface generation state", () => {
737
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
738
  });
739
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
737
  expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
738
  });
739
  });
740
+
741
+ describe("ChatInterface previous follow-up questions", () => {
742
+ it("does not record an empty follow-up question", async () => {
743
+ vi.mocked(generateFollowUpQuestion)
744
+ .mockResolvedValueOnce("Is it supported in Safari?")
745
+ .mockResolvedValueOnce("")
746
+ .mockResolvedValueOnce("Does it drain the battery?");
747
+
748
+ renderChatInterface({ suppressInitialFollowUp: false });
749
+ await act(async () => {});
750
+
751
+ await act(async () => {
752
+ await sendMessage("And how do I use it?");
753
+ });
754
+ await act(async () => {
755
+ await sendMessage("Does it work in the background?");
756
+ });
757
+
758
+ expect(generateFollowUpQuestion).toHaveBeenCalledTimes(3);
759
+ expect(
760
+ vi.mocked(generateFollowUpQuestion).mock.calls[2][0].previousQuestions,
761
+ ).toEqual(["Is it supported in Safari?"]);
762
+ });
763
+ });
client/components/AiResponse/ChatInterface.tsx CHANGED
@@ -131,9 +131,14 @@ export default function ChatInterface({
131
  // A newer call, or an unmount, took over while this one awaited.
132
  if (invocation !== followUpInvocationRef.current) return;
133
 
134
- setPreviousFollowUpQuestions((prev) =>
135
- [...prev, newQuestion].slice(-5),
136
- );
 
 
 
 
 
137
  setFollowUpQuestion(newQuestion);
138
  setGenerationState({
139
  ...getChatGenerationState(),
 
131
  // A newer call, or an unmount, took over while this one awaited.
132
  if (invocation !== followUpInvocationRef.current) return;
133
 
134
+ // No question was found in the reply: an empty entry would show up as
135
+ // a blank line in the next prompt's "do not repeat" list and push a
136
+ // real question out of it.
137
+ if (newQuestion) {
138
+ setPreviousFollowUpQuestions((prev) =>
139
+ [...prev, newQuestion].slice(-5),
140
+ );
141
+ }
142
  setFollowUpQuestion(newQuestion);
143
  setGenerationState({
144
  ...getChatGenerationState(),
client/components/AiResponse/hooks/useReasoningContent.ts CHANGED
@@ -1,6 +1,7 @@
1
  import { usePubSub } from "create-pubsub/react";
2
  import { useCallback } from "react";
3
  import { settingsPubSub } from "@/modules/pubSub";
 
4
 
5
  /**
6
  * Splits a streamed AI response into the part between the reasoning markers
@@ -17,32 +18,16 @@ export function useReasoningContent(
17
 
18
  const extractReasoningAndMainContent = useCallback(
19
  (text: string, startMarker: string, endMarker: string) => {
20
- if (!text)
21
- return { reasoningContent: "", mainContent: "", isGenerating: false };
22
-
23
- const trimmedText = text.trim();
24
-
25
- if (!trimmedText.startsWith(startMarker))
26
- return { reasoningContent: "", mainContent: text, isGenerating: false };
27
-
28
- const startIndex = trimmedText.indexOf(startMarker);
29
- const endIndex = trimmedText.indexOf(endMarker);
30
-
31
- if (endIndex === -1) {
32
- return {
33
- reasoningContent: trimmedText.slice(startIndex + startMarker.length),
34
- mainContent: "",
35
- isGenerating: isResponseGenerating,
36
- };
37
- }
38
 
39
  return {
40
- reasoningContent: trimmedText.slice(
41
- startIndex + startMarker.length,
42
- endIndex,
43
- ),
44
- mainContent: trimmedText.slice(endIndex + endMarker.length),
45
- isGenerating: false,
46
  };
47
  },
48
  [isResponseGenerating],
 
1
  import { usePubSub } from "create-pubsub/react";
2
  import { useCallback } from "react";
3
  import { settingsPubSub } from "@/modules/pubSub";
4
+ import { splitReasoning } from "@/modules/reasoning";
5
 
6
  /**
7
  * Splits a streamed AI response into the part between the reasoning markers
 
18
 
19
  const extractReasoningAndMainContent = useCallback(
20
  (text: string, startMarker: string, endMarker: string) => {
21
+ const { reasoning, answer, isOpen } = splitReasoning(
22
+ text,
23
+ startMarker,
24
+ endMarker,
25
+ );
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
  return {
28
+ reasoningContent: reasoning,
29
+ mainContent: answer,
30
+ isGenerating: isOpen && isResponseGenerating,
 
 
 
31
  };
32
  },
33
  [isResponseGenerating],
client/components/Analytics/SearchStats.test.tsx CHANGED
@@ -1,41 +1,21 @@
1
  import { MantineProvider } from "@mantine/core";
2
- import { render, screen } from "@testing-library/react";
3
- import { useSearchHistory } from "@/hooks/useSearchHistory";
4
- import type { SearchEntry } from "@/modules/history";
 
5
  import SearchStats from "./SearchStats";
6
 
7
- vi.mock("@/hooks/useSearchHistory", () => ({
8
- useSearchHistory: vi.fn(),
 
 
 
 
 
 
9
  }));
10
 
11
- /** The hook mock has to return the full shape the real hook returns. */
12
- const mockHistory = (recentSearches: SearchEntry[]) => {
13
- const noop = vi.fn(async (): Promise<void> => {});
14
- vi.mocked(useSearchHistory).mockReturnValue({
15
- recentSearches,
16
- llmResponseCount: 0,
17
- chatMessageCount: 0,
18
- filteredSearches: recentSearches,
19
- groupedSearches: {},
20
- isLoading: false,
21
- error: null,
22
- currentPage: 0,
23
- totalPages: 0,
24
- hasNextPage: false,
25
- hasPreviousPage: false,
26
- retryLastOperation: noop,
27
- clearError: vi.fn(),
28
- searchHistory: vi.fn(),
29
- addToHistory: noop,
30
- togglePin: noop,
31
- deleteEntry: noop,
32
- clearAll: noop,
33
- refreshHistory: noop,
34
- nextPage: vi.fn(),
35
- previousPage: vi.fn(),
36
- goToPage: vi.fn(),
37
- });
38
- };
39
 
40
  /** Metric cards print the value below the label; the heatmap above it. */
41
  const valueBelow = (label: string) =>
@@ -46,8 +26,9 @@ const valueAbove = (label: string) =>
46
  describe("SearchStats", () => {
47
  let originalTimeZone: string | undefined;
48
 
49
- beforeEach(() => {
50
  originalTimeZone = process.env.TZ;
 
51
  });
52
 
53
  afterEach(() => {
@@ -56,7 +37,7 @@ describe("SearchStats", () => {
56
  else process.env.TZ = originalTimeZone;
57
  });
58
 
59
- it("buckets the Daily Average by local day, like the heatmap", () => {
60
  process.env.TZ = "Europe/Zurich"; // UTC+1 in January
61
  vi.useFakeTimers({ toFake: ["Date"] });
62
  vi.setSystemTime(new Date(2026, 0, 15, 12));
@@ -69,9 +50,9 @@ describe("SearchStats", () => {
69
  expect(new Date(first).getUTCDate()).toBe(14);
70
  expect(new Date(second).getUTCDate()).toBe(15);
71
 
72
- mockHistory([
73
- { id: 1, query: "first", timestamp: first },
74
- { id: 2, query: "second", timestamp: second },
75
  ]);
76
  render(
77
  <MantineProvider>
@@ -79,7 +60,89 @@ describe("SearchStats", () => {
79
  </MantineProvider>,
80
  );
81
 
82
- expect(valueBelow("Daily Average")).toBe("2");
83
  expect(valueAbove("Active days")).toBe("1");
84
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  });
 
1
  import { MantineProvider } from "@mantine/core";
2
+ import { render, screen, waitFor } from "@testing-library/react";
3
+ import * as historyModule from "@/modules/history";
4
+ import { historyDatabase } from "@/modules/history";
5
+ import { getSettings } from "@/modules/pubSub";
6
  import SearchStats from "./SearchStats";
7
 
8
+ // Pin the settings the history module reads, and keep pubSub's module-level
9
+ // localStorage reads out of the test.
10
+ vi.mock("@/modules/pubSub", () => ({
11
+ getSettings: vi.fn(() => ({
12
+ historyAutoCleanup: false,
13
+ historyRetentionDays: 30,
14
+ historyMaxEntries: 500,
15
+ })),
16
  }));
17
 
18
+ const DAY_MS = 24 * 60 * 60 * 1000;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  /** Metric cards print the value below the label; the heatmap above it. */
21
  const valueBelow = (label: string) =>
 
26
  describe("SearchStats", () => {
27
  let originalTimeZone: string | undefined;
28
 
29
+ beforeEach(async () => {
30
  originalTimeZone = process.env.TZ;
31
+ await historyDatabase.searches.clear();
32
  });
33
 
34
  afterEach(() => {
 
37
  else process.env.TZ = originalTimeZone;
38
  });
39
 
40
+ it("buckets the Daily Average by local day, like the heatmap", async () => {
41
  process.env.TZ = "Europe/Zurich"; // UTC+1 in January
42
  vi.useFakeTimers({ toFake: ["Date"] });
43
  vi.setSystemTime(new Date(2026, 0, 15, 12));
 
50
  expect(new Date(first).getUTCDate()).toBe(14);
51
  expect(new Date(second).getUTCDate()).toBe(15);
52
 
53
+ await historyDatabase.searches.bulkAdd([
54
+ { query: "first", timestamp: first },
55
+ { query: "second", timestamp: second },
56
  ]);
57
  render(
58
  <MantineProvider>
 
60
  </MantineProvider>,
61
  );
62
 
63
+ await waitFor(() => expect(valueBelow("Daily Average")).toBe("2"));
64
  expect(valueAbove("Active days")).toBe("1");
65
  });
66
+ it("counts every stored search, not only the newest 1000", async () => {
67
+ const now = Date.now();
68
+ // 1,500 searches over the last 20 days; the oldest 500 are the ones a
69
+ // window of the newest 1000 drops.
70
+ await historyDatabase.searches.bulkAdd(
71
+ Array.from({ length: 1500 }, (_, i) => ({
72
+ query: `query ${i}`,
73
+ timestamp: now - (1500 - i) * ((20 * DAY_MS) / 1500),
74
+ source: i < 500 ? "followup" : "user",
75
+ })),
76
+ );
77
+
78
+ render(
79
+ <MantineProvider>
80
+ <SearchStats period="all" />
81
+ </MantineProvider>,
82
+ );
83
+
84
+ await waitFor(() =>
85
+ expect(valueBelow("Total Searches")).toBe((1500).toLocaleString()),
86
+ );
87
+ // The sources card includes the oldest entries too.
88
+ expect(screen.getByText("500 searches")).toBeTruthy();
89
+ expect(screen.getByText("1000 searches")).toBeTruthy();
90
+ // So does the heatmap. The newest 1,000 of these cover about 14 days; all
91
+ // 1,500 cover about 21 (the span plus the day it ends on).
92
+ expect(Number(valueAbove("Active days"))).toBeGreaterThanOrEqual(20);
93
+ });
94
+
95
+ it("pairs each search with its own source, also when timestamps tie", async () => {
96
+ const tied = Date.now();
97
+ await historyDatabase.searches.bulkAdd([
98
+ { query: "saved before sources existed", timestamp: tied },
99
+ { query: "typed", timestamp: tied, source: "user" },
100
+ { query: "typed again", timestamp: tied, source: "user" },
101
+ { query: "asked after", timestamp: tied, source: "followup" },
102
+ ]);
103
+
104
+ render(
105
+ <MantineProvider>
106
+ <SearchStats period="all" />
107
+ </MantineProvider>,
108
+ );
109
+
110
+ await waitFor(() => expect(valueBelow("Total Searches")).toBe("4"));
111
+ const sourceRow = (name: string) =>
112
+ screen.getByText(name).closest("div")?.parentElement?.textContent;
113
+ expect(sourceRow("User")).toContain("2 searches");
114
+ expect(sourceRow("Followup")).toContain("1 searches");
115
+ expect(sourceRow("Unknown")).toContain("1 searches");
116
+ });
117
+
118
+ it("leaves IndexedDB alone while history is turned off", async () => {
119
+ await historyDatabase.searches.add({
120
+ query: "kept but hidden",
121
+ timestamp: Date.now(),
122
+ });
123
+ const settingsMock = vi.mocked(getSettings);
124
+ const historyOn = settingsMock.getMockImplementation();
125
+ settingsMock.mockImplementation(
126
+ () =>
127
+ ({
128
+ ...historyOn?.(),
129
+ enableHistory: false,
130
+ }) as ReturnType<typeof getSettings>,
131
+ );
132
+ const readSpy = vi.spyOn(historyModule, "getSearchActivityRecords");
133
+
134
+ try {
135
+ render(
136
+ <MantineProvider>
137
+ <SearchStats period="all" />
138
+ </MantineProvider>,
139
+ );
140
+
141
+ expect(await screen.findByText("No search data available")).toBeTruthy();
142
+ expect(readSpy).not.toHaveBeenCalled();
143
+ } finally {
144
+ readSpy.mockRestore();
145
+ if (historyOn) settingsMock.mockImplementation(historyOn);
146
+ }
147
+ });
148
  });
client/components/Analytics/SearchStats.tsx CHANGED
@@ -11,9 +11,13 @@ import {
11
  Title,
12
  } from "@mantine/core";
13
  import { IconSearch } from "@tabler/icons-react";
14
- import { useMemo } from "react";
15
- import { useSearchHistory } from "@/hooks/useSearchHistory";
16
- import type { SearchEntry } from "@/modules/history";
 
 
 
 
17
  import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";
18
  import { formatRelativeTime } from "@/modules/stringFormatters";
19
  import ActivityHeatmap from "./ActivityHeatmap";
@@ -28,7 +32,7 @@ interface StatsData {
28
  avgPerDay: number;
29
  mostActiveHour: number;
30
  topSources: { source: string; count: number; percentage: number }[];
31
- recentActivity: SearchEntry[];
32
  }
33
 
34
  function MetricCard({
@@ -58,7 +62,34 @@ export default function SearchStats({
58
  period = "week",
59
  compact = false,
60
  }: SearchStatsProps) {
61
- const { recentSearches, isLoading } = useSearchHistory({ limit: 1000 });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  const stats = useMemo((): StatsData => {
64
  if (!recentSearches.length) {
 
11
  Title,
12
  } from "@mantine/core";
13
  import { IconSearch } from "@tabler/icons-react";
14
+ import { useEffect, useMemo, useState } from "react";
15
+ import { REFRESH_INTERVAL_MS } from "@/hooks/useSearchHistory";
16
+ import {
17
+ getSearchActivityRecords,
18
+ isHistoryEnabled,
19
+ type SearchActivityRecord,
20
+ } from "@/modules/history";
21
  import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";
22
  import { formatRelativeTime } from "@/modules/stringFormatters";
23
  import ActivityHeatmap from "./ActivityHeatmap";
 
32
  avgPerDay: number;
33
  mostActiveHour: number;
34
  topSources: { source: string; count: number; percentage: number }[];
35
+ recentActivity: SearchActivityRecord[];
36
  }
37
 
38
  function MetricCard({
 
62
  period = "week",
63
  compact = false,
64
  }: SearchStatsProps) {
65
+ const [recentSearches, setRecentSearches] = useState<SearchActivityRecord[]>(
66
+ [],
67
+ );
68
+ const [isLoading, setIsLoading] = useState(true);
69
+
70
+ // The whole table, not a window of the newest rows: the totals, the
71
+ // averages and the heatmap are only right if the oldest searches count too.
72
+ // A disabled history is shown as empty without opening the database.
73
+ useEffect(() => {
74
+ let cancelled = false;
75
+
76
+ const load = async () => {
77
+ const records = isHistoryEnabled()
78
+ ? await getSearchActivityRecords()
79
+ : [];
80
+ if (cancelled) return;
81
+ setRecentSearches(records);
82
+ setIsLoading(false);
83
+ };
84
+
85
+ load();
86
+ const intervalId = setInterval(load, REFRESH_INTERVAL_MS);
87
+
88
+ return () => {
89
+ cancelled = true;
90
+ clearInterval(intervalId);
91
+ };
92
+ }, []);
93
 
94
  const stats = useMemo((): StatsData => {
95
  if (!recentSearches.length) {
client/components/App/App.test.tsx CHANGED
@@ -1,5 +1,5 @@
1
  import type { ServerConfig } from "@shared/serverConfig";
2
- import { render, screen, waitFor } from "@testing-library/react";
3
  import { beforeEach, describe, expect, it, vi } from "vitest";
4
  import { getConfig } from "@/modules/config";
5
  import App from "./App";
@@ -30,6 +30,7 @@ const serverConfig: ServerConfig = {
30
  internalApiName: "Internal API",
31
  defaultInferenceType: "browser",
32
  searchToken: "a".repeat(64),
 
33
  };
34
 
35
  describe("App", () => {
@@ -62,9 +63,12 @@ describe("App", () => {
62
  * Renders a fresh module instance so the settings module reads the profile
63
  * seeded here, since it captures localStorage once at import.
64
  */
65
- async function renderWithStoredSettings(stored: Record<string, unknown>) {
 
 
 
66
  vi.resetModules();
67
- localStorage.setItem("settings", JSON.stringify(stored));
68
 
69
  const [
70
  { getConfig: freshGetConfig },
@@ -75,7 +79,7 @@ describe("App", () => {
75
  import("./App"),
76
  import("@/modules/pubSub"),
77
  ]);
78
- vi.mocked(freshGetConfig).mockResolvedValue(serverConfig);
79
 
80
  render(<FreshApp />);
81
  await screen.findByTestId("main-page");
@@ -106,6 +110,59 @@ describe("App", () => {
106
  );
107
  });
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  // An unreachable /api/config must not look like `accessKeysEnabled: false`,
110
  // which would let the app through the gate.
111
  it("refuses to render the app when the config cannot be loaded", async () => {
 
1
  import type { ServerConfig } from "@shared/serverConfig";
2
+ import { act, cleanup, render, screen, waitFor } from "@testing-library/react";
3
  import { beforeEach, describe, expect, it, vi } from "vitest";
4
  import { getConfig } from "@/modules/config";
5
  import App from "./App";
 
30
  internalApiName: "Internal API",
31
  defaultInferenceType: "browser",
32
  searchToken: "a".repeat(64),
33
+ parentWindowOrigins: ["https://huggingface.co"],
34
  };
35
 
36
  describe("App", () => {
 
63
  * Renders a fresh module instance so the settings module reads the profile
64
  * seeded here, since it captures localStorage once at import.
65
  */
66
+ async function renderWithStoredSettings(
67
+ stored?: Record<string, unknown>,
68
+ config: ServerConfig = serverConfig,
69
+ ) {
70
  vi.resetModules();
71
+ if (stored) localStorage.setItem("settings", JSON.stringify(stored));
72
 
73
  const [
74
  { getConfig: freshGetConfig },
 
79
  import("./App"),
80
  import("@/modules/pubSub"),
81
  ]);
82
+ vi.mocked(freshGetConfig).mockResolvedValue(config);
83
 
84
  render(<FreshApp />);
85
  await screen.findByTestId("main-page");
 
110
  );
111
  });
112
 
113
+ /** Renders a fresh module instance against a server whose config fails to load. */
114
+ async function renderWithoutConfig(stored?: Record<string, unknown>) {
115
+ vi.resetModules();
116
+ if (stored) localStorage.setItem("settings", JSON.stringify(stored));
117
+
118
+ const [
119
+ { getConfig: freshGetConfig },
120
+ { default: FreshApp },
121
+ { webGpuSupport },
122
+ ] = await Promise.all([
123
+ import("@/modules/config"),
124
+ import("./App"),
125
+ import("@/modules/webGpu"),
126
+ ]);
127
+ vi.mocked(freshGetConfig).mockRejectedValue(new Error("Network error"));
128
+
129
+ render(<FreshApp />);
130
+ await screen.findByText(/could not load the server configuration/i);
131
+ // Settings are initialized once the WebGPU check is in, so let it finish.
132
+ await webGpuSupport;
133
+ await act(async () => {});
134
+ }
135
+
136
+ describe("when the config cannot be loaded", () => {
137
+ it("saves no settings on a first visit", async () => {
138
+ await renderWithoutConfig();
139
+
140
+ expect(localStorage.getItem("settings")).toBeNull();
141
+ });
142
+
143
+ it("leaves a stored profile as it was", async () => {
144
+ const stored = { enableAiResponse: true };
145
+
146
+ await renderWithoutConfig(stored);
147
+
148
+ expect(localStorage.getItem("settings")).toBe(JSON.stringify(stored));
149
+ });
150
+
151
+ // Settings saved from shipped defaults would count as the user's own
152
+ // choices, and the server's defaults could never seed them again.
153
+ it("lets a later load seed the server's defaults", async () => {
154
+ await renderWithoutConfig();
155
+ cleanup();
156
+
157
+ const getSettings = await renderWithStoredSettings(undefined, {
158
+ ...serverConfig,
159
+ defaultInferenceType: "openai",
160
+ });
161
+
162
+ await waitFor(() => expect(getSettings().inferenceType).toBe("openai"));
163
+ });
164
+ });
165
+
166
  // An unreachable /api/config must not look like `accessKeysEnabled: false`,
167
  // which would let the app through the gate.
168
  it("refuses to render the app when the config cannot be loaded", async () => {
client/components/App/App.tsx CHANGED
@@ -12,21 +12,15 @@ import { Notifications } from "@mantine/notifications";
12
  import { usePubSub } from "create-pubsub/react";
13
  import { lazy, useEffect, useState } from "react";
14
  import { addLogEntry } from "@/modules/logEntries";
15
- import { settingsPubSub } from "@/modules/pubSub";
16
  import {
17
  applyServerConfig,
18
- defaultSettings,
19
- hasStoredUserSettings,
20
  upgradeUntouchedSystemPrompt,
21
  } from "@/modules/settings";
22
  import { webGpuSupport } from "@/modules/webGpu";
23
  import "@mantine/notifications/styles.css";
24
  import { verifyStoredAccessKey } from "@/modules/accessKey";
25
- import {
26
- FALLBACK_CONFIG,
27
- getConfig,
28
- type ServerConfig,
29
- } from "@/modules/config";
30
  import MainPage from "../Pages/Main/MainPage";
31
 
32
  const AccessPage = lazy(() => import("../Pages/AccessPage"));
@@ -103,9 +97,9 @@ function useServerConfig(): ConfigState {
103
  /**
104
  * Waits for the server config so its defaults can seed a fresh profile, and
105
  * for the WebGPU check, which picks between the GPU and the CPU default model.
106
- * Falling back to shipped defaults is safe here: unlike access control,
107
- * guessing wrong only means the user sees the settings they can already
108
- * change themselves.
109
  */
110
  function useInitializeSettings(config: ConfigState) {
111
  const [settings, setSettings] = usePubSub(settingsPubSub);
@@ -120,6 +114,7 @@ function useInitializeSettings(config: ConfigState) {
120
  if (
121
  settingsInitialized ||
122
  config === "loading" ||
 
123
  hasWebGpu === undefined
124
  ) {
125
  return;
@@ -127,8 +122,8 @@ function useInitializeSettings(config: ConfigState) {
127
 
128
  setSettings(
129
  applyServerConfig(
130
- upgradeUntouchedSystemPrompt({ ...defaultSettings, ...settings }),
131
- config === "unavailable" ? FALLBACK_CONFIG : config,
132
  hasStoredUserSettings,
133
  hasWebGpu,
134
  ),
 
12
  import { usePubSub } from "create-pubsub/react";
13
  import { lazy, useEffect, useState } from "react";
14
  import { addLogEntry } from "@/modules/logEntries";
15
+ import { hasStoredUserSettings, settingsPubSub } from "@/modules/pubSub";
16
  import {
17
  applyServerConfig,
 
 
18
  upgradeUntouchedSystemPrompt,
19
  } from "@/modules/settings";
20
  import { webGpuSupport } from "@/modules/webGpu";
21
  import "@mantine/notifications/styles.css";
22
  import { verifyStoredAccessKey } from "@/modules/accessKey";
23
+ import { getConfig, type ServerConfig } from "@/modules/config";
 
 
 
 
24
  import MainPage from "../Pages/Main/MainPage";
25
 
26
  const AccessPage = lazy(() => import("../Pages/AccessPage"));
 
97
  /**
98
  * Waits for the server config so its defaults can seed a fresh profile, and
99
  * for the WebGPU check, which picks between the GPU and the CPU default model.
100
+ * When the config could not be loaded nothing is written: the app shows an
101
+ * error instead, and settings seeded from shipped defaults would be taken for
102
+ * the user's own choices on every later load.
103
  */
104
  function useInitializeSettings(config: ConfigState) {
105
  const [settings, setSettings] = usePubSub(settingsPubSub);
 
114
  if (
115
  settingsInitialized ||
116
  config === "loading" ||
117
+ config === "unavailable" ||
118
  hasWebGpu === undefined
119
  ) {
120
  return;
 
122
 
123
  setSettings(
124
  applyServerConfig(
125
+ upgradeUntouchedSystemPrompt(settings),
126
+ config,
127
  hasStoredUserSettings,
128
  hasWebGpu,
129
  ),
client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.ts ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { listOpenAiCompatibleModels } from "@shared/openaiModels";
2
+ import { renderHook, waitFor } from "@testing-library/react";
3
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
4
+ import { addLogEntry } from "@/modules/logEntries";
5
+ import { defaultSettings } from "@/modules/settings";
6
+ import {
7
+ aiHordeDefaultApiKey,
8
+ fetchHordeModels,
9
+ fetchHordeUserInfo,
10
+ } from "@/modules/textGenerationWithHorde";
11
+ import { useHordeModels } from "./useHordeModels";
12
+ import { useHordeUserInfo } from "./useHordeUserInfo";
13
+ import { useOpenAiModels } from "./useOpenAiModels";
14
+
15
+ vi.mock("@shared/openaiModels", () => ({
16
+ listOpenAiCompatibleModels: vi.fn(),
17
+ }));
18
+ vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
19
+ vi.mock("@/modules/textGenerationWithHorde", () => ({
20
+ aiHordeDefaultApiKey: "0000000000",
21
+ fetchHordeUserInfo: vi.fn(),
22
+ fetchHordeModels: vi.fn(),
23
+ }));
24
+
25
+ type Settings = typeof defaultSettings;
26
+
27
+ function deferred<T>() {
28
+ let resolve!: (v: T) => void;
29
+ const promise = new Promise<T>((res) => {
30
+ resolve = res;
31
+ });
32
+ return { promise, resolve };
33
+ }
34
+
35
+ /** Records the signal of each call and lets the test settle calls in any order. */
36
+ function controlled<T>(mock: ReturnType<typeof vi.fn>, signalArg: number) {
37
+ const calls: { signal: AbortSignal; resolve: (v: T) => void }[] = [];
38
+ mock.mockImplementation((...args: unknown[]) => {
39
+ const d = deferred<T>();
40
+ calls.push({ signal: args[signalArg] as AbortSignal, resolve: d.resolve });
41
+ return d.promise;
42
+ });
43
+ return calls;
44
+ }
45
+
46
+ /** Replaces `AbortSignal.timeout` with timeouts the test fires by hand. */
47
+ function manualTimeouts() {
48
+ const timeouts: { ms: number; fire: () => void }[] = [];
49
+ vi.spyOn(AbortSignal, "timeout").mockImplementation((ms: number) => {
50
+ const c = new AbortController();
51
+ timeouts.push({
52
+ ms,
53
+ fire: () => c.abort(new DOMException("Timed out", "TimeoutError")),
54
+ });
55
+ return c.signal;
56
+ });
57
+ return timeouts;
58
+ }
59
+
60
+ const openAi = (patch: Partial<Settings>): Settings => ({
61
+ ...defaultSettings,
62
+ inferenceType: "openai",
63
+ ...patch,
64
+ });
65
+ const horde = (patch: Partial<Settings>): Settings => ({
66
+ ...defaultSettings,
67
+ inferenceType: "horde",
68
+ ...patch,
69
+ });
70
+
71
+ beforeEach(() => {
72
+ vi.mocked(addLogEntry).mockClear();
73
+ });
74
+ afterEach(() => {
75
+ vi.restoreAllMocks();
76
+ });
77
+
78
+ describe("useOpenAiModels", () => {
79
+ it("keeps the latest server's list when an older response arrives last", async () => {
80
+ const calls = controlled<{ id: string }[]>(
81
+ vi.mocked(listOpenAiCompatibleModels),
82
+ 2,
83
+ );
84
+ const { result, rerender } = renderHook(
85
+ (s: Settings) => useOpenAiModels(s),
86
+ {
87
+ initialProps: openAi({ openAiApiBaseUrl: "http://old" }),
88
+ },
89
+ );
90
+ rerender(openAi({ openAiApiBaseUrl: "http://new" }));
91
+
92
+ expect(calls).toHaveLength(2);
93
+ expect(calls[0].signal.aborted).toBe(true);
94
+ expect(calls[1].signal.aborted).toBe(false);
95
+
96
+ calls[1].resolve([{ id: "new-model" }]);
97
+ await waitFor(() =>
98
+ expect(result.current.openAiModels).toEqual([
99
+ { label: "new-model", value: "new-model" },
100
+ ]),
101
+ );
102
+ calls[0].resolve([{ id: "old-model" }]);
103
+ await Promise.resolve();
104
+
105
+ expect(result.current.openAiModels).toEqual([
106
+ { label: "new-model", value: "new-model" },
107
+ ]);
108
+ expect(result.current.useTextInput).toBe(false);
109
+ });
110
+
111
+ it("does not log an error for a request aborted by a newer keystroke", async () => {
112
+ vi.mocked(listOpenAiCompatibleModels).mockImplementation(
113
+ (_url, _key, signal) =>
114
+ new Promise((_resolve, reject) =>
115
+ signal?.addEventListener("abort", () =>
116
+ reject(new DOMException("Aborted", "AbortError")),
117
+ ),
118
+ ),
119
+ );
120
+ const { rerender } = renderHook((s: Settings) => useOpenAiModels(s), {
121
+ initialProps: openAi({ openAiApiBaseUrl: "http://a" }),
122
+ });
123
+ rerender(openAi({ openAiApiBaseUrl: "http://ab" }));
124
+ await Promise.resolve();
125
+
126
+ expect(addLogEntry).not.toHaveBeenCalled();
127
+ });
128
+
129
+ it("forgets the previous server's models when the base URL is cleared", async () => {
130
+ vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "m" }]);
131
+ const { result, rerender } = renderHook(
132
+ (s: Settings) => useOpenAiModels(s),
133
+ {
134
+ initialProps: openAi({ openAiApiBaseUrl: "http://a" }),
135
+ },
136
+ );
137
+ await waitFor(() => expect(result.current.openAiModels).toHaveLength(1));
138
+
139
+ rerender(openAi({ openAiApiBaseUrl: "" }));
140
+
141
+ expect(result.current.openAiModels).toEqual([]);
142
+ expect(result.current.useTextInput).toBe(false);
143
+ });
144
+ });
145
+
146
+ describe("useHordeUserInfo", () => {
147
+ it("stays cleared when the key is cleared while a lookup is in flight", async () => {
148
+ const calls = controlled<{ username: string; kudos: number } | null>(
149
+ vi.mocked(fetchHordeUserInfo),
150
+ 1,
151
+ );
152
+ const { result, rerender } = renderHook(
153
+ (s: Settings) => useHordeUserInfo(s),
154
+ {
155
+ initialProps: horde({ hordeApiKey: "secret-key" }),
156
+ },
157
+ );
158
+ rerender(horde({ hordeApiKey: "" }));
159
+
160
+ expect(calls[0].signal.aborted).toBe(true);
161
+ calls[0].resolve({ username: "old#1", kudos: 5 });
162
+ await Promise.resolve();
163
+
164
+ expect(result.current).toBeNull();
165
+ });
166
+
167
+ it("gives up on a /find_user that never answers after 10 seconds", () => {
168
+ const timeouts = manualTimeouts();
169
+ const calls = controlled<null>(vi.mocked(fetchHordeUserInfo), 1);
170
+ renderHook(() => useHordeUserInfo(horde({ hordeApiKey: "secret-key" })));
171
+
172
+ expect(timeouts.map((t) => t.ms)).toEqual([10_000]);
173
+ expect(calls[0].signal.aborted).toBe(false);
174
+ timeouts[0].fire();
175
+ expect(calls[0].signal.aborted).toBe(true);
176
+ });
177
+
178
+ it("does not look up the anonymous key", () => {
179
+ vi.mocked(fetchHordeUserInfo).mockClear();
180
+ renderHook(() =>
181
+ useHordeUserInfo(horde({ hordeApiKey: aiHordeDefaultApiKey })),
182
+ );
183
+ expect(fetchHordeUserInfo).not.toHaveBeenCalled();
184
+ });
185
+ });
186
+
187
+ describe("useHordeModels", () => {
188
+ it("aborts the request when another backend is selected", () => {
189
+ const calls = controlled<never[]>(vi.mocked(fetchHordeModels), 0);
190
+ const { rerender } = renderHook((s: Settings) => useHordeModels(s), {
191
+ initialProps: horde({}),
192
+ });
193
+ rerender(openAi({}));
194
+
195
+ expect(calls[0].signal.aborted).toBe(true);
196
+ });
197
+
198
+ it("gives up on a /status/models that never answers after 10 seconds", () => {
199
+ const timeouts = manualTimeouts();
200
+ const calls = controlled<never[]>(vi.mocked(fetchHordeModels), 0);
201
+ renderHook(() => useHordeModels(horde({})));
202
+
203
+ expect(timeouts.map((t) => t.ms)).toEqual([10_000]);
204
+ timeouts[0].fire();
205
+ expect(calls[0].signal.aborted).toBe(true);
206
+ });
207
+ });
client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { useEffect, useState } from "react";
2
  import { addLogEntry } from "@/modules/logEntries";
3
  import type { defaultSettings } from "@/modules/settings";
@@ -6,20 +7,32 @@ import type { ModelOption } from "../types";
6
 
7
  type Settings = typeof defaultSettings;
8
 
9
- /** AI Horde models as select options; only fetched while Horde is the selected backend. */
 
 
 
 
 
 
10
  export const useHordeModels = (settings: Settings) => {
11
  const [hordeModels, setHordeModels] = useState<ModelOption[]>([]);
12
 
13
  useEffect(() => {
 
 
 
 
14
  async function fetchAvailableHordeModels() {
15
  try {
16
- const models = await fetchHordeModels();
17
- const formattedModels = models.map((model) => ({
18
- label: model.name,
19
- value: model.name,
20
- }));
21
- setHordeModels(formattedModels);
 
22
  } catch (error) {
 
23
  const errorMessage =
24
  error instanceof Error ? error.message : String(error);
25
  addLogEntry(`Error fetching AI Horde models: ${errorMessage}`);
@@ -27,9 +40,8 @@ export const useHordeModels = (settings: Settings) => {
27
  }
28
  }
29
 
30
- if (settings.inferenceType === "horde") {
31
- fetchAvailableHordeModels();
32
- }
33
  }, [settings.inferenceType]);
34
 
35
  return hordeModels;
 
1
+ import { withTimeout } from "@shared/withTimeout";
2
  import { useEffect, useState } from "react";
3
  import { addLogEntry } from "@/modules/logEntries";
4
  import type { defaultSettings } from "@/modules/settings";
 
7
 
8
  type Settings = typeof defaultSettings;
9
 
10
+ /** How long `/status/models` may take before the list falls back to empty. */
11
+ const HORDE_MODELS_TIMEOUT_MS = 10_000;
12
+
13
+ /**
14
+ * AI Horde models as select options; only fetched while Horde is the selected
15
+ * backend. Switching away aborts the request in flight.
16
+ */
17
  export const useHordeModels = (settings: Settings) => {
18
  const [hordeModels, setHordeModels] = useState<ModelOption[]>([]);
19
 
20
  useEffect(() => {
21
+ if (settings.inferenceType !== "horde") return;
22
+
23
+ const controller = new AbortController();
24
+
25
  async function fetchAvailableHordeModels() {
26
  try {
27
+ const models = await fetchHordeModels(
28
+ withTimeout(controller.signal, HORDE_MODELS_TIMEOUT_MS),
29
+ );
30
+ if (controller.signal.aborted) return;
31
+ setHordeModels(
32
+ models.map((model) => ({ label: model.name, value: model.name })),
33
+ );
34
  } catch (error) {
35
+ if (controller.signal.aborted) return;
36
  const errorMessage =
37
  error instanceof Error ? error.message : String(error);
38
  addLogEntry(`Error fetching AI Horde models: ${errorMessage}`);
 
40
  }
41
  }
42
 
43
+ fetchAvailableHordeModels();
44
+ return () => controller.abort();
 
45
  }, [settings.inferenceType]);
46
 
47
  return hordeModels;
client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { useEffect, useState } from "react";
2
  import { addLogEntry } from "@/modules/logEntries";
3
  import type { defaultSettings } from "@/modules/settings";
@@ -9,25 +10,42 @@ import type { HordeUserInfo } from "../types";
9
 
10
  type Settings = typeof defaultSettings;
11
 
12
- /** The logged-in Horde user, or null when the key is empty or the anonymous one. */
 
 
 
 
 
 
 
13
  export const useHordeUserInfo = (settings: Settings) => {
14
  const [hordeUserInfo, setHordeUserInfo] = useState<HordeUserInfo | null>(
15
  null,
16
  );
17
 
18
  useEffect(() => {
 
 
 
 
 
 
 
 
 
 
 
 
19
  async function fetchUserInfo() {
20
  try {
21
- if (
22
- settings.hordeApiKey &&
23
- settings.hordeApiKey !== aiHordeDefaultApiKey
24
- ) {
25
- const userInfo = await fetchHordeUserInfo(settings.hordeApiKey);
26
- setHordeUserInfo(userInfo);
27
- } else {
28
- setHordeUserInfo(null);
29
- }
30
  } catch (error) {
 
31
  const errorMessage =
32
  error instanceof Error ? error.message : String(error);
33
  addLogEntry(`Error fetching AI Horde user info: ${errorMessage}`);
@@ -35,9 +53,8 @@ export const useHordeUserInfo = (settings: Settings) => {
35
  }
36
  }
37
 
38
- if (settings.inferenceType === "horde") {
39
- fetchUserInfo();
40
- }
41
  }, [settings.inferenceType, settings.hordeApiKey]);
42
 
43
  return hordeUserInfo;
 
1
+ import { withTimeout } from "@shared/withTimeout";
2
  import { useEffect, useState } from "react";
3
  import { addLogEntry } from "@/modules/logEntries";
4
  import type { defaultSettings } from "@/modules/settings";
 
10
 
11
  type Settings = typeof defaultSettings;
12
 
13
+ /** How long `/find_user` may take before the user info falls back to none. */
14
+ const HORDE_USER_INFO_TIMEOUT_MS = 10_000;
15
+
16
+ /**
17
+ * The logged-in Horde user, or null when the key is empty or the anonymous one.
18
+ * A key change aborts the request for the previous key, so a slow answer for an
19
+ * old or cleared key can never show up afterwards.
20
+ */
21
  export const useHordeUserInfo = (settings: Settings) => {
22
  const [hordeUserInfo, setHordeUserInfo] = useState<HordeUserInfo | null>(
23
  null,
24
  );
25
 
26
  useEffect(() => {
27
+ if (settings.inferenceType !== "horde") return;
28
+
29
+ if (
30
+ !settings.hordeApiKey ||
31
+ settings.hordeApiKey === aiHordeDefaultApiKey
32
+ ) {
33
+ setHordeUserInfo(null);
34
+ return;
35
+ }
36
+
37
+ const controller = new AbortController();
38
+
39
  async function fetchUserInfo() {
40
  try {
41
+ const userInfo = await fetchHordeUserInfo(
42
+ settings.hordeApiKey,
43
+ withTimeout(controller.signal, HORDE_USER_INFO_TIMEOUT_MS),
44
+ );
45
+ if (controller.signal.aborted) return;
46
+ setHordeUserInfo(userInfo);
 
 
 
47
  } catch (error) {
48
+ if (controller.signal.aborted) return;
49
  const errorMessage =
50
  error instanceof Error ? error.message : String(error);
51
  addLogEntry(`Error fetching AI Horde user info: ${errorMessage}`);
 
53
  }
54
  }
55
 
56
+ fetchUserInfo();
57
+ return () => controller.abort();
 
58
  }, [settings.inferenceType, settings.hordeApiKey]);
59
 
60
  return hordeUserInfo;
client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts CHANGED
@@ -9,29 +9,44 @@ type Settings = typeof defaultSettings;
9
  /**
10
  * Falls back to a free-text model input when the API does not list its models
11
  * or cannot be reached, so the setting stays usable either way.
 
 
 
12
  */
13
  export const useOpenAiModels = (settings: Settings) => {
14
  const [openAiModels, setOpenAiModels] = useState<ModelOption[]>([]);
15
  const [useTextInput, setUseTextInput] = useState(false);
16
 
17
  useEffect(() => {
 
 
 
 
 
 
 
 
 
 
 
18
  async function fetchOpenAiModels() {
19
  try {
20
  const models = await listOpenAiCompatibleModels(
21
  settings.openAiApiBaseUrl,
22
  settings.openAiApiKey,
 
23
  );
24
- const uniqueModelIds = [
25
- ...new Set(models.map((m: { id: string }) => m.id)),
26
- ];
27
  const options: ModelOption[] = uniqueModelIds.map((id) => ({
28
  label: id,
29
  value: id,
30
  }));
31
 
32
  setOpenAiModels(options);
33
- setUseTextInput(!Array.isArray(options) || options.length === 0);
34
  } catch (error) {
 
35
  const errorMessage =
36
  error instanceof Error ? error.message : String(error);
37
  addLogEntry(`Error fetching OpenAI models: ${errorMessage}`);
@@ -40,9 +55,8 @@ export const useOpenAiModels = (settings: Settings) => {
40
  }
41
  }
42
 
43
- if (settings.inferenceType === "openai" && settings.openAiApiBaseUrl) {
44
- fetchOpenAiModels();
45
- }
46
  }, [
47
  settings.inferenceType,
48
  settings.openAiApiBaseUrl,
 
9
  /**
10
  * Falls back to a free-text model input when the API does not list its models
11
  * or cannot be reached, so the setting stays usable either way.
12
+ *
13
+ * Settings change on every keystroke, so each change aborts the request of the
14
+ * previous one: only the latest base URL and key can update the list.
15
  */
16
  export const useOpenAiModels = (settings: Settings) => {
17
  const [openAiModels, setOpenAiModels] = useState<ModelOption[]>([]);
18
  const [useTextInput, setUseTextInput] = useState(false);
19
 
20
  useEffect(() => {
21
+ if (settings.inferenceType !== "openai") return;
22
+
23
+ if (!settings.openAiApiBaseUrl) {
24
+ // No server: forget the previous server's models.
25
+ setOpenAiModels([]);
26
+ setUseTextInput(false);
27
+ return;
28
+ }
29
+
30
+ const controller = new AbortController();
31
+
32
  async function fetchOpenAiModels() {
33
  try {
34
  const models = await listOpenAiCompatibleModels(
35
  settings.openAiApiBaseUrl,
36
  settings.openAiApiKey,
37
+ controller.signal,
38
  );
39
+ if (controller.signal.aborted) return;
40
+ const uniqueModelIds = [...new Set(models.map((m) => m.id))];
 
41
  const options: ModelOption[] = uniqueModelIds.map((id) => ({
42
  label: id,
43
  value: id,
44
  }));
45
 
46
  setOpenAiModels(options);
47
+ setUseTextInput(options.length === 0);
48
  } catch (error) {
49
+ if (controller.signal.aborted) return;
50
  const errorMessage =
51
  error instanceof Error ? error.message : String(error);
52
  addLogEntry(`Error fetching OpenAI models: ${errorMessage}`);
 
55
  }
56
  }
57
 
58
+ fetchOpenAiModels();
59
+ return () => controller.abort();
 
60
  }, [
61
  settings.inferenceType,
62
  settings.openAiApiBaseUrl,
client/components/Search/Form/SearchForm.suggestions.test.tsx ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { MantineProvider } from "@mantine/core";
2
+ import { act, render, screen } 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 { getQuerySuggestions, updateQuerySuggestions } from "@/modules/pubSub";
7
+
8
+ const mockFetch = vi.fn();
9
+ vi.stubGlobal("fetch", mockFetch);
10
+
11
+ vi.mock("wouter", () => ({
12
+ useLocation: () => ["/", vi.fn()],
13
+ }));
14
+
15
+ vi.mock("@/hooks/useSearchHistory", () => ({
16
+ useSearchHistory: () => ({ addToHistory: vi.fn() }),
17
+ }));
18
+
19
+ vi.mock("@/hooks/useHistoryRestore", () => ({
20
+ useHistoryRestore: () => ({ restoreSearch: vi.fn() }),
21
+ }));
22
+
23
+ vi.mock("../History/HistoryButton", () => ({ default: () => null }));
24
+
25
+ vi.mock("@/modules/textGeneration", () => ({ searchAndRespond: vi.fn() }));
26
+
27
+ vi.mock("@/components/DictationButton", () => ({
28
+ dictationButtonWidth: 34,
29
+ default: () => null,
30
+ }));
31
+
32
+ const storedSuggestions = Array.from(
33
+ { length: 25 },
34
+ (_, index) => `suggestion ${index}`,
35
+ );
36
+
37
+ function renderSearchForm(query: string) {
38
+ render(
39
+ <MantineProvider>
40
+ <SearchForm query={query} updateQuery={vi.fn()} />
41
+ </MantineProvider>,
42
+ );
43
+ }
44
+
45
+ /** Lets the suggestion that an emptied field asks for finish arriving. */
46
+ const settle = () => act(async () => {});
47
+
48
+ describe("SearchForm and the stored suggestions", () => {
49
+ beforeEach(() => {
50
+ vi.clearAllMocks();
51
+ resetHandledQuery();
52
+ window.history.replaceState({}, "", "/");
53
+ updateQuerySuggestions([...storedSuggestions]);
54
+ });
55
+
56
+ it("uses one stored suggestion when the last character is deleted", async () => {
57
+ const user = userEvent.setup();
58
+ renderSearchForm("a");
59
+
60
+ await user.type(await screen.findByRole("textbox"), "{Backspace}");
61
+ await settle();
62
+
63
+ expect(getQuerySuggestions()).toHaveLength(24);
64
+ });
65
+
66
+ it("uses one stored suggestion when Clear is clicked", async () => {
67
+ const user = userEvent.setup();
68
+ renderSearchForm("hello");
69
+
70
+ await user.click(await screen.findByRole("button", { name: "Clear" }));
71
+ await settle();
72
+
73
+ expect(getQuerySuggestions()).toHaveLength(24);
74
+ });
75
+
76
+ it("fetches the suggestions once when Clear finds the store empty", async () => {
77
+ updateQuerySuggestions([]);
78
+ mockFetch.mockImplementation(
79
+ async () => new Response(JSON.stringify(["x", "y", "z"])),
80
+ );
81
+ const user = userEvent.setup();
82
+ renderSearchForm("hello");
83
+
84
+ await user.click(await screen.findByRole("button", { name: "Clear" }));
85
+ await settle();
86
+
87
+ expect(mockFetch).toHaveBeenCalledTimes(1);
88
+ expect(getQuerySuggestions()).toHaveLength(2);
89
+ });
90
+ });
client/components/Search/Form/SearchForm.test.tsx CHANGED
@@ -4,6 +4,7 @@ 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 { defaultSettings } from "@/modules/settings";
8
  import { searchAndRespond } from "@/modules/textGeneration";
9
 
@@ -100,6 +101,49 @@ describe("SearchForm component", () => {
100
  await waitForPlaceholder();
101
  });
102
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  describe("Enter and Shift+Enter", () => {
104
  afterEach(() => {
105
  settingsPubSub[0]({ ...defaultSettings });
 
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";
8
  import { defaultSettings } from "@/modules/settings";
9
  import { searchAndRespond } from "@/modules/textGeneration";
10
 
 
101
  await waitForPlaceholder();
102
  });
103
 
104
+ describe("the suggestion for an emptied field", () => {
105
+ it("is taken once when the last character is deleted", async () => {
106
+ const user = userEvent.setup();
107
+ renderSearchForm("a", vi.fn());
108
+ const textarea = await screen.findByRole("textbox");
109
+ vi.mocked(getRandomQuerySuggestion).mockClear();
110
+
111
+ await user.type(textarea, "{Backspace}");
112
+ await act(async () => {});
113
+
114
+ expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);
115
+ });
116
+
117
+ it("is taken once when Clear is clicked", async () => {
118
+ const user = userEvent.setup();
119
+ renderSearchForm("hello", vi.fn());
120
+ await screen.findByRole("textbox");
121
+ vi.mocked(getRandomQuerySuggestion).mockClear();
122
+
123
+ await user.click(screen.getByRole("button", { name: "Clear" }));
124
+ await act(async () => {});
125
+
126
+ expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);
127
+ });
128
+
129
+ it("is dropped when the field was filled again before it arrived", async () => {
130
+ let deliver: (suggestion: string) => void = () => {};
131
+ vi.mocked(getRandomQuerySuggestion)
132
+ .mockImplementationOnce(
133
+ () => new Promise((resolve) => (deliver = resolve)),
134
+ )
135
+ .mockImplementationOnce(() => new Promise(() => {}));
136
+ const user = userEvent.setup();
137
+ renderSearchForm("a", vi.fn());
138
+ const textarea = await screen.findByRole("textbox");
139
+
140
+ await user.type(textarea, "{Backspace}b{Backspace}");
141
+ await act(async () => deliver("a late suggestion"));
142
+
143
+ expect(textarea).toHaveAttribute("placeholder", "Anything you need!");
144
+ });
145
+ });
146
+
147
  describe("Enter and Shift+Enter", () => {
148
  afterEach(() => {
149
  settingsPubSub[0]({ ...defaultSettings });
client/components/Search/Form/SearchForm.tsx CHANGED
@@ -122,52 +122,44 @@ export default memo(function SearchForm({
122
  void initializeComponent();
123
  }, [updateQuery, isRestoringFromHistory, addToHistory]);
124
 
 
 
 
125
  useEffect(() => {
126
- if (state.textAreaValue.length === 0) {
127
- fetchQuerySuggestion()
128
- .then((suggestion) => {
 
 
 
129
  setState((prev) => ({ ...prev, suggestedQuery: suggestion }));
130
- })
131
- .catch(() => {
 
132
  setState((prev) => ({
133
  ...prev,
134
  suggestedQuery: DEFAULT_QUERY_SUGGESTION,
135
  }));
136
- });
137
- }
 
 
 
138
  }, [state.textAreaValue.length, fetchQuerySuggestion]);
139
 
140
- const handleInputChange = async (event: ChangeEvent<HTMLTextAreaElement>) => {
141
  const text = event.target.value;
142
 
143
  setState((prev) => ({ ...prev, textAreaValue: text }));
144
-
145
- if (text.length === 0) {
146
- try {
147
- const suggestion = await getRandomQuerySuggestion();
148
- setState((prev) => ({ ...prev, suggestedQuery: suggestion }));
149
- } catch {
150
- addLogEntry("Failed to get query suggestion");
151
- setState((prev) => ({
152
- ...prev,
153
- suggestedQuery: DEFAULT_QUERY_SUGGESTION,
154
- }));
155
- }
156
- }
157
  };
158
 
159
- const handleClearButtonClick = async () => {
160
  textAreaRef.current?.focus();
161
  setState((prev) => ({
162
  ...prev,
163
  textAreaValue: "",
164
  }));
165
  addLogEntry("User cleaned the search query field");
166
- const suggestion = await fetchQuerySuggestion();
167
- setState((prev) => ({
168
- ...prev,
169
- suggestedQuery: suggestion,
170
- }));
171
  };
172
 
173
  // Stable identities, so `memo` on the dictation button actually holds.
 
122
  void initializeComponent();
123
  }, [updateQuery, isRestoringFromHistory, addToHistory]);
124
 
125
+ // The only place a suggestion is taken when the field empties, whether by
126
+ // typing or by Clear. An answer that arrives after the field was filled again
127
+ // is dropped, so it cannot replace a newer one.
128
  useEffect(() => {
129
+ if (state.textAreaValue.length !== 0) return;
130
+
131
+ let isCurrent = true;
132
+ fetchQuerySuggestion()
133
+ .then((suggestion) => {
134
+ if (isCurrent)
135
  setState((prev) => ({ ...prev, suggestedQuery: suggestion }));
136
+ })
137
+ .catch(() => {
138
+ if (isCurrent)
139
  setState((prev) => ({
140
  ...prev,
141
  suggestedQuery: DEFAULT_QUERY_SUGGESTION,
142
  }));
143
+ });
144
+
145
+ return () => {
146
+ isCurrent = false;
147
+ };
148
  }, [state.textAreaValue.length, fetchQuerySuggestion]);
149
 
150
+ const handleInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
151
  const text = event.target.value;
152
 
153
  setState((prev) => ({ ...prev, textAreaValue: text }));
 
 
 
 
 
 
 
 
 
 
 
 
 
154
  };
155
 
156
+ const handleClearButtonClick = () => {
157
  textAreaRef.current?.focus();
158
  setState((prev) => ({
159
  ...prev,
160
  textAreaValue: "",
161
  }));
162
  addLogEntry("User cleaned the search query field");
 
 
 
 
 
163
  };
164
 
165
  // Stable identities, so `memo` on the dictation button actually holds.
client/components/Search/History/HistoryDrawer.test.tsx CHANGED
@@ -90,6 +90,13 @@ describe("HistoryDrawer component", () => {
90
  expect(await screen.findByText("Search history is disabled")).toBeVisible();
91
  });
92
 
 
 
 
 
 
 
 
93
  it("shows the empty state when there is no history", async () => {
94
  renderDrawer();
95
  expect(await screen.findByText("No search history yet")).toBeVisible();
 
90
  expect(await screen.findByText("Search history is disabled")).toBeVisible();
91
  });
92
 
93
+ it("asks for every pinned search, not only the recent ones", () => {
94
+ renderDrawer();
95
+ expect(useSearchHistory).toHaveBeenCalledWith(
96
+ expect.objectContaining({ includeAllPinned: true }),
97
+ );
98
+ });
99
+
100
  it("shows the empty state when there is no history", async () => {
101
  renderDrawer();
102
  expect(await screen.findByText("No search history yet")).toBeVisible();
client/components/Search/History/HistoryDrawer.tsx CHANGED
@@ -53,7 +53,11 @@ export default function HistoryDrawer({
53
  togglePin,
54
  deleteEntry,
55
  searchHistory,
56
- } = useSearchHistory({ limit: 100, enableGrouping: true });
 
 
 
 
57
 
58
  useEffect(() => {
59
  searchHistory(searchQuery);
 
53
  togglePin,
54
  deleteEntry,
55
  searchHistory,
56
+ } = useSearchHistory({
57
+ limit: 100,
58
+ enableGrouping: true,
59
+ includeAllPinned: true,
60
+ });
61
 
62
  useEffect(() => {
63
  searchHistory(searchQuery);
client/hooks/useHistoryRestore.test.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
  getSuppressNextFollowUp,
8
  imageSearchResultsPubSub,
9
  imageSearchStatePubSub,
 
10
  textSearchResultsPubSub,
11
  updateImageSearchResults,
12
  updateSuppressNextFollowUp,
@@ -19,6 +20,12 @@ vi.mock("wouter", () => ({
19
 
20
  vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
21
 
 
 
 
 
 
 
22
  vi.mock("@/modules/history", async (importOriginal) => ({
23
  ...(await importOriginal<typeof import("@/modules/history")>()),
24
  getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),
@@ -150,4 +157,31 @@ describe("useHistoryRestore", () => {
150
 
151
  expect(getSuppressNextFollowUp()).toBe(true);
152
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  });
 
7
  getSuppressNextFollowUp,
8
  imageSearchResultsPubSub,
9
  imageSearchStatePubSub,
10
+ isRestoringFromHistoryPubSub,
11
  textSearchResultsPubSub,
12
  updateImageSearchResults,
13
  updateSuppressNextFollowUp,
 
20
 
21
  vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
22
 
23
+ vi.mock("@/modules/config", () => ({
24
+ getConfig: vi.fn().mockResolvedValue({
25
+ parentWindowOrigins: ["https://huggingface.co"],
26
+ }),
27
+ }));
28
+
29
  vi.mock("@/modules/history", async (importOriginal) => ({
30
  ...(await importOriginal<typeof import("@/modules/history")>()),
31
  getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),
 
157
 
158
  expect(getSuppressNextFollowUp()).toBe(true);
159
  });
160
+
161
+ it("finishes the restore when embedded after a cross-origin frame", async () => {
162
+ const parentWindow = {
163
+ 0: {
164
+ get location(): Location {
165
+ throw new DOMException("Blocked a frame", "SecurityError");
166
+ },
167
+ },
168
+ postMessage: vi.fn(),
169
+ };
170
+ vi.stubGlobal("parent", parentWindow);
171
+
172
+ try {
173
+ await restoreEntry({ textResults });
174
+ act(() => {
175
+ vi.runOnlyPendingTimers();
176
+ });
177
+
178
+ expect(isRestoringFromHistoryPubSub[2]()).toBe(false);
179
+ expect(parentWindow.postMessage).toHaveBeenCalledWith(
180
+ { queryString: "q=saved%20search", hash: "" },
181
+ "https://huggingface.co",
182
+ );
183
+ } finally {
184
+ vi.unstubAllGlobals();
185
+ }
186
+ });
187
  });
client/hooks/useSearchHistory.test.ts CHANGED
@@ -83,6 +83,160 @@ async function settle() {
83
  });
84
  }
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  describe("useSearchHistory", () => {
87
  it("leaves IndexedDB alone while history is turned off", async () => {
88
  const settingsMock = vi.mocked(getSettings);
 
83
  });
84
  }
85
 
86
+ /**
87
+ * Waits for the hook's read to finish. With includeAllPinned the read also
88
+ * queries the `pinnedAt` index, which takes fake-indexeddb more turns of
89
+ * the real event loop than `settle` alone gives it. setImmediate is left real
90
+ * by the fake timers above, so each await yields one real turn; `vi.waitFor`
91
+ * would not, since under fake timers it polls by advancing fake time.
92
+ */
93
+ async function untilLoaded(result: {
94
+ current: ReturnType<typeof useSearchHistory>;
95
+ }) {
96
+ for (let turn = 0; turn < 500 && result.current.isLoading; turn++) {
97
+ await act(async () => {
98
+ await new Promise((resolve) => setImmediate(resolve));
99
+ });
100
+ }
101
+ expect(result.current.isLoading).toBe(false);
102
+ }
103
+
104
+ /** Pins the oldest seeded entry, "weather in lisbon". */
105
+ async function pinOldestEntry() {
106
+ const [oldest] = await historyDatabase.searches
107
+ .orderBy("timestamp")
108
+ .limit(1)
109
+ .toArray();
110
+ await historyDatabase.searches.update(oldest.id as number, {
111
+ pinned: true,
112
+ pinnedAt: oldest.timestamp,
113
+ });
114
+ }
115
+
116
+ /** Adds newer searches, so the pinned entry falls out of the recent window. */
117
+ async function addNewerSearches(count: number) {
118
+ for (let i = 1; i <= count; i++) {
119
+ await addSearchToHistory(`newer search ${i}`, textResults);
120
+ vi.advanceTimersByTime(1000);
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",
138
+ "newer search 3",
139
+ "weather in lisbon",
140
+ ]);
141
+ });
142
+
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",
154
+ "best pizza porto",
155
+ "weather in lisbon",
156
+ ]);
157
+ });
158
+
159
+ it("lets the filter find a pinned search outside the recent window", async () => {
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
+
171
+ expect(queriesOf(result.current.filteredSearches)).toEqual([
172
+ "weather in lisbon",
173
+ ]);
174
+ });
175
+
176
+ it("still reads IndexedDB only on load, never while typing", async () => {
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"]) {
188
+ act(() => result.current.searchHistory(query));
189
+ await settle();
190
+ }
191
+
192
+ expect(pinnedReadSpy).toHaveBeenCalledTimes(1);
193
+ });
194
+
195
+ it("leaves the recent window as it is without the option", async () => {
196
+ await pinOldestEntry();
197
+ await addNewerSearches(4);
198
+
199
+ const { result } = renderHook(() => useSearchHistory({ limit: 2 }));
200
+ await settle();
201
+ await untilLoaded(result);
202
+
203
+ expect(queriesOf(result.current.filteredSearches)).toEqual([
204
+ "newer search 4",
205
+ "newer search 3",
206
+ ]);
207
+ });
208
+ it("pins and unpins through both fields, so the index agrees with the flag", async () => {
209
+ const [oldest] = await historyDatabase.searches
210
+ .orderBy("timestamp")
211
+ .limit(1)
212
+ .toArray();
213
+ const id = oldest.id as number;
214
+
215
+ const { result } = renderHook(() =>
216
+ useSearchHistory({ limit: 2, includeAllPinned: true }),
217
+ );
218
+ await untilLoaded(result);
219
+
220
+ await act(async () => {
221
+ await result.current.togglePin(id);
222
+ });
223
+ const pinned = await historyDatabase.searches.get(id);
224
+ expect(pinned?.pinned).toBe(true);
225
+ expect(pinned?.pinnedAt).toBe(Date.now());
226
+ expect(queriesOf(await historyModule.getPinnedSearches())).toEqual([
227
+ "weather in lisbon",
228
+ ]);
229
+
230
+ await act(async () => {
231
+ await result.current.togglePin(id);
232
+ });
233
+ const unpinned = await historyDatabase.searches.get(id);
234
+ expect(unpinned?.pinned).toBe(false);
235
+ expect(unpinned && "pinnedAt" in unpinned).toBe(false);
236
+ expect(await historyModule.getPinnedSearches()).toEqual([]);
237
+ });
238
+ });
239
+
240
  describe("useSearchHistory", () => {
241
  it("leaves IndexedDB alone while history is turned off", async () => {
242
  const settingsMock = vi.mocked(getSettings);
client/hooks/useSearchHistory.ts CHANGED
@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
2
  import {
3
  addSearchToHistory,
4
  clearAllHistory,
 
5
  getRecentSearches,
6
  historyDatabase,
7
  type ImageResults,
@@ -22,6 +23,12 @@ interface UseSearchHistoryOptions {
22
  enableGrouping?: boolean;
23
  enablePagination?: boolean;
24
  pageSize?: number;
 
 
 
 
 
 
25
  }
26
 
27
  interface UseSearchHistoryReturn {
@@ -69,6 +76,7 @@ export function useSearchHistory(
69
  enableGrouping = true,
70
  enablePagination = false,
71
  pageSize = 20,
 
72
  } = options;
73
 
74
  const [entries, setEntries] = useState<SearchEntry[]>([]);
@@ -104,14 +112,21 @@ export function useSearchHistory(
104
  return;
105
  }
106
 
107
- const searches = await getRecentSearches(
108
- enablePagination ? 1000 : limit * 2,
109
- );
110
-
111
- const [llmCount, chatCount] = await Promise.all([
112
  historyDatabase.llmResponses.count(),
113
  historyDatabase.chatHistory.count(),
114
  ]);
 
 
 
 
 
 
 
 
 
115
  setLlmResponseCount(llmCount);
116
  setChatMessageCount(chatCount);
117
  setEntries(searches);
@@ -124,7 +139,7 @@ export function useSearchHistory(
124
  isLoadingRef.current = false;
125
  setIsLoading(false);
126
  }
127
- }, [limit, enablePagination]);
128
 
129
  // Typing only schedules a debounced settle of the query; it never reaches
130
  // IndexedDB. Clearing settles synchronously so the full list returns on the
@@ -175,17 +190,30 @@ export function useSearchHistory(
175
  entries,
176
  query,
177
  (search) => search.query,
178
- enablePagination ? entries.length : limit,
179
  ).map((result) => result.item);
180
- }, [entries, settledQuery, enablePagination, limit]);
181
 
182
  const filteredSearches = useMemo(() => {
183
  if (enablePagination) {
184
  const startIndex = currentPage * pageSize;
185
  return matched.slice(startIndex, startIndex + pageSize);
186
  }
187
- return matched.slice(0, limit);
188
- }, [matched, enablePagination, currentPage, pageSize, limit]);
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  const matchedCount = matched.length;
191
 
@@ -222,8 +250,12 @@ export function useSearchHistory(
222
  try {
223
  const search = await historyDatabase.searches.get(searchId);
224
  if (search) {
 
 
 
225
  await historyDatabase.searches.update(searchId, {
226
- pinned: !search.pinned,
 
227
  });
228
  await refreshHistory();
229
  addLogEntry(
 
2
  import {
3
  addSearchToHistory,
4
  clearAllHistory,
5
+ getPinnedSearches,
6
  getRecentSearches,
7
  historyDatabase,
8
  type ImageResults,
 
23
  enableGrouping?: boolean;
24
  enablePagination?: boolean;
25
  pageSize?: number;
26
+ /**
27
+ * Keep every pinned search in the list, however many newer searches exist.
28
+ * Costs one extra read of the `pinnedAt` index per refresh; only the History
29
+ * drawer asks for it.
30
+ */
31
+ includeAllPinned?: boolean;
32
  }
33
 
34
  interface UseSearchHistoryReturn {
 
76
  enableGrouping = true,
77
  enablePagination = false,
78
  pageSize = 20,
79
+ includeAllPinned = false,
80
  } = options;
81
 
82
  const [entries, setEntries] = useState<SearchEntry[]>([]);
 
112
  return;
113
  }
114
 
115
+ const [recent, pinned, llmCount, chatCount] = await Promise.all([
116
+ getRecentSearches(enablePagination ? 1000 : limit * 2),
117
+ includeAllPinned ? getPinnedSearches() : Promise.resolve([]),
 
 
118
  historyDatabase.llmResponses.count(),
119
  historyDatabase.chatHistory.count(),
120
  ]);
121
+
122
+ // A pinned entry missing from the recent window is older than all of
123
+ // it, so appending keeps the list newest first.
124
+ const recentIds = new Set(recent.map((search) => search.id));
125
+ const searches = [
126
+ ...recent,
127
+ ...pinned.filter((search) => !recentIds.has(search.id)),
128
+ ];
129
+
130
  setLlmResponseCount(llmCount);
131
  setChatMessageCount(chatCount);
132
  setEntries(searches);
 
139
  isLoadingRef.current = false;
140
  setIsLoading(false);
141
  }
142
+ }, [limit, enablePagination, includeAllPinned]);
143
 
144
  // Typing only schedules a debounced settle of the query; it never reaches
145
  // IndexedDB. Clearing settles synchronously so the full list returns on the
 
190
  entries,
191
  query,
192
  (search) => search.query,
193
+ enablePagination || includeAllPinned ? entries.length : limit,
194
  ).map((result) => result.item);
195
+ }, [entries, settledQuery, enablePagination, includeAllPinned, limit]);
196
 
197
  const filteredSearches = useMemo(() => {
198
  if (enablePagination) {
199
  const startIndex = currentPage * pageSize;
200
  return matched.slice(startIndex, startIndex + pageSize);
201
  }
202
+ const shown = matched.slice(0, limit);
203
+ if (!includeAllPinned) return shown;
204
+ // The limit caps the unpinned list only: a pinned match past it stays.
205
+ return [
206
+ ...shown,
207
+ ...matched.slice(limit).filter((search) => search.pinned),
208
+ ];
209
+ }, [
210
+ matched,
211
+ enablePagination,
212
+ includeAllPinned,
213
+ currentPage,
214
+ pageSize,
215
+ limit,
216
+ ]);
217
 
218
  const matchedCount = matched.length;
219
 
 
250
  try {
251
  const search = await historyDatabase.searches.get(searchId);
252
  if (search) {
253
+ // One update for both fields, so the `pinnedAt` index never
254
+ // disagrees with `pinned`. Dexie deletes a key set to undefined.
255
+ const pinned = !search.pinned;
256
  await historyDatabase.searches.update(searchId, {
257
+ pinned,
258
+ pinnedAt: pinned ? Date.now() : undefined,
259
  });
260
  await refreshHistory();
261
  addLogEntry(
client/modules/accessKey.test.ts CHANGED
@@ -172,6 +172,7 @@ describe("Access Key Module", () => {
172
  );
173
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
174
  expect(result).toBe(false);
 
175
  });
176
 
177
  it("should return false without asking the server when the timeout is zero", async () => {
@@ -196,6 +197,19 @@ describe("Access Key Module", () => {
196
 
197
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
198
  expect(result).toBe(false);
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  });
200
 
201
  it("keeps the stored hash on a 429 instead of deleting it", async () => {
@@ -215,5 +229,75 @@ describe("Access Key Module", () => {
215
  // A rate-limited validation must not be read as a wrong key.
216
  expect(localStorage.getItem("accessKeyHash")).not.toBeNull();
217
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  });
219
  });
 
172
  );
173
  const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
174
  expect(result).toBe(false);
175
+ expect(localStorage.getItem("accessKeyHash")).toBeNull();
176
  });
177
 
178
  it("should return false without asking the server when the timeout is zero", async () => {
 
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 () => {
205
+ const { verifyStoredAccessKey } = await import("./accessKey");
206
+ localStorage.setItem("accessKeyHash", "not-json");
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 () => {
 
229
  // A rate-limited validation must not be read as a wrong key.
230
  expect(localStorage.getItem("accessKeyHash")).not.toBeNull();
231
  });
232
+
233
+ describe("when the server gives no verdict on the key", () => {
234
+ const storedValue = JSON.stringify({
235
+ hash: "test-hash",
236
+ timestamp: Date.now(),
237
+ });
238
+
239
+ it.each([
240
+ [
241
+ "the fetch rejects",
242
+ () => mockFetch.mockRejectedValue(new TypeError("Failed to fetch")),
243
+ ],
244
+ [
245
+ "a proxy answers 502 with a page that is not JSON",
246
+ () =>
247
+ mockFetch.mockResolvedValue({
248
+ ok: false,
249
+ status: 502,
250
+ json: vi
251
+ .fn()
252
+ .mockRejectedValue(new SyntaxError("Unexpected token <")),
253
+ }),
254
+ ],
255
+ [
256
+ "the SPA fallback answers 200 with the app page",
257
+ () =>
258
+ mockFetch.mockResolvedValue({
259
+ ok: true,
260
+ status: 200,
261
+ json: vi
262
+ .fn()
263
+ .mockRejectedValue(new SyntaxError("Unexpected token <")),
264
+ }),
265
+ ],
266
+ [
267
+ "a proxy answers 503 with JSON that has no verdict",
268
+ () =>
269
+ mockFetch.mockResolvedValue({
270
+ ok: false,
271
+ status: 503,
272
+ json: vi
273
+ .fn()
274
+ .mockResolvedValue({ error: "upstream unavailable" }),
275
+ }),
276
+ ],
277
+ ])("keeps the stored hash when %s", async (_situation, answerWithIt) => {
278
+ const { verifyStoredAccessKey } = await import("./accessKey");
279
+ answerWithIt();
280
+ localStorage.setItem("accessKeyHash", storedValue);
281
+
282
+ const result = await verifyStoredAccessKey(TIMEOUT_HOURS);
283
+
284
+ expect(result).toBe(false);
285
+ expect(localStorage.getItem("accessKeyHash")).toBe(storedValue);
286
+ });
287
+
288
+ it("accepts the same hash on the next load once the server answers", async () => {
289
+ const { verifyStoredAccessKey } = await import("./accessKey");
290
+ localStorage.setItem("accessKeyHash", storedValue);
291
+
292
+ mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));
293
+ await verifyStoredAccessKey(TIMEOUT_HOURS);
294
+ mockFetch.mockResolvedValue({
295
+ ok: true,
296
+ json: vi.fn().mockResolvedValue({ valid: true }),
297
+ });
298
+
299
+ await expect(verifyStoredAccessKey(TIMEOUT_HOURS)).resolves.toBe(true);
300
+ });
301
+ });
302
  });
303
  });
client/modules/accessKey.ts CHANGED
@@ -95,42 +95,58 @@ export async function verifyStoredAccessKey(
95
  const storedData = localStorage.getItem(ACCESS_KEY_STORAGE_KEY);
96
  if (!storedData) return false;
97
 
 
 
98
  try {
99
- const { hash, timestamp }: StoredAccessKey = JSON.parse(storedData);
 
 
 
 
 
100
 
101
- const expirationTime = timeoutHours * 60 * 60 * 1000;
102
- if (Date.now() - timestamp > expirationTime) {
103
- localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
104
- addLogEntry("Stored access key expired");
105
- return false;
106
- }
107
 
 
 
 
 
 
 
108
  const response = await fetch("/api/validate-access-key", {
109
  method: "POST",
110
  headers: { "Content-Type": "application/json" },
111
  body: JSON.stringify({ accessKeyHash: hash }),
112
  });
113
 
114
- // A 429 must not be read as "wrong key": the stored hash may be fine and
115
- // the caller simply hit the rate limiter. Keep the hash on disk so a
116
- // later load can still validate it.
117
- if (response.status === 429) {
118
- addLogEntry("Stored access key validation rate-limited");
119
  return false;
120
  }
121
 
122
  const data = await response.json();
123
- if (!data.valid) {
 
 
 
 
 
124
  localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
125
  addLogEntry("Stored access key is no longer valid");
126
  return false;
127
  }
128
 
129
- addLogEntry("Using stored access key");
130
- return true;
131
  } catch (error) {
132
  addLogEntry(`Error verifying stored access key: ${error}`);
133
- localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
134
  return false;
135
  }
136
  }
 
95
  const storedData = localStorage.getItem(ACCESS_KEY_STORAGE_KEY);
96
  if (!storedData) return false;
97
 
98
+ let hash: string;
99
+ let timestamp: number;
100
  try {
101
+ ({ hash, timestamp } = JSON.parse(storedData) as StoredAccessKey);
102
+ } catch (error) {
103
+ addLogEntry(`Error reading stored access key: ${error}`);
104
+ localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
105
+ return false;
106
+ }
107
 
108
+ const expirationTime = timeoutHours * 60 * 60 * 1000;
109
+ if (Date.now() - timestamp > expirationTime) {
110
+ localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
111
+ addLogEntry("Stored access key expired");
112
+ return false;
113
+ }
114
 
115
+ // Only the server saying the key is invalid may delete the hash. Anything
116
+ // else leaves the server's verdict unknown: an unreachable server, a rate
117
+ // limit, a proxy's error page. The user would have to retype a key that is
118
+ // still good, while keeping the hash costs nothing, because access still
119
+ // needs a fresh `valid: true` on every load.
120
+ try {
121
  const response = await fetch("/api/validate-access-key", {
122
  method: "POST",
123
  headers: { "Content-Type": "application/json" },
124
  body: JSON.stringify({ accessKeyHash: hash }),
125
  });
126
 
127
+ if (!response.ok) {
128
+ addLogEntry(
129
+ `Stored access key could not be verified (status ${response.status})`,
130
+ );
 
131
  return false;
132
  }
133
 
134
  const data = await response.json();
135
+ if (data.valid === true) {
136
+ addLogEntry("Using stored access key");
137
+ return true;
138
+ }
139
+
140
+ if (data.valid === false) {
141
  localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);
142
  addLogEntry("Stored access key is no longer valid");
143
  return false;
144
  }
145
 
146
+ addLogEntry("Stored access key could not be verified (unexpected reply)");
147
+ return false;
148
  } catch (error) {
149
  addLogEntry(`Error verifying stored access key: ${error}`);
 
150
  return false;
151
  }
152
  }
client/modules/config.test.ts CHANGED
@@ -13,6 +13,7 @@ const serverConfig: ServerConfig = {
13
  internalApiName: "Custom LLM",
14
  defaultInferenceType: "internal",
15
  searchToken: "a".repeat(64),
 
16
  };
17
 
18
  /** Imports a fresh copy of the module so its cache starts empty. */
 
13
  internalApiName: "Custom LLM",
14
  defaultInferenceType: "internal",
15
  searchToken: "a".repeat(64),
16
+ parentWindowOrigins: ["https://huggingface.co"],
17
  };
18
 
19
  /** Imports a fresh copy of the module so its cache starts empty. */
client/modules/config.ts CHANGED
@@ -23,7 +23,9 @@ export type { ServerConfig };
23
  *
24
  * `searchToken` has no harmless stand-in, so it is empty here. Anything that
25
  * needs it goes through `getConfig`, which rejects rather than handing back a
26
- * token the server would turn away.
 
 
27
  */
28
  export const FALLBACK_CONFIG: ServerConfig = {
29
  accessKeysEnabled: false,
@@ -34,6 +36,7 @@ export const FALLBACK_CONFIG: ServerConfig = {
34
  internalApiName: DEFAULT_INTERNAL_API_NAME,
35
  defaultInferenceType: DEFAULT_INFERENCE_TYPE,
36
  searchToken: "",
 
37
  };
38
 
39
  const FETCH_TIMEOUT_MS = 5000;
 
23
  *
24
  * `searchToken` has no harmless stand-in, so it is empty here. Anything that
25
  * needs it goes through `getConfig`, which rejects rather than handing back a
26
+ * token the server would turn away. `parentWindowOrigins` is empty for the
27
+ * same reason: without the server's list, no embedding page is trusted with
28
+ * the query.
29
  */
30
  export const FALLBACK_CONFIG: ServerConfig = {
31
  accessKeysEnabled: false,
 
36
  internalApiName: DEFAULT_INTERNAL_API_NAME,
37
  defaultInferenceType: DEFAULT_INFERENCE_TYPE,
38
  searchToken: "",
39
+ parentWindowOrigins: [],
40
  };
41
 
42
  const FETCH_TIMEOUT_MS = 5000;
client/modules/followUpQuestions.test.ts CHANGED
@@ -3,11 +3,15 @@ import { generateFollowUpQuestion } from "./followUpQuestions";
3
 
4
  vi.mock("./textGeneration", () => ({
5
  generateChatResponse: vi.fn(),
 
6
  }));
7
 
8
- import { generateChatResponse } from "./textGeneration";
 
 
 
9
 
10
- const mockedGenerateChatResponse = vi.mocked(generateChatResponse);
11
 
12
  beforeEach(() => {
13
  vi.clearAllMocks();
@@ -15,7 +19,7 @@ beforeEach(() => {
15
 
16
  describe("generateFollowUpQuestion", () => {
17
  it("keeps an English question with leading numbering", async () => {
18
- mockedGenerateChatResponse.mockResolvedValue(
19
  "1. What about the alternatives?",
20
  );
21
 
@@ -28,7 +32,7 @@ describe("generateFollowUpQuestion", () => {
28
  });
29
 
30
  it("keeps a Chinese question ending in a fullwidth question mark", async () => {
31
- mockedGenerateChatResponse.mockResolvedValue("你觉得这个方案怎么样?");
32
 
33
  const question = await generateFollowUpQuestion({
34
  topic: "方案",
@@ -39,7 +43,7 @@ describe("generateFollowUpQuestion", () => {
39
  });
40
 
41
  it("strips a leading bullet from a Japanese question without touching the text", async () => {
42
- mockedGenerateChatResponse.mockResolvedValue(
43
  "- この案についてどう思いますか?",
44
  );
45
 
@@ -52,7 +56,7 @@ describe("generateFollowUpQuestion", () => {
52
  });
53
 
54
  it("keeps an Arabic question ending in an Arabic question mark", async () => {
55
- mockedGenerateChatResponse.mockResolvedValue("ما رأيك في البدائل؟");
56
 
57
  const question = await generateFollowUpQuestion({
58
  topic: "البدائل",
@@ -63,7 +67,7 @@ describe("generateFollowUpQuestion", () => {
63
  });
64
 
65
  it("returns an empty string when no line ends with a question mark", async () => {
66
- mockedGenerateChatResponse.mockResolvedValue("No questions here.");
67
 
68
  const question = await generateFollowUpQuestion({
69
  topic: "cats",
@@ -74,11 +78,48 @@ describe("generateFollowUpQuestion", () => {
74
  });
75
  });
76
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  describe("generateFollowUpQuestion and the chat history", () => {
78
  it("writes no chat rows for the follow-up exchange, since nothing reads them", async () => {
79
  const { historyDatabase } = await import("./history");
80
  const before = await historyDatabase.chatHistory.count();
81
- mockedGenerateChatResponse.mockResolvedValue("1. What comes next?");
82
 
83
  await generateFollowUpQuestion({
84
  topic: "cats",
@@ -88,3 +129,20 @@ describe("generateFollowUpQuestion and the chat history", () => {
88
  expect(await historyDatabase.chatHistory.count()).toBe(before);
89
  });
90
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
  vi.mock("./textGeneration", () => ({
5
  generateChatResponse: vi.fn(),
6
+ generateReplyToMessages: vi.fn(),
7
  }));
8
 
9
+ import {
10
+ generateChatResponse,
11
+ generateReplyToMessages,
12
+ } from "./textGeneration";
13
 
14
+ const mockedGenerateReplyToMessages = vi.mocked(generateReplyToMessages);
15
 
16
  beforeEach(() => {
17
  vi.clearAllMocks();
 
19
 
20
  describe("generateFollowUpQuestion", () => {
21
  it("keeps an English question with leading numbering", async () => {
22
+ mockedGenerateReplyToMessages.mockResolvedValue(
23
  "1. What about the alternatives?",
24
  );
25
 
 
32
  });
33
 
34
  it("keeps a Chinese question ending in a fullwidth question mark", async () => {
35
+ mockedGenerateReplyToMessages.mockResolvedValue("你觉得这个方案怎么样?");
36
 
37
  const question = await generateFollowUpQuestion({
38
  topic: "方案",
 
43
  });
44
 
45
  it("strips a leading bullet from a Japanese question without touching the text", async () => {
46
+ mockedGenerateReplyToMessages.mockResolvedValue(
47
  "- この案についてどう思いますか?",
48
  );
49
 
 
56
  });
57
 
58
  it("keeps an Arabic question ending in an Arabic question mark", async () => {
59
+ mockedGenerateReplyToMessages.mockResolvedValue("ما رأيك في البدائل؟");
60
 
61
  const question = await generateFollowUpQuestion({
62
  topic: "البدائل",
 
67
  });
68
 
69
  it("returns an empty string when no line ends with a question mark", async () => {
70
+ mockedGenerateReplyToMessages.mockResolvedValue("No questions here.");
71
 
72
  const question = await generateFollowUpQuestion({
73
  topic: "cats",
 
78
  });
79
  });
80
 
81
+ describe("generateFollowUpQuestion and the chat generation", () => {
82
+ it("sends the prompt alone, with the topic and the answer in it", async () => {
83
+ mockedGenerateReplyToMessages.mockResolvedValue("What comes next?");
84
+
85
+ await generateFollowUpQuestion({
86
+ topic: "cats",
87
+ currentContent: "Cats sleep up to sixteen hours a day.",
88
+ previousQuestions: ["Why do cats purr?"],
89
+ });
90
+
91
+ // The chat path puts the system prompt and the search results in front,
92
+ // and keys the conversation summary by the first message.
93
+ expect(generateChatResponse).not.toHaveBeenCalled();
94
+ const [messages] = mockedGenerateReplyToMessages.mock.calls[0];
95
+ expect(messages).toHaveLength(1);
96
+ expect(messages[0].role).toBe("user");
97
+ expect(messages[0].content).toContain("cats");
98
+ expect(messages[0].content).toContain(
99
+ "Cats sleep up to sixteen hours a day.",
100
+ );
101
+ expect(messages[0].content).toContain("1. Why do cats purr?");
102
+ });
103
+
104
+ it("returns an empty string when the prompt is too long to send", async () => {
105
+ mockedGenerateReplyToMessages.mockRejectedValue(
106
+ new Error("The newest message is too long"),
107
+ );
108
+
109
+ const question = await generateFollowUpQuestion({
110
+ topic: "cats",
111
+ currentContent: "Cats are independent. ".repeat(5000),
112
+ });
113
+
114
+ expect(question).toBe("");
115
+ });
116
+ });
117
+
118
  describe("generateFollowUpQuestion and the chat history", () => {
119
  it("writes no chat rows for the follow-up exchange, since nothing reads them", async () => {
120
  const { historyDatabase } = await import("./history");
121
  const before = await historyDatabase.chatHistory.count();
122
+ mockedGenerateReplyToMessages.mockResolvedValue("1. What comes next?");
123
 
124
  await generateFollowUpQuestion({
125
  topic: "cats",
 
129
  expect(await historyDatabase.chatHistory.count()).toBe(before);
130
  });
131
  });
132
+
133
+ describe("generateFollowUpQuestion and reasoning", () => {
134
+ it("leaves the reasoning block out of the prompt", async () => {
135
+ mockedGenerateReplyToMessages.mockResolvedValue("1. What comes next?");
136
+
137
+ await generateFollowUpQuestion({
138
+ topic: "cats",
139
+ currentContent:
140
+ "<think>The user wants cat facts.</think>\n\nCats are independent.",
141
+ });
142
+
143
+ const [messages] = mockedGenerateReplyToMessages.mock.calls[0];
144
+ const prompt = messages.map((message) => message.content).join("\n");
145
+ expect(prompt).toContain("Cats are independent.");
146
+ expect(prompt).not.toContain("The user wants cat facts.");
147
+ });
148
+ });
client/modules/followUpQuestions.ts CHANGED
@@ -1,5 +1,6 @@
1
  import { addLogEntry } from "./logEntries";
2
- import { generateChatResponse } from "./textGeneration";
 
3
  import type { ChatMessage } from "./types";
4
 
5
  interface FollowUpQuestionParams {
@@ -30,7 +31,7 @@ ${topic}
30
 
31
  The response was:
32
  ~~~
33
- ${currentContent}
34
  ~~~
35
 
36
  Follow these instructions:
@@ -58,7 +59,10 @@ Respond with just the question, no additional text or explanations.`,
58
  },
59
  ];
60
 
61
- const response = await generateChatResponse(promptMessages, () => {});
 
 
 
62
 
63
  const lines = response
64
  .trim()
 
1
  import { addLogEntry } from "./logEntries";
2
+ import { generateReplyToMessages } from "./textGeneration";
3
+ import { answerOnly } from "./textGenerationUtilities";
4
  import type { ChatMessage } from "./types";
5
 
6
  interface FollowUpQuestionParams {
 
31
 
32
  The response was:
33
  ~~~
34
+ ${answerOnly(currentContent)}
35
  ~~~
36
 
37
  Follow these instructions:
 
59
  },
60
  ];
61
 
62
+ // The prompt carries the topic and the answer itself, so it goes out
63
+ // alone: no system prompt or search results in front of it, and no
64
+ // reading or writing of the chat's conversation summary.
65
+ const response = await generateReplyToMessages(promptMessages);
66
 
67
  const lines = response
68
  .trim()
client/modules/history.test.ts CHANGED
@@ -278,6 +278,36 @@ describe("History Module - Dexie CRUD", () => {
278
  });
279
  });
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  describe("addSearchToHistory + getRecentSearches round-trip", () => {
282
  it("should preserve query, source, and searchRunId through a write/read cycle", async () => {
283
  const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =
@@ -905,4 +935,45 @@ describe("History Module - a search takes its answers and chats with it", () =>
905
  expect(chats.map((row) => row.content)).toEqual(["kept"]);
906
  expect(await historyDatabase.searches.count()).toBe(1);
907
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  });
 
278
  });
279
  });
280
 
281
+ describe("getPinnedSearches", () => {
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);
292
+ vi.setSystemTime(new Date(2000, 0, 2));
293
+ await addSearchToHistory("never pinned", results);
294
+ vi.setSystemTime(new Date(2000, 0, 3));
295
+ const newest = await addSearchToHistory("pinned lately", results);
296
+ for (const id of [oldest, newest]) {
297
+ await historyDatabase.searches.update(id as number, {
298
+ pinned: true,
299
+ pinnedAt: Date.now(),
300
+ });
301
+ }
302
+
303
+ const pinned = await getPinnedSearches();
304
+ expect(pinned.map((search) => search.query)).toEqual([
305
+ "pinned lately",
306
+ "pinned long ago",
307
+ ]);
308
+ });
309
+ });
310
+
311
  describe("addSearchToHistory + getRecentSearches round-trip", () => {
312
  it("should preserve query, source, and searchRunId through a write/read cycle", async () => {
313
  const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =
 
935
  expect(chats.map((row) => row.content)).toEqual(["kept"]);
936
  expect(await historyDatabase.searches.count()).toBe(1);
937
  });
938
+
939
+ it("indexes the searches pinned before a version 2 database is upgraded", async () => {
940
+ const { getPinnedSearches, historyDatabase } = await import("./history");
941
+ historyDatabase.close({ disableAutoOpen: false });
942
+ await Dexie.delete("History");
943
+
944
+ const v2Schema = {
945
+ searches: "++id, searchRunId, query, timestamp, source, pinned, results",
946
+ llmResponses: "++id, searchId, searchRunId, timestamp, model",
947
+ chatHistory:
948
+ "++id, conversationId, timestamp, [conversationId+timestamp]",
949
+ };
950
+ const v2 = new Dexie("History");
951
+ v2.version(1).stores(v2Schema);
952
+ v2.version(2).stores(v2Schema);
953
+ await v2.table("searches").bulkAdd([
954
+ { query: "pinned long ago", timestamp: 1_000, pinned: true },
955
+ { query: "never pinned", timestamp: 2_000, pinned: false },
956
+ { query: "pinned lately", timestamp: 3_000, pinned: true },
957
+ ]);
958
+ v2.close();
959
+
960
+ await historyDatabase.open();
961
+
962
+ const pinned = await getPinnedSearches();
963
+ expect(pinned.map((search) => [search.query, search.pinnedAt])).toEqual([
964
+ ["pinned lately", 3_000],
965
+ ["pinned long ago", 1_000],
966
+ ]);
967
+ const unpinned = await historyDatabase.searches
968
+ .where("query")
969
+ .equals("never pinned")
970
+ .first();
971
+ expect(unpinned && "pinnedAt" in unpinned).toBe(false);
972
+ // The boolean index never held an entry, so version 3 drops it.
973
+ const indexNames = historyDatabase.searches.schema.indexes.map(
974
+ (index) => index.name,
975
+ );
976
+ expect(indexNames).toContain("pinnedAt");
977
+ expect(indexNames).not.toContain("pinned");
978
+ });
979
  });
client/modules/history.ts CHANGED
@@ -93,6 +93,12 @@ export interface SearchEntry {
93
  content: string;
94
  }>;
95
  pinned?: boolean;
 
 
 
 
 
 
96
  source?: string;
97
  }
98
 
@@ -147,12 +153,36 @@ async function dropRowsNoSearchOwns(tx: Transaction): Promise<void> {
147
  .delete();
148
  }
149
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  const historySchema = {
151
  searches: "++id, searchRunId, query, timestamp, source, pinned, results",
152
  llmResponses: "++id, searchId, searchRunId, timestamp, model",
153
  chatHistory: "++id, conversationId, timestamp, [conversationId+timestamp]",
154
  };
155
 
 
 
 
 
 
 
 
 
 
 
156
  class HistoryDatabase extends Dexie {
157
  searches!: Table<SearchEntry>;
158
  llmResponses!: Table<LLMResponse>;
@@ -163,6 +193,7 @@ class HistoryDatabase extends Dexie {
163
 
164
  this.version(1).stores(historySchema);
165
  this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns);
 
166
  }
167
 
168
  /**
@@ -362,6 +393,71 @@ export async function getRecentSearches(
362
  });
363
  }
364
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  export async function saveLlmResponseForQuery(
366
  query: string,
367
  response: string,
 
93
  content: string;
94
  }>;
95
  pinned?: boolean;
96
+ /**
97
+ * When the entry was pinned; absent while unpinned. It is indexed in place of
98
+ * `pinned`, because IndexedDB does not index boolean values, so only pinned
99
+ * entries are in this index. `togglePin` writes both fields in one update.
100
+ */
101
+ pinnedAt?: number;
102
  source?: string;
103
  }
104
 
 
153
  .delete();
154
  }
155
 
156
+ /**
157
+ * Entries pinned before `pinnedAt` existed get one, so the index finds them.
158
+ * Their real pin time is unknown; the entry's own `timestamp` stands in, which
159
+ * keeps a plausible pin order.
160
+ */
161
+ async function indexPinnedEntries(tx: Transaction): Promise<void> {
162
+ await tx
163
+ .table<SearchEntry>("searches")
164
+ .filter((search) => search.pinned === true)
165
+ .modify((search) => {
166
+ search.pinnedAt = search.timestamp;
167
+ });
168
+ }
169
+
170
  const historySchema = {
171
  searches: "++id, searchRunId, query, timestamp, source, pinned, results",
172
  llmResponses: "++id, searchId, searchRunId, timestamp, model",
173
  chatHistory: "++id, conversationId, timestamp, [conversationId+timestamp]",
174
  };
175
 
176
+ /**
177
+ * Version 3 drops the `pinned` index, which never held an entry (IndexedDB
178
+ * does not index booleans), and indexes `pinnedAt` instead. The `pinned`
179
+ * field itself stays.
180
+ */
181
+ const historySchemaV3 = {
182
+ ...historySchema,
183
+ searches: "++id, searchRunId, query, timestamp, source, pinnedAt, results",
184
+ };
185
+
186
  class HistoryDatabase extends Dexie {
187
  searches!: Table<SearchEntry>;
188
  llmResponses!: Table<LLMResponse>;
 
193
 
194
  this.version(1).stores(historySchema);
195
  this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns);
196
+ this.version(3).stores(historySchemaV3).upgrade(indexPinnedEntries);
197
  }
198
 
199
  /**
 
393
  });
394
  }
395
 
396
+ /** What the analytics need of a saved search: when it happened and where it came from. */
397
+ export interface SearchActivityRecord {
398
+ timestamp: number;
399
+ source?: string;
400
+ }
401
+
402
+ /**
403
+ * Every saved search as a timestamp and a source, read from the two indexes
404
+ * alone, so the result payloads (which dominate a row's size) are never
405
+ * loaded. The analytics have to see the whole table, and a table can hold
406
+ * 10,000 rows. A search saved without a source has no entry in the `source`
407
+ * index, so it comes back without one.
408
+ */
409
+ export async function getSearchActivityRecords(): Promise<
410
+ SearchActivityRecord[]
411
+ > {
412
+ return measurePerformance("Get search activity", () =>
413
+ historyDatabase.transaction("r", historyDatabase.searches, async () => {
414
+ const byTime = historyDatabase.searches.orderBy("timestamp");
415
+ const [timestamps, ids, distinctSources] = await Promise.all([
416
+ byTime.keys(),
417
+ byTime.primaryKeys(),
418
+ historyDatabase.searches.orderBy("source").uniqueKeys(),
419
+ ]);
420
+
421
+ // A handful of sources exist ("user", "followup", "suggestion"), so one
422
+ // index lookup per source is far cheaper than walking the whole index.
423
+ const sourceById = new Map<unknown, string>();
424
+ await Promise.all(
425
+ distinctSources.map(async (source) => {
426
+ const sourceIds = await historyDatabase.searches
427
+ .where("source")
428
+ .equals(source)
429
+ .primaryKeys();
430
+ for (const id of sourceIds) sourceById.set(id, String(source));
431
+ }),
432
+ );
433
+
434
+ return ids.map((id, index) => ({
435
+ timestamp: Number(timestamps[index]),
436
+ source: sourceById.get(id),
437
+ }));
438
+ }),
439
+ ).catch((error) => {
440
+ addLogEntry(`Error fetching search activity: ${error}`);
441
+ return [];
442
+ });
443
+ }
444
+
445
+ /**
446
+ * Every pinned search, newest first, however old. Cleanup never deletes a
447
+ * pinned entry, so a window of recent searches would sooner or later leave
448
+ * some out. Only pinned entries have a `pinnedAt`, so its index reads them
449
+ * alone, without scanning the table.
450
+ */
451
+ export async function getPinnedSearches(): Promise<SearchEntry[]> {
452
+ return measurePerformance("Get pinned searches", async () => {
453
+ const pinned = await historyDatabase.searches.orderBy("pinnedAt").toArray();
454
+ return pinned.sort((a, b) => b.timestamp - a.timestamp);
455
+ }).catch((error) => {
456
+ addLogEntry(`Error fetching pinned searches: ${error}`);
457
+ return [];
458
+ });
459
+ }
460
+
461
  export async function saveLlmResponseForQuery(
462
  query: string,
463
  response: string,
client/modules/parentWindow.test.ts ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { getConfig } from "./config";
3
+ import { postMessageToParentWindow } from "./parentWindow";
4
+
5
+ vi.mock("./config", () => ({
6
+ getConfig: vi.fn(),
7
+ }));
8
+
9
+ vi.mock("./logEntries", () => ({
10
+ addLogEntry: vi.fn(),
11
+ }));
12
+
13
+ const message = { queryString: "q=test", hash: "" };
14
+
15
+ /**
16
+ * A parent page whose first child frame is cross-origin, so reading that
17
+ * frame's `location` throws, as it does in a browser.
18
+ */
19
+ function stubParentWindow() {
20
+ const crossOriginFrame = {
21
+ get location(): Location {
22
+ throw new DOMException("Blocked a frame", "SecurityError");
23
+ },
24
+ };
25
+ const parentWindow = { 0: crossOriginFrame, postMessage: vi.fn() };
26
+ vi.stubGlobal("parent", parentWindow);
27
+ return parentWindow;
28
+ }
29
+
30
+ function serveOrigins(parentWindowOrigins: string[]) {
31
+ vi.mocked(getConfig).mockResolvedValue({ parentWindowOrigins } as Awaited<
32
+ ReturnType<typeof getConfig>
33
+ >);
34
+ }
35
+
36
+ /** Lets the post that waits on the config run. */
37
+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
38
+
39
+ describe("postMessageToParentWindow", () => {
40
+ beforeEach(() => {
41
+ vi.clearAllMocks();
42
+ });
43
+
44
+ afterEach(() => {
45
+ vi.unstubAllGlobals();
46
+ });
47
+
48
+ it("posts once to each allowed origin, whatever frame comes first in the parent", async () => {
49
+ const parentWindow = stubParentWindow();
50
+ serveOrigins(["https://huggingface.co"]);
51
+
52
+ expect(() => postMessageToParentWindow(message)).not.toThrow();
53
+ await flush();
54
+
55
+ expect(parentWindow.postMessage).toHaveBeenCalledTimes(1);
56
+ expect(parentWindow.postMessage).toHaveBeenCalledWith(
57
+ message,
58
+ "https://huggingface.co",
59
+ );
60
+ });
61
+
62
+ it("posts nothing when no origin is allowed", async () => {
63
+ const parentWindow = stubParentWindow();
64
+ serveOrigins([]);
65
+
66
+ postMessageToParentWindow(message);
67
+ await flush();
68
+
69
+ expect(parentWindow.postMessage).not.toHaveBeenCalled();
70
+ });
71
+
72
+ it("posts nothing when the page is not embedded", async () => {
73
+ const postMessage = vi.spyOn(window, "postMessage");
74
+ serveOrigins(["https://huggingface.co"]);
75
+
76
+ postMessageToParentWindow(message);
77
+ await flush();
78
+
79
+ expect(getConfig).not.toHaveBeenCalled();
80
+ expect(postMessage).not.toHaveBeenCalled();
81
+ postMessage.mockRestore();
82
+ });
83
+
84
+ it("posts nothing, and does not throw, when the config cannot be fetched", async () => {
85
+ const parentWindow = stubParentWindow();
86
+ vi.mocked(getConfig).mockRejectedValue(new Error("offline"));
87
+
88
+ expect(() => postMessageToParentWindow(message)).not.toThrow();
89
+ await flush();
90
+
91
+ expect(parentWindow.postMessage).not.toHaveBeenCalled();
92
+ });
93
+
94
+ it("still posts to the other origins when one of them is not a valid target", async () => {
95
+ const parentWindow = stubParentWindow();
96
+ parentWindow.postMessage.mockImplementationOnce(() => {
97
+ throw new DOMException("Invalid target origin", "SyntaxError");
98
+ });
99
+ serveOrigins(["huggingface.co", "https://huggingface.co"]);
100
+
101
+ postMessageToParentWindow(message);
102
+ await flush();
103
+
104
+ expect(parentWindow.postMessage).toHaveBeenCalledTimes(2);
105
+ expect(parentWindow.postMessage).toHaveBeenLastCalledWith(
106
+ message,
107
+ "https://huggingface.co",
108
+ );
109
+ });
110
+ });
client/modules/parentWindow.ts CHANGED
@@ -1,6 +1,30 @@
1
- /** Forwards a message to the embedding parent window, targeting the origin from `ancestorOrigins`. */
 
 
 
 
 
 
 
 
 
 
2
  export function postMessageToParentWindow(message: unknown) {
3
  const parentWindow = self.parent;
4
- const targetOrigin = parentWindow?.[0]?.location?.ancestorOrigins?.[0];
5
- if (targetOrigin) parentWindow.postMessage(message, targetOrigin);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  }
 
1
+ import { getConfig } from "./config";
2
+ import { addLogEntry } from "./logEntries";
3
+
4
+ /**
5
+ * Forwards a message to the page embedding MiniSearch (a Hugging Face Space,
6
+ * for example), addressed to each origin in `PARENT_WINDOW_ORIGINS`. The
7
+ * browser delivers it only when the embedding page is on that origin, so no
8
+ * other frame's state is read to find out where the page is embedded.
9
+ *
10
+ * Never throws: callers post right before navigating and searching.
11
+ */
12
  export function postMessageToParentWindow(message: unknown) {
13
  const parentWindow = self.parent;
14
+ if (parentWindow === self) return;
15
+
16
+ getConfig().then(
17
+ ({ parentWindowOrigins }) => {
18
+ for (const origin of parentWindowOrigins) {
19
+ try {
20
+ parentWindow.postMessage(message, origin);
21
+ } catch (error) {
22
+ addLogEntry(`Failed to post the query to ${origin}: ${error}`);
23
+ }
24
+ }
25
+ },
26
+ () => {
27
+ // Without the server's list, no embedding page is trusted with the query.
28
+ },
29
+ );
30
  }
client/modules/pubSub.test.ts CHANGED
@@ -168,3 +168,85 @@ describe("numeric settings never hold an empty string", () => {
168
  expect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength);
169
  });
170
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
  expect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength);
169
  });
170
  });
171
+
172
+ describe("settings hydration merges the stored profile into the defaults", () => {
173
+ it("fills keys a stored profile predates, before anything renders", async () => {
174
+ localStorage.setItem(
175
+ "settings",
176
+ JSON.stringify({ enableAiResponse: true }),
177
+ );
178
+ const { getSettings } = await import("./pubSub");
179
+ expect(getSettings().enableAiResponse).toBe(true);
180
+ expect(getSettings().enablePageContentFetch).toBe(true);
181
+ });
182
+
183
+ it("hydrates a wrong-type key to its default and keeps a deliberate false", async () => {
184
+ localStorage.setItem(
185
+ "settings",
186
+ JSON.stringify({
187
+ searchResultsLimit: "15",
188
+ enablePageContentFetch: false,
189
+ customKeyFromAnOlderBuild: "keep me",
190
+ }),
191
+ );
192
+ const { getSettings } = await import("./pubSub");
193
+ const settings = getSettings() as unknown as Record<string, unknown>;
194
+ expect(settings.searchResultsLimit).toBe(15);
195
+ expect(settings.enablePageContentFetch).toBe(false);
196
+ expect(settings.customKeyFromAnOlderBuild).toBe("keep me");
197
+ });
198
+
199
+ it("leaves an array store exactly as stored", async () => {
200
+ const stored = JSON.stringify(["ai", "history"]);
201
+ localStorage.setItem("menuExpandedAccordions", stored);
202
+ const { menuExpandedAccordionsPubSub } = await import("./pubSub");
203
+ const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub;
204
+ expect(getMenuExpandedAccordions()).toEqual(["ai", "history"]);
205
+ expect(localStorage.getItem("menuExpandedAccordions")).toBe(stored);
206
+ });
207
+
208
+ it("does not write the hydrated value back to storage", async () => {
209
+ const stored = JSON.stringify({ enableAiResponse: true });
210
+ localStorage.setItem("settings", stored);
211
+ await import("./pubSub");
212
+ expect(localStorage.getItem("settings")).toBe(stored);
213
+ });
214
+
215
+ it("reports a usable stored object as stored user settings", async () => {
216
+ localStorage.setItem(
217
+ "settings",
218
+ JSON.stringify({ enableAiResponse: true }),
219
+ );
220
+ const { hasStoredUserSettings } = await import("./pubSub");
221
+ expect(hasStoredUserSettings).toBe(true);
222
+ });
223
+
224
+ it.each(["{not json", "[]", '"x"'])(
225
+ "treats an unusable stored value (%s) as no stored settings, so the server defaults apply",
226
+ async (stored) => {
227
+ localStorage.setItem("settings", stored);
228
+ const { hasStoredUserSettings } = await import("./pubSub");
229
+ expect(hasStoredUserSettings).toBe(false);
230
+ const { applyServerConfig, defaultSettings } = await import("./settings");
231
+ const config = {
232
+ accessKeysEnabled: false,
233
+ accessKeyTimeoutHours: 0,
234
+ wllamaDefaultModelId: "custom-model",
235
+ wllamaDefaultGpuModelId: "gemma-3-4b",
236
+ internalApiEnabled: false,
237
+ internalApiName: "Internal API",
238
+ defaultInferenceType: "openai",
239
+ searchToken: "a".repeat(64),
240
+ parentWindowOrigins: ["https://huggingface.co"],
241
+ };
242
+ const applied = applyServerConfig(
243
+ defaultSettings,
244
+ config,
245
+ hasStoredUserSettings,
246
+ false,
247
+ );
248
+ expect(applied.inferenceType).toBe("openai");
249
+ expect(applied.wllamaModelId).toBe("custom-model");
250
+ },
251
+ );
252
+ });
client/modules/pubSub.ts CHANGED
@@ -31,10 +31,41 @@ function isSameJsonKind(value: unknown, reference: unknown): boolean {
31
  return typeof value === typeof reference;
32
  }
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  function createLocalStoragePubSub<T>(
35
  localStorageKey: string,
36
  defaultValue: T,
37
  normalize?: (value: T) => T,
 
38
  ) {
39
  const localStorageValue = safeStorage.getItem(localStorageKey);
40
  let initialValue: T = defaultValue;
@@ -46,7 +77,9 @@ function createLocalStoragePubSub<T>(
46
  parsed = undefined;
47
  }
48
  if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) {
49
- initialValue = normalize ? normalize(parsed as T) : (parsed as T);
 
 
50
  } else {
51
  // Runs at module load, so an unparseable or wrong-type stored value must
52
  // not crash the app. Remove it (so the fallback doesn't repeat on every
@@ -55,6 +88,7 @@ function createLocalStoragePubSub<T>(
55
  addLogEntry(
56
  `Discarded an unusable stored value for '${localStorageKey}'`,
57
  );
 
58
  }
59
  }
60
  const localStoragePubSub = createPubSub(initialValue);
@@ -128,12 +162,26 @@ export const modelLoadingProgressPubSub = createPubSub(0);
128
 
129
  export const [updateModelLoadingProgress] = modelLoadingProgressPubSub;
130
 
 
 
131
  export const settingsPubSub = createLocalStoragePubSub(
132
  SETTINGS_STORAGE_KEY,
133
  defaultSettings,
134
  coerceNumericSettings,
 
 
 
135
  );
136
 
 
 
 
 
 
 
 
 
 
137
  export const [updateSettings, listenToSettingsChanges, getSettings] =
138
  settingsPubSub;
139
 
 
31
  return typeof value === typeof reference;
32
  }
33
 
34
+ /**
35
+ * Fill a stored settings object with the defaults for the keys it does not
36
+ * have, so the first value a reader sees is complete even when the stored
37
+ * profile predates a newly added key. A stored key whose value has a
38
+ * different JSON kind than the default falls back to the default alone; keys
39
+ * the defaults do not know are kept.
40
+ */
41
+ function hydrateWithDefaults<T>(defaultValue: T, parsed: unknown): T {
42
+ if (
43
+ typeof defaultValue !== "object" ||
44
+ defaultValue === null ||
45
+ Array.isArray(defaultValue) ||
46
+ typeof parsed !== "object" ||
47
+ parsed === null ||
48
+ Array.isArray(parsed)
49
+ ) {
50
+ return parsed as T;
51
+ }
52
+ const defaults = defaultValue as Record<string, unknown>;
53
+ const accepted: Record<string, unknown> = {};
54
+ for (const [key, value] of Object.entries(
55
+ parsed as Record<string, unknown>,
56
+ )) {
57
+ if (!(key in defaults) || isSameJsonKind(value, defaults[key])) {
58
+ accepted[key] = value;
59
+ }
60
+ }
61
+ return { ...defaults, ...accepted } as T;
62
+ }
63
+
64
  function createLocalStoragePubSub<T>(
65
  localStorageKey: string,
66
  defaultValue: T,
67
  normalize?: (value: T) => T,
68
+ reportUsableStoredValue?: (usable: boolean) => void,
69
  ) {
70
  const localStorageValue = safeStorage.getItem(localStorageKey);
71
  let initialValue: T = defaultValue;
 
77
  parsed = undefined;
78
  }
79
  if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) {
80
+ const hydrated = hydrateWithDefaults(defaultValue, parsed);
81
+ initialValue = normalize ? normalize(hydrated) : hydrated;
82
+ reportUsableStoredValue?.(true);
83
  } else {
84
  // Runs at module load, so an unparseable or wrong-type stored value must
85
  // not crash the app. Remove it (so the fallback doesn't repeat on every
 
88
  addLogEntry(
89
  `Discarded an unusable stored value for '${localStorageKey}'`,
90
  );
91
+ reportUsableStoredValue?.(false);
92
  }
93
  }
94
  const localStoragePubSub = createPubSub(initialValue);
 
162
 
163
  export const [updateModelLoadingProgress] = modelLoadingProgressPubSub;
164
 
165
+ let storedSettingsUsable = false;
166
+
167
  export const settingsPubSub = createLocalStoragePubSub(
168
  SETTINGS_STORAGE_KEY,
169
  defaultSettings,
170
  coerceNumericSettings,
171
+ (usable) => {
172
+ storedSettingsUsable = usable;
173
+ },
174
  );
175
 
176
+ /**
177
+ * Whether this browser already had a usable settings object from an earlier
178
+ * visit, decided while `settingsPubSub` hydrated. `applyServerConfig()` uses
179
+ * it to tell an untouched profile from a user who deliberately picked a value
180
+ * that happens to equal a default. A stored value that was discarded as
181
+ * unusable counts as no stored settings, which is what the merge assumes.
182
+ */
183
+ export const hasStoredUserSettings = storedSettingsUsable;
184
+
185
  export const [updateSettings, listenToSettingsChanges, getSettings] =
186
  settingsPubSub;
187
 
client/modules/querySuggestions.test.ts CHANGED
@@ -53,6 +53,42 @@ describe("getRandomQuerySuggestion", () => {
53
  expect(getQuerySuggestions()).toEqual([]);
54
  });
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  it("logs how many suggestions the refill actually stored", async () => {
57
  mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));
58
 
 
53
  expect(getQuerySuggestions()).toEqual([]);
54
  });
55
 
56
+ it("stores at most 25 of the fetched suggestions, each once", async () => {
57
+ const fetched = Array.from({ length: 40 }, (_, index) => `s${index}`);
58
+ mockFetch.mockResolvedValueOnce(jsonResponse(fetched));
59
+
60
+ await getRandomQuerySuggestion();
61
+
62
+ const stored = getQuerySuggestions();
63
+ expect(stored).toHaveLength(24);
64
+ expect(new Set(stored).size).toBe(24);
65
+ expect(stored.every((entry) => fetched.includes(entry))).toBe(true);
66
+ });
67
+
68
+ it("shares one fetch between callers that find the store empty together", async () => {
69
+ mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));
70
+
71
+ const [first, second] = await Promise.all([
72
+ getRandomQuerySuggestion(),
73
+ getRandomQuerySuggestion(),
74
+ ]);
75
+
76
+ expect(mockFetch).toHaveBeenCalledTimes(1);
77
+ expect(first).not.toBe(second);
78
+ expect(getQuerySuggestions()).toHaveLength(1);
79
+ });
80
+
81
+ it("fetches again once a finished refill has been used up", async () => {
82
+ mockFetch
83
+ .mockResolvedValueOnce(jsonResponse(["a"]))
84
+ .mockResolvedValueOnce(jsonResponse(["b"]));
85
+
86
+ await expect(getRandomQuerySuggestion()).resolves.toBe("a");
87
+ await expect(getRandomQuerySuggestion()).resolves.toBe("b");
88
+
89
+ expect(mockFetch).toHaveBeenCalledTimes(2);
90
+ });
91
+
92
  it("logs how many suggestions the refill actually stored", async () => {
93
  mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));
94
 
client/modules/querySuggestions.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { addLogEntry } from "./logEntries";
2
  import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub";
3
 
@@ -13,13 +14,21 @@ function toNonEmptyStrings(value: unknown): string[] {
13
  );
14
  }
15
 
 
 
 
16
  /** Pops a stored suggestion, refilling the store when it is empty; never resolves to an empty string. */
17
  export async function getRandomQuerySuggestion(): Promise<string> {
18
- let querySuggestions = toNonEmptyStrings(getQuerySuggestions());
19
-
20
- if (querySuggestions.length === 0)
21
- querySuggestions = await refillQuerySuggestions(25);
 
 
22
 
 
 
 
23
  const randomQuerySuggestion = querySuggestions.pop();
24
 
25
  updateQuerySuggestions(querySuggestions);
@@ -27,7 +36,7 @@ export async function getRandomQuerySuggestion(): Promise<string> {
27
  return randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION;
28
  }
29
 
30
- async function refillQuerySuggestions(limit: number): Promise<string[]> {
31
  const querySuggestionsFileUrl = new URL(
32
  "/query-suggestions.json",
33
  self.location.origin,
@@ -46,21 +55,21 @@ async function refillQuerySuggestions(limit: number): Promise<string[]> {
46
  throw new Error("the response is not a list");
47
  }
48
 
49
- const querySuggestionsList = toNonEmptyStrings(body)
50
- .sort(() => Math.random() - 0.5)
51
- .slice(0, limit);
 
 
 
52
 
53
  addLogEntry(
54
  `Query suggestions refilled with ${querySuggestionsList.length} suggestions`,
55
  );
56
-
57
- return querySuggestionsList;
58
  } catch (error) {
59
  addLogEntry(
60
  `Failed to refill query suggestions: ${
61
  error instanceof Error ? error.message : String(error)
62
  }`,
63
  );
64
- return [];
65
  }
66
  }
 
1
+ import { shuffle } from "@shared/shuffle";
2
  import { addLogEntry } from "./logEntries";
3
  import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub";
4
 
 
14
  );
15
  }
16
 
17
+ /** The refill under way, so callers that find the store empty together share one fetch. */
18
+ let refillInFlight: Promise<void> | undefined;
19
+
20
  /** Pops a stored suggestion, refilling the store when it is empty; never resolves to an empty string. */
21
  export async function getRandomQuerySuggestion(): Promise<string> {
22
+ if (toNonEmptyStrings(getQuerySuggestions()).length === 0) {
23
+ refillInFlight ??= refillQuerySuggestions(25).finally(() => {
24
+ refillInFlight = undefined;
25
+ });
26
+ await refillInFlight;
27
+ }
28
 
29
+ // Read after the wait, not before: callers that waited on the same refill
30
+ // each take their own suggestion from what it stored.
31
+ const querySuggestions = toNonEmptyStrings(getQuerySuggestions());
32
  const randomQuerySuggestion = querySuggestions.pop();
33
 
34
  updateQuerySuggestions(querySuggestions);
 
36
  return randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION;
37
  }
38
 
39
+ async function refillQuerySuggestions(limit: number): Promise<void> {
40
  const querySuggestionsFileUrl = new URL(
41
  "/query-suggestions.json",
42
  self.location.origin,
 
55
  throw new Error("the response is not a list");
56
  }
57
 
58
+ const querySuggestionsList = shuffle(toNonEmptyStrings(body)).slice(
59
+ 0,
60
+ limit,
61
+ );
62
+
63
+ updateQuerySuggestions(querySuggestionsList);
64
 
65
  addLogEntry(
66
  `Query suggestions refilled with ${querySuggestionsList.length} suggestions`,
67
  );
 
 
68
  } catch (error) {
69
  addLogEntry(
70
  `Failed to refill query suggestions: ${
71
  error instanceof Error ? error.message : String(error)
72
  }`,
73
  );
 
74
  }
75
  }
client/modules/reasoning.test.ts ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, expect, it } from "vitest";
2
+ import { splitReasoning } from "./reasoning";
3
+
4
+ describe("splitReasoning", () => {
5
+ it("splits a terminated reasoning block from the answer", () => {
6
+ expect(
7
+ splitReasoning(
8
+ "<think>Let me think about this</think>\nHere is the answer.",
9
+ "<think>",
10
+ "</think>",
11
+ ),
12
+ ).toEqual({
13
+ reasoning: "Let me think about this",
14
+ answer: "\nHere is the answer.",
15
+ isOpen: false,
16
+ });
17
+ });
18
+
19
+ it("treats an unterminated block as reasoning running to the end", () => {
20
+ expect(
21
+ splitReasoning("<think>still thinking", "<think>", "</think>"),
22
+ ).toEqual({
23
+ reasoning: "still thinking",
24
+ answer: "",
25
+ isOpen: true,
26
+ });
27
+ });
28
+
29
+ it("leaves a marker mentioned mid-answer intact", () => {
30
+ const text = "Models wrap reasoning in <think> tags like this.";
31
+ expect(splitReasoning(text, "<think>", "</think>")).toEqual({
32
+ reasoning: "",
33
+ answer: text,
34
+ isOpen: false,
35
+ });
36
+ });
37
+
38
+ it("returns the text as answer when no start marker opens the response", () => {
39
+ const text = "This is a normal response.";
40
+ expect(splitReasoning(text, "<think>", "</think>")).toEqual({
41
+ reasoning: "",
42
+ answer: text,
43
+ isOpen: false,
44
+ });
45
+ });
46
+
47
+ it.each([
48
+ ["empty text", ""],
49
+ ["whitespace-only text", " "],
50
+ ])("reports nothing for %s", (_, text) => {
51
+ expect(splitReasoning(text, "<think>", "</think>")).toEqual({
52
+ reasoning: "",
53
+ answer: text,
54
+ isOpen: false,
55
+ });
56
+ });
57
+
58
+ it("trims before checking the start marker, like the UI does", () => {
59
+ expect(
60
+ splitReasoning(" <think>quiet</think>loud", "<think>", "</think>"),
61
+ ).toEqual({
62
+ reasoning: "quiet",
63
+ answer: "loud",
64
+ isOpen: false,
65
+ });
66
+ });
67
+
68
+ it("supports custom marker pairs", () => {
69
+ expect(
70
+ splitReasoning(
71
+ "[REASONING]hmm[/REASONING]yes",
72
+ "[REASONING]",
73
+ "[/REASONING]",
74
+ ),
75
+ ).toEqual({
76
+ reasoning: "hmm",
77
+ answer: "yes",
78
+ isOpen: false,
79
+ });
80
+ });
81
+ });
client/modules/reasoning.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Splits a response that may carry a reasoning block into the reasoning and
3
+ * the answer. Text counts as reasoning only when it starts with the start
4
+ * marker after trimming, and the end marker is searched after the start
5
+ * marker; without an end marker the reasoning runs to the end of the text and
6
+ * `isOpen` reports the unterminated block. This is the single parser shared by
7
+ * the UI hook and plain modules like text-to-speech, which cannot import a
8
+ * React hook.
9
+ */
10
+ export function splitReasoning(
11
+ text: string,
12
+ startMarker: string,
13
+ endMarker: string,
14
+ ): { reasoning: string; answer: string; isOpen: boolean } {
15
+ if (!text) return { reasoning: "", answer: "", isOpen: false };
16
+
17
+ const trimmedText = text.trim();
18
+
19
+ if (!trimmedText.startsWith(startMarker))
20
+ return { reasoning: "", answer: text, isOpen: false };
21
+
22
+ const startIndex = trimmedText.indexOf(startMarker);
23
+ const endIndex = trimmedText.indexOf(
24
+ endMarker,
25
+ startIndex + startMarker.length,
26
+ );
27
+
28
+ if (endIndex === -1) {
29
+ return {
30
+ reasoning: trimmedText.slice(startIndex + startMarker.length),
31
+ answer: "",
32
+ isOpen: true,
33
+ };
34
+ }
35
+
36
+ return {
37
+ reasoning: trimmedText.slice(startIndex + startMarker.length, endIndex),
38
+ answer: trimmedText.slice(endIndex + endMarker.length),
39
+ isOpen: false,
40
+ };
41
+ }
client/modules/settings.test.ts CHANGED
@@ -21,6 +21,7 @@ const mockConfig: ServerConfig = {
21
  internalApiName: "Internal API",
22
  defaultInferenceType: "browser",
23
  searchToken: "a".repeat(64),
 
24
  };
25
 
26
  describe("Settings Module", () => {
 
21
  internalApiName: "Internal API",
22
  defaultInferenceType: "browser",
23
  searchToken: "a".repeat(64),
24
+ parentWindowOrigins: ["https://huggingface.co"],
25
  };
26
 
27
  describe("Settings Module", () => {
client/modules/settings.ts CHANGED
@@ -14,15 +14,6 @@ import * as safeStorage from "./safeStorage";
14
 
15
  export const SETTINGS_STORAGE_KEY = "settings";
16
 
17
- /**
18
- * Whether this browser already had settings from an earlier visit. Read at
19
- * module load, before anything writes the key back, so `applyServerConfig()`
20
- * can tell an untouched profile from a user who deliberately picked a value
21
- * that happens to equal a default.
22
- */
23
- export const hasStoredUserSettings =
24
- safeStorage.getItem(SETTINGS_STORAGE_KEY) !== null;
25
-
26
  /**
27
  * Whether this profile picked an OS voice before the local engine existed.
28
  * Such a value is a bare `speechSynthesis` voice URI rather than a prefixed
 
14
 
15
  export const SETTINGS_STORAGE_KEY = "settings";
16
 
 
 
 
 
 
 
 
 
 
17
  /**
18
  * Whether this profile picked an OS voice before the local engine existed.
19
  * Such a value is a bare `speechSynthesis` voice URI rather than a prefixed
client/modules/textGeneration.chatBudget.test.ts CHANGED
@@ -4,6 +4,8 @@ const state = vi.hoisted(() => ({
4
  settings: { inferenceType: "browser" } as {
5
  inferenceType: string;
6
  openAiContextLength?: number;
 
 
7
  },
8
  systemPrompt: "",
9
  }));
@@ -62,7 +64,10 @@ vi.mock("./textGenerationWithOpenAi", () => ({
62
  }));
63
 
64
  import { getConversationSummary, updateConversationSummary } from "./pubSub";
65
- import { generateChatResponse } from "./textGeneration";
 
 
 
66
  import { generateChatWithOpenAi } from "./textGenerationWithOpenAi";
67
  import { generateChatWithWllama } from "./textGenerationWithWllama";
68
  import type { ChatMessage } from "./types";
@@ -253,3 +258,65 @@ describe("generateChatResponse context budget", () => {
253
  expect(answer[0][0].content).toContain("S1");
254
  });
255
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  settings: { inferenceType: "browser" } as {
5
  inferenceType: string;
6
  openAiContextLength?: number;
7
+ reasoningStartMarker?: string;
8
+ reasoningEndMarker?: string;
9
  },
10
  systemPrompt: "",
11
  }));
 
64
  }));
65
 
66
  import { getConversationSummary, updateConversationSummary } from "./pubSub";
67
+ import {
68
+ generateChatResponse,
69
+ generateReplyToMessages,
70
+ } from "./textGeneration";
71
  import { generateChatWithOpenAi } from "./textGenerationWithOpenAi";
72
  import { generateChatWithWllama } from "./textGenerationWithWllama";
73
  import type { ChatMessage } from "./types";
 
258
  expect(answer[0][0].content).toContain("S1");
259
  });
260
  });
261
+
262
+ describe("reasoning in earlier assistant turns", () => {
263
+ const reasoning = "Let me think about the first question at length.";
264
+ const turnsWithReasoning: ChatMessage[] = [
265
+ { role: "user", content: "first question" },
266
+ {
267
+ role: "assistant",
268
+ content: `<think>${reasoning}</think>\n\nfirst answer`,
269
+ },
270
+ ];
271
+ const question: ChatMessage = { role: "user", content: "second question" };
272
+
273
+ beforeEach(() => {
274
+ vi.clearAllMocks();
275
+ state.settings = {
276
+ inferenceType: "browser",
277
+ reasoningStartMarker: "<think>",
278
+ reasoningEndMarker: "</think>",
279
+ };
280
+ state.systemPrompt = "";
281
+ mockGenerateChat(generateChatWithWllama);
282
+ });
283
+
284
+ function sentText(messages: ChatMessage[]) {
285
+ return messages.map((message) => message.content).join("\n");
286
+ }
287
+
288
+ it("keeps the reasoning out of the main continuation", async () => {
289
+ await generateChatResponse([...turnsWithReasoning, question], () => {});
290
+
291
+ const { answer } = callsTo(generateChatWithWllama);
292
+ expect(sentText(answer[0])).toContain("first answer");
293
+ expect(sentText(answer[0])).not.toContain(reasoning);
294
+ });
295
+
296
+ it("keeps the reasoning out of the summary prompt and the stored summary", async () => {
297
+ state.systemPrompt = "s".repeat(3500);
298
+ vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => {
299
+ if (chat[0].content.startsWith(summarizerInstruction)) {
300
+ throw new Error("summarizer unavailable");
301
+ }
302
+ return "the answer";
303
+ });
304
+
305
+ await generateChatResponse([...turnsWithReasoning, question], () => {});
306
+
307
+ const { summarizer } = callsTo(generateChatWithWllama);
308
+ expect(sentText(summarizer[0])).toContain("first answer");
309
+ expect(sentText(summarizer[0])).not.toContain(reasoning);
310
+ const [stored] = vi.mocked(updateConversationSummary).mock.calls[0];
311
+ expect(stored.summary).toContain("first answer");
312
+ expect(stored.summary).not.toContain(reasoning);
313
+ });
314
+
315
+ it("keeps the reasoning out of replies built from the conversation", async () => {
316
+ await generateReplyToMessages([...turnsWithReasoning, question]);
317
+
318
+ const [[sent]] = vi.mocked(generateChatWithWllama).mock.calls;
319
+ expect(sentText(sent)).toContain("first answer");
320
+ expect(sentText(sent)).not.toContain(reasoning);
321
+ });
322
+ });
client/modules/textGeneration.inference.test.ts CHANGED
@@ -42,6 +42,7 @@ vi.mock("./textGenerationUtilities", () => ({
42
  defaultContextSize: 4096,
43
  getFormattedSearchResults: vi.fn(() => ""),
44
  searchResultsToConsider: 6,
 
45
  }));
46
  vi.mock("gpt-tokenizer", () => ({
47
  default: { encode: vi.fn(() => [1, 2, 3]) },
 
42
  defaultContextSize: 4096,
43
  getFormattedSearchResults: vi.fn(() => ""),
44
  searchResultsToConsider: 6,
45
+ withoutReasoning: (messages: unknown) => messages,
46
  }));
47
  vi.mock("gpt-tokenizer", () => ({
48
  default: { encode: vi.fn(() => [1, 2, 3]) },
client/modules/textGeneration.ts CHANGED
@@ -40,6 +40,7 @@ import {
40
  getFormattedSearchResults,
41
  imageResultTag,
42
  searchResultsToConsider,
 
43
  } from "./textGenerationUtilities";
44
  import type {
45
  ChatMessage,
@@ -369,7 +370,7 @@ export async function generateReplyToMessages(
369
  messages: ChatMessage[],
370
  ): Promise<string> {
371
  const keptMessages = keepNewestMessagesWithinBudget(
372
- messages,
373
  defaultContextSize * historyBudgetRatio,
374
  );
375
 
@@ -382,9 +383,10 @@ export async function generateReplyToMessages(
382
  }
383
 
384
  export async function generateChatResponse(
385
- newMessages: ChatMessage[],
386
  onUpdate: (partialResponse: string) => void,
387
  ) {
 
388
  let response = "";
389
 
390
  try {
 
40
  getFormattedSearchResults,
41
  imageResultTag,
42
  searchResultsToConsider,
43
+ withoutReasoning,
44
  } from "./textGenerationUtilities";
45
  import type {
46
  ChatMessage,
 
370
  messages: ChatMessage[],
371
  ): Promise<string> {
372
  const keptMessages = keepNewestMessagesWithinBudget(
373
+ withoutReasoning(messages),
374
  defaultContextSize * historyBudgetRatio,
375
  );
376
 
 
383
  }
384
 
385
  export async function generateChatResponse(
386
+ messages: ChatMessage[],
387
  onUpdate: (partialResponse: string) => void,
388
  ) {
389
+ const newMessages = withoutReasoning(messages);
390
  let response = "";
391
 
392
  try {
client/modules/textGenerationUtilities.test.ts CHANGED
@@ -13,6 +13,8 @@ const state = vi.hoisted(() => ({
13
  settings: { inferenceType: "openai", openAiContextLength: 4096 } as {
14
  inferenceType?: string;
15
  openAiContextLength?: number;
 
 
16
  },
17
  }));
18
 
@@ -37,12 +39,14 @@ vi.mock("./systemPrompt", () => ({
37
  }));
38
 
39
  import {
 
40
  getDefaultChatCompletionCreateParamsStreaming,
41
  getDefaultChatMessages,
42
  getEffectiveContextSize,
43
  getFormattedSearchResults,
44
  minimumOutputTokens,
45
  setWorkerFactory,
 
46
  } from "./textGenerationUtilities";
47
  import type { ChatMessage } from "./types";
48
 
@@ -510,3 +514,40 @@ describe("worker handoff", () => {
510
  expect(factory).not.toHaveBeenCalled();
511
  });
512
  });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  settings: { inferenceType: "openai", openAiContextLength: 4096 } as {
14
  inferenceType?: string;
15
  openAiContextLength?: number;
16
+ reasoningStartMarker?: string;
17
+ reasoningEndMarker?: string;
18
  },
19
  }));
20
 
 
39
  }));
40
 
41
  import {
42
+ answerOnly,
43
  getDefaultChatCompletionCreateParamsStreaming,
44
  getDefaultChatMessages,
45
  getEffectiveContextSize,
46
  getFormattedSearchResults,
47
  minimumOutputTokens,
48
  setWorkerFactory,
49
+ withoutReasoning,
50
  } from "./textGenerationUtilities";
51
  import type { ChatMessage } from "./types";
52
 
 
514
  expect(factory).not.toHaveBeenCalled();
515
  });
516
  });
517
+
518
+ describe("answerOnly", () => {
519
+ beforeEach(() => {
520
+ state.settings = {
521
+ inferenceType: "openai",
522
+ reasoningStartMarker: "<think>",
523
+ reasoningEndMarker: "</think>",
524
+ };
525
+ });
526
+
527
+ it("drops a terminated reasoning block", () => {
528
+ expect(answerOnly("<think>step by step</think>\n\nThe answer.")).toBe(
529
+ "The answer.",
530
+ );
531
+ });
532
+
533
+ it("returns an empty answer for an unterminated block", () => {
534
+ expect(answerOnly("<think>still thinking")).toBe("");
535
+ });
536
+
537
+ it("leaves a marker mentioned mid-answer intact", () => {
538
+ const text = "Models wrap thoughts in <think></think> tags.";
539
+ expect(answerOnly(text)).toBe(text);
540
+ });
541
+
542
+ it("strips assistant turns only", () => {
543
+ const messages: ChatMessage[] = [
544
+ { role: "user", content: "<think>quoted by the user</think> hi" },
545
+ { role: "assistant", content: "<think>plan</think>\n\nHello!" },
546
+ ];
547
+
548
+ expect(withoutReasoning(messages)).toEqual([
549
+ messages[0],
550
+ { role: "assistant", content: "Hello!" },
551
+ ]);
552
+ });
553
+ });
client/modules/textGenerationUtilities.ts CHANGED
@@ -14,6 +14,7 @@ import {
14
  getTextSearchStale,
15
  updateTextGenerationState,
16
  } from "./pubSub";
 
17
  import { getSystemPrompt } from "./systemPrompt";
18
  import type { ChatMessage, TextSearchResult } from "./types";
19
 
@@ -313,3 +314,26 @@ export function getDefaultChatMessages(searchResults: string): ChatMessage[] {
313
  { role: "user", content: getQuery() },
314
  ];
315
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  getTextSearchStale,
15
  updateTextGenerationState,
16
  } from "./pubSub";
17
+ import { splitReasoning } from "./reasoning";
18
  import { getSystemPrompt } from "./systemPrompt";
19
  import type { ChatMessage, TextSearchResult } from "./types";
20
 
 
314
  { role: "user", content: getQuery() },
315
  ];
316
  }
317
+
318
+ /**
319
+ * The answer part of a stored response, without the reasoning block that
320
+ * generation wraps in the configured markers. Prompts built from earlier
321
+ * turns use it so the chain of thought is not sent back to the model.
322
+ */
323
+ export function answerOnly(text: string): string {
324
+ const { reasoningStartMarker, reasoningEndMarker } = getSettings();
325
+ const { answer } = splitReasoning(
326
+ text,
327
+ reasoningStartMarker,
328
+ reasoningEndMarker,
329
+ );
330
+ return answer === text ? text : answer.trim();
331
+ }
332
+
333
+ export function withoutReasoning(messages: ChatMessage[]): ChatMessage[] {
334
+ return messages.map((message) =>
335
+ message.role === "assistant"
336
+ ? { ...message, content: answerOnly(message.content) }
337
+ : message,
338
+ );
339
+ }
client/modules/textGenerationWithHorde.ts CHANGED
@@ -454,8 +454,10 @@ async function getTopHordeModels(): Promise<string[]> {
454
 
455
  export async function fetchHordeUserInfo(
456
  apiKey: string,
 
457
  ): Promise<HordeUserInfo | null> {
458
  const response = await fetch(buildHordeUrl("/find_user"), {
 
459
  headers: {
460
  [HTTP_HEADERS.API_KEY]: apiKey,
461
  [HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,
 
454
 
455
  export async function fetchHordeUserInfo(
456
  apiKey: string,
457
+ signal?: AbortSignal,
458
  ): Promise<HordeUserInfo | null> {
459
  const response = await fetch(buildHordeUrl("/find_user"), {
460
+ signal,
461
  headers: {
462
  [HTTP_HEADERS.API_KEY]: apiKey,
463
  [HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,
client/modules/textGenerationWithWllama.test.ts CHANGED
@@ -1,4 +1,5 @@
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
 
2
  import { addLogEntry } from "./logEntries";
3
  import {
4
  getSettings,
@@ -37,7 +38,10 @@ vi.mock("./config", () => ({
37
  wllamaDefaultModelId: "test-model",
38
  wllamaDefaultGpuModelId: "test-gpu-model",
39
  }),
40
- FALLBACK_CONFIG: {},
 
 
 
41
  }));
42
 
43
  vi.mock("./systemPrompt", () => ({
@@ -148,6 +152,27 @@ describe("generateTextWithWllama", () => {
148
  );
149
  });
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  it("keeps the last known size when the total is not available yet", async () => {
152
  mockDownload([{ loaded: 0, total: 0 }]);
153
 
 
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { getConfig } from "./config";
3
  import { addLogEntry } from "./logEntries";
4
  import {
5
  getSettings,
 
38
  wllamaDefaultModelId: "test-model",
39
  wllamaDefaultGpuModelId: "test-gpu-model",
40
  }),
41
+ FALLBACK_CONFIG: {
42
+ wllamaDefaultModelId: "test-model",
43
+ wllamaDefaultGpuModelId: "test-gpu-model",
44
+ },
45
  }));
46
 
47
  vi.mock("./systemPrompt", () => ({
 
152
  );
153
  });
154
 
155
+ it("uses the default model without saving it when the server config cannot be loaded", async () => {
156
+ const savedSettings = getSettings();
157
+ vi.mocked(getSettings).mockReturnValue({
158
+ ...savedSettings,
159
+ wllamaModelId: "removed-model",
160
+ });
161
+ const serverConfig = await getConfig();
162
+ vi.mocked(getConfig).mockRejectedValue(new Error("Network error"));
163
+ mockDownload([]);
164
+
165
+ try {
166
+ await generateTextWithWllama();
167
+ } finally {
168
+ vi.mocked(getSettings).mockReturnValue(savedSettings);
169
+ vi.mocked(getConfig).mockResolvedValue(serverConfig);
170
+ }
171
+
172
+ expect(vi.mocked(initializeWllama).mock.calls[0]?.[0]).toBe("repo");
173
+ expect(updateSettings).not.toHaveBeenCalled();
174
+ });
175
+
176
  it("keeps the last known size when the total is not available yet", async () => {
177
  mockDownload([{ loaded: 0, total: 0 }]);
178
 
client/modules/textGenerationWithWllama.ts CHANGED
@@ -191,8 +191,8 @@ async function getSelectedWllamaModel(): Promise<WllamaModel> {
191
  const model = wllamaModels[wllamaModelId];
192
  if (model) return model;
193
 
194
- // Safe without the server: the fallback is only a model to switch to.
195
- const config = await getConfig().catch(() => FALLBACK_CONFIG);
196
  const defaultId = (await webGpuSupport)
197
  ? config.wllamaDefaultGpuModelId
198
  : config.wllamaDefaultModelId;
@@ -206,7 +206,11 @@ async function getSelectedWllamaModel(): Promise<WllamaModel> {
206
  addLogEntry(
207
  `Model "${wllamaModelId}" is no longer available; switched to "${defaultId}"`,
208
  );
209
- updateSettings({ ...getSettings(), wllamaModelId: defaultId });
 
 
 
 
210
  return defaultModel;
211
  }
212
 
 
191
  const model = wllamaModels[wllamaModelId];
192
  if (model) return model;
193
 
194
+ const serverConfig = await getConfig().catch(() => undefined);
195
+ const config = serverConfig ?? FALLBACK_CONFIG;
196
  const defaultId = (await webGpuSupport)
197
  ? config.wllamaDefaultGpuModelId
198
  : config.wllamaDefaultModelId;
 
206
  addLogEntry(
207
  `Model "${wllamaModelId}" is no longer available; switched to "${defaultId}"`,
208
  );
209
+ // The shipped default serves this answer only: saved, it would stand in for
210
+ // the server's own default on every later load.
211
+ if (serverConfig) {
212
+ updateSettings({ ...getSettings(), wllamaModelId: defaultId });
213
+ }
214
  return defaultModel;
215
  }
216
 
client/modules/textToSpeech.test.ts CHANGED
@@ -212,6 +212,18 @@ describe("prepareTextForSpeech", () => {
212
  "Title\nSee (the docs) now",
213
  );
214
  });
 
 
 
 
 
 
 
 
 
 
 
 
215
  });
216
 
217
  describe("splitIntoSentences", () => {
@@ -297,6 +309,17 @@ describe("speak", () => {
297
  expect(spoken).toEqual(["Hello there."]);
298
  });
299
 
 
 
 
 
 
 
 
 
 
 
 
300
  it("does not fall back after audio has started", async () => {
301
  const worker = createFakeWorker();
302
  tts.setWorkerFactory(() => worker as unknown as Worker);
 
212
  "Title\nSee (the docs) now",
213
  );
214
  });
215
+
216
+ it("returns an empty string when the reasoning block never closed", () => {
217
+ const text = "<think>The user wants the capital. Maybe Paris?";
218
+ expect(tts.prepareTextForSpeech(text, "<think>", "</think>")).toBe("");
219
+ });
220
+
221
+ it("keeps a marker mentioned mid-answer as plain text", () => {
222
+ const text = "Models wrap reasoning in <think> tags like this.";
223
+ expect(tts.prepareTextForSpeech(text, "<think>", "</think>")).toBe(
224
+ "Models wrap reasoning in <think> tags like this.",
225
+ );
226
+ });
227
  });
228
 
229
  describe("splitIntoSentences", () => {
 
309
  expect(spoken).toEqual(["Hello there."]);
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
+
318
+ expect(worker.sent).toEqual([]);
319
+ expect(spoken).toEqual([]);
320
+ expect(mockUpdateState).not.toHaveBeenCalled();
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);
client/modules/textToSpeech.ts CHANGED
@@ -2,6 +2,7 @@ import { addLogEntry } from "./logEntries";
2
  import type { Voice, VoiceId } from "./piper";
3
  import { voices } from "./piper";
4
  import { getSettings, updateTextToSpeechState } from "./pubSub";
 
5
  import type {
6
  WorkerRequest,
7
  WorkerResponse,
@@ -27,31 +28,23 @@ export interface VoiceOption {
27
  languageName?: string;
28
  }
29
 
30
- /** The markers come from user settings, so a character like `(` must not be read as syntax. */
31
- function escapeForRegExp(value: string): string {
32
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
- }
34
-
35
  /**
36
- * Strips reasoning blocks, links and markdown punctuation so both engines are
37
- * fed the same plain text.
 
 
38
  */
39
  export function prepareTextForSpeech(
40
  text: string,
41
  reasoningStartMarker: string,
42
  reasoningEndMarker: string,
43
  ): string {
44
- const withoutReasoning = text.replace(
45
- new RegExp(
46
- `${escapeForRegExp(reasoningStartMarker)}[\\s\\S]*?${escapeForRegExp(reasoningEndMarker)}`,
47
- "g",
48
- ),
49
- "",
50
- );
51
- const withoutLinks = withoutReasoning.replace(
52
- /\[([^\]]+)\]\([^)]+\)/g,
53
- "($1)",
54
  );
 
55
  return withoutLinks.replace(/[#*`_~[\]]/g, "").trim();
56
  }
57
 
 
2
  import type { Voice, VoiceId } from "./piper";
3
  import { voices } from "./piper";
4
  import { getSettings, updateTextToSpeechState } from "./pubSub";
5
+ import { splitReasoning } from "./reasoning";
6
  import type {
7
  WorkerRequest,
8
  WorkerResponse,
 
28
  languageName?: string;
29
  }
30
 
 
 
 
 
 
31
  /**
32
+ * Strips the reasoning block, links and markdown punctuation so both engines
33
+ * are fed the same plain text. The reasoning rule is the UI's shared one: only
34
+ * a block at the start of the response counts, and an unterminated one has no
35
+ * answer to speak.
36
  */
37
  export function prepareTextForSpeech(
38
  text: string,
39
  reasoningStartMarker: string,
40
  reasoningEndMarker: string,
41
  ): string {
42
+ const { answer } = splitReasoning(
43
+ text,
44
+ reasoningStartMarker,
45
+ reasoningEndMarker,
 
 
 
 
 
 
46
  );
47
+ const withoutLinks = answer.replace(/\[([^\]]+)\]\([^)]+\)/g, "($1)");
48
  return withoutLinks.replace(/[#*`_~[\]]/g, "").trim();
49
  }
50
 
docs/ai-integration.md CHANGED
@@ -93,7 +93,7 @@ Uses OpenAI's API or any OpenAI-compatible service.
93
  - Streaming responses, built on the Vercel AI SDK (`ai` + `@ai-sdk/openai-compatible`)
94
  - Auto model selection (if blank)
95
  - On a request error, automatically retries up to 5 times, switching to a different model fetched from the provider's `/models` endpoint each time (100ms × attempt backoff between retries)
96
- - Reasoning content support: reasoning/thinking output is wrapped between configurable `reasoningStartMarker`/`reasoningEndMarker` settings (default `<think>` / `</think>`)
97
 
98
  **Configuration:**
99
 
@@ -266,6 +266,8 @@ Save to history database
266
 
267
  Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19. The model still drops the phrase at times, writing a year of its own ("苹果 2025 新手机 发布时间" for 明年的呢), so the anchors come from the question the user typed: `normalizeFollowUpDates` (`shared/relativeDates.ts`) removes the years the model wrote and the user did not type in any message, then appends the question's anchors. A month the model writes without a year ("November releases") stays in the query next to the anchor. A query that still comes out in another script than the question's (Turkish or Persian for a Chinese question) gets one more call that translates it, naming the language: that held where asking harder in the main prompt did not. The question's script is the non-Latin one with the most words, since brand names can outnumber the Chinese letters ("iPhone呢"). A CJK character or a Hangul syllable counts as a word, while the other scripts need three letters in a row, because English questions write Greek letters as symbols, alone or in pairs ("α and β error", "γδ T cells"). Latin counts only when nothing else is there, and then any Latin letter in the query is enough ("Tencent founder 马化腾"). A question whose script serves several languages (Arabic, Bengali, Cyrillic, Devanagari) or is Latin cannot be named safely, so its query falls back to the typed question, as does a translation that misses again. Known gaps: Latin-script drift (English to French) is not caught; a Chinese query passes for a Japanese question, since kanji and kana count as one script; a Japanese question in kanji only is translated as Chinese; and an English question that quotes a word in another script gets its query translated into that language ("who is 雷军") or searched as typed when the script has no single language ("who is Путин").
268
 
 
 
269
  ### Text Generation State Machine
270
 
271
  `textGenerationStatePubSub` drives the AI response UI through these states:
 
93
  - Streaming responses, built on the Vercel AI SDK (`ai` + `@ai-sdk/openai-compatible`)
94
  - Auto model selection (if blank)
95
  - On a request error, automatically retries up to 5 times, switching to a different model fetched from the provider's `/models` endpoint each time (100ms × attempt backoff between retries)
96
+ - Reasoning content support: reasoning/thinking output is wrapped between configurable `reasoningStartMarker`/`reasoningEndMarker` settings (default `<think>` / `</think>`). The wrapped block stays in the stored response for the thinking UI, but prompts built from earlier turns (the chat continuation, conversation summaries, follow-up questions and related search queries) send only the answer, via `answerOnly` / `withoutReasoning` in `textGenerationUtilities.ts`
97
 
98
  **Configuration:**
99
 
 
266
 
267
  Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19. The model still drops the phrase at times, writing a year of its own ("苹果 2025 新手机 发布时间" for 明年的呢), so the anchors come from the question the user typed: `normalizeFollowUpDates` (`shared/relativeDates.ts`) removes the years the model wrote and the user did not type in any message, then appends the question's anchors. A month the model writes without a year ("November releases") stays in the query next to the anchor. A query that still comes out in another script than the question's (Turkish or Persian for a Chinese question) gets one more call that translates it, naming the language: that held where asking harder in the main prompt did not. The question's script is the non-Latin one with the most words, since brand names can outnumber the Chinese letters ("iPhone呢"). A CJK character or a Hangul syllable counts as a word, while the other scripts need three letters in a row, because English questions write Greek letters as symbols, alone or in pairs ("α and β error", "γδ T cells"). Latin counts only when nothing else is there, and then any Latin letter in the query is enough ("Tencent founder 马化腾"). A question whose script serves several languages (Arabic, Bengali, Cyrillic, Devanagari) or is Latin cannot be named safely, so its query falls back to the typed question, as does a translation that misses again. Known gaps: Latin-script drift (English to French) is not caught; a Chinese query passes for a Japanese question, since kanji and kana count as one script; a Japanese question in kanji only is translated as Chinese; and an English question that quotes a word in another script gets its query translated into that language ("who is 雷军") or searched as typed when the script has no single language ("who is Путин").
268
 
269
+ After the answer, the follow-up question suggested in the chat input is written by `generateFollowUpQuestion` (`client/modules/followUpQuestions.ts`), also through `generateReplyToMessages`. Its prompt carries the topic and the answer itself, so it needs neither the system prompt nor the search results, and it never reads or writes the conversation summary. A prompt over the 75% budget yields no suggestion.
270
+
271
  ### Text Generation State Machine
272
 
273
  `textGenerationStatePubSub` drives the AI response UI through these states: