Spaces:
Running
Running
Sync from felladrin/MiniSearch@43edeee
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.example+5-2
- changelog.md+19
- client/components/AiResponse/ChatInterface.test.tsx+24
- client/components/AiResponse/ChatInterface.tsx+8-3
- client/components/AiResponse/hooks/useReasoningContent.ts+9-24
- client/components/Analytics/SearchStats.test.tsx+102-39
- client/components/Analytics/SearchStats.tsx+36-5
- client/components/App/App.test.tsx+61-4
- client/components/App/App.tsx+8-13
- client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.tsAdded+207
- client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts+22-10
- client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts+30-13
- client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts+21-7
- client/components/Search/Form/SearchForm.suggestions.test.tsxAdded+90
- client/components/Search/Form/SearchForm.test.tsx+44
- client/components/Search/Form/SearchForm.tsx+19-27
- client/components/Search/History/HistoryDrawer.test.tsx+7
- client/components/Search/History/HistoryDrawer.tsx+5-1
- client/hooks/useHistoryRestore.test.ts+34
- client/hooks/useSearchHistory.test.ts+154
- client/hooks/useSearchHistory.ts+43-11
- client/modules/accessKey.test.ts+84
- client/modules/accessKey.ts+32-16
- client/modules/config.test.ts+1
- client/modules/config.ts+4-1
- client/modules/followUpQuestions.test.ts+66-8
- client/modules/followUpQuestions.ts+7-3
- client/modules/history.test.ts+71
- client/modules/history.ts+96
- client/modules/parentWindow.test.tsAdded+110
- client/modules/parentWindow.ts+27-3
- client/modules/pubSub.test.ts+82
- client/modules/pubSub.ts+49-1
- client/modules/querySuggestions.test.ts+36
- client/modules/querySuggestions.ts+20-11
- client/modules/reasoning.test.tsAdded+81
- client/modules/reasoning.tsAdded+41
- client/modules/settings.test.ts+1
- client/modules/settings.ts-9
- client/modules/textGeneration.chatBudget.test.ts+68-1
- client/modules/textGeneration.inference.test.ts+1
- client/modules/textGeneration.ts+4-2
- client/modules/textGenerationUtilities.test.ts+41
- client/modules/textGenerationUtilities.ts+24
- client/modules/textGenerationWithHorde.ts+2
- client/modules/textGenerationWithWllama.test.ts+26-1
- client/modules/textGenerationWithWllama.ts+7-3
- client/modules/textToSpeech.test.ts+23
- client/modules/textToSpeech.ts+10-17
- docs/ai-integration.md+3-1
28 unmodified lines293031323334353637382 unmodified lines4142434445464728 unmodified lines# "internal" -> $INTERNAL_OPENAI_COMPATIBLE_API_NAMEDEFAULT_INFERENCE_TYPE="browser"# 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.SEARCH_FALLBACK_ENABLED="false"# 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.SEARCH_FALLBACK_PROVIDERS=""# 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.2 unmodified lines# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.SEARCH_FALLBACK_YOUCOM_API_KEY=""# 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.SEARCH_FALLBACK_KEENABLE_API_KEY=""# 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.28 unmodified lines293031323334353637383940412 unmodified lines4445464748495028 unmodified lines# "internal" -> $INTERNAL_OPENAI_COMPATIBLE_API_NAMEDEFAULT_INFERENCE_TYPE="browser"# 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.PARENT_WINDOW_ORIGINS="https://huggingface.co"# 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.SEARCH_FALLBACK_ENABLED="false"# 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.SEARCH_FALLBACK_PROVIDERS=""# 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.2 unmodified lines# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.SEARCH_FALLBACK_YOUCOM_API_KEY=""# 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.SEARCH_FALLBACK_KEENABLE_API_KEY=""# 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.
1 unmodified line2345678919 unmodified lines2930313233341 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-24- 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.- 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.- 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.19 unmodified lines- 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`.- 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.- 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.## 2026-11-231 unmodified line2345678910111213141516171819202122232425262719 unmodified lines474849505152531 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-25- 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.- 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.- 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.- 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.## 2026-11-24- 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.- `/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.- 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.- `/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.- 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.- 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`.- 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.- 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.- 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.- 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.- 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.- 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.- 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.19 unmodified lines- 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`.- 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.- 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.- 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.## 2026-11-23
736 unmodified lines737738739736 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);});});736 unmodified lines737738739740741742743744745746747748749750751752753754755756757758759760761762763736 unmodified linesexpect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);});});describe("ChatInterface previous follow-up questions", () => {it("does not record an empty follow-up question", async () => {vi.mocked(generateFollowUpQuestion).mockResolvedValueOnce("Is it supported in Safari?").mockResolvedValueOnce("").mockResolvedValueOnce("Does it drain the battery?");renderChatInterface({ suppressInitialFollowUp: false });await act(async () => {});await act(async () => {await sendMessage("And how do I use it?");});await act(async () => {await sendMessage("Does it work in the background?");});expect(generateFollowUpQuestion).toHaveBeenCalledTimes(3);expect(vi.mocked(generateFollowUpQuestion).mock.calls[2][0].previousQuestions,).toEqual(["Is it supported in Safari?"]);});});
130 unmodified lines131132133134135136137138139130 unmodified lines// A newer call, or an unmount, took over while this one awaited.if (invocation !== followUpInvocationRef.current) return;setPreviousFollowUpQuestions((prev) =>[...prev, newQuestion].slice(-5),);setFollowUpQuestion(newQuestion);setGenerationState({...getChatGenerationState(),130 unmodified lines131132133134135136137138139140141142143144130 unmodified lines// A newer call, or an unmount, took over while this one awaited.if (invocation !== followUpInvocationRef.current) return;// No question was found in the reply: an empty entry would show up as// a blank line in the next prompt's "do not repeat" list and push a// real question out of it.if (newQuestion) {setPreviousFollowUpQuestions((prev) =>[...prev, newQuestion].slice(-5),);}setFollowUpQuestion(newQuestion);setGenerationState({...getChatGenerationState(),
12345610 unmodified lines1718192021222324252627282930313233343536373839404142434445464748import { usePubSub } from "create-pubsub/react";import { useCallback } from "react";import { settingsPubSub } from "@/modules/pubSub";/*** Splits a streamed AI response into the part between the reasoning markers10 unmodified linesconst extractReasoningAndMainContent = useCallback((text: string, startMarker: string, endMarker: string) => {if (!text)return { reasoningContent: "", mainContent: "", isGenerating: false };const trimmedText = text.trim();if (!trimmedText.startsWith(startMarker))return { reasoningContent: "", mainContent: text, isGenerating: false };const startIndex = trimmedText.indexOf(startMarker);const endIndex = trimmedText.indexOf(endMarker);if (endIndex === -1) {return {reasoningContent: trimmedText.slice(startIndex + startMarker.length),mainContent: "",isGenerating: isResponseGenerating,};}return {reasoningContent: trimmedText.slice(startIndex + startMarker.length,endIndex,),mainContent: trimmedText.slice(endIndex + endMarker.length),isGenerating: false,};},[isResponseGenerating],123456710 unmodified lines18192021222324252627282930313233import { usePubSub } from "create-pubsub/react";import { useCallback } from "react";import { settingsPubSub } from "@/modules/pubSub";import { splitReasoning } from "@/modules/reasoning";/*** Splits a streamed AI response into the part between the reasoning markers10 unmodified linesconst extractReasoningAndMainContent = useCallback((text: string, startMarker: string, endMarker: string) => {const { reasoning, answer, isOpen } = splitReasoning(text,startMarker,endMarker,);return {reasoningContent: reasoning,mainContent: answer,isGenerating: isOpen && isResponseGenerating,};},[isResponseGenerating],
12345678910111213141516171819202122232425262728293031323334353637383940414 unmodified lines46474849505152532 unmodified lines565758596061626 unmodified lines6970717273747576771 unmodified line79808182838485import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { useSearchHistory } from "@/hooks/useSearchHistory";import type { SearchEntry } from "@/modules/history";import SearchStats from "./SearchStats";vi.mock("@/hooks/useSearchHistory", () => ({useSearchHistory: vi.fn(),}));/** The hook mock has to return the full shape the real hook returns. */const mockHistory = (recentSearches: SearchEntry[]) => {const noop = vi.fn(async (): Promise<void> => {});vi.mocked(useSearchHistory).mockReturnValue({recentSearches,llmResponseCount: 0,chatMessageCount: 0,filteredSearches: recentSearches,groupedSearches: {},isLoading: false,error: null,currentPage: 0,totalPages: 0,hasNextPage: false,hasPreviousPage: false,retryLastOperation: noop,clearError: vi.fn(),searchHistory: vi.fn(),addToHistory: noop,togglePin: noop,deleteEntry: noop,clearAll: noop,refreshHistory: noop,nextPage: vi.fn(),previousPage: vi.fn(),goToPage: vi.fn(),});};/** Metric cards print the value below the label; the heatmap above it. */const valueBelow = (label: string) =>4 unmodified linesdescribe("SearchStats", () => {let originalTimeZone: string | undefined;beforeEach(() => {originalTimeZone = process.env.TZ;});afterEach(() => {2 unmodified lineselse process.env.TZ = originalTimeZone;});it("buckets the Daily Average by local day, like the heatmap", () => {process.env.TZ = "Europe/Zurich"; // UTC+1 in Januaryvi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(new Date(2026, 0, 15, 12));6 unmodified linesexpect(new Date(first).getUTCDate()).toBe(14);expect(new Date(second).getUTCDate()).toBe(15);mockHistory([{ id: 1, query: "first", timestamp: first },{ id: 2, query: "second", timestamp: second },]);render(<MantineProvider>1 unmodified line</MantineProvider>,);expect(valueBelow("Daily Average")).toBe("2");expect(valueAbove("Active days")).toBe("1");});});1234567891011121314151617181920214 unmodified lines2627282930313233342 unmodified lines373839404142436 unmodified lines5051525354555657581 unmodified line60616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148import { MantineProvider } from "@mantine/core";import { render, screen, waitFor } from "@testing-library/react";import * as historyModule from "@/modules/history";import { historyDatabase } from "@/modules/history";import { getSettings } from "@/modules/pubSub";import SearchStats from "./SearchStats";// Pin the settings the history module reads, and keep pubSub's module-level// localStorage reads out of the test.vi.mock("@/modules/pubSub", () => ({getSettings: vi.fn(() => ({historyAutoCleanup: false,historyRetentionDays: 30,historyMaxEntries: 500,})),}));const DAY_MS = 24 * 60 * 60 * 1000;/** Metric cards print the value below the label; the heatmap above it. */const valueBelow = (label: string) =>4 unmodified linesdescribe("SearchStats", () => {let originalTimeZone: string | undefined;beforeEach(async () => {originalTimeZone = process.env.TZ;await historyDatabase.searches.clear();});afterEach(() => {2 unmodified lineselse process.env.TZ = originalTimeZone;});it("buckets the Daily Average by local day, like the heatmap", async () => {process.env.TZ = "Europe/Zurich"; // UTC+1 in Januaryvi.useFakeTimers({ toFake: ["Date"] });vi.setSystemTime(new Date(2026, 0, 15, 12));6 unmodified linesexpect(new Date(first).getUTCDate()).toBe(14);expect(new Date(second).getUTCDate()).toBe(15);await historyDatabase.searches.bulkAdd([{ query: "first", timestamp: first },{ query: "second", timestamp: second },]);render(<MantineProvider>1 unmodified line</MantineProvider>,);await waitFor(() => expect(valueBelow("Daily Average")).toBe("2"));expect(valueAbove("Active days")).toBe("1");});it("counts every stored search, not only the newest 1000", async () => {const now = Date.now();// 1,500 searches over the last 20 days; the oldest 500 are the ones a// window of the newest 1000 drops.await historyDatabase.searches.bulkAdd(Array.from({ length: 1500 }, (_, i) => ({query: `query ${i}`,timestamp: now - (1500 - i) * ((20 * DAY_MS) / 1500),source: i < 500 ? "followup" : "user",})),);render(<MantineProvider><SearchStats period="all" /></MantineProvider>,);await waitFor(() =>expect(valueBelow("Total Searches")).toBe((1500).toLocaleString()),);// The sources card includes the oldest entries too.expect(screen.getByText("500 searches")).toBeTruthy();expect(screen.getByText("1000 searches")).toBeTruthy();// So does the heatmap. The newest 1,000 of these cover about 14 days; all// 1,500 cover about 21 (the span plus the day it ends on).expect(Number(valueAbove("Active days"))).toBeGreaterThanOrEqual(20);});it("pairs each search with its own source, also when timestamps tie", async () => {const tied = Date.now();await historyDatabase.searches.bulkAdd([{ query: "saved before sources existed", timestamp: tied },{ query: "typed", timestamp: tied, source: "user" },{ query: "typed again", timestamp: tied, source: "user" },{ query: "asked after", timestamp: tied, source: "followup" },]);render(<MantineProvider><SearchStats period="all" /></MantineProvider>,);await waitFor(() => expect(valueBelow("Total Searches")).toBe("4"));const sourceRow = (name: string) =>screen.getByText(name).closest("div")?.parentElement?.textContent;expect(sourceRow("User")).toContain("2 searches");expect(sourceRow("Followup")).toContain("1 searches");expect(sourceRow("Unknown")).toContain("1 searches");});it("leaves IndexedDB alone while history is turned off", async () => {await historyDatabase.searches.add({query: "kept but hidden",timestamp: Date.now(),});const settingsMock = vi.mocked(getSettings);const historyOn = settingsMock.getMockImplementation();settingsMock.mockImplementation(() =>({...historyOn?.(),enableHistory: false,}) as ReturnType<typeof getSettings>,);const readSpy = vi.spyOn(historyModule, "getSearchActivityRecords");try {render(<MantineProvider><SearchStats period="all" /></MantineProvider>,);expect(await screen.findByText("No search data available")).toBeTruthy();expect(readSpy).not.toHaveBeenCalled();} finally {readSpy.mockRestore();if (historyOn) settingsMock.mockImplementation(historyOn);}});});
10 unmodified lines1112131415161718198 unmodified lines2829303132333423 unmodified lines5859606162636410 unmodified linesTitle,} from "@mantine/core";import { IconSearch } from "@tabler/icons-react";import { useMemo } from "react";import { useSearchHistory } from "@/hooks/useSearchHistory";import type { SearchEntry } from "@/modules/history";import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";import { formatRelativeTime } from "@/modules/stringFormatters";import ActivityHeatmap from "./ActivityHeatmap";8 unmodified linesavgPerDay: number;mostActiveHour: number;topSources: { source: string; count: number; percentage: number }[];recentActivity: SearchEntry[];}function MetricCard({23 unmodified linesperiod = "week",compact = false,}: SearchStatsProps) {const { recentSearches, isLoading } = useSearchHistory({ limit: 1000 });const stats = useMemo((): StatsData => {if (!recentSearches.length) {10 unmodified lines111213141516171819202122238 unmodified lines3233343536373823 unmodified lines6263646566676869707172737475767778798081828384858687888990919293949510 unmodified linesTitle,} from "@mantine/core";import { IconSearch } from "@tabler/icons-react";import { useEffect, useMemo, useState } from "react";import { REFRESH_INTERVAL_MS } from "@/hooks/useSearchHistory";import {getSearchActivityRecords,isHistoryEnabled,type SearchActivityRecord,} from "@/modules/history";import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";import { formatRelativeTime } from "@/modules/stringFormatters";import ActivityHeatmap from "./ActivityHeatmap";8 unmodified linesavgPerDay: number;mostActiveHour: number;topSources: { source: string; count: number; percentage: number }[];recentActivity: SearchActivityRecord[];}function MetricCard({23 unmodified linesperiod = "week",compact = false,}: SearchStatsProps) {const [recentSearches, setRecentSearches] = useState<SearchActivityRecord[]>([],);const [isLoading, setIsLoading] = useState(true);// The whole table, not a window of the newest rows: the totals, the// averages and the heatmap are only right if the oldest searches count too.// A disabled history is shown as empty without opening the database.useEffect(() => {let cancelled = false;const load = async () => {const records = isHistoryEnabled()? await getSearchActivityRecords(): [];if (cancelled) return;setRecentSearches(records);setIsLoading(false);};load();const intervalId = setInterval(load, REFRESH_INTERVAL_MS);return () => {cancelled = true;clearInterval(intervalId);};}, []);const stats = useMemo((): StatsData => {if (!recentSearches.length) {
1234524 unmodified lines30313233343526 unmodified lines6263646566676869704 unmodified lines7576777879808124 unmodified lines106107108109110111import type { ServerConfig } from "@shared/serverConfig";import { render, screen, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { getConfig } from "@/modules/config";import App from "./App";24 unmodified linesinternalApiName: "Internal API",defaultInferenceType: "browser",searchToken: "a".repeat(64),};describe("App", () => {26 unmodified lines* Renders a fresh module instance so the settings module reads the profile* seeded here, since it captures localStorage once at import.*/async function renderWithStoredSettings(stored: Record<string, unknown>) {vi.resetModules();localStorage.setItem("settings", JSON.stringify(stored));const [{ getConfig: freshGetConfig },4 unmodified linesimport("./App"),import("@/modules/pubSub"),]);vi.mocked(freshGetConfig).mockResolvedValue(serverConfig);render(<FreshApp />);await screen.findByTestId("main-page");24 unmodified lines);});// An unreachable /api/config must not look like `accessKeysEnabled: false`,// which would let the app through the gate.it("refuses to render the app when the config cannot be loaded", async () => {1234524 unmodified lines3031323334353626 unmodified lines6364656667686970717273744 unmodified lines7980818283848524 unmodified lines110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168import type { ServerConfig } from "@shared/serverConfig";import { act, cleanup, render, screen, waitFor } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";import { getConfig } from "@/modules/config";import App from "./App";24 unmodified linesinternalApiName: "Internal API",defaultInferenceType: "browser",searchToken: "a".repeat(64),parentWindowOrigins: ["https://huggingface.co"],};describe("App", () => {26 unmodified lines* Renders a fresh module instance so the settings module reads the profile* seeded here, since it captures localStorage once at import.*/async function renderWithStoredSettings(stored?: Record<string, unknown>,config: ServerConfig = serverConfig,) {vi.resetModules();if (stored) localStorage.setItem("settings", JSON.stringify(stored));const [{ getConfig: freshGetConfig },4 unmodified linesimport("./App"),import("@/modules/pubSub"),]);vi.mocked(freshGetConfig).mockResolvedValue(config);render(<FreshApp />);await screen.findByTestId("main-page");24 unmodified lines);});/** Renders a fresh module instance against a server whose config fails to load. */async function renderWithoutConfig(stored?: Record<string, unknown>) {vi.resetModules();if (stored) localStorage.setItem("settings", JSON.stringify(stored));const [{ getConfig: freshGetConfig },{ default: FreshApp },{ webGpuSupport },] = await Promise.all([import("@/modules/config"),import("./App"),import("@/modules/webGpu"),]);vi.mocked(freshGetConfig).mockRejectedValue(new Error("Network error"));render(<FreshApp />);await screen.findByText(/could not load the server configuration/i);// Settings are initialized once the WebGPU check is in, so let it finish.await webGpuSupport;await act(async () => {});}describe("when the config cannot be loaded", () => {it("saves no settings on a first visit", async () => {await renderWithoutConfig();expect(localStorage.getItem("settings")).toBeNull();});it("leaves a stored profile as it was", async () => {const stored = { enableAiResponse: true };await renderWithoutConfig(stored);expect(localStorage.getItem("settings")).toBe(JSON.stringify(stored));});// Settings saved from shipped defaults would count as the user's own// choices, and the server's defaults could never seed them again.it("lets a later load seed the server's defaults", async () => {await renderWithoutConfig();cleanup();const getSettings = await renderWithStoredSettings(undefined, {...serverConfig,defaultInferenceType: "openai",});await waitFor(() => expect(getSettings().inferenceType).toBe("openai"));});});// An unreachable /api/config must not look like `accessKeysEnabled: false`,// which would let the app through the gate.it("refuses to render the app when the config cannot be loaded", async () => {
11 unmodified lines12131415161718192021222324252627282930313270 unmodified lines1031041051061071081091101118 unmodified lines1201211221231241251 unmodified line12712812913013113213313411 unmodified linesimport { usePubSub } from "create-pubsub/react";import { lazy, useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import { settingsPubSub } from "@/modules/pubSub";import {applyServerConfig,defaultSettings,hasStoredUserSettings,upgradeUntouchedSystemPrompt,} from "@/modules/settings";import { webGpuSupport } from "@/modules/webGpu";import "@mantine/notifications/styles.css";import { verifyStoredAccessKey } from "@/modules/accessKey";import {FALLBACK_CONFIG,getConfig,type ServerConfig,} from "@/modules/config";import MainPage from "../Pages/Main/MainPage";const AccessPage = lazy(() => import("../Pages/AccessPage"));70 unmodified lines/*** Waits for the server config so its defaults can seed a fresh profile, and* for the WebGPU check, which picks between the GPU and the CPU default model.* Falling back to shipped defaults is safe here: unlike access control,* guessing wrong only means the user sees the settings they can already* change themselves.*/function useInitializeSettings(config: ConfigState) {const [settings, setSettings] = usePubSub(settingsPubSub);8 unmodified linesif (settingsInitialized ||config === "loading" ||hasWebGpu === undefined) {return;1 unmodified linesetSettings(applyServerConfig(upgradeUntouchedSystemPrompt({ ...defaultSettings, ...settings }),config === "unavailable" ? FALLBACK_CONFIG : config,hasStoredUserSettings,hasWebGpu,),11 unmodified lines12131415161718192021222324252670 unmodified lines9798991001011021031041058 unmodified lines1141151161171181191201 unmodified line12212312412512612712812911 unmodified linesimport { usePubSub } from "create-pubsub/react";import { lazy, useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import { hasStoredUserSettings, settingsPubSub } from "@/modules/pubSub";import {applyServerConfig,upgradeUntouchedSystemPrompt,} from "@/modules/settings";import { webGpuSupport } from "@/modules/webGpu";import "@mantine/notifications/styles.css";import { verifyStoredAccessKey } from "@/modules/accessKey";import { getConfig, type ServerConfig } from "@/modules/config";import MainPage from "../Pages/Main/MainPage";const AccessPage = lazy(() => import("../Pages/AccessPage"));70 unmodified lines/*** Waits for the server config so its defaults can seed a fresh profile, and* for the WebGPU check, which picks between the GPU and the CPU default model.* When the config could not be loaded nothing is written: the app shows an* error instead, and settings seeded from shipped defaults would be taken for* the user's own choices on every later load.*/function useInitializeSettings(config: ConfigState) {const [settings, setSettings] = usePubSub(settingsPubSub);8 unmodified linesif (settingsInitialized ||config === "loading" ||config === "unavailable" ||hasWebGpu === undefined) {return;1 unmodified linesetSettings(applyServerConfig(upgradeUntouchedSystemPrompt(settings),config,hasStoredUserSettings,hasWebGpu,),
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import { listOpenAiCompatibleModels } from "@shared/openaiModels";import { renderHook, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { addLogEntry } from "@/modules/logEntries";import { defaultSettings } from "@/modules/settings";import { aiHordeDefaultApiKey, fetchHordeModels, fetchHordeUserInfo,} from "@/modules/textGenerationWithHorde";import { useHordeModels } from "./useHordeModels";import { useHordeUserInfo } from "./useHordeUserInfo";import { useOpenAiModels } from "./useOpenAiModels";
vi.mock("@shared/openaiModels", () => ({ listOpenAiCompatibleModels: vi.fn(),}));vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("@/modules/textGenerationWithHorde", () => ({ aiHordeDefaultApiKey: "0000000000", fetchHordeUserInfo: vi.fn(), fetchHordeModels: vi.fn(),}));
type Settings = typeof defaultSettings;
function deferred<T>() { let resolve!: (v: T) => void; const promise = new Promise<T>((res) => { resolve = res; }); return { promise, resolve };}
/** Records the signal of each call and lets the test settle calls in any order. */function controlled<T>(mock: ReturnType<typeof vi.fn>, signalArg: number) { const calls: { signal: AbortSignal; resolve: (v: T) => void }[] = []; mock.mockImplementation((...args: unknown[]) => { const d = deferred<T>(); calls.push({ signal: args[signalArg] as AbortSignal, resolve: d.resolve }); return d.promise; }); return calls;}
/** Replaces `AbortSignal.timeout` with timeouts the test fires by hand. */function manualTimeouts() { const timeouts: { ms: number; fire: () => void }[] = []; vi.spyOn(AbortSignal, "timeout").mockImplementation((ms: number) => { const c = new AbortController(); timeouts.push({ ms, fire: () => c.abort(new DOMException("Timed out", "TimeoutError")), }); return c.signal; }); return timeouts;}
const openAi = (patch: Partial<Settings>): Settings => ({ ...defaultSettings, inferenceType: "openai", ...patch,});const horde = (patch: Partial<Settings>): Settings => ({ ...defaultSettings, inferenceType: "horde", ...patch,});
beforeEach(() => { vi.mocked(addLogEntry).mockClear();});afterEach(() => { vi.restoreAllMocks();});
describe("useOpenAiModels", () => { it("keeps the latest server's list when an older response arrives last", async () => { const calls = controlled<{ id: string }[]>( vi.mocked(listOpenAiCompatibleModels), 2, ); const { result, rerender } = renderHook( (s: Settings) => useOpenAiModels(s), { initialProps: openAi({ openAiApiBaseUrl: "http://old" }), }, ); rerender(openAi({ openAiApiBaseUrl: "http://new" }));
expect(calls).toHaveLength(2); expect(calls[0].signal.aborted).toBe(true); expect(calls[1].signal.aborted).toBe(false);
calls[1].resolve([{ id: "new-model" }]); await waitFor(() => expect(result.current.openAiModels).toEqual([ { label: "new-model", value: "new-model" }, ]), ); calls[0].resolve([{ id: "old-model" }]); await Promise.resolve();
expect(result.current.openAiModels).toEqual([ { label: "new-model", value: "new-model" }, ]); expect(result.current.useTextInput).toBe(false); });
it("does not log an error for a request aborted by a newer keystroke", async () => { vi.mocked(listOpenAiCompatibleModels).mockImplementation( (_url, _key, signal) => new Promise((_resolve, reject) => signal?.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), ), ), ); const { rerender } = renderHook((s: Settings) => useOpenAiModels(s), { initialProps: openAi({ openAiApiBaseUrl: "http://a" }), }); rerender(openAi({ openAiApiBaseUrl: "http://ab" })); await Promise.resolve();
expect(addLogEntry).not.toHaveBeenCalled(); });
it("forgets the previous server's models when the base URL is cleared", async () => { vi.mocked(listOpenAiCompatibleModels).mockResolvedValue([{ id: "m" }]); const { result, rerender } = renderHook( (s: Settings) => useOpenAiModels(s), { initialProps: openAi({ openAiApiBaseUrl: "http://a" }), }, ); await waitFor(() => expect(result.current.openAiModels).toHaveLength(1));
rerender(openAi({ openAiApiBaseUrl: "" }));
expect(result.current.openAiModels).toEqual([]); expect(result.current.useTextInput).toBe(false); });});
describe("useHordeUserInfo", () => { it("stays cleared when the key is cleared while a lookup is in flight", async () => { const calls = controlled<{ username: string; kudos: number } | null>( vi.mocked(fetchHordeUserInfo), 1, ); const { result, rerender } = renderHook( (s: Settings) => useHordeUserInfo(s), { initialProps: horde({ hordeApiKey: "secret-key" }), }, ); rerender(horde({ hordeApiKey: "" }));
expect(calls[0].signal.aborted).toBe(true); calls[0].resolve({ username: "old#1", kudos: 5 }); await Promise.resolve();
expect(result.current).toBeNull(); });
it("gives up on a /find_user that never answers after 10 seconds", () => { const timeouts = manualTimeouts(); const calls = controlled<null>(vi.mocked(fetchHordeUserInfo), 1); renderHook(() => useHordeUserInfo(horde({ hordeApiKey: "secret-key" })));
expect(timeouts.map((t) => t.ms)).toEqual([10_000]); expect(calls[0].signal.aborted).toBe(false); timeouts[0].fire(); expect(calls[0].signal.aborted).toBe(true); });
it("does not look up the anonymous key", () => { vi.mocked(fetchHordeUserInfo).mockClear(); renderHook(() => useHordeUserInfo(horde({ hordeApiKey: aiHordeDefaultApiKey })), ); expect(fetchHordeUserInfo).not.toHaveBeenCalled(); });});
describe("useHordeModels", () => { it("aborts the request when another backend is selected", () => { const calls = controlled<never[]>(vi.mocked(fetchHordeModels), 0); const { rerender } = renderHook((s: Settings) => useHordeModels(s), { initialProps: horde({}), }); rerender(openAi({}));
expect(calls[0].signal.aborted).toBe(true); });
it("gives up on a /status/models that never answers after 10 seconds", () => { const timeouts = manualTimeouts(); const calls = controlled<never[]>(vi.mocked(fetchHordeModels), 0); renderHook(() => useHordeModels(horde({})));
expect(timeouts.map((t) => t.ms)).toEqual([10_000]); timeouts[0].fire(); expect(calls[0].signal.aborted).toBe(true); });});1232 unmodified lines6789101112131415161718192021222324251 unmodified line272829303132333435import { useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import type { defaultSettings } from "@/modules/settings";2 unmodified linestype Settings = typeof defaultSettings;/** AI Horde models as select options; only fetched while Horde is the selected backend. */export const useHordeModels = (settings: Settings) => {const [hordeModels, setHordeModels] = useState<ModelOption[]>([]);useEffect(() => {async function fetchAvailableHordeModels() {try {const models = await fetchHordeModels();const formattedModels = models.map((model) => ({label: model.name,value: model.name,}));setHordeModels(formattedModels);} catch (error) {const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching AI Horde models: ${errorMessage}`);1 unmodified line}}if (settings.inferenceType === "horde") {fetchAvailableHordeModels();}}, [settings.inferenceType]);return hordeModels;12342 unmodified lines78910111213141516171819202122232425262728293031323334353637381 unmodified line4041424344454647import { withTimeout } from "@shared/withTimeout";import { useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import type { defaultSettings } from "@/modules/settings";2 unmodified linestype Settings = typeof defaultSettings;/** How long `/status/models` may take before the list falls back to empty. */const HORDE_MODELS_TIMEOUT_MS = 10_000;/*** AI Horde models as select options; only fetched while Horde is the selected* backend. Switching away aborts the request in flight.*/export const useHordeModels = (settings: Settings) => {const [hordeModels, setHordeModels] = useState<ModelOption[]>([]);useEffect(() => {if (settings.inferenceType !== "horde") return;const controller = new AbortController();async function fetchAvailableHordeModels() {try {const models = await fetchHordeModels(withTimeout(controller.signal, HORDE_MODELS_TIMEOUT_MS),);if (controller.signal.aborted) return;setHordeModels(models.map((model) => ({ label: model.name, value: model.name })),);} catch (error) {if (controller.signal.aborted) return;const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching AI Horde models: ${errorMessage}`);1 unmodified line}}fetchAvailableHordeModels();return () => controller.abort();}, [settings.inferenceType]);return hordeModels;
1235 unmodified lines91011121314151617181920212223242526272829303132331 unmodified line353637383940414243import { useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import type { defaultSettings } from "@/modules/settings";5 unmodified linestype Settings = typeof defaultSettings;/** The logged-in Horde user, or null when the key is empty or the anonymous one. */export const useHordeUserInfo = (settings: Settings) => {const [hordeUserInfo, setHordeUserInfo] = useState<HordeUserInfo | null>(null,);useEffect(() => {async function fetchUserInfo() {try {if (settings.hordeApiKey &&settings.hordeApiKey !== aiHordeDefaultApiKey) {const userInfo = await fetchHordeUserInfo(settings.hordeApiKey);setHordeUserInfo(userInfo);} else {setHordeUserInfo(null);}} catch (error) {const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching AI Horde user info: ${errorMessage}`);1 unmodified line}}if (settings.inferenceType === "horde") {fetchUserInfo();}}, [settings.inferenceType, settings.hordeApiKey]);return hordeUserInfo;12345 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950511 unmodified line5354555657585960import { withTimeout } from "@shared/withTimeout";import { useEffect, useState } from "react";import { addLogEntry } from "@/modules/logEntries";import type { defaultSettings } from "@/modules/settings";5 unmodified linestype Settings = typeof defaultSettings;/** How long `/find_user` may take before the user info falls back to none. */const HORDE_USER_INFO_TIMEOUT_MS = 10_000;/*** The logged-in Horde user, or null when the key is empty or the anonymous one.* A key change aborts the request for the previous key, so a slow answer for an* old or cleared key can never show up afterwards.*/export const useHordeUserInfo = (settings: Settings) => {const [hordeUserInfo, setHordeUserInfo] = useState<HordeUserInfo | null>(null,);useEffect(() => {if (settings.inferenceType !== "horde") return;if (!settings.hordeApiKey ||settings.hordeApiKey === aiHordeDefaultApiKey) {setHordeUserInfo(null);return;}const controller = new AbortController();async function fetchUserInfo() {try {const userInfo = await fetchHordeUserInfo(settings.hordeApiKey,withTimeout(controller.signal, HORDE_USER_INFO_TIMEOUT_MS),);if (controller.signal.aborted) return;setHordeUserInfo(userInfo);} catch (error) {if (controller.signal.aborted) return;const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching AI Horde user info: ${errorMessage}`);1 unmodified line}}fetchUserInfo();return () => controller.abort();}, [settings.inferenceType, settings.hordeApiKey]);return hordeUserInfo;
8 unmodified lines9101112131415161718192021222324252627282930313233343536372 unmodified lines4041424344454647488 unmodified lines/*** Falls back to a free-text model input when the API does not list its models* or cannot be reached, so the setting stays usable either way.*/export const useOpenAiModels = (settings: Settings) => {const [openAiModels, setOpenAiModels] = useState<ModelOption[]>([]);const [useTextInput, setUseTextInput] = useState(false);useEffect(() => {async function fetchOpenAiModels() {try {const models = await listOpenAiCompatibleModels(settings.openAiApiBaseUrl,settings.openAiApiKey,);const uniqueModelIds = [...new Set(models.map((m: { id: string }) => m.id)),];const options: ModelOption[] = uniqueModelIds.map((id) => ({label: id,value: id,}));setOpenAiModels(options);setUseTextInput(!Array.isArray(options) || options.length === 0);} catch (error) {const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching OpenAI models: ${errorMessage}`);2 unmodified lines}}if (settings.inferenceType === "openai" && settings.openAiApiBaseUrl) {fetchOpenAiModels();}}, [settings.inferenceType,settings.openAiApiBaseUrl,8 unmodified lines9101112131415161718192021222324252627282930313233343536373839404142434445464748495051522 unmodified lines55565758596061628 unmodified lines/*** Falls back to a free-text model input when the API does not list its models* or cannot be reached, so the setting stays usable either way.** Settings change on every keystroke, so each change aborts the request of the* previous one: only the latest base URL and key can update the list.*/export const useOpenAiModels = (settings: Settings) => {const [openAiModels, setOpenAiModels] = useState<ModelOption[]>([]);const [useTextInput, setUseTextInput] = useState(false);useEffect(() => {if (settings.inferenceType !== "openai") return;if (!settings.openAiApiBaseUrl) {// No server: forget the previous server's models.setOpenAiModels([]);setUseTextInput(false);return;}const controller = new AbortController();async function fetchOpenAiModels() {try {const models = await listOpenAiCompatibleModels(settings.openAiApiBaseUrl,settings.openAiApiKey,controller.signal,);if (controller.signal.aborted) return;const uniqueModelIds = [...new Set(models.map((m) => m.id))];const options: ModelOption[] = uniqueModelIds.map((id) => ({label: id,value: id,}));setOpenAiModels(options);setUseTextInput(options.length === 0);} catch (error) {if (controller.signal.aborted) return;const errorMessage =error instanceof Error ? error.message : String(error);addLogEntry(`Error fetching OpenAI models: ${errorMessage}`);2 unmodified lines}}fetchOpenAiModels();return () => controller.abort();}, [settings.inferenceType,settings.openAiApiBaseUrl,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { MantineProvider } from "@mantine/core";import { act, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import SearchForm from "@/components/Search/Form/SearchForm";import { resetHandledQuery } from "@/modules/autoSearch";import { getQuerySuggestions, updateQuerySuggestions } from "@/modules/pubSub";
const mockFetch = vi.fn();vi.stubGlobal("fetch", mockFetch);
vi.mock("wouter", () => ({ useLocation: () => ["/", vi.fn()],}));
vi.mock("@/hooks/useSearchHistory", () => ({ useSearchHistory: () => ({ addToHistory: vi.fn() }),}));
vi.mock("@/hooks/useHistoryRestore", () => ({ useHistoryRestore: () => ({ restoreSearch: vi.fn() }),}));
vi.mock("../History/HistoryButton", () => ({ default: () => null }));
vi.mock("@/modules/textGeneration", () => ({ searchAndRespond: vi.fn() }));
vi.mock("@/components/DictationButton", () => ({ dictationButtonWidth: 34, default: () => null,}));
const storedSuggestions = Array.from( { length: 25 }, (_, index) => `suggestion ${index}`,);
function renderSearchForm(query: string) { render( <MantineProvider> <SearchForm query={query} updateQuery={vi.fn()} /> </MantineProvider>, );}
/** Lets the suggestion that an emptied field asks for finish arriving. */const settle = () => act(async () => {});
describe("SearchForm and the stored suggestions", () => { beforeEach(() => { vi.clearAllMocks(); resetHandledQuery(); window.history.replaceState({}, "", "/"); updateQuerySuggestions([...storedSuggestions]); });
it("uses one stored suggestion when the last character is deleted", async () => { const user = userEvent.setup(); renderSearchForm("a");
await user.type(await screen.findByRole("textbox"), "{Backspace}"); await settle();
expect(getQuerySuggestions()).toHaveLength(24); });
it("uses one stored suggestion when Clear is clicked", async () => { const user = userEvent.setup(); renderSearchForm("hello");
await user.click(await screen.findByRole("button", { name: "Clear" })); await settle();
expect(getQuerySuggestions()).toHaveLength(24); });
it("fetches the suggestions once when Clear finds the store empty", async () => { updateQuerySuggestions([]); mockFetch.mockImplementation( async () => new Response(JSON.stringify(["x", "y", "z"])), ); const user = userEvent.setup(); renderSearchForm("hello");
await user.click(await screen.findByRole("button", { name: "Clear" })); await settle();
expect(mockFetch).toHaveBeenCalledTimes(1); expect(getQuerySuggestions()).toHaveLength(2); });});3 unmodified lines45678990 unmodified lines1001011021031041053 unmodified linesimport SearchForm from "@/components/Search/Form/SearchForm";import { resetHandledQuery } from "@/modules/autoSearch";import { settingsPubSub } from "@/modules/pubSub";import { defaultSettings } from "@/modules/settings";import { searchAndRespond } from "@/modules/textGeneration";90 unmodified linesawait waitForPlaceholder();});describe("Enter and Shift+Enter", () => {afterEach(() => {settingsPubSub[0]({ ...defaultSettings });3 unmodified lines4567891090 unmodified lines1011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481493 unmodified linesimport SearchForm from "@/components/Search/Form/SearchForm";import { resetHandledQuery } from "@/modules/autoSearch";import { settingsPubSub } from "@/modules/pubSub";import { getRandomQuerySuggestion } from "@/modules/querySuggestions";import { defaultSettings } from "@/modules/settings";import { searchAndRespond } from "@/modules/textGeneration";90 unmodified linesawait waitForPlaceholder();});describe("the suggestion for an emptied field", () => {it("is taken once when the last character is deleted", async () => {const user = userEvent.setup();renderSearchForm("a", vi.fn());const textarea = await screen.findByRole("textbox");vi.mocked(getRandomQuerySuggestion).mockClear();await user.type(textarea, "{Backspace}");await act(async () => {});expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);});it("is taken once when Clear is clicked", async () => {const user = userEvent.setup();renderSearchForm("hello", vi.fn());await screen.findByRole("textbox");vi.mocked(getRandomQuerySuggestion).mockClear();await user.click(screen.getByRole("button", { name: "Clear" }));await act(async () => {});expect(getRandomQuerySuggestion).toHaveBeenCalledTimes(1);});it("is dropped when the field was filled again before it arrived", async () => {let deliver: (suggestion: string) => void = () => {};vi.mocked(getRandomQuerySuggestion).mockImplementationOnce(() => new Promise((resolve) => (deliver = resolve)),).mockImplementationOnce(() => new Promise(() => {}));const user = userEvent.setup();renderSearchForm("a", vi.fn());const textarea = await screen.findByRole("textbox");await user.type(textarea, "{Backspace}b{Backspace}");await act(async () => deliver("a late suggestion"));expect(textarea).toHaveAttribute("placeholder", "Anything you need!");});});describe("Enter and Shift+Enter", () => {afterEach(() => {settingsPubSub[0]({ ...defaultSettings });
121 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173121 unmodified linesvoid initializeComponent();}, [updateQuery, isRestoringFromHistory, addToHistory]);useEffect(() => {if (state.textAreaValue.length === 0) {fetchQuerySuggestion().then((suggestion) => {setState((prev) => ({ ...prev, suggestedQuery: suggestion }));}).catch(() => {setState((prev) => ({...prev,suggestedQuery: DEFAULT_QUERY_SUGGESTION,}));});}}, [state.textAreaValue.length, fetchQuerySuggestion]);const handleInputChange = async (event: ChangeEvent<HTMLTextAreaElement>) => {const text = event.target.value;setState((prev) => ({ ...prev, textAreaValue: text }));if (text.length === 0) {try {const suggestion = await getRandomQuerySuggestion();setState((prev) => ({ ...prev, suggestedQuery: suggestion }));} catch {addLogEntry("Failed to get query suggestion");setState((prev) => ({...prev,suggestedQuery: DEFAULT_QUERY_SUGGESTION,}));}}};const handleClearButtonClick = async () => {textAreaRef.current?.focus();setState((prev) => ({...prev,textAreaValue: "",}));addLogEntry("User cleaned the search query field");const suggestion = await fetchQuerySuggestion();setState((prev) => ({...prev,suggestedQuery: suggestion,}));};// Stable identities, so `memo` on the dictation button actually holds.121 unmodified lines122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165121 unmodified linesvoid initializeComponent();}, [updateQuery, isRestoringFromHistory, addToHistory]);// The only place a suggestion is taken when the field empties, whether by// typing or by Clear. An answer that arrives after the field was filled again// is dropped, so it cannot replace a newer one.useEffect(() => {if (state.textAreaValue.length !== 0) return;let isCurrent = true;fetchQuerySuggestion().then((suggestion) => {if (isCurrent)setState((prev) => ({ ...prev, suggestedQuery: suggestion }));}).catch(() => {if (isCurrent)setState((prev) => ({...prev,suggestedQuery: DEFAULT_QUERY_SUGGESTION,}));});return () => {isCurrent = false;};}, [state.textAreaValue.length, fetchQuerySuggestion]);const handleInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {const text = event.target.value;setState((prev) => ({ ...prev, textAreaValue: text }));};const handleClearButtonClick = () => {textAreaRef.current?.focus();setState((prev) => ({...prev,textAreaValue: "",}));addLogEntry("User cleaned the search query field");};// Stable identities, so `memo` on the dictation button actually holds.
89 unmodified lines90919293949589 unmodified linesexpect(await screen.findByText("Search history is disabled")).toBeVisible();});it("shows the empty state when there is no history", async () => {renderDrawer();expect(await screen.findByText("No search history yet")).toBeVisible();89 unmodified lines9091929394959697989910010110289 unmodified linesexpect(await screen.findByText("Search history is disabled")).toBeVisible();});it("asks for every pinned search, not only the recent ones", () => {renderDrawer();expect(useSearchHistory).toHaveBeenCalledWith(expect.objectContaining({ includeAllPinned: true }),);});it("shows the empty state when there is no history", async () => {renderDrawer();expect(await screen.findByText("No search history yet")).toBeVisible();
52 unmodified lines5354555657585952 unmodified linestogglePin,deleteEntry,searchHistory,} = useSearchHistory({ limit: 100, enableGrouping: true });useEffect(() => {searchHistory(searchQuery);52 unmodified lines535455565758596061626352 unmodified linestogglePin,deleteEntry,searchHistory,} = useSearchHistory({limit: 100,enableGrouping: true,includeAllPinned: true,});useEffect(() => {searchHistory(searchQuery);
6 unmodified lines7891011126 unmodified lines192021222324125 unmodified lines1501511521536 unmodified linesgetSuppressNextFollowUp,imageSearchResultsPubSub,imageSearchStatePubSub,textSearchResultsPubSub,updateImageSearchResults,updateSuppressNextFollowUp,6 unmodified linesvi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("@/modules/history", async (importOriginal) => ({...(await importOriginal<typeof import("@/modules/history")>()),getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),125 unmodified linesexpect(getSuppressNextFollowUp()).toBe(true);});});6 unmodified lines789101112136 unmodified lines202122232425262728293031125 unmodified lines1571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861876 unmodified linesgetSuppressNextFollowUp,imageSearchResultsPubSub,imageSearchStatePubSub,isRestoringFromHistoryPubSub,textSearchResultsPubSub,updateImageSearchResults,updateSuppressNextFollowUp,6 unmodified linesvi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));vi.mock("@/modules/config", () => ({getConfig: vi.fn().mockResolvedValue({parentWindowOrigins: ["https://huggingface.co"],}),}));vi.mock("@/modules/history", async (importOriginal) => ({...(await importOriginal<typeof import("@/modules/history")>()),getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),125 unmodified linesexpect(getSuppressNextFollowUp()).toBe(true);});it("finishes the restore when embedded after a cross-origin frame", async () => {const parentWindow = {0: {get location(): Location {throw new DOMException("Blocked a frame", "SecurityError");},},postMessage: vi.fn(),};vi.stubGlobal("parent", parentWindow);try {await restoreEntry({ textResults });act(() => {vi.runOnlyPendingTimers();});expect(isRestoringFromHistoryPubSub[2]()).toBe(false);expect(parentWindow.postMessage).toHaveBeenCalledWith({ queryString: "q=saved%20search", hash: "" },"https://huggingface.co",);} finally {vi.unstubAllGlobals();}});});
82 unmodified lines83848586878882 unmodified lines});}describe("useSearchHistory", () => {it("leaves IndexedDB alone while history is turned off", async () => {const settingsMock = vi.mocked(getSettings);82 unmodified lines838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124282 unmodified lines});}/*** Waits for the hook's read to finish. With includeAllPinned the read also* queries the `pinnedAt` index, which takes fake-indexeddb more turns of* the real event loop than `settle` alone gives it. setImmediate is left real* by the fake timers above, so each await yields one real turn; `vi.waitFor`* would not, since under fake timers it polls by advancing fake time.*/async function untilLoaded(result: {current: ReturnType<typeof useSearchHistory>;}) {for (let turn = 0; turn < 500 && result.current.isLoading; turn++) {await act(async () => {await new Promise((resolve) => setImmediate(resolve));});}expect(result.current.isLoading).toBe(false);}/** Pins the oldest seeded entry, "weather in lisbon". */async function pinOldestEntry() {const [oldest] = await historyDatabase.searches.orderBy("timestamp").limit(1).toArray();await historyDatabase.searches.update(oldest.id as number, {pinned: true,pinnedAt: oldest.timestamp,});}/** Adds newer searches, so the pinned entry falls out of the recent window. */async function addNewerSearches(count: number) {for (let i = 1; i <= count; i++) {await addSearchToHistory(`newer search ${i}`, textResults);vi.advanceTimersByTime(1000);}}describe("useSearchHistory with includeAllPinned", () => {it("keeps a pinned search older than the whole recent window", async () => {await pinOldestEntry();// limit 2 reads the newest 4: the pinned entry is the 7th newest.await addNewerSearches(4);const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);expect(queriesOf(result.current.filteredSearches)).toEqual(["newer search 4","newer search 3","weather in lisbon",]);});it("keeps a pinned search inside the window but past the limit", async () => {await pinOldestEntry();const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);expect(queriesOf(result.current.filteredSearches)).toEqual(["rust async tutorial","best pizza porto","weather in lisbon",]);});it("lets the filter find a pinned search outside the recent window", async () => {await pinOldestEntry();await addNewerSearches(4);const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);act(() => result.current.searchHistory("lisbon"));await settle();expect(queriesOf(result.current.filteredSearches)).toEqual(["weather in lisbon",]);});it("still reads IndexedDB only on load, never while typing", async () => {await pinOldestEntry();const pinnedReadSpy = vi.spyOn(historyModule, "getPinnedSearches");const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await settle();await untilLoaded(result);expect(pinnedReadSpy).toHaveBeenCalledTimes(1);for (const query of ["w", "we", "wea"]) {act(() => result.current.searchHistory(query));await settle();}expect(pinnedReadSpy).toHaveBeenCalledTimes(1);});it("leaves the recent window as it is without the option", async () => {await pinOldestEntry();await addNewerSearches(4);const { result } = renderHook(() => useSearchHistory({ limit: 2 }));await settle();await untilLoaded(result);expect(queriesOf(result.current.filteredSearches)).toEqual(["newer search 4","newer search 3",]);});it("pins and unpins through both fields, so the index agrees with the flag", async () => {const [oldest] = await historyDatabase.searches.orderBy("timestamp").limit(1).toArray();const id = oldest.id as number;const { result } = renderHook(() =>useSearchHistory({ limit: 2, includeAllPinned: true }),);await untilLoaded(result);await act(async () => {await result.current.togglePin(id);});const pinned = await historyDatabase.searches.get(id);expect(pinned?.pinned).toBe(true);expect(pinned?.pinnedAt).toBe(Date.now());expect(queriesOf(await historyModule.getPinnedSearches())).toEqual(["weather in lisbon",]);await act(async () => {await result.current.togglePin(id);});const unpinned = await historyDatabase.searches.get(id);expect(unpinned?.pinned).toBe(false);expect(unpinned && "pinnedAt" in unpinned).toBe(false);expect(await historyModule.getPinnedSearches()).toEqual([]);});});describe("useSearchHistory", () => {it("leaves IndexedDB alone while history is turned off", async () => {const settingsMock = vi.mocked(getSettings);
1 unmodified line23456714 unmodified lines22232425262741 unmodified lines69707172737429 unmodified lines1041051061071081091101111121131141151161176 unmodified lines12412512612712812913044 unmodified lines17517617717817918018118218318418518618718818919019130 unmodified lines2222232242252262272282291 unmodified lineimport {addSearchToHistory,clearAllHistory,getRecentSearches,historyDatabase,type ImageResults,14 unmodified linesenableGrouping?: boolean;enablePagination?: boolean;pageSize?: number;}interface UseSearchHistoryReturn {41 unmodified linesenableGrouping = true,enablePagination = false,pageSize = 20,} = options;const [entries, setEntries] = useState<SearchEntry[]>([]);29 unmodified linesreturn;}const searches = await getRecentSearches(enablePagination ? 1000 : limit * 2,);const [llmCount, chatCount] = await Promise.all([historyDatabase.llmResponses.count(),historyDatabase.chatHistory.count(),]);setLlmResponseCount(llmCount);setChatMessageCount(chatCount);setEntries(searches);6 unmodified linesisLoadingRef.current = false;setIsLoading(false);}}, [limit, enablePagination]);// Typing only schedules a debounced settle of the query; it never reaches// IndexedDB. Clearing settles synchronously so the full list returns on the44 unmodified linesentries,query,(search) => search.query,enablePagination ? entries.length : limit,).map((result) => result.item);}, [entries, settledQuery, enablePagination, limit]);const filteredSearches = useMemo(() => {if (enablePagination) {const startIndex = currentPage * pageSize;return matched.slice(startIndex, startIndex + pageSize);}return matched.slice(0, limit);}, [matched, enablePagination, currentPage, pageSize, limit]);const matchedCount = matched.length;30 unmodified linestry {const search = await historyDatabase.searches.get(searchId);if (search) {await historyDatabase.searches.update(searchId, {pinned: !search.pinned,});await refreshHistory();addLogEntry(1 unmodified line234567814 unmodified lines23242526272829303132333441 unmodified lines7677787980818229 unmodified lines1121131141151161171181191201211221231241251261271281291301311326 unmodified lines13914014114214314414544 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821930 unmodified lines2502512522532542552562572582592602611 unmodified lineimport {addSearchToHistory,clearAllHistory,getPinnedSearches,getRecentSearches,historyDatabase,type ImageResults,14 unmodified linesenableGrouping?: boolean;enablePagination?: boolean;pageSize?: number;/*** Keep every pinned search in the list, however many newer searches exist.* Costs one extra read of the `pinnedAt` index per refresh; only the History* drawer asks for it.*/includeAllPinned?: boolean;}interface UseSearchHistoryReturn {41 unmodified linesenableGrouping = true,enablePagination = false,pageSize = 20,includeAllPinned = false,} = options;const [entries, setEntries] = useState<SearchEntry[]>([]);29 unmodified linesreturn;}const [recent, pinned, llmCount, chatCount] = await Promise.all([getRecentSearches(enablePagination ? 1000 : limit * 2),includeAllPinned ? getPinnedSearches() : Promise.resolve([]),historyDatabase.llmResponses.count(),historyDatabase.chatHistory.count(),]);// A pinned entry missing from the recent window is older than all of// it, so appending keeps the list newest first.const recentIds = new Set(recent.map((search) => search.id));const searches = [...recent,...pinned.filter((search) => !recentIds.has(search.id)),];setLlmResponseCount(llmCount);setChatMessageCount(chatCount);setEntries(searches);6 unmodified linesisLoadingRef.current = false;setIsLoading(false);}}, [limit, enablePagination, includeAllPinned]);// Typing only schedules a debounced settle of the query; it never reaches// IndexedDB. Clearing settles synchronously so the full list returns on the44 unmodified linesentries,query,(search) => search.query,enablePagination || includeAllPinned ? entries.length : limit,).map((result) => result.item);}, [entries, settledQuery, enablePagination, includeAllPinned, limit]);const filteredSearches = useMemo(() => {if (enablePagination) {const startIndex = currentPage * pageSize;return matched.slice(startIndex, startIndex + pageSize);}const shown = matched.slice(0, limit);if (!includeAllPinned) return shown;// The limit caps the unpinned list only: a pinned match past it stays.return [...shown,...matched.slice(limit).filter((search) => search.pinned),];}, [matched,enablePagination,includeAllPinned,currentPage,pageSize,limit,]);const matchedCount = matched.length;30 unmodified linestry {const search = await historyDatabase.searches.get(searchId);if (search) {// One update for both fields, so the `pinnedAt` index never// disagrees with `pinned`. Dexie deletes a key set to undefined.const pinned = !search.pinned;await historyDatabase.searches.update(searchId, {pinned,pinnedAt: pinned ? Date.now() : undefined,});await refreshHistory();addLogEntry(
171 unmodified lines17217317417517617718 unmodified lines19619719819920020113 unmodified lines215216217218219171 unmodified lines);const result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);});it("should return false without asking the server when the timeout is zero", async () => {18 unmodified linesconst result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);});it("keeps the stored hash on a 429 instead of deleting it", async () => {13 unmodified lines// A rate-limited validation must not be read as a wrong key.expect(localStorage.getItem("accessKeyHash")).not.toBeNull();});});});171 unmodified lines17217317417517617717818 unmodified lines19719819920020120220320420520620720820921021121221321421513 unmodified lines229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303171 unmodified lines);const result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);expect(localStorage.getItem("accessKeyHash")).toBeNull();});it("should return false without asking the server when the timeout is zero", async () => {18 unmodified linesconst result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);expect(localStorage.getItem("accessKeyHash")).toBeNull();expect(mockFetch).not.toHaveBeenCalled();});it("deletes a stored value that is not JSON without asking the server", async () => {const { verifyStoredAccessKey } = await import("./accessKey");localStorage.setItem("accessKeyHash", "not-json");const result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);expect(localStorage.getItem("accessKeyHash")).toBeNull();expect(mockFetch).not.toHaveBeenCalled();});it("keeps the stored hash on a 429 instead of deleting it", async () => {13 unmodified lines// A rate-limited validation must not be read as a wrong key.expect(localStorage.getItem("accessKeyHash")).not.toBeNull();});describe("when the server gives no verdict on the key", () => {const storedValue = JSON.stringify({hash: "test-hash",timestamp: Date.now(),});it.each([["the fetch rejects",() => mockFetch.mockRejectedValue(new TypeError("Failed to fetch")),],["a proxy answers 502 with a page that is not JSON",() =>mockFetch.mockResolvedValue({ok: false,status: 502,json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token <")),}),],["the SPA fallback answers 200 with the app page",() =>mockFetch.mockResolvedValue({ok: true,status: 200,json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token <")),}),],["a proxy answers 503 with JSON that has no verdict",() =>mockFetch.mockResolvedValue({ok: false,status: 503,json: vi.fn().mockResolvedValue({ error: "upstream unavailable" }),}),],])("keeps the stored hash when %s", async (_situation, answerWithIt) => {const { verifyStoredAccessKey } = await import("./accessKey");answerWithIt();localStorage.setItem("accessKeyHash", storedValue);const result = await verifyStoredAccessKey(TIMEOUT_HOURS);expect(result).toBe(false);expect(localStorage.getItem("accessKeyHash")).toBe(storedValue);});it("accepts the same hash on the next load once the server answers", async () => {const { verifyStoredAccessKey } = await import("./accessKey");localStorage.setItem("accessKeyHash", storedValue);mockFetch.mockRejectedValue(new TypeError("Failed to fetch"));await verifyStoredAccessKey(TIMEOUT_HOURS);mockFetch.mockResolvedValue({ok: true,json: vi.fn().mockResolvedValue({ valid: true }),});await expect(verifyStoredAccessKey(TIMEOUT_HOURS)).resolves.toBe(true);});});});});
94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513694 unmodified linesconst storedData = localStorage.getItem(ACCESS_KEY_STORAGE_KEY);if (!storedData) return false;try {const { hash, timestamp }: StoredAccessKey = JSON.parse(storedData);const expirationTime = timeoutHours * 60 * 60 * 1000;if (Date.now() - timestamp > expirationTime) {localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);addLogEntry("Stored access key expired");return false;}const response = await fetch("/api/validate-access-key", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ accessKeyHash: hash }),});// A 429 must not be read as "wrong key": the stored hash may be fine and// the caller simply hit the rate limiter. Keep the hash on disk so a// later load can still validate it.if (response.status === 429) {addLogEntry("Stored access key validation rate-limited");return false;}const data = await response.json();if (!data.valid) {localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);addLogEntry("Stored access key is no longer valid");return false;}addLogEntry("Using stored access key");return true;} catch (error) {addLogEntry(`Error verifying stored access key: ${error}`);localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);return false;}}94 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115294 unmodified linesconst storedData = localStorage.getItem(ACCESS_KEY_STORAGE_KEY);if (!storedData) return false;let hash: string;let timestamp: number;try {({ hash, timestamp } = JSON.parse(storedData) as StoredAccessKey);} catch (error) {addLogEntry(`Error reading stored access key: ${error}`);localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);return false;}const expirationTime = timeoutHours * 60 * 60 * 1000;if (Date.now() - timestamp > expirationTime) {localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);addLogEntry("Stored access key expired");return false;}// Only the server saying the key is invalid may delete the hash. Anything// else leaves the server's verdict unknown: an unreachable server, a rate// limit, a proxy's error page. The user would have to retype a key that is// still good, while keeping the hash costs nothing, because access still// needs a fresh `valid: true` on every load.try {const response = await fetch("/api/validate-access-key", {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ accessKeyHash: hash }),});if (!response.ok) {addLogEntry(`Stored access key could not be verified (status ${response.status})`,);return false;}const data = await response.json();if (data.valid === true) {addLogEntry("Using stored access key");return true;}if (data.valid === false) {localStorage.removeItem(ACCESS_KEY_STORAGE_KEY);addLogEntry("Stored access key is no longer valid");return false;}addLogEntry("Stored access key could not be verified (unexpected reply)");return false;} catch (error) {addLogEntry(`Error verifying stored access key: ${error}`);return false;}}
12 unmodified lines13141516171812 unmodified linesinternalApiName: "Custom LLM",defaultInferenceType: "internal",searchToken: "a".repeat(64),};/** Imports a fresh copy of the module so its cache starts empty. */12 unmodified lines1314151617181912 unmodified linesinternalApiName: "Custom LLM",defaultInferenceType: "internal",searchToken: "a".repeat(64),parentWindowOrigins: ["https://huggingface.co"],};/** Imports a fresh copy of the module so its cache starts empty. */
22 unmodified lines232425262728294 unmodified lines34353637383922 unmodified lines** `searchToken` has no harmless stand-in, so it is empty here. Anything that* needs it goes through `getConfig`, which rejects rather than handing back a* token the server would turn away.*/export const FALLBACK_CONFIG: ServerConfig = {accessKeysEnabled: false,4 unmodified linesinternalApiName: DEFAULT_INTERNAL_API_NAME,defaultInferenceType: DEFAULT_INFERENCE_TYPE,searchToken: "",};const FETCH_TIMEOUT_MS = 5000;22 unmodified lines2324252627282930314 unmodified lines3637383940414222 unmodified lines** `searchToken` has no harmless stand-in, so it is empty here. Anything that* needs it goes through `getConfig`, which rejects rather than handing back a* token the server would turn away. `parentWindowOrigins` is empty for the* same reason: without the server's list, no embedding page is trusted with* the query.*/export const FALLBACK_CONFIG: ServerConfig = {accessKeysEnabled: false,4 unmodified linesinternalApiName: DEFAULT_INTERNAL_API_NAME,defaultInferenceType: DEFAULT_INFERENCE_TYPE,searchToken: "",parentWindowOrigins: [],};const FETCH_TIMEOUT_MS = 5000;
2 unmodified lines3456789101112131 unmodified line151617181920216 unmodified lines282930313233344 unmodified lines394041424344456 unmodified lines525354555657584 unmodified lines636465666768694 unmodified lines74757677787980818283843 unmodified lines8889902 unmodified linesvi.mock("./textGeneration", () => ({generateChatResponse: vi.fn(),}));import { generateChatResponse } from "./textGeneration";const mockedGenerateChatResponse = vi.mocked(generateChatResponse);beforeEach(() => {vi.clearAllMocks();1 unmodified linedescribe("generateFollowUpQuestion", () => {it("keeps an English question with leading numbering", async () => {mockedGenerateChatResponse.mockResolvedValue("1. What about the alternatives?",);6 unmodified lines});it("keeps a Chinese question ending in a fullwidth question mark", async () => {mockedGenerateChatResponse.mockResolvedValue("你觉得这个方案怎么样?");const question = await generateFollowUpQuestion({topic: "方案",4 unmodified lines});it("strips a leading bullet from a Japanese question without touching the text", async () => {mockedGenerateChatResponse.mockResolvedValue("- この案についてどう思いますか?",);6 unmodified lines});it("keeps an Arabic question ending in an Arabic question mark", async () => {mockedGenerateChatResponse.mockResolvedValue("ما رأيك في البدائل؟");const question = await generateFollowUpQuestion({topic: "البدائل",4 unmodified lines});it("returns an empty string when no line ends with a question mark", async () => {mockedGenerateChatResponse.mockResolvedValue("No questions here.");const question = await generateFollowUpQuestion({topic: "cats",4 unmodified lines});});describe("generateFollowUpQuestion and the chat history", () => {it("writes no chat rows for the follow-up exchange, since nothing reads them", async () => {const { historyDatabase } = await import("./history");const before = await historyDatabase.chatHistory.count();mockedGenerateChatResponse.mockResolvedValue("1. What comes next?");await generateFollowUpQuestion({topic: "cats",3 unmodified linesexpect(await historyDatabase.chatHistory.count()).toBe(before);});});2 unmodified lines345678910111213141516171 unmodified line192021222324256 unmodified lines323334353637384 unmodified lines434445464748496 unmodified lines565758596061624 unmodified lines676869707172734 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241253 unmodified lines1291301311321331341351361371381391401411421431441451461471482 unmodified linesvi.mock("./textGeneration", () => ({generateChatResponse: vi.fn(),generateReplyToMessages: vi.fn(),}));import {generateChatResponse,generateReplyToMessages,} from "./textGeneration";const mockedGenerateReplyToMessages = vi.mocked(generateReplyToMessages);beforeEach(() => {vi.clearAllMocks();1 unmodified linedescribe("generateFollowUpQuestion", () => {it("keeps an English question with leading numbering", async () => {mockedGenerateReplyToMessages.mockResolvedValue("1. What about the alternatives?",);6 unmodified lines});it("keeps a Chinese question ending in a fullwidth question mark", async () => {mockedGenerateReplyToMessages.mockResolvedValue("你觉得这个方案怎么样?");const question = await generateFollowUpQuestion({topic: "方案",4 unmodified lines});it("strips a leading bullet from a Japanese question without touching the text", async () => {mockedGenerateReplyToMessages.mockResolvedValue("- この案についてどう思いますか?",);6 unmodified lines});it("keeps an Arabic question ending in an Arabic question mark", async () => {mockedGenerateReplyToMessages.mockResolvedValue("ما رأيك في البدائل؟");const question = await generateFollowUpQuestion({topic: "البدائل",4 unmodified lines});it("returns an empty string when no line ends with a question mark", async () => {mockedGenerateReplyToMessages.mockResolvedValue("No questions here.");const question = await generateFollowUpQuestion({topic: "cats",4 unmodified lines});});describe("generateFollowUpQuestion and the chat generation", () => {it("sends the prompt alone, with the topic and the answer in it", async () => {mockedGenerateReplyToMessages.mockResolvedValue("What comes next?");await generateFollowUpQuestion({topic: "cats",currentContent: "Cats sleep up to sixteen hours a day.",previousQuestions: ["Why do cats purr?"],});// The chat path puts the system prompt and the search results in front,// and keys the conversation summary by the first message.expect(generateChatResponse).not.toHaveBeenCalled();const [messages] = mockedGenerateReplyToMessages.mock.calls[0];expect(messages).toHaveLength(1);expect(messages[0].role).toBe("user");expect(messages[0].content).toContain("cats");expect(messages[0].content).toContain("Cats sleep up to sixteen hours a day.",);expect(messages[0].content).toContain("1. Why do cats purr?");});it("returns an empty string when the prompt is too long to send", async () => {mockedGenerateReplyToMessages.mockRejectedValue(new Error("The newest message is too long"),);const question = await generateFollowUpQuestion({topic: "cats",currentContent: "Cats are independent. ".repeat(5000),});expect(question).toBe("");});});describe("generateFollowUpQuestion and the chat history", () => {it("writes no chat rows for the follow-up exchange, since nothing reads them", async () => {const { historyDatabase } = await import("./history");const before = await historyDatabase.chatHistory.count();mockedGenerateReplyToMessages.mockResolvedValue("1. What comes next?");await generateFollowUpQuestion({topic: "cats",3 unmodified linesexpect(await historyDatabase.chatHistory.count()).toBe(before);});});describe("generateFollowUpQuestion and reasoning", () => {it("leaves the reasoning block out of the prompt", async () => {mockedGenerateReplyToMessages.mockResolvedValue("1. What comes next?");await generateFollowUpQuestion({topic: "cats",currentContent:"<think>The user wants cat facts.</think>\n\nCats are independent.",});const [messages] = mockedGenerateReplyToMessages.mock.calls[0];const prompt = messages.map((message) => message.content).join("\n");expect(prompt).toContain("Cats are independent.");expect(prompt).not.toContain("The user wants cat facts.");});});
1234524 unmodified lines3031323334353621 unmodified lines58596061626364import { addLogEntry } from "./logEntries";import { generateChatResponse } from "./textGeneration";import type { ChatMessage } from "./types";interface FollowUpQuestionParams {24 unmodified linesThe response was:~~~${currentContent}~~~Follow these instructions:21 unmodified lines},];const response = await generateChatResponse(promptMessages, () => {});const lines = response.trim()12345624 unmodified lines3132333435363721 unmodified lines59606162636465666768import { addLogEntry } from "./logEntries";import { generateReplyToMessages } from "./textGeneration";import { answerOnly } from "./textGenerationUtilities";import type { ChatMessage } from "./types";interface FollowUpQuestionParams {24 unmodified linesThe response was:~~~${answerOnly(currentContent)}~~~Follow these instructions:21 unmodified lines},];// The prompt carries the topic and the answer itself, so it goes out// alone: no system prompt or search results in front of it, and no// reading or writing of the chat's conversation summary.const response = await generateReplyToMessages(promptMessages);const lines = response.trim()
277 unmodified lines278279280281282283621 unmodified lines905906907908277 unmodified lines});});describe("addSearchToHistory + getRecentSearches round-trip", () => {it("should preserve query, source, and searchRunId through a write/read cycle", async () => {const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =621 unmodified linesexpect(chats.map((row) => row.content)).toEqual(["kept"]);expect(await historyDatabase.searches.count()).toBe(1);});});277 unmodified lines278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313621 unmodified lines935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979277 unmodified lines});});describe("getPinnedSearches", () => {it("returns only pinned entries, newest first, however old", async () => {const { addSearchToHistory, getPinnedSearches, historyDatabase } =await import("./history");const results = {type: "text" as const,items: [{ title: "T", url: "https://t.com", snippet: "S" }],};vi.setSystemTime(new Date(2000, 0, 1));const oldest = await addSearchToHistory("pinned long ago", results);vi.setSystemTime(new Date(2000, 0, 2));await addSearchToHistory("never pinned", results);vi.setSystemTime(new Date(2000, 0, 3));const newest = await addSearchToHistory("pinned lately", results);for (const id of [oldest, newest]) {await historyDatabase.searches.update(id as number, {pinned: true,pinnedAt: Date.now(),});}const pinned = await getPinnedSearches();expect(pinned.map((search) => search.query)).toEqual(["pinned lately","pinned long ago",]);});});describe("addSearchToHistory + getRecentSearches round-trip", () => {it("should preserve query, source, and searchRunId through a write/read cycle", async () => {const { addSearchToHistory, getRecentSearches, getCurrentSearchRunId } =621 unmodified linesexpect(chats.map((row) => row.content)).toEqual(["kept"]);expect(await historyDatabase.searches.count()).toBe(1);});it("indexes the searches pinned before a version 2 database is upgraded", async () => {const { getPinnedSearches, historyDatabase } = await import("./history");historyDatabase.close({ disableAutoOpen: false });await Dexie.delete("History");const v2Schema = {searches: "++id, searchRunId, query, timestamp, source, pinned, results",llmResponses: "++id, searchId, searchRunId, timestamp, model",chatHistory:"++id, conversationId, timestamp, [conversationId+timestamp]",};const v2 = new Dexie("History");v2.version(1).stores(v2Schema);v2.version(2).stores(v2Schema);await v2.table("searches").bulkAdd([{ query: "pinned long ago", timestamp: 1_000, pinned: true },{ query: "never pinned", timestamp: 2_000, pinned: false },{ query: "pinned lately", timestamp: 3_000, pinned: true },]);v2.close();await historyDatabase.open();const pinned = await getPinnedSearches();expect(pinned.map((search) => [search.query, search.pinnedAt])).toEqual([["pinned lately", 3_000],["pinned long ago", 1_000],]);const unpinned = await historyDatabase.searches.where("query").equals("never pinned").first();expect(unpinned && "pinnedAt" in unpinned).toBe(false);// The boolean index never held an entry, so version 3 drops it.const indexNames = historyDatabase.searches.schema.indexes.map((index) => index.name,);expect(indexNames).toContain("pinnedAt");expect(indexNames).not.toContain("pinned");});});
92 unmodified lines93949596979848 unmodified lines1471481491501511521531541551561571584 unmodified lines163164165166167168193 unmodified lines36236336436536636792 unmodified linescontent: string;}>;pinned?: boolean;source?: string;}48 unmodified lines.delete();}const historySchema = {searches: "++id, searchRunId, query, timestamp, source, pinned, results",llmResponses: "++id, searchId, searchRunId, timestamp, model",chatHistory: "++id, conversationId, timestamp, [conversationId+timestamp]",};class HistoryDatabase extends Dexie {searches!: Table<SearchEntry>;llmResponses!: Table<LLMResponse>;4 unmodified linesthis.version(1).stores(historySchema);this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns);}/**193 unmodified lines});}export async function saveLlmResponseForQuery(query: string,response: string,92 unmodified lines9394959697989910010110210310448 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871884 unmodified lines193194195196197198199193 unmodified lines39339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246392 unmodified linescontent: string;}>;pinned?: boolean;/*** When the entry was pinned; absent while unpinned. It is indexed in place of* `pinned`, because IndexedDB does not index boolean values, so only pinned* entries are in this index. `togglePin` writes both fields in one update.*/pinnedAt?: number;source?: string;}48 unmodified lines.delete();}/*** Entries pinned before `pinnedAt` existed get one, so the index finds them.* Their real pin time is unknown; the entry's own `timestamp` stands in, which* keeps a plausible pin order.*/async function indexPinnedEntries(tx: Transaction): Promise<void> {await tx.table<SearchEntry>("searches").filter((search) => search.pinned === true).modify((search) => {search.pinnedAt = search.timestamp;});}const historySchema = {searches: "++id, searchRunId, query, timestamp, source, pinned, results",llmResponses: "++id, searchId, searchRunId, timestamp, model",chatHistory: "++id, conversationId, timestamp, [conversationId+timestamp]",};/*** Version 3 drops the `pinned` index, which never held an entry (IndexedDB* does not index booleans), and indexes `pinnedAt` instead. The `pinned`* field itself stays.*/const historySchemaV3 = {...historySchema,searches: "++id, searchRunId, query, timestamp, source, pinnedAt, results",};class HistoryDatabase extends Dexie {searches!: Table<SearchEntry>;llmResponses!: Table<LLMResponse>;4 unmodified linesthis.version(1).stores(historySchema);this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns);this.version(3).stores(historySchemaV3).upgrade(indexPinnedEntries);}/**193 unmodified lines});}/** What the analytics need of a saved search: when it happened and where it came from. */export interface SearchActivityRecord {timestamp: number;source?: string;}/*** Every saved search as a timestamp and a source, read from the two indexes* alone, so the result payloads (which dominate a row's size) are never* loaded. The analytics have to see the whole table, and a table can hold* 10,000 rows. A search saved without a source has no entry in the `source`* index, so it comes back without one.*/export async function getSearchActivityRecords(): Promise<SearchActivityRecord[]> {return measurePerformance("Get search activity", () =>historyDatabase.transaction("r", historyDatabase.searches, async () => {const byTime = historyDatabase.searches.orderBy("timestamp");const [timestamps, ids, distinctSources] = await Promise.all([byTime.keys(),byTime.primaryKeys(),historyDatabase.searches.orderBy("source").uniqueKeys(),]);// A handful of sources exist ("user", "followup", "suggestion"), so one// index lookup per source is far cheaper than walking the whole index.const sourceById = new Map<unknown, string>();await Promise.all(distinctSources.map(async (source) => {const sourceIds = await historyDatabase.searches.where("source").equals(source).primaryKeys();for (const id of sourceIds) sourceById.set(id, String(source));}),);return ids.map((id, index) => ({timestamp: Number(timestamps[index]),source: sourceById.get(id),}));}),).catch((error) => {addLogEntry(`Error fetching search activity: ${error}`);return [];});}/*** Every pinned search, newest first, however old. Cleanup never deletes a* pinned entry, so a window of recent searches would sooner or later leave* some out. Only pinned entries have a `pinnedAt`, so its index reads them* alone, without scanning the table.*/export async function getPinnedSearches(): Promise<SearchEntry[]> {return measurePerformance("Get pinned searches", async () => {const pinned = await historyDatabase.searches.orderBy("pinnedAt").toArray();return pinned.sort((a, b) => b.timestamp - a.timestamp);}).catch((error) => {addLogEntry(`Error fetching pinned searches: ${error}`);return [];});}export async function saveLlmResponseForQuery(query: string,response: string,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { getConfig } from "./config";import { postMessageToParentWindow } from "./parentWindow";
vi.mock("./config", () => ({ getConfig: vi.fn(),}));
vi.mock("./logEntries", () => ({ addLogEntry: vi.fn(),}));
const message = { queryString: "q=test", hash: "" };
/** * A parent page whose first child frame is cross-origin, so reading that * frame's `location` throws, as it does in a browser. */function stubParentWindow() { const crossOriginFrame = { get location(): Location { throw new DOMException("Blocked a frame", "SecurityError"); }, }; const parentWindow = { 0: crossOriginFrame, postMessage: vi.fn() }; vi.stubGlobal("parent", parentWindow); return parentWindow;}
function serveOrigins(parentWindowOrigins: string[]) { vi.mocked(getConfig).mockResolvedValue({ parentWindowOrigins } as Awaited< ReturnType<typeof getConfig> >);}
/** Lets the post that waits on the config run. */const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
describe("postMessageToParentWindow", () => { beforeEach(() => { vi.clearAllMocks(); });
afterEach(() => { vi.unstubAllGlobals(); });
it("posts once to each allowed origin, whatever frame comes first in the parent", async () => { const parentWindow = stubParentWindow(); serveOrigins(["https://huggingface.co"]);
expect(() => postMessageToParentWindow(message)).not.toThrow(); await flush();
expect(parentWindow.postMessage).toHaveBeenCalledTimes(1); expect(parentWindow.postMessage).toHaveBeenCalledWith( message, "https://huggingface.co", ); });
it("posts nothing when no origin is allowed", async () => { const parentWindow = stubParentWindow(); serveOrigins([]);
postMessageToParentWindow(message); await flush();
expect(parentWindow.postMessage).not.toHaveBeenCalled(); });
it("posts nothing when the page is not embedded", async () => { const postMessage = vi.spyOn(window, "postMessage"); serveOrigins(["https://huggingface.co"]);
postMessageToParentWindow(message); await flush();
expect(getConfig).not.toHaveBeenCalled(); expect(postMessage).not.toHaveBeenCalled(); postMessage.mockRestore(); });
it("posts nothing, and does not throw, when the config cannot be fetched", async () => { const parentWindow = stubParentWindow(); vi.mocked(getConfig).mockRejectedValue(new Error("offline"));
expect(() => postMessageToParentWindow(message)).not.toThrow(); await flush();
expect(parentWindow.postMessage).not.toHaveBeenCalled(); });
it("still posts to the other origins when one of them is not a valid target", async () => { const parentWindow = stubParentWindow(); parentWindow.postMessage.mockImplementationOnce(() => { throw new DOMException("Invalid target origin", "SyntaxError"); }); serveOrigins(["huggingface.co", "https://huggingface.co"]);
postMessageToParentWindow(message); await flush();
expect(parentWindow.postMessage).toHaveBeenCalledTimes(2); expect(parentWindow.postMessage).toHaveBeenLastCalledWith( message, "https://huggingface.co", ); });});123456/** Forwards a message to the embedding parent window, targeting the origin from `ancestorOrigins`. */export function postMessageToParentWindow(message: unknown) {const parentWindow = self.parent;const targetOrigin = parentWindow?.[0]?.location?.ancestorOrigins?.[0];if (targetOrigin) parentWindow.postMessage(message, targetOrigin);}123456789101112131415161718192021222324252627282930import { getConfig } from "./config";import { addLogEntry } from "./logEntries";/*** Forwards a message to the page embedding MiniSearch (a Hugging Face Space,* for example), addressed to each origin in `PARENT_WINDOW_ORIGINS`. The* browser delivers it only when the embedding page is on that origin, so no* other frame's state is read to find out where the page is embedded.** Never throws: callers post right before navigating and searching.*/export function postMessageToParentWindow(message: unknown) {const parentWindow = self.parent;if (parentWindow === self) return;getConfig().then(({ parentWindowOrigins }) => {for (const origin of parentWindowOrigins) {try {parentWindow.postMessage(message, origin);} catch (error) {addLogEntry(`Failed to post the query to ${origin}: ${error}`);}}},() => {// Without the server's list, no embedding page is trusted with the query.},);}
167 unmodified lines168169170167 unmodified linesexpect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength);});});167 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252167 unmodified linesexpect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength);});});describe("settings hydration merges the stored profile into the defaults", () => {it("fills keys a stored profile predates, before anything renders", async () => {localStorage.setItem("settings",JSON.stringify({ enableAiResponse: true }),);const { getSettings } = await import("./pubSub");expect(getSettings().enableAiResponse).toBe(true);expect(getSettings().enablePageContentFetch).toBe(true);});it("hydrates a wrong-type key to its default and keeps a deliberate false", async () => {localStorage.setItem("settings",JSON.stringify({searchResultsLimit: "15",enablePageContentFetch: false,customKeyFromAnOlderBuild: "keep me",}),);const { getSettings } = await import("./pubSub");const settings = getSettings() as unknown as Record<string, unknown>;expect(settings.searchResultsLimit).toBe(15);expect(settings.enablePageContentFetch).toBe(false);expect(settings.customKeyFromAnOlderBuild).toBe("keep me");});it("leaves an array store exactly as stored", async () => {const stored = JSON.stringify(["ai", "history"]);localStorage.setItem("menuExpandedAccordions", stored);const { menuExpandedAccordionsPubSub } = await import("./pubSub");const [, , getMenuExpandedAccordions] = menuExpandedAccordionsPubSub;expect(getMenuExpandedAccordions()).toEqual(["ai", "history"]);expect(localStorage.getItem("menuExpandedAccordions")).toBe(stored);});it("does not write the hydrated value back to storage", async () => {const stored = JSON.stringify({ enableAiResponse: true });localStorage.setItem("settings", stored);await import("./pubSub");expect(localStorage.getItem("settings")).toBe(stored);});it("reports a usable stored object as stored user settings", async () => {localStorage.setItem("settings",JSON.stringify({ enableAiResponse: true }),);const { hasStoredUserSettings } = await import("./pubSub");expect(hasStoredUserSettings).toBe(true);});it.each(["{not json", "[]", '"x"'])("treats an unusable stored value (%s) as no stored settings, so the server defaults apply",async (stored) => {localStorage.setItem("settings", stored);const { hasStoredUserSettings } = await import("./pubSub");expect(hasStoredUserSettings).toBe(false);const { applyServerConfig, defaultSettings } = await import("./settings");const config = {accessKeysEnabled: false,accessKeyTimeoutHours: 0,wllamaDefaultModelId: "custom-model",wllamaDefaultGpuModelId: "gemma-3-4b",internalApiEnabled: false,internalApiName: "Internal API",defaultInferenceType: "openai",searchToken: "a".repeat(64),parentWindowOrigins: ["https://huggingface.co"],};const applied = applyServerConfig(defaultSettings,config,hasStoredUserSettings,false,);expect(applied.inferenceType).toBe("openai");expect(applied.wllamaModelId).toBe("custom-model");},);});
30 unmodified lines313233343536373839405 unmodified lines464748495051522 unmodified lines55565758596067 unmodified lines12812913013113213313413513613713813930 unmodified linesreturn typeof value === typeof reference;}function createLocalStoragePubSub<T>(localStorageKey: string,defaultValue: T,normalize?: (value: T) => T,) {const localStorageValue = safeStorage.getItem(localStorageKey);let initialValue: T = defaultValue;5 unmodified linesparsed = undefined;}if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) {initialValue = normalize ? normalize(parsed as T) : (parsed as T);} else {// Runs at module load, so an unparseable or wrong-type stored value must// not crash the app. Remove it (so the fallback doesn't repeat on every2 unmodified linesaddLogEntry(`Discarded an unusable stored value for '${localStorageKey}'`,);}}const localStoragePubSub = createPubSub(initialValue);67 unmodified linesexport const [updateModelLoadingProgress] = modelLoadingProgressPubSub;export const settingsPubSub = createLocalStoragePubSub(SETTINGS_STORAGE_KEY,defaultSettings,coerceNumericSettings,);export const [updateSettings, listenToSettingsChanges, getSettings] =settingsPubSub;30 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667686970715 unmodified lines7778798081828384852 unmodified lines8889909192939467 unmodified lines16216316416516616716816917017117217317417517617717817918018118218318418518618730 unmodified linesreturn typeof value === typeof reference;}/*** Fill a stored settings object with the defaults for the keys it does not* have, so the first value a reader sees is complete even when the stored* profile predates a newly added key. A stored key whose value has a* different JSON kind than the default falls back to the default alone; keys* the defaults do not know are kept.*/function hydrateWithDefaults<T>(defaultValue: T, parsed: unknown): T {if (typeof defaultValue !== "object" ||defaultValue === null ||Array.isArray(defaultValue) ||typeof parsed !== "object" ||parsed === null ||Array.isArray(parsed)) {return parsed as T;}const defaults = defaultValue as Record<string, unknown>;const accepted: Record<string, unknown> = {};for (const [key, value] of Object.entries(parsed as Record<string, unknown>,)) {if (!(key in defaults) || isSameJsonKind(value, defaults[key])) {accepted[key] = value;}}return { ...defaults, ...accepted } as T;}function createLocalStoragePubSub<T>(localStorageKey: string,defaultValue: T,normalize?: (value: T) => T,reportUsableStoredValue?: (usable: boolean) => void,) {const localStorageValue = safeStorage.getItem(localStorageKey);let initialValue: T = defaultValue;5 unmodified linesparsed = undefined;}if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) {const hydrated = hydrateWithDefaults(defaultValue, parsed);initialValue = normalize ? normalize(hydrated) : hydrated;reportUsableStoredValue?.(true);} else {// Runs at module load, so an unparseable or wrong-type stored value must// not crash the app. Remove it (so the fallback doesn't repeat on every2 unmodified linesaddLogEntry(`Discarded an unusable stored value for '${localStorageKey}'`,);reportUsableStoredValue?.(false);}}const localStoragePubSub = createPubSub(initialValue);67 unmodified linesexport const [updateModelLoadingProgress] = modelLoadingProgressPubSub;let storedSettingsUsable = false;export const settingsPubSub = createLocalStoragePubSub(SETTINGS_STORAGE_KEY,defaultSettings,coerceNumericSettings,(usable) => {storedSettingsUsable = usable;},);/*** Whether this browser already had a usable settings object from an earlier* visit, decided while `settingsPubSub` hydrated. `applyServerConfig()` uses* it to tell an untouched profile from a user who deliberately picked a value* that happens to equal a default. A stored value that was discarded as* unusable counts as no stored settings, which is what the merge assumes.*/export const hasStoredUserSettings = storedSettingsUsable;export const [updateSettings, listenToSettingsChanges, getSettings] =settingsPubSub;
52 unmodified lines53545556575852 unmodified linesexpect(getQuerySuggestions()).toEqual([]);});it("logs how many suggestions the refill actually stored", async () => {mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));52 unmodified lines53545556575859606162636465666768697071727374757677787980818283848586878889909192939452 unmodified linesexpect(getQuerySuggestions()).toEqual([]);});it("stores at most 25 of the fetched suggestions, each once", async () => {const fetched = Array.from({ length: 40 }, (_, index) => `s${index}`);mockFetch.mockResolvedValueOnce(jsonResponse(fetched));await getRandomQuerySuggestion();const stored = getQuerySuggestions();expect(stored).toHaveLength(24);expect(new Set(stored).size).toBe(24);expect(stored.every((entry) => fetched.includes(entry))).toBe(true);});it("shares one fetch between callers that find the store empty together", async () => {mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));const [first, second] = await Promise.all([getRandomQuerySuggestion(),getRandomQuerySuggestion(),]);expect(mockFetch).toHaveBeenCalledTimes(1);expect(first).not.toBe(second);expect(getQuerySuggestions()).toHaveLength(1);});it("fetches again once a finished refill has been used up", async () => {mockFetch.mockResolvedValueOnce(jsonResponse(["a"])).mockResolvedValueOnce(jsonResponse(["b"]));await expect(getRandomQuerySuggestion()).resolves.toBe("a");await expect(getRandomQuerySuggestion()).resolves.toBe("b");expect(mockFetch).toHaveBeenCalledTimes(2);});it("logs how many suggestions the refill actually stored", async () => {mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"]));
1239 unmodified lines131415161718192021222324251 unmodified line2728293031323312 unmodified lines464748495051525354555657585960616263646566import { addLogEntry } from "./logEntries";import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub";9 unmodified lines);}/** Pops a stored suggestion, refilling the store when it is empty; never resolves to an empty string. */export async function getRandomQuerySuggestion(): Promise<string> {let querySuggestions = toNonEmptyStrings(getQuerySuggestions());if (querySuggestions.length === 0)querySuggestions = await refillQuerySuggestions(25);const randomQuerySuggestion = querySuggestions.pop();updateQuerySuggestions(querySuggestions);1 unmodified linereturn randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION;}async function refillQuerySuggestions(limit: number): Promise<string[]> {const querySuggestionsFileUrl = new URL("/query-suggestions.json",self.location.origin,12 unmodified linesthrow new Error("the response is not a list");}const querySuggestionsList = toNonEmptyStrings(body).sort(() => Math.random() - 0.5).slice(0, limit);addLogEntry(`Query suggestions refilled with ${querySuggestionsList.length} suggestions`,);return querySuggestionsList;} catch (error) {addLogEntry(`Failed to refill query suggestions: ${error instanceof Error ? error.message : String(error)}`,);return [];}}12349 unmodified lines1415161718192021222324252627282930313233341 unmodified line3637383940414212 unmodified lines555657585960616263646566676869707172737475import { shuffle } from "@shared/shuffle";import { addLogEntry } from "./logEntries";import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub";9 unmodified lines);}/** The refill under way, so callers that find the store empty together share one fetch. */let refillInFlight: Promise<void> | undefined;/** Pops a stored suggestion, refilling the store when it is empty; never resolves to an empty string. */export async function getRandomQuerySuggestion(): Promise<string> {if (toNonEmptyStrings(getQuerySuggestions()).length === 0) {refillInFlight ??= refillQuerySuggestions(25).finally(() => {refillInFlight = undefined;});await refillInFlight;}// Read after the wait, not before: callers that waited on the same refill// each take their own suggestion from what it stored.const querySuggestions = toNonEmptyStrings(getQuerySuggestions());const randomQuerySuggestion = querySuggestions.pop();updateQuerySuggestions(querySuggestions);1 unmodified linereturn randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION;}async function refillQuerySuggestions(limit: number): Promise<void> {const querySuggestionsFileUrl = new URL("/query-suggestions.json",self.location.origin,12 unmodified linesthrow new Error("the response is not a list");}const querySuggestionsList = shuffle(toNonEmptyStrings(body)).slice(0,limit,);updateQuerySuggestions(querySuggestionsList);addLogEntry(`Query suggestions refilled with ${querySuggestionsList.length} suggestions`,);} catch (error) {addLogEntry(`Failed to refill query suggestions: ${error instanceof Error ? error.message : String(error)}`,);}}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081import { describe, expect, it } from "vitest";import { splitReasoning } from "./reasoning";
describe("splitReasoning", () => { it("splits a terminated reasoning block from the answer", () => { expect( splitReasoning( "<think>Let me think about this</think>\nHere is the answer.", "<think>", "</think>", ), ).toEqual({ reasoning: "Let me think about this", answer: "\nHere is the answer.", isOpen: false, }); });
it("treats an unterminated block as reasoning running to the end", () => { expect( splitReasoning("<think>still thinking", "<think>", "</think>"), ).toEqual({ reasoning: "still thinking", answer: "", isOpen: true, }); });
it("leaves a marker mentioned mid-answer intact", () => { const text = "Models wrap reasoning in <think> tags like this."; expect(splitReasoning(text, "<think>", "</think>")).toEqual({ reasoning: "", answer: text, isOpen: false, }); });
it("returns the text as answer when no start marker opens the response", () => { const text = "This is a normal response."; expect(splitReasoning(text, "<think>", "</think>")).toEqual({ reasoning: "", answer: text, isOpen: false, }); });
it.each([ ["empty text", ""], ["whitespace-only text", " "], ])("reports nothing for %s", (_, text) => { expect(splitReasoning(text, "<think>", "</think>")).toEqual({ reasoning: "", answer: text, isOpen: false, }); });
it("trims before checking the start marker, like the UI does", () => { expect( splitReasoning(" <think>quiet</think>loud", "<think>", "</think>"), ).toEqual({ reasoning: "quiet", answer: "loud", isOpen: false, }); });
it("supports custom marker pairs", () => { expect( splitReasoning( "[REASONING]hmm[/REASONING]yes", "[REASONING]", "[/REASONING]", ), ).toEqual({ reasoning: "hmm", answer: "yes", isOpen: false, }); });});1234567891011121314151617181920212223242526272829303132333435363738394041/** * Splits a response that may carry a reasoning block into the reasoning and * the answer. Text counts as reasoning only when it starts with the start * marker after trimming, and the end marker is searched after the start * marker; without an end marker the reasoning runs to the end of the text and * `isOpen` reports the unterminated block. This is the single parser shared by * the UI hook and plain modules like text-to-speech, which cannot import a * React hook. */export function splitReasoning( text: string, startMarker: string, endMarker: string,): { reasoning: string; answer: string; isOpen: boolean } { if (!text) return { reasoning: "", answer: "", isOpen: false };
const trimmedText = text.trim();
if (!trimmedText.startsWith(startMarker)) return { reasoning: "", answer: text, isOpen: false };
const startIndex = trimmedText.indexOf(startMarker); const endIndex = trimmedText.indexOf( endMarker, startIndex + startMarker.length, );
if (endIndex === -1) { return { reasoning: trimmedText.slice(startIndex + startMarker.length), answer: "", isOpen: true, }; }
return { reasoning: trimmedText.slice(startIndex + startMarker.length, endIndex), answer: trimmedText.slice(endIndex + endMarker.length), isOpen: false, };}20 unmodified lines21222324252620 unmodified linesinternalApiName: "Internal API",defaultInferenceType: "browser",searchToken: "a".repeat(64),};describe("Settings Module", () => {20 unmodified lines2122232425262720 unmodified linesinternalApiName: "Internal API",defaultInferenceType: "browser",searchToken: "a".repeat(64),parentWindowOrigins: ["https://huggingface.co"],};describe("Settings Module", () => {
13 unmodified lines14151617181920212223242526272813 unmodified linesexport const SETTINGS_STORAGE_KEY = "settings";/*** Whether this browser already had settings from an earlier visit. Read at* module load, before anything writes the key back, so `applyServerConfig()`* can tell an untouched profile from a user who deliberately picked a value* that happens to equal a default.*/export const hasStoredUserSettings =safeStorage.getItem(SETTINGS_STORAGE_KEY) !== null;/*** Whether this profile picked an OS voice before the local engine existed.* Such a value is a bare `speechSynthesis` voice URI rather than a prefixed13 unmodified lines14151617181913 unmodified linesexport const SETTINGS_STORAGE_KEY = "settings";/*** Whether this profile picked an OS voice before the local engine existed.* Such a value is a bare `speechSynthesis` voice URI rather than a prefixed
3 unmodified lines45678952 unmodified lines62636465666768184 unmodified lines2532542553 unmodified linessettings: { inferenceType: "browser" } as {inferenceType: string;openAiContextLength?: number;},systemPrompt: "",}));52 unmodified lines}));import { getConversationSummary, updateConversationSummary } from "./pubSub";import { generateChatResponse } from "./textGeneration";import { generateChatWithOpenAi } from "./textGenerationWithOpenAi";import { generateChatWithWllama } from "./textGenerationWithWllama";import type { ChatMessage } from "./types";184 unmodified linesexpect(answer[0][0].content).toContain("S1");});});3 unmodified lines456789101152 unmodified lines64656667686970717273184 unmodified lines2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223 unmodified linessettings: { inferenceType: "browser" } as {inferenceType: string;openAiContextLength?: number;reasoningStartMarker?: string;reasoningEndMarker?: string;},systemPrompt: "",}));52 unmodified lines}));import { getConversationSummary, updateConversationSummary } from "./pubSub";import {generateChatResponse,generateReplyToMessages,} from "./textGeneration";import { generateChatWithOpenAi } from "./textGenerationWithOpenAi";import { generateChatWithWllama } from "./textGenerationWithWllama";import type { ChatMessage } from "./types";184 unmodified linesexpect(answer[0][0].content).toContain("S1");});});describe("reasoning in earlier assistant turns", () => {const reasoning = "Let me think about the first question at length.";const turnsWithReasoning: ChatMessage[] = [{ role: "user", content: "first question" },{role: "assistant",content: `<think>${reasoning}</think>\n\nfirst answer`,},];const question: ChatMessage = { role: "user", content: "second question" };beforeEach(() => {vi.clearAllMocks();state.settings = {inferenceType: "browser",reasoningStartMarker: "<think>",reasoningEndMarker: "</think>",};state.systemPrompt = "";mockGenerateChat(generateChatWithWllama);});function sentText(messages: ChatMessage[]) {return messages.map((message) => message.content).join("\n");}it("keeps the reasoning out of the main continuation", async () => {await generateChatResponse([...turnsWithReasoning, question], () => {});const { answer } = callsTo(generateChatWithWllama);expect(sentText(answer[0])).toContain("first answer");expect(sentText(answer[0])).not.toContain(reasoning);});it("keeps the reasoning out of the summary prompt and the stored summary", async () => {state.systemPrompt = "s".repeat(3500);vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => {if (chat[0].content.startsWith(summarizerInstruction)) {throw new Error("summarizer unavailable");}return "the answer";});await generateChatResponse([...turnsWithReasoning, question], () => {});const { summarizer } = callsTo(generateChatWithWllama);expect(sentText(summarizer[0])).toContain("first answer");expect(sentText(summarizer[0])).not.toContain(reasoning);const [stored] = vi.mocked(updateConversationSummary).mock.calls[0];expect(stored.summary).toContain("first answer");expect(stored.summary).not.toContain(reasoning);});it("keeps the reasoning out of replies built from the conversation", async () => {await generateReplyToMessages([...turnsWithReasoning, question]);const [[sent]] = vi.mocked(generateChatWithWllama).mock.calls;expect(sentText(sent)).toContain("first answer");expect(sentText(sent)).not.toContain(reasoning);});});
41 unmodified lines42434445464741 unmodified linesdefaultContextSize: 4096,getFormattedSearchResults: vi.fn(() => ""),searchResultsToConsider: 6,}));vi.mock("gpt-tokenizer", () => ({default: { encode: vi.fn(() => [1, 2, 3]) },41 unmodified lines4243444546474841 unmodified linesdefaultContextSize: 4096,getFormattedSearchResults: vi.fn(() => ""),searchResultsToConsider: 6,withoutReasoning: (messages: unknown) => messages,}));vi.mock("gpt-tokenizer", () => ({default: { encode: vi.fn(() => [1, 2, 3]) },
39 unmodified lines404142434445323 unmodified lines3693703713723733743756 unmodified lines38238338438538638738838939039 unmodified linesgetFormattedSearchResults,imageResultTag,searchResultsToConsider,} from "./textGenerationUtilities";import type {ChatMessage,323 unmodified linesmessages: ChatMessage[],): Promise<string> {const keptMessages = keepNewestMessagesWithinBudget(messages,defaultContextSize * historyBudgetRatio,);6 unmodified lines}export async function generateChatResponse(newMessages: ChatMessage[],onUpdate: (partialResponse: string) => void,) {let response = "";try {39 unmodified lines40414243444546323 unmodified lines3703713723733743753766 unmodified lines38338438538638738838939039139239 unmodified linesgetFormattedSearchResults,imageResultTag,searchResultsToConsider,withoutReasoning,} from "./textGenerationUtilities";import type {ChatMessage,323 unmodified linesmessages: ChatMessage[],): Promise<string> {const keptMessages = keepNewestMessagesWithinBudget(withoutReasoning(messages),defaultContextSize * historyBudgetRatio,);6 unmodified lines}export async function generateChatResponse(messages: ChatMessage[],onUpdate: (partialResponse: string) => void,) {const newMessages = withoutReasoning(messages);let response = "";try {
12 unmodified lines13141516171818 unmodified lines373839404142434445464748461 unmodified lines51051151212 unmodified linessettings: { inferenceType: "openai", openAiContextLength: 4096 } as {inferenceType?: string;openAiContextLength?: number;},}));18 unmodified lines}));import {getDefaultChatCompletionCreateParamsStreaming,getDefaultChatMessages,getEffectiveContextSize,getFormattedSearchResults,minimumOutputTokens,setWorkerFactory,} from "./textGenerationUtilities";import type { ChatMessage } from "./types";461 unmodified linesexpect(factory).not.toHaveBeenCalled();});});12 unmodified lines131415161718192018 unmodified lines3940414243444546474849505152461 unmodified lines51451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255312 unmodified linessettings: { inferenceType: "openai", openAiContextLength: 4096 } as {inferenceType?: string;openAiContextLength?: number;reasoningStartMarker?: string;reasoningEndMarker?: string;},}));18 unmodified lines}));import {answerOnly,getDefaultChatCompletionCreateParamsStreaming,getDefaultChatMessages,getEffectiveContextSize,getFormattedSearchResults,minimumOutputTokens,setWorkerFactory,withoutReasoning,} from "./textGenerationUtilities";import type { ChatMessage } from "./types";461 unmodified linesexpect(factory).not.toHaveBeenCalled();});});describe("answerOnly", () => {beforeEach(() => {state.settings = {inferenceType: "openai",reasoningStartMarker: "<think>",reasoningEndMarker: "</think>",};});it("drops a terminated reasoning block", () => {expect(answerOnly("<think>step by step</think>\n\nThe answer.")).toBe("The answer.",);});it("returns an empty answer for an unterminated block", () => {expect(answerOnly("<think>still thinking")).toBe("");});it("leaves a marker mentioned mid-answer intact", () => {const text = "Models wrap thoughts in <think></think> tags.";expect(answerOnly(text)).toBe(text);});it("strips assistant turns only", () => {const messages: ChatMessage[] = [{ role: "user", content: "<think>quoted by the user</think> hi" },{ role: "assistant", content: "<think>plan</think>\n\nHello!" },];expect(withoutReasoning(messages)).toEqual([messages[0],{ role: "assistant", content: "Hello!" },]);});});
13 unmodified lines141516171819293 unmodified lines31331431513 unmodified linesgetTextSearchStale,updateTextGenerationState,} from "./pubSub";import { getSystemPrompt } from "./systemPrompt";import type { ChatMessage, TextSearchResult } from "./types";293 unmodified lines{ role: "user", content: getQuery() },];}13 unmodified lines14151617181920293 unmodified lines31431531631731831932032132232332432532632732832933033133233333433533633733833913 unmodified linesgetTextSearchStale,updateTextGenerationState,} from "./pubSub";import { splitReasoning } from "./reasoning";import { getSystemPrompt } from "./systemPrompt";import type { ChatMessage, TextSearchResult } from "./types";293 unmodified lines{ role: "user", content: getQuery() },];}/*** The answer part of a stored response, without the reasoning block that* generation wraps in the configured markers. Prompts built from earlier* turns use it so the chain of thought is not sent back to the model.*/export function answerOnly(text: string): string {const { reasoningStartMarker, reasoningEndMarker } = getSettings();const { answer } = splitReasoning(text,reasoningStartMarker,reasoningEndMarker,);return answer === text ? text : answer.trim();}export function withoutReasoning(messages: ChatMessage[]): ChatMessage[] {return messages.map((message) =>message.role === "assistant"? { ...message, content: answerOnly(message.content) }: message,);}
453 unmodified lines454455456457458459460461453 unmodified linesexport async function fetchHordeUserInfo(apiKey: string,): Promise<HordeUserInfo | null> {const response = await fetch(buildHordeUrl("/find_user"), {headers: {[HTTP_HEADERS.API_KEY]: apiKey,[HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,453 unmodified lines454455456457458459460461462463453 unmodified linesexport async function fetchHordeUserInfo(apiKey: string,signal?: AbortSignal,): Promise<HordeUserInfo | null> {const response = await fetch(buildHordeUrl("/find_user"), {signal,headers: {[HTTP_HEADERS.API_KEY]: apiKey,[HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent,
123432 unmodified lines37383940414243104 unmodified lines148149150151152153import { beforeEach, describe, expect, it, vi } from "vitest";import { addLogEntry } from "./logEntries";import {getSettings,32 unmodified lineswllamaDefaultModelId: "test-model",wllamaDefaultGpuModelId: "test-gpu-model",}),FALLBACK_CONFIG: {},}));vi.mock("./systemPrompt", () => ({104 unmodified lines);});it("keeps the last known size when the total is not available yet", async () => {mockDownload([{ loaded: 0, total: 0 }]);1234532 unmodified lines38394041424344454647104 unmodified lines152153154155156157158159160161162163164165166167168169170171172173174175176177178import { beforeEach, describe, expect, it, vi } from "vitest";import { getConfig } from "./config";import { addLogEntry } from "./logEntries";import {getSettings,32 unmodified lineswllamaDefaultModelId: "test-model",wllamaDefaultGpuModelId: "test-gpu-model",}),FALLBACK_CONFIG: {wllamaDefaultModelId: "test-model",wllamaDefaultGpuModelId: "test-gpu-model",},}));vi.mock("./systemPrompt", () => ({104 unmodified lines);});it("uses the default model without saving it when the server config cannot be loaded", async () => {const savedSettings = getSettings();vi.mocked(getSettings).mockReturnValue({...savedSettings,wllamaModelId: "removed-model",});const serverConfig = await getConfig();vi.mocked(getConfig).mockRejectedValue(new Error("Network error"));mockDownload([]);try {await generateTextWithWllama();} finally {vi.mocked(getSettings).mockReturnValue(savedSettings);vi.mocked(getConfig).mockResolvedValue(serverConfig);}expect(vi.mocked(initializeWllama).mock.calls[0]?.[0]).toBe("repo");expect(updateSettings).not.toHaveBeenCalled();});it("keeps the last known size when the total is not available yet", async () => {mockDownload([{ loaded: 0, total: 0 }]);
190 unmodified lines1911921931941951961971987 unmodified lines206207208209210211212190 unmodified linesconst model = wllamaModels[wllamaModelId];if (model) return model;// Safe without the server: the fallback is only a model to switch to.const config = await getConfig().catch(() => FALLBACK_CONFIG);const defaultId = (await webGpuSupport)? config.wllamaDefaultGpuModelId: config.wllamaDefaultModelId;7 unmodified linesaddLogEntry(`Model "${wllamaModelId}" is no longer available; switched to "${defaultId}"`,);updateSettings({ ...getSettings(), wllamaModelId: defaultId });return defaultModel;}190 unmodified lines1911921931941951961971987 unmodified lines206207208209210211212213214215216190 unmodified linesconst model = wllamaModels[wllamaModelId];if (model) return model;const serverConfig = await getConfig().catch(() => undefined);const config = serverConfig ?? FALLBACK_CONFIG;const defaultId = (await webGpuSupport)? config.wllamaDefaultGpuModelId: config.wllamaDefaultModelId;7 unmodified linesaddLogEntry(`Model "${wllamaModelId}" is no longer available; switched to "${defaultId}"`,);// The shipped default serves this answer only: saved, it would stand in for// the server's own default on every later load.if (serverConfig) {updateSettings({ ...getSettings(), wllamaModelId: defaultId });}return defaultModel;}
211 unmodified lines21221321421521621779 unmodified lines297298299300301302211 unmodified lines"Title\nSee (the docs) now",);});});describe("splitIntoSentences", () => {79 unmodified linesexpect(spoken).toEqual(["Hello there."]);});it("does not fall back after audio has started", async () => {const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);211 unmodified lines21221321421521621721821922022122222322422522622722822979 unmodified lines309310311312313314315316317318319320321322323324325211 unmodified lines"Title\nSee (the docs) now",);});it("returns an empty string when the reasoning block never closed", () => {const text = "<think>The user wants the capital. Maybe Paris?";expect(tts.prepareTextForSpeech(text, "<think>", "</think>")).toBe("");});it("keeps a marker mentioned mid-answer as plain text", () => {const text = "Models wrap reasoning in <think> tags like this.";expect(tts.prepareTextForSpeech(text, "<think>", "</think>")).toBe("Models wrap reasoning in <think> tags like this.",);});});describe("splitIntoSentences", () => {79 unmodified linesexpect(spoken).toEqual(["Hello there."]);});it("creates no utterance and never enters the speaking state for an open reasoning block", async () => {const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);await tts.speak("<think>The user wants the capital. Maybe Paris?");expect(worker.sent).toEqual([]);expect(spoken).toEqual([]);expect(mockUpdateState).not.toHaveBeenCalled();});it("does not fall back after audio has started", async () => {const worker = createFakeWorker();tts.setWorkerFactory(() => worker as unknown as Worker);
1 unmodified line23456719 unmodified lines272829303132333435363738394041424344454647484950515253545556571 unmodified lineimport type { Voice, VoiceId } from "./piper";import { voices } from "./piper";import { getSettings, updateTextToSpeechState } from "./pubSub";import type {WorkerRequest,WorkerResponse,19 unmodified lineslanguageName?: string;}/** The markers come from user settings, so a character like `(` must not be read as syntax. */function escapeForRegExp(value: string): string {return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");}/*** Strips reasoning blocks, links and markdown punctuation so both engines are* fed the same plain text.*/export function prepareTextForSpeech(text: string,reasoningStartMarker: string,reasoningEndMarker: string,): string {const withoutReasoning = text.replace(new RegExp(`${escapeForRegExp(reasoningStartMarker)}[\\s\\S]*?${escapeForRegExp(reasoningEndMarker)}`,"g",),"",);const withoutLinks = withoutReasoning.replace(/\[([^\]]+)\]\([^)]+\)/g,"($1)",);return withoutLinks.replace(/[#*`_~[\]]/g, "").trim();}1 unmodified line234567819 unmodified lines28293031323334353637383940414243444546474849501 unmodified lineimport type { Voice, VoiceId } from "./piper";import { voices } from "./piper";import { getSettings, updateTextToSpeechState } from "./pubSub";import { splitReasoning } from "./reasoning";import type {WorkerRequest,WorkerResponse,19 unmodified lineslanguageName?: string;}/*** Strips the reasoning block, links and markdown punctuation so both engines* are fed the same plain text. The reasoning rule is the UI's shared one: only* a block at the start of the response counts, and an unterminated one has no* answer to speak.*/export function prepareTextForSpeech(text: string,reasoningStartMarker: string,reasoningEndMarker: string,): string {const { answer } = splitReasoning(text,reasoningStartMarker,reasoningEndMarker,);const withoutLinks = answer.replace(/\[([^\]]+)\]\([^)]+\)/g, "($1)");return withoutLinks.replace(/[#*`_~[\]]/g, "").trim();}
92 unmodified lines93949596979899166 unmodified lines26626726826927027192 unmodified lines- Streaming responses, built on the Vercel AI SDK (`ai` + `@ai-sdk/openai-compatible`)- Auto model selection (if blank)- 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)- Reasoning content support: reasoning/thinking output is wrapped between configurable `reasoningStartMarker`/`reasoningEndMarker` settings (default `<think>` / `</think>`)**Configuration:**166 unmodified linesBefore 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 Путин").### Text Generation State Machine`textGenerationStatePubSub` drives the AI response UI through these states:92 unmodified lines93949596979899166 unmodified lines26626726826927027127227392 unmodified lines- Streaming responses, built on the Vercel AI SDK (`ai` + `@ai-sdk/openai-compatible`)- Auto model selection (if blank)- 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)- 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`**Configuration:**166 unmodified linesBefore 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 Путин").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.### Text Generation State Machine`textGenerationStatePubSub` drives the AI response UI through these states:
.env.example+5-2
changelog.md+19
client/components/AiResponse/ChatInterface.test.tsx+24
client/components/AiResponse/ChatInterface.tsx+8-3
client/components/AiResponse/hooks/useReasoningContent.ts+9-24
client/components/Analytics/SearchStats.test.tsx+102-39
client/components/Analytics/SearchStats.tsx+36-5
client/components/App/App.test.tsx+61-4
client/components/App/App.tsx+8-13
client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.tsAdded+207
client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts+22-10
client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts+30-13
client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts+21-7
client/components/Search/Form/SearchForm.suggestions.test.tsxAdded+90
client/components/Search/Form/SearchForm.test.tsx+44
client/components/Search/Form/SearchForm.tsx+19-27
client/components/Search/History/HistoryDrawer.test.tsx+7
client/components/Search/History/HistoryDrawer.tsx+5-1
client/hooks/useHistoryRestore.test.ts+34
client/hooks/useSearchHistory.test.ts+154
client/hooks/useSearchHistory.ts+43-11
client/modules/accessKey.test.ts+84
client/modules/accessKey.ts+32-16
client/modules/config.test.ts+1
client/modules/config.ts+4-1
client/modules/followUpQuestions.test.ts+66-8
client/modules/followUpQuestions.ts+7-3
client/modules/history.test.ts+71
client/modules/history.ts+96
client/modules/parentWindow.test.tsAdded+110
client/modules/parentWindow.ts+27-3
client/modules/pubSub.test.ts+82
client/modules/pubSub.ts+49-1
client/modules/querySuggestions.test.ts+36
client/modules/querySuggestions.ts+20-11
client/modules/reasoning.test.tsAdded+81
client/modules/reasoning.tsAdded+41
client/modules/settings.test.ts+1
client/modules/settings.ts-9
client/modules/textGeneration.chatBudget.test.ts+68-1
client/modules/textGeneration.inference.test.ts+1
client/modules/textGeneration.ts+4-2
client/modules/textGenerationUtilities.test.ts+41
client/modules/textGenerationUtilities.ts+24
client/modules/textGenerationWithHorde.ts+2
client/modules/textGenerationWithWllama.test.ts+26-1
client/modules/textGenerationWithWllama.ts+7-3
client/modules/textToSpeech.test.ts+23
client/modules/textToSpeech.ts+10-17
docs/ai-integration.md+3-1