diff --git a/.env.example b/.env.example index ed6f446fd372b2ecfedd99f3bdb7ae2f272d74bc..284d01bf1c59aa20b1d599888dee02c006036ec7 100644 --- a/.env.example +++ b/.env.example @@ -29,10 +29,13 @@ INTERNAL_OPENAI_COMPATIBLE_API_NAME="Internal API" # "internal" -> $INTERNAL_OPENAI_COMPATIBLE_API_NAME DEFAULT_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 Parallel and You.com, plus Keenable when its key is set. With the fallback enabled, an unknown name stops the server at start. +# 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. @@ -41,7 +44,7 @@ SEARCH_FALLBACK_PARALLEL_API_KEY="" # 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. +# 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. diff --git a/changelog.md b/changelog.md index 3faac405341a244155103dfb6ddf7ed1915f3191..12f0597e58ca3e4f82359bd44121ad107501c534 100644 --- a/changelog.md +++ b/changelog.md @@ -2,8 +2,26 @@ Notable 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. @@ -29,6 +47,7 @@ Notable changes, grouped by date, most recent first. - 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 diff --git a/client/components/AiResponse/ChatInterface.test.tsx b/client/components/AiResponse/ChatInterface.test.tsx index 34b92b8b9d42556095a74beaedb83fc166329313..1f888c39fa5924882c6b0304ab3a60f79266b01b 100644 --- a/client/components/AiResponse/ChatInterface.test.tsx +++ b/client/components/AiResponse/ChatInterface.test.tsx @@ -737,3 +737,27 @@ describe("ChatInterface generation state", () => { expect(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?"]); + }); +}); diff --git a/client/components/AiResponse/ChatInterface.tsx b/client/components/AiResponse/ChatInterface.tsx index 3588defcd4e0f0c8fca708288c33224f05a5daad..223b9f5d3467770a2c1cabddc68cf5e7d495f368 100644 --- a/client/components/AiResponse/ChatInterface.tsx +++ b/client/components/AiResponse/ChatInterface.tsx @@ -131,9 +131,14 @@ export default function ChatInterface({ // A newer call, or an unmount, took over while this one awaited. if (invocation !== followUpInvocationRef.current) return; - setPreviousFollowUpQuestions((prev) => - [...prev, newQuestion].slice(-5), - ); + // 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(), diff --git a/client/components/AiResponse/hooks/useReasoningContent.ts b/client/components/AiResponse/hooks/useReasoningContent.ts index 500f0d6f58da628bfa9f22b3d7b38ff2950f68a2..c004ecaa808187191568ca38c4b6b12893feda5b 100644 --- a/client/components/AiResponse/hooks/useReasoningContent.ts +++ b/client/components/AiResponse/hooks/useReasoningContent.ts @@ -1,6 +1,7 @@ import { 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 markers @@ -17,32 +18,16 @@ export function useReasoningContent( const 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, - }; - } + const { reasoning, answer, isOpen } = splitReasoning( + text, + startMarker, + endMarker, + ); return { - reasoningContent: trimmedText.slice( - startIndex + startMarker.length, - endIndex, - ), - mainContent: trimmedText.slice(endIndex + endMarker.length), - isGenerating: false, + reasoningContent: reasoning, + mainContent: answer, + isGenerating: isOpen && isResponseGenerating, }; }, [isResponseGenerating], diff --git a/client/components/Analytics/SearchStats.test.tsx b/client/components/Analytics/SearchStats.test.tsx index 0c74402d399a5bb771ca978e6f1660d8e97a190f..a485367213756400f2538fe8a3817101662268b0 100644 --- a/client/components/Analytics/SearchStats.test.tsx +++ b/client/components/Analytics/SearchStats.test.tsx @@ -1,41 +1,21 @@ import { MantineProvider } from "@mantine/core"; -import { render, screen } from "@testing-library/react"; -import { useSearchHistory } from "@/hooks/useSearchHistory"; -import type { SearchEntry } from "@/modules/history"; +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"; -vi.mock("@/hooks/useSearchHistory", () => ({ - useSearchHistory: vi.fn(), +// 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, + })), })); -/** The hook mock has to return the full shape the real hook returns. */ -const mockHistory = (recentSearches: SearchEntry[]) => { - const noop = vi.fn(async (): Promise => {}); - 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(), - }); -}; +const DAY_MS = 24 * 60 * 60 * 1000; /** Metric cards print the value below the label; the heatmap above it. */ const valueBelow = (label: string) => @@ -46,8 +26,9 @@ const valueAbove = (label: string) => describe("SearchStats", () => { let originalTimeZone: string | undefined; - beforeEach(() => { + beforeEach(async () => { originalTimeZone = process.env.TZ; + await historyDatabase.searches.clear(); }); afterEach(() => { @@ -56,7 +37,7 @@ describe("SearchStats", () => { else process.env.TZ = originalTimeZone; }); - it("buckets the Daily Average by local day, like the heatmap", () => { + it("buckets the Daily Average by local day, like the heatmap", async () => { process.env.TZ = "Europe/Zurich"; // UTC+1 in January vi.useFakeTimers({ toFake: ["Date"] }); vi.setSystemTime(new Date(2026, 0, 15, 12)); @@ -69,9 +50,9 @@ describe("SearchStats", () => { expect(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 }, + await historyDatabase.searches.bulkAdd([ + { query: "first", timestamp: first }, + { query: "second", timestamp: second }, ]); render( @@ -79,7 +60,89 @@ describe("SearchStats", () => { , ); - expect(valueBelow("Daily Average")).toBe("2"); + 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( + + + , + ); + + 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( + + + , + ); + + 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, + ); + const readSpy = vi.spyOn(historyModule, "getSearchActivityRecords"); + + try { + render( + + + , + ); + + expect(await screen.findByText("No search data available")).toBeTruthy(); + expect(readSpy).not.toHaveBeenCalled(); + } finally { + readSpy.mockRestore(); + if (historyOn) settingsMock.mockImplementation(historyOn); + } + }); }); diff --git a/client/components/Analytics/SearchStats.tsx b/client/components/Analytics/SearchStats.tsx index cd976fdc9ef6a1625f5ed86409d22b764ac8536b..bdd0dc46c507486138e32536c864d39fcb4650f9 100644 --- a/client/components/Analytics/SearchStats.tsx +++ b/client/components/Analytics/SearchStats.tsx @@ -11,9 +11,13 @@ import { Title, } 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 { 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"; @@ -28,7 +32,7 @@ interface StatsData { avgPerDay: number; mostActiveHour: number; topSources: { source: string; count: number; percentage: number }[]; - recentActivity: SearchEntry[]; + recentActivity: SearchActivityRecord[]; } function MetricCard({ @@ -58,7 +62,34 @@ export default function SearchStats({ period = "week", compact = false, }: SearchStatsProps) { - const { recentSearches, isLoading } = useSearchHistory({ limit: 1000 }); + const [recentSearches, setRecentSearches] = useState( + [], + ); + 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) { diff --git a/client/components/App/App.test.tsx b/client/components/App/App.test.tsx index fa1efeae1be7ab17531983fdc4c441cd2413e5df..99fca6f48a9a9c6338bff9e174c84fefa5f70acb 100644 --- a/client/components/App/App.test.tsx +++ b/client/components/App/App.test.tsx @@ -1,5 +1,5 @@ import type { ServerConfig } from "@shared/serverConfig"; -import { render, screen, waitFor } from "@testing-library/react"; +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"; @@ -30,6 +30,7 @@ const serverConfig: ServerConfig = { internalApiName: "Internal API", defaultInferenceType: "browser", searchToken: "a".repeat(64), + parentWindowOrigins: ["https://huggingface.co"], }; describe("App", () => { @@ -62,9 +63,12 @@ describe("App", () => { * 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) { + async function renderWithStoredSettings( + stored?: Record, + config: ServerConfig = serverConfig, + ) { vi.resetModules(); - localStorage.setItem("settings", JSON.stringify(stored)); + if (stored) localStorage.setItem("settings", JSON.stringify(stored)); const [ { getConfig: freshGetConfig }, @@ -75,7 +79,7 @@ describe("App", () => { import("./App"), import("@/modules/pubSub"), ]); - vi.mocked(freshGetConfig).mockResolvedValue(serverConfig); + vi.mocked(freshGetConfig).mockResolvedValue(config); render(); await screen.findByTestId("main-page"); @@ -106,6 +110,59 @@ describe("App", () => { ); }); + /** Renders a fresh module instance against a server whose config fails to load. */ + async function renderWithoutConfig(stored?: Record) { + 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(); + 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 () => { diff --git a/client/components/App/App.tsx b/client/components/App/App.tsx index f08b9b7684c940f6dc9eb4bcc7e34b0e5dd44f39..50dbede42bb97eb02cf53d457a1f2e01b5ef4244 100644 --- a/client/components/App/App.tsx +++ b/client/components/App/App.tsx @@ -12,21 +12,15 @@ import { Notifications } from "@mantine/notifications"; import { usePubSub } from "create-pubsub/react"; import { lazy, useEffect, useState } from "react"; import { addLogEntry } from "@/modules/logEntries"; -import { settingsPubSub } from "@/modules/pubSub"; +import { hasStoredUserSettings, 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 { getConfig, type ServerConfig } from "@/modules/config"; import MainPage from "../Pages/Main/MainPage"; const AccessPage = lazy(() => import("../Pages/AccessPage")); @@ -103,9 +97,9 @@ function useServerConfig(): ConfigState { /** * 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. + * 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); @@ -120,6 +114,7 @@ function useInitializeSettings(config: ConfigState) { if ( settingsInitialized || config === "loading" || + config === "unavailable" || hasWebGpu === undefined ) { return; @@ -127,8 +122,8 @@ function useInitializeSettings(config: ConfigState) { setSettings( applyServerConfig( - upgradeUntouchedSystemPrompt({ ...defaultSettings, ...settings }), - config === "unavailable" ? FALLBACK_CONFIG : config, + upgradeUntouchedSystemPrompt(settings), + config, hasStoredUserSettings, hasWebGpu, ), diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.ts b/client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fe34278a9ae55d74bb257df9383ed289dbd158c3 --- /dev/null +++ b/client/components/Pages/Main/Menu/AISettings/hooks/settingsFetches.test.ts @@ -0,0 +1,207 @@ +import { 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() { + let resolve!: (v: T) => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +/** Records the signal of each call and lets the test settle calls in any order. */ +function controlled(mock: ReturnType, signalArg: number) { + const calls: { signal: AbortSignal; resolve: (v: T) => void }[] = []; + mock.mockImplementation((...args: unknown[]) => { + const d = deferred(); + 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 => ({ + ...defaultSettings, + inferenceType: "openai", + ...patch, +}); +const horde = (patch: Partial): 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(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(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(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); + }); +}); diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts index 1a4ca0369fdd887d870ef81f1218b87356dbdb7e..6971b19aaf246542b7a1ed0153ea75964115481f 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeModels.ts @@ -1,3 +1,4 @@ +import { withTimeout } from "@shared/withTimeout"; import { useEffect, useState } from "react"; import { addLogEntry } from "@/modules/logEntries"; import type { defaultSettings } from "@/modules/settings"; @@ -6,20 +7,32 @@ import type { ModelOption } from "../types"; type Settings = typeof defaultSettings; -/** AI Horde models as select options; only fetched while Horde is the selected backend. */ +/** 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([]); useEffect(() => { + if (settings.inferenceType !== "horde") return; + + const controller = new AbortController(); + async function fetchAvailableHordeModels() { try { - const models = await fetchHordeModels(); - const formattedModels = models.map((model) => ({ - label: model.name, - value: model.name, - })); - setHordeModels(formattedModels); + 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}`); @@ -27,9 +40,8 @@ export const useHordeModels = (settings: Settings) => { } } - if (settings.inferenceType === "horde") { - fetchAvailableHordeModels(); - } + fetchAvailableHordeModels(); + return () => controller.abort(); }, [settings.inferenceType]); return hordeModels; diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts index df171cc2363c8808104755b64fd45524c3a323f1..9b2e88a62732c742fdef9ecddcfb967ec590bda3 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useHordeUserInfo.ts @@ -1,3 +1,4 @@ +import { withTimeout } from "@shared/withTimeout"; import { useEffect, useState } from "react"; import { addLogEntry } from "@/modules/logEntries"; import type { defaultSettings } from "@/modules/settings"; @@ -9,25 +10,42 @@ import type { HordeUserInfo } from "../types"; type Settings = typeof defaultSettings; -/** The logged-in Horde user, or null when the key is empty or the anonymous one. */ +/** 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( null, ); useEffect(() => { + if (settings.inferenceType !== "horde") return; + + if ( + !settings.hordeApiKey || + settings.hordeApiKey === aiHordeDefaultApiKey + ) { + setHordeUserInfo(null); + return; + } + + const controller = new AbortController(); + async function fetchUserInfo() { try { - if ( - settings.hordeApiKey && - settings.hordeApiKey !== aiHordeDefaultApiKey - ) { - const userInfo = await fetchHordeUserInfo(settings.hordeApiKey); - setHordeUserInfo(userInfo); - } else { - setHordeUserInfo(null); - } + 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}`); @@ -35,9 +53,8 @@ export const useHordeUserInfo = (settings: Settings) => { } } - if (settings.inferenceType === "horde") { - fetchUserInfo(); - } + fetchUserInfo(); + return () => controller.abort(); }, [settings.inferenceType, settings.hordeApiKey]); return hordeUserInfo; diff --git a/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts b/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts index c3248615adb78d13e2323953c7285c2c2a486ad3..ea092bc5031e804ea2d2ec531b7788942c822e34 100644 --- a/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts +++ b/client/components/Pages/Main/Menu/AISettings/hooks/useOpenAiModels.ts @@ -9,29 +9,44 @@ type Settings = typeof defaultSettings; /** * 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([]); 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, ); - const uniqueModelIds = [ - ...new Set(models.map((m: { id: string }) => m.id)), - ]; + 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(!Array.isArray(options) || options.length === 0); + 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}`); @@ -40,9 +55,8 @@ export const useOpenAiModels = (settings: Settings) => { } } - if (settings.inferenceType === "openai" && settings.openAiApiBaseUrl) { - fetchOpenAiModels(); - } + fetchOpenAiModels(); + return () => controller.abort(); }, [ settings.inferenceType, settings.openAiApiBaseUrl, diff --git a/client/components/Search/Form/SearchForm.suggestions.test.tsx b/client/components/Search/Form/SearchForm.suggestions.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..e06426cef3de5ea010fffcf89fc5b69ee936c70c --- /dev/null +++ b/client/components/Search/Form/SearchForm.suggestions.test.tsx @@ -0,0 +1,90 @@ +import { 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( + + + , + ); +} + +/** 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); + }); +}); diff --git a/client/components/Search/Form/SearchForm.test.tsx b/client/components/Search/Form/SearchForm.test.tsx index be9678f6112153086cd3d6fac2a2b0a2871bc4fe..e53b088e85e584ec923b4fe0d2893b903c798159 100644 --- a/client/components/Search/Form/SearchForm.test.tsx +++ b/client/components/Search/Form/SearchForm.test.tsx @@ -4,6 +4,7 @@ import userEvent from "@testing-library/user-event"; import SearchForm from "@/components/Search/Form/SearchForm"; import { resetHandledQuery } from "@/modules/autoSearch"; import { settingsPubSub } from "@/modules/pubSub"; +import { getRandomQuerySuggestion } from "@/modules/querySuggestions"; import { defaultSettings } from "@/modules/settings"; import { searchAndRespond } from "@/modules/textGeneration"; @@ -100,6 +101,49 @@ describe("SearchForm component", () => { await 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 }); diff --git a/client/components/Search/Form/SearchForm.tsx b/client/components/Search/Form/SearchForm.tsx index e1914ea941945211c2636ded91db118ca552a6c1..07af6a6fd1cb662866e761724dd1355b04be1299 100644 --- a/client/components/Search/Form/SearchForm.tsx +++ b/client/components/Search/Form/SearchForm.tsx @@ -122,52 +122,44 @@ export default memo(function SearchForm({ void 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) { - fetchQuerySuggestion() - .then((suggestion) => { + if (state.textAreaValue.length !== 0) return; + + let isCurrent = true; + fetchQuerySuggestion() + .then((suggestion) => { + if (isCurrent) setState((prev) => ({ ...prev, suggestedQuery: suggestion })); - }) - .catch(() => { + }) + .catch(() => { + if (isCurrent) setState((prev) => ({ ...prev, suggestedQuery: DEFAULT_QUERY_SUGGESTION, })); - }); - } + }); + + return () => { + isCurrent = false; + }; }, [state.textAreaValue.length, fetchQuerySuggestion]); - const handleInputChange = async (event: ChangeEvent) => { + const handleInputChange = (event: ChangeEvent) => { 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 () => { + const handleClearButtonClick = () => { 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. diff --git a/client/components/Search/History/HistoryDrawer.test.tsx b/client/components/Search/History/HistoryDrawer.test.tsx index 3ce6e2b7c45c7940344959fcb52b446ebfbf8334..7b10b3086ad43610b25fc21d73d56f4e8584d6f2 100644 --- a/client/components/Search/History/HistoryDrawer.test.tsx +++ b/client/components/Search/History/HistoryDrawer.test.tsx @@ -90,6 +90,13 @@ describe("HistoryDrawer component", () => { expect(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(); diff --git a/client/components/Search/History/HistoryDrawer.tsx b/client/components/Search/History/HistoryDrawer.tsx index 20556086f95f412b225e476db495b6ebb2b63c16..d91006c62658c562a57b1af8acda7ac258d97612 100644 --- a/client/components/Search/History/HistoryDrawer.tsx +++ b/client/components/Search/History/HistoryDrawer.tsx @@ -53,7 +53,11 @@ export default function HistoryDrawer({ togglePin, deleteEntry, searchHistory, - } = useSearchHistory({ limit: 100, enableGrouping: true }); + } = useSearchHistory({ + limit: 100, + enableGrouping: true, + includeAllPinned: true, + }); useEffect(() => { searchHistory(searchQuery); diff --git a/client/hooks/useHistoryRestore.test.ts b/client/hooks/useHistoryRestore.test.ts index 9df477333eba01642dcc820b8878a1a617c40496..1a856518be4f55e87a015f7f7af8bfc1bc3293da 100644 --- a/client/hooks/useHistoryRestore.test.ts +++ b/client/hooks/useHistoryRestore.test.ts @@ -7,6 +7,7 @@ import { getSuppressNextFollowUp, imageSearchResultsPubSub, imageSearchStatePubSub, + isRestoringFromHistoryPubSub, textSearchResultsPubSub, updateImageSearchResults, updateSuppressNextFollowUp, @@ -19,6 +20,12 @@ vi.mock("wouter", () => ({ vi.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()), getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null), @@ -150,4 +157,31 @@ describe("useHistoryRestore", () => { expect(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(); + } + }); }); diff --git a/client/hooks/useSearchHistory.test.ts b/client/hooks/useSearchHistory.test.ts index 0b52fdaa675b4f87de652b77ea4912b6beb88c1a..1c1b6aea7a2705ef6e7b4d76c91d2e5feeeb1ee4 100644 --- a/client/hooks/useSearchHistory.test.ts +++ b/client/hooks/useSearchHistory.test.ts @@ -83,6 +83,160 @@ async function settle() { }); } +/** + * 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; +}) { + 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); diff --git a/client/hooks/useSearchHistory.ts b/client/hooks/useSearchHistory.ts index d345d439434171599e46b52e8ca259a0561d53d9..82939beeb2ddd8e1dcb01190a2ffe4e7484ebf81 100644 --- a/client/hooks/useSearchHistory.ts +++ b/client/hooks/useSearchHistory.ts @@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { addSearchToHistory, clearAllHistory, + getPinnedSearches, getRecentSearches, historyDatabase, type ImageResults, @@ -22,6 +23,12 @@ interface UseSearchHistoryOptions { enableGrouping?: 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 { @@ -69,6 +76,7 @@ export function useSearchHistory( enableGrouping = true, enablePagination = false, pageSize = 20, + includeAllPinned = false, } = options; const [entries, setEntries] = useState([]); @@ -104,14 +112,21 @@ export function useSearchHistory( return; } - const searches = await getRecentSearches( - enablePagination ? 1000 : limit * 2, - ); - - const [llmCount, chatCount] = await Promise.all([ + 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); @@ -124,7 +139,7 @@ export function useSearchHistory( isLoadingRef.current = false; setIsLoading(false); } - }, [limit, enablePagination]); + }, [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 the @@ -175,17 +190,30 @@ export function useSearchHistory( entries, query, (search) => search.query, - enablePagination ? entries.length : limit, + enablePagination || includeAllPinned ? entries.length : limit, ).map((result) => result.item); - }, [entries, settledQuery, enablePagination, limit]); + }, [entries, settledQuery, enablePagination, includeAllPinned, 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 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; @@ -222,8 +250,12 @@ export function useSearchHistory( try { 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: !search.pinned, + pinned, + pinnedAt: pinned ? Date.now() : undefined, }); await refreshHistory(); addLogEntry( diff --git a/client/modules/accessKey.test.ts b/client/modules/accessKey.test.ts index 4f78b55ee3d277b79fa3b05e82fac054b2a1ccfb..050fba139b41301c2cfec9e80fce3e76ec1908cf 100644 --- a/client/modules/accessKey.test.ts +++ b/client/modules/accessKey.test.ts @@ -172,6 +172,7 @@ describe("Access Key Module", () => { ); 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 () => { @@ -196,6 +197,19 @@ describe("Access Key Module", () => { const result = await verifyStoredAccessKey(TIMEOUT_HOURS); expect(result).toBe(false); + expect(localStorage.getItem("accessKeyHash")).toBeNull(); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it("deletes a stored value that is not JSON without asking the server", async () => { + 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 () => { @@ -215,5 +229,75 @@ describe("Access Key Module", () => { // 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); + }); + }); }); }); diff --git a/client/modules/accessKey.ts b/client/modules/accessKey.ts index 1644e90295365b5e17b46d976e37f6313949b50b..5fe694cda1481c6fbb967246fd41b46cedc07f8f 100644 --- a/client/modules/accessKey.ts +++ b/client/modules/accessKey.ts @@ -95,42 +95,58 @@ export async function verifyStoredAccessKey( const storedData = localStorage.getItem(ACCESS_KEY_STORAGE_KEY); if (!storedData) return false; + let hash: string; + let timestamp: number; try { - const { hash, timestamp }: StoredAccessKey = JSON.parse(storedData); + ({ 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; - } + 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 }), }); - // 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"); + if (!response.ok) { + addLogEntry( + `Stored access key could not be verified (status ${response.status})`, + ); return false; } const data = await response.json(); - if (!data.valid) { + 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("Using stored access key"); - return true; + addLogEntry("Stored access key could not be verified (unexpected reply)"); + return false; } catch (error) { addLogEntry(`Error verifying stored access key: ${error}`); - localStorage.removeItem(ACCESS_KEY_STORAGE_KEY); return false; } } diff --git a/client/modules/config.test.ts b/client/modules/config.test.ts index cd2dbace33cb931cacc723737045518c8ce351ec..91030760288092d07d44be2dd03afa4e134467e4 100644 --- a/client/modules/config.test.ts +++ b/client/modules/config.test.ts @@ -13,6 +13,7 @@ const serverConfig: ServerConfig = { internalApiName: "Custom LLM", defaultInferenceType: "internal", searchToken: "a".repeat(64), + parentWindowOrigins: ["https://huggingface.co"], }; /** Imports a fresh copy of the module so its cache starts empty. */ diff --git a/client/modules/config.ts b/client/modules/config.ts index 6db5d0c4f66c424ba1210ef93de7f026479aa800..b64170728bb3f2b6d9fdcdbb957e087977b8fc42 100644 --- a/client/modules/config.ts +++ b/client/modules/config.ts @@ -23,7 +23,9 @@ export type { ServerConfig }; * * `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. + * 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, @@ -34,6 +36,7 @@ export const FALLBACK_CONFIG: ServerConfig = { internalApiName: DEFAULT_INTERNAL_API_NAME, defaultInferenceType: DEFAULT_INFERENCE_TYPE, searchToken: "", + parentWindowOrigins: [], }; const FETCH_TIMEOUT_MS = 5000; diff --git a/client/modules/followUpQuestions.test.ts b/client/modules/followUpQuestions.test.ts index 33a29119e3208ace3f2e1907fe9e1807287629f6..a8de96731dd7053aacd6e3d1d90353393e86ec8b 100644 --- a/client/modules/followUpQuestions.test.ts +++ b/client/modules/followUpQuestions.test.ts @@ -3,11 +3,15 @@ import { generateFollowUpQuestion } from "./followUpQuestions"; vi.mock("./textGeneration", () => ({ generateChatResponse: vi.fn(), + generateReplyToMessages: vi.fn(), })); -import { generateChatResponse } from "./textGeneration"; +import { + generateChatResponse, + generateReplyToMessages, +} from "./textGeneration"; -const mockedGenerateChatResponse = vi.mocked(generateChatResponse); +const mockedGenerateReplyToMessages = vi.mocked(generateReplyToMessages); beforeEach(() => { vi.clearAllMocks(); @@ -15,7 +19,7 @@ beforeEach(() => { describe("generateFollowUpQuestion", () => { it("keeps an English question with leading numbering", async () => { - mockedGenerateChatResponse.mockResolvedValue( + mockedGenerateReplyToMessages.mockResolvedValue( "1. What about the alternatives?", ); @@ -28,7 +32,7 @@ describe("generateFollowUpQuestion", () => { }); it("keeps a Chinese question ending in a fullwidth question mark", async () => { - mockedGenerateChatResponse.mockResolvedValue("你觉得这个方案怎么样?"); + mockedGenerateReplyToMessages.mockResolvedValue("你觉得这个方案怎么样?"); const question = await generateFollowUpQuestion({ topic: "方案", @@ -39,7 +43,7 @@ describe("generateFollowUpQuestion", () => { }); it("strips a leading bullet from a Japanese question without touching the text", async () => { - mockedGenerateChatResponse.mockResolvedValue( + mockedGenerateReplyToMessages.mockResolvedValue( "- この案についてどう思いますか?", ); @@ -52,7 +56,7 @@ describe("generateFollowUpQuestion", () => { }); it("keeps an Arabic question ending in an Arabic question mark", async () => { - mockedGenerateChatResponse.mockResolvedValue("ما رأيك في البدائل؟"); + mockedGenerateReplyToMessages.mockResolvedValue("ما رأيك في البدائل؟"); const question = await generateFollowUpQuestion({ topic: "البدائل", @@ -63,7 +67,7 @@ describe("generateFollowUpQuestion", () => { }); it("returns an empty string when no line ends with a question mark", async () => { - mockedGenerateChatResponse.mockResolvedValue("No questions here."); + mockedGenerateReplyToMessages.mockResolvedValue("No questions here."); const question = await generateFollowUpQuestion({ topic: "cats", @@ -74,11 +78,48 @@ describe("generateFollowUpQuestion", () => { }); }); +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(); - mockedGenerateChatResponse.mockResolvedValue("1. What comes next?"); + mockedGenerateReplyToMessages.mockResolvedValue("1. What comes next?"); await generateFollowUpQuestion({ topic: "cats", @@ -88,3 +129,20 @@ describe("generateFollowUpQuestion and the chat history", () => { expect(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: + "The user wants cat facts.\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."); + }); +}); diff --git a/client/modules/followUpQuestions.ts b/client/modules/followUpQuestions.ts index a0cb63034be5fc6cabbfbd0b4f6f2eacbba592ef..22639acabe44e0d8fd04af658b9cc862785fdd4b 100644 --- a/client/modules/followUpQuestions.ts +++ b/client/modules/followUpQuestions.ts @@ -1,5 +1,6 @@ import { addLogEntry } from "./logEntries"; -import { generateChatResponse } from "./textGeneration"; +import { generateReplyToMessages } from "./textGeneration"; +import { answerOnly } from "./textGenerationUtilities"; import type { ChatMessage } from "./types"; interface FollowUpQuestionParams { @@ -30,7 +31,7 @@ ${topic} The response was: ~~~ -${currentContent} +${answerOnly(currentContent)} ~~~ Follow these instructions: @@ -58,7 +59,10 @@ Respond with just the question, no additional text or explanations.`, }, ]; - const response = await generateChatResponse(promptMessages, () => {}); + // 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() diff --git a/client/modules/history.test.ts b/client/modules/history.test.ts index 6fe89543c6179532e56186fff0afaee0b3b0d38b..8e6f788d6504e9272c07be27eeaad35024869203 100644 --- a/client/modules/history.test.ts +++ b/client/modules/history.test.ts @@ -278,6 +278,36 @@ describe("History Module - Dexie CRUD", () => { }); }); + 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 } = @@ -905,4 +935,45 @@ describe("History Module - a search takes its answers and chats with it", () => expect(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"); + }); }); diff --git a/client/modules/history.ts b/client/modules/history.ts index 9c2a1a1a1189180a767aafe69b76e341ced41034..8a73675a4c563b98b699fb412e2b9a513ce95e23 100644 --- a/client/modules/history.ts +++ b/client/modules/history.ts @@ -93,6 +93,12 @@ export interface SearchEntry { content: 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; } @@ -147,12 +153,36 @@ async function dropRowsNoSearchOwns(tx: Transaction): Promise { .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 { + await tx + .table("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; llmResponses!: Table; @@ -163,6 +193,7 @@ class HistoryDatabase extends Dexie { this.version(1).stores(historySchema); this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns); + this.version(3).stores(historySchemaV3).upgrade(indexPinnedEntries); } /** @@ -362,6 +393,71 @@ export async function getRecentSearches( }); } +/** 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(); + 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 { + 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, diff --git a/client/modules/parentWindow.test.ts b/client/modules/parentWindow.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9aceeb53dd703558a3d22afc1bd1a2dbed1d82a5 --- /dev/null +++ b/client/modules/parentWindow.test.ts @@ -0,0 +1,110 @@ +import { 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 + >); +} + +/** 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", + ); + }); +}); diff --git a/client/modules/parentWindow.ts b/client/modules/parentWindow.ts index 7d79231e003fb1a23e27858b37f62728ce92d247..54ab0de2d5d6bc3bee1c90bb1a02da8e5e4c9a63 100644 --- a/client/modules/parentWindow.ts +++ b/client/modules/parentWindow.ts @@ -1,6 +1,30 @@ -/** Forwards a message to the embedding parent window, targeting the origin from `ancestorOrigins`. */ +import { 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; - const targetOrigin = parentWindow?.[0]?.location?.ancestorOrigins?.[0]; - if (targetOrigin) parentWindow.postMessage(message, targetOrigin); + 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. + }, + ); } diff --git a/client/modules/pubSub.test.ts b/client/modules/pubSub.test.ts index cf27fbd9b2d68e5a88aae0877e48accabd0f8042..c8bbd1a32027e8ab6fba56774db29e76cf268271 100644 --- a/client/modules/pubSub.test.ts +++ b/client/modules/pubSub.test.ts @@ -168,3 +168,85 @@ describe("numeric settings never hold an empty string", () => { expect(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; + 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"); + }, + ); +}); diff --git a/client/modules/pubSub.ts b/client/modules/pubSub.ts index 6c37a5a6f206ce46269629d4e8bf5ef4a26d1e7e..5dae1f966c5fdf8d9c04794e120ff7700092a025 100644 --- a/client/modules/pubSub.ts +++ b/client/modules/pubSub.ts @@ -31,10 +31,41 @@ function isSameJsonKind(value: unknown, reference: unknown): boolean { return 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(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; + const accepted: Record = {}; + for (const [key, value] of Object.entries( + parsed as Record, + )) { + if (!(key in defaults) || isSameJsonKind(value, defaults[key])) { + accepted[key] = value; + } + } + return { ...defaults, ...accepted } as T; +} + function createLocalStoragePubSub( localStorageKey: string, defaultValue: T, normalize?: (value: T) => T, + reportUsableStoredValue?: (usable: boolean) => void, ) { const localStorageValue = safeStorage.getItem(localStorageKey); let initialValue: T = defaultValue; @@ -46,7 +77,9 @@ function createLocalStoragePubSub( parsed = undefined; } if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) { - initialValue = normalize ? normalize(parsed as T) : (parsed as T); + 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 every @@ -55,6 +88,7 @@ function createLocalStoragePubSub( addLogEntry( `Discarded an unusable stored value for '${localStorageKey}'`, ); + reportUsableStoredValue?.(false); } } const localStoragePubSub = createPubSub(initialValue); @@ -128,12 +162,26 @@ export const modelLoadingProgressPubSub = createPubSub(0); export 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; diff --git a/client/modules/querySuggestions.test.ts b/client/modules/querySuggestions.test.ts index 2d49894ce0069a9f6348ad98d09e2da44fb14fd5..2bfe4ba8c3b0c5e519591249378860ff32c2dd4a 100644 --- a/client/modules/querySuggestions.test.ts +++ b/client/modules/querySuggestions.test.ts @@ -53,6 +53,42 @@ describe("getRandomQuerySuggestion", () => { expect(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"])); diff --git a/client/modules/querySuggestions.ts b/client/modules/querySuggestions.ts index 63a00bc4aa4a134b77ee99090d70d7f9fc3a8f8a..934c220c618c9b560135a4156fb705d9642114e9 100644 --- a/client/modules/querySuggestions.ts +++ b/client/modules/querySuggestions.ts @@ -1,3 +1,4 @@ +import { shuffle } from "@shared/shuffle"; import { addLogEntry } from "./logEntries"; import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub"; @@ -13,13 +14,21 @@ function toNonEmptyStrings(value: unknown): string[] { ); } +/** The refill under way, so callers that find the store empty together share one fetch. */ +let refillInFlight: Promise | undefined; + /** Pops a stored suggestion, refilling the store when it is empty; never resolves to an empty string. */ export async function getRandomQuerySuggestion(): Promise { - let querySuggestions = toNonEmptyStrings(getQuerySuggestions()); - - if (querySuggestions.length === 0) - querySuggestions = await refillQuerySuggestions(25); + 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); @@ -27,7 +36,7 @@ export async function getRandomQuerySuggestion(): Promise { return randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION; } -async function refillQuerySuggestions(limit: number): Promise { +async function refillQuerySuggestions(limit: number): Promise { const querySuggestionsFileUrl = new URL( "/query-suggestions.json", self.location.origin, @@ -46,21 +55,21 @@ async function refillQuerySuggestions(limit: number): Promise { throw new Error("the response is not a list"); } - const querySuggestionsList = toNonEmptyStrings(body) - .sort(() => Math.random() - 0.5) - .slice(0, limit); + const querySuggestionsList = shuffle(toNonEmptyStrings(body)).slice( + 0, + limit, + ); + + updateQuerySuggestions(querySuggestionsList); 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 []; } } diff --git a/client/modules/reasoning.test.ts b/client/modules/reasoning.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ca28244b13d1f30fc012769233ca13284b23c55 --- /dev/null +++ b/client/modules/reasoning.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { splitReasoning } from "./reasoning"; + +describe("splitReasoning", () => { + it("splits a terminated reasoning block from the answer", () => { + expect( + splitReasoning( + "Let me think about this\nHere is the answer.", + "", + "", + ), + ).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("still thinking", "", ""), + ).toEqual({ + reasoning: "still thinking", + answer: "", + isOpen: true, + }); + }); + + it("leaves a marker mentioned mid-answer intact", () => { + const text = "Models wrap reasoning in tags like this."; + expect(splitReasoning(text, "", "")).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, "", "")).toEqual({ + reasoning: "", + answer: text, + isOpen: false, + }); + }); + + it.each([ + ["empty text", ""], + ["whitespace-only text", " "], + ])("reports nothing for %s", (_, text) => { + expect(splitReasoning(text, "", "")).toEqual({ + reasoning: "", + answer: text, + isOpen: false, + }); + }); + + it("trims before checking the start marker, like the UI does", () => { + expect( + splitReasoning(" quietloud", "", ""), + ).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, + }); + }); +}); diff --git a/client/modules/reasoning.ts b/client/modules/reasoning.ts new file mode 100644 index 0000000000000000000000000000000000000000..8ef74d1b263fbf0bd7ba64f615b75543a8c08e2c --- /dev/null +++ b/client/modules/reasoning.ts @@ -0,0 +1,41 @@ +/** + * 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, + }; +} diff --git a/client/modules/settings.test.ts b/client/modules/settings.test.ts index 4ebd0e814dc75e6f874cfc4eafd17e47691b8912..a68e6b2a5df1a238fe12bd2eb40602e90563372d 100644 --- a/client/modules/settings.test.ts +++ b/client/modules/settings.test.ts @@ -21,6 +21,7 @@ const mockConfig: ServerConfig = { internalApiName: "Internal API", defaultInferenceType: "browser", searchToken: "a".repeat(64), + parentWindowOrigins: ["https://huggingface.co"], }; describe("Settings Module", () => { diff --git a/client/modules/settings.ts b/client/modules/settings.ts index 42924706508654d1f6351b11a71ee2e96f1022b2..613bdd63f644c2d638d336681294c0b293f8ccc3 100644 --- a/client/modules/settings.ts +++ b/client/modules/settings.ts @@ -14,15 +14,6 @@ import * as safeStorage from "./safeStorage"; export 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 prefixed diff --git a/client/modules/textGeneration.chatBudget.test.ts b/client/modules/textGeneration.chatBudget.test.ts index 84fc24c26f8911a56de055c4a6cc27677f6a7eaa..2ea9406d7d28b77c835b59c38a74a69eeeb9340d 100644 --- a/client/modules/textGeneration.chatBudget.test.ts +++ b/client/modules/textGeneration.chatBudget.test.ts @@ -4,6 +4,8 @@ const state = vi.hoisted(() => ({ settings: { inferenceType: "browser" } as { inferenceType: string; openAiContextLength?: number; + reasoningStartMarker?: string; + reasoningEndMarker?: string; }, systemPrompt: "", })); @@ -62,7 +64,10 @@ vi.mock("./textGenerationWithOpenAi", () => ({ })); import { getConversationSummary, updateConversationSummary } from "./pubSub"; -import { generateChatResponse } from "./textGeneration"; +import { + generateChatResponse, + generateReplyToMessages, +} from "./textGeneration"; import { generateChatWithOpenAi } from "./textGenerationWithOpenAi"; import { generateChatWithWllama } from "./textGenerationWithWllama"; import type { ChatMessage } from "./types"; @@ -253,3 +258,65 @@ describe("generateChatResponse context budget", () => { expect(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: `${reasoning}\n\nfirst answer`, + }, + ]; + const question: ChatMessage = { role: "user", content: "second question" }; + + beforeEach(() => { + vi.clearAllMocks(); + state.settings = { + inferenceType: "browser", + reasoningStartMarker: "", + reasoningEndMarker: "", + }; + 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); + }); +}); diff --git a/client/modules/textGeneration.inference.test.ts b/client/modules/textGeneration.inference.test.ts index c6a9bc50523bdbf3819adcade8b4ced04a01b631..9d9ac5303e8a9a0867e7c3d115e7c05bc7942695 100644 --- a/client/modules/textGeneration.inference.test.ts +++ b/client/modules/textGeneration.inference.test.ts @@ -42,6 +42,7 @@ vi.mock("./textGenerationUtilities", () => ({ defaultContextSize: 4096, getFormattedSearchResults: vi.fn(() => ""), searchResultsToConsider: 6, + withoutReasoning: (messages: unknown) => messages, })); vi.mock("gpt-tokenizer", () => ({ default: { encode: vi.fn(() => [1, 2, 3]) }, diff --git a/client/modules/textGeneration.ts b/client/modules/textGeneration.ts index 4bbe6c67aa830e32bb6f0bf9d096d13e396d1af8..c52ef8d6229da37f55de42bdb603faf06b5d4927 100644 --- a/client/modules/textGeneration.ts +++ b/client/modules/textGeneration.ts @@ -40,6 +40,7 @@ import { getFormattedSearchResults, imageResultTag, searchResultsToConsider, + withoutReasoning, } from "./textGenerationUtilities"; import type { ChatMessage, @@ -369,7 +370,7 @@ export async function generateReplyToMessages( messages: ChatMessage[], ): Promise { const keptMessages = keepNewestMessagesWithinBudget( - messages, + withoutReasoning(messages), defaultContextSize * historyBudgetRatio, ); @@ -382,9 +383,10 @@ export async function generateReplyToMessages( } export async function generateChatResponse( - newMessages: ChatMessage[], + messages: ChatMessage[], onUpdate: (partialResponse: string) => void, ) { + const newMessages = withoutReasoning(messages); let response = ""; try { diff --git a/client/modules/textGenerationUtilities.test.ts b/client/modules/textGenerationUtilities.test.ts index 586d4d3e7280bd170324f7d2405aa9ac753e67e1..5101515059e34fcc36661307f1a905253799c0a7 100644 --- a/client/modules/textGenerationUtilities.test.ts +++ b/client/modules/textGenerationUtilities.test.ts @@ -13,6 +13,8 @@ const state = vi.hoisted(() => ({ settings: { inferenceType: "openai", openAiContextLength: 4096 } as { inferenceType?: string; openAiContextLength?: number; + reasoningStartMarker?: string; + reasoningEndMarker?: string; }, })); @@ -37,12 +39,14 @@ vi.mock("./systemPrompt", () => ({ })); import { + answerOnly, getDefaultChatCompletionCreateParamsStreaming, getDefaultChatMessages, getEffectiveContextSize, getFormattedSearchResults, minimumOutputTokens, setWorkerFactory, + withoutReasoning, } from "./textGenerationUtilities"; import type { ChatMessage } from "./types"; @@ -510,3 +514,40 @@ describe("worker handoff", () => { expect(factory).not.toHaveBeenCalled(); }); }); + +describe("answerOnly", () => { + beforeEach(() => { + state.settings = { + inferenceType: "openai", + reasoningStartMarker: "", + reasoningEndMarker: "", + }; + }); + + it("drops a terminated reasoning block", () => { + expect(answerOnly("step by step\n\nThe answer.")).toBe( + "The answer.", + ); + }); + + it("returns an empty answer for an unterminated block", () => { + expect(answerOnly("still thinking")).toBe(""); + }); + + it("leaves a marker mentioned mid-answer intact", () => { + const text = "Models wrap thoughts in tags."; + expect(answerOnly(text)).toBe(text); + }); + + it("strips assistant turns only", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "quoted by the user hi" }, + { role: "assistant", content: "plan\n\nHello!" }, + ]; + + expect(withoutReasoning(messages)).toEqual([ + messages[0], + { role: "assistant", content: "Hello!" }, + ]); + }); +}); diff --git a/client/modules/textGenerationUtilities.ts b/client/modules/textGenerationUtilities.ts index 01cb4899dc93188b9959e48d0566c747a46eb832..0630b0c622cbc384872f4415531e5bb58454ec6a 100644 --- a/client/modules/textGenerationUtilities.ts +++ b/client/modules/textGenerationUtilities.ts @@ -14,6 +14,7 @@ import { getTextSearchStale, updateTextGenerationState, } from "./pubSub"; +import { splitReasoning } from "./reasoning"; import { getSystemPrompt } from "./systemPrompt"; import type { ChatMessage, TextSearchResult } from "./types"; @@ -313,3 +314,26 @@ export function getDefaultChatMessages(searchResults: string): ChatMessage[] { { 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, + ); +} diff --git a/client/modules/textGenerationWithHorde.ts b/client/modules/textGenerationWithHorde.ts index 2a7256f362ec98389f286e7f4306824f5d3f0578..005b26419491e18373a81f05c9186432a30595bf 100644 --- a/client/modules/textGenerationWithHorde.ts +++ b/client/modules/textGenerationWithHorde.ts @@ -454,8 +454,10 @@ async function getTopHordeModels(): Promise { export async function fetchHordeUserInfo( apiKey: string, + signal?: AbortSignal, ): Promise { const response = await fetch(buildHordeUrl("/find_user"), { + signal, headers: { [HTTP_HEADERS.API_KEY]: apiKey, [HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent, diff --git a/client/modules/textGenerationWithWllama.test.ts b/client/modules/textGenerationWithWllama.test.ts index c6ffeb8ca670c46db27ccd28421d18d74c0d82c8..14eac2730997cad1d1eba76e0e63462da3afb460 100644 --- a/client/modules/textGenerationWithWllama.test.ts +++ b/client/modules/textGenerationWithWllama.test.ts @@ -1,4 +1,5 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; +import { getConfig } from "./config"; import { addLogEntry } from "./logEntries"; import { getSettings, @@ -37,7 +38,10 @@ vi.mock("./config", () => ({ wllamaDefaultModelId: "test-model", wllamaDefaultGpuModelId: "test-gpu-model", }), - FALLBACK_CONFIG: {}, + FALLBACK_CONFIG: { + wllamaDefaultModelId: "test-model", + wllamaDefaultGpuModelId: "test-gpu-model", + }, })); vi.mock("./systemPrompt", () => ({ @@ -148,6 +152,27 @@ describe("generateTextWithWllama", () => { ); }); + 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 }]); diff --git a/client/modules/textGenerationWithWllama.ts b/client/modules/textGenerationWithWllama.ts index cba20c713ead9b39aef2cbdf3eb4fe51e4394dde..5c87622437ab50c1c19b3a5f2b9db5a7d2699563 100644 --- a/client/modules/textGenerationWithWllama.ts +++ b/client/modules/textGenerationWithWllama.ts @@ -191,8 +191,8 @@ async function getSelectedWllamaModel(): Promise { const 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 serverConfig = await getConfig().catch(() => undefined); + const config = serverConfig ?? FALLBACK_CONFIG; const defaultId = (await webGpuSupport) ? config.wllamaDefaultGpuModelId : config.wllamaDefaultModelId; @@ -206,7 +206,11 @@ async function getSelectedWllamaModel(): Promise { addLogEntry( `Model "${wllamaModelId}" is no longer available; switched to "${defaultId}"`, ); - updateSettings({ ...getSettings(), wllamaModelId: 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; } diff --git a/client/modules/textToSpeech.test.ts b/client/modules/textToSpeech.test.ts index 9842c9986c183e9b8abb6bd673c433c16e5e224e..6dc8b6e745085b21a08c133c4b5ad8b09cf3d2da 100644 --- a/client/modules/textToSpeech.test.ts +++ b/client/modules/textToSpeech.test.ts @@ -212,6 +212,18 @@ describe("prepareTextForSpeech", () => { "Title\nSee (the docs) now", ); }); + + it("returns an empty string when the reasoning block never closed", () => { + const text = "The user wants the capital. Maybe Paris?"; + expect(tts.prepareTextForSpeech(text, "", "")).toBe(""); + }); + + it("keeps a marker mentioned mid-answer as plain text", () => { + const text = "Models wrap reasoning in tags like this."; + expect(tts.prepareTextForSpeech(text, "", "")).toBe( + "Models wrap reasoning in tags like this.", + ); + }); }); describe("splitIntoSentences", () => { @@ -297,6 +309,17 @@ describe("speak", () => { expect(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("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); diff --git a/client/modules/textToSpeech.ts b/client/modules/textToSpeech.ts index 863b8abb68a61bfb01cd30227cc9ce97e3856835..a52406c1d74271dd2e70405c4b6a4d653c25abaf 100644 --- a/client/modules/textToSpeech.ts +++ b/client/modules/textToSpeech.ts @@ -2,6 +2,7 @@ import { addLogEntry } from "./logEntries"; import type { Voice, VoiceId } from "./piper"; import { voices } from "./piper"; import { getSettings, updateTextToSpeechState } from "./pubSub"; +import { splitReasoning } from "./reasoning"; import type { WorkerRequest, WorkerResponse, @@ -27,31 +28,23 @@ export interface VoiceOption { languageName?: 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. + * 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 withoutReasoning = text.replace( - new RegExp( - `${escapeForRegExp(reasoningStartMarker)}[\\s\\S]*?${escapeForRegExp(reasoningEndMarker)}`, - "g", - ), - "", - ); - const withoutLinks = withoutReasoning.replace( - /\[([^\]]+)\]\([^)]+\)/g, - "($1)", + const { answer } = splitReasoning( + text, + reasoningStartMarker, + reasoningEndMarker, ); + const withoutLinks = answer.replace(/\[([^\]]+)\]\([^)]+\)/g, "($1)"); return withoutLinks.replace(/[#*`_~[\]]/g, "").trim(); } diff --git a/docs/ai-integration.md b/docs/ai-integration.md index 5e3d321c13d9be5f00f2c939514af312f9099284..d7b5854dadfa808a01631ad6a1b86946808dfde7 100644 --- a/docs/ai-integration.md +++ b/docs/ai-integration.md @@ -93,7 +93,7 @@ Uses OpenAI's API or any OpenAI-compatible service. - 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 `` / ``) +- Reasoning content support: reasoning/thinking output is wrapped between configurable `reasoningStartMarker`/`reasoningEndMarker` settings (default `` / ``). 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:** @@ -266,6 +266,8 @@ Save to history database Before the answer, a follow-up question gets its own web search, and the query for it is written by `generateRelatedSearchQuery` (`client/modules/relatedSearchQuery.ts`). That call goes through `generateReplyToMessages`, not `generateChatResponse`: it sends the conversation with the same 75% token budget, but without the system prompt and the search results. Those carry pages in many languages: with them in front and the instruction to name the subject, Gemma 3 4B wrote the query for a Chinese question in another language (Turkish, Persian) in 4 of 9 runs, and without them in 2 of 9 (the old prompt, which did not ask for the subject, stayed in Chinese in 9 of 9). The prompt also asks for a query that makes sense on its own, so "why did they delay the release" becomes a query that names what "they" delayed. It also asks the model to copy a relative date ("next month", 明年) as written: `runFollowUpSearch` then anchors it, while a 4B model given today's date wrote "November 2026" for "next month" on 2026-11-19. The model still drops the phrase at times, writing a year of its own ("苹果 2025 新手机 发布时间" for 明年的呢), so the anchors come from the question the user typed: `normalizeFollowUpDates` (`shared/relativeDates.ts`) removes the years the model wrote and the user did not type in any message, then appends the question's anchors. A month the model writes without a year ("November releases") stays in the query next to the anchor. A query that still comes out in another script than the question's (Turkish or Persian for a Chinese question) gets one more call that translates it, naming the language: that held where asking harder in the main prompt did not. The question's script is the non-Latin one with the most words, since brand names can outnumber the Chinese letters ("iPhone呢"). A CJK character or a Hangul syllable counts as a word, while the other scripts need three letters in a row, because English questions write Greek letters as symbols, alone or in pairs ("α and β error", "γδ T cells"). Latin counts only when nothing else is there, and then any Latin letter in the query is enough ("Tencent founder 马化腾"). A question whose script serves several languages (Arabic, Bengali, Cyrillic, Devanagari) or is Latin cannot be named safely, so its query falls back to the typed question, as does a translation that misses again. Known gaps: Latin-script drift (English to French) is not caught; a Chinese query passes for a Japanese question, since kanji and kana count as one script; a Japanese question in kanji only is translated as Chinese; and an English question that quotes a word in another script gets its query translated into that language ("who is 雷军") or searched as typed when the script has no single language ("who is Путин"). +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: diff --git a/docs/api.md b/docs/api.md index 0131997b81d506b1182fedf20704d1bc08bce58d..5902ca41180932414a5765a1770ee1ca5c0a2913 100644 --- a/docs/api.md +++ b/docs/api.md @@ -32,6 +32,10 @@ Those two compare the whole request target, query string included, so do not check the method at all: a `POST` to `/search/text` is served like a `GET`. Only `/inference` answers `405`. +A path under `/search/` never reaches Vite's static handler: the search hook +claims the whole prefix and answers `404` to any path other than `/search/text` +and `/search/images`. + ## Authentication ### Search token @@ -201,8 +205,10 @@ search fall through to the same `502`. Same parameters and failures as `/search/text`, except that the text-search fallback above never applies here: an image search has no second source, so its `502` still means SearXNG failed. The hook claims the whole -`/search/` prefix and treats every path that does not start with `/search/text` -as an image search, so `/search/anything` is an image search. +`/search/` prefix but serves only the exact paths `/search/text` and +`/search/images`. Any other path under it, such as `/search/anything` or +`/search/text/`, answers `404` with `{"error":"Not found"}` before the token is +checked, so it costs no rate-limit point and runs no search. The ordering above does not carry over: image results are a plain score sort, nothing is pinned at index 0, and no result is exempt from the score filter diff --git a/docs/configuration.md b/docs/configuration.md index 99fb293477c6ac7e3cbe5f11f8274037427308ba..e57628ba726f20ece3ffd3be8fe0baeca1c26d0b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -27,7 +27,7 @@ Configure default models for different inference types: | `WLLAMA_DEFAULT_MODEL_ID` | `littlelamb-290m` | Default Wllama model ID for browsers without WebGPU, where the model runs on the CPU | | `WLLAMA_DEFAULT_GPU_MODEL_ID` | `gemma-3-4b` | Default Wllama model ID for browsers with WebGPU. It does not fall back to the variable above | -Both only seed a profile that has never saved settings; a user's own choice always wins. Detection is the same check that decides whether the model runs on the GPU: the browser must have WebGPU, and its GPU must be able to run wllama's shaders (`client/modules/webGpu.ts`, described in [ai-integration.md](ai-integration.md)). +Both only seed a profile that has never saved settings; a user's own choice always wins. A page load where the server configuration could not be fetched saves nothing, so a first-time profile is still seeded on a later load. Detection is the same check that decides whether the model runs on the GPU: the browser must have WebGPU, and its GPU must be able to run wllama's shaders (`client/modules/webGpu.ts`, described in [ai-integration.md](ai-integration.md)). ### Server Model Request Configuration @@ -75,6 +75,16 @@ INTERNAL_OPENAI_COMPATIBLE_API_NAME="Company LLM" | ------------------------ | --------- | -------------------------------------------------------------------- | | `DEFAULT_INFERENCE_TYPE` | `browser` | Default AI inference type (`browser`, `openai`, `horde`, `internal`) | +### Embedding + +When MiniSearch runs inside an iframe, it posts each search to the embedding page as `{ queryString, hash: "" }`, so a page such as a Hugging Face Space can keep its own address in sync with the search. + +| Variable | Default | Description | +| ----------------------- | ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `PARENT_WINDOW_ORIGINS` | `https://huggingface.co` | Comma-separated list of the origins allowed to receive the query. It is posted to each one, and the browser delivers it only when the embedding page is on that origin. Set it empty to never post the query | + +An origin is the scheme, host and port, with no path (`https://example.com`, `http://localhost:8080`). The query is never posted to `*`, since any site can frame an instance. + ### Server Configuration These variables control the Vite development/preview server behavior: @@ -92,15 +102,15 @@ These defaults are provided by `docker-compose.yml`/`docker-compose.production.y ### Search Fallback -When SearXNG fails on a text search, the server can retry that search against second providers: `search.parallel.ai` (Parallel) and You.com's MCP endpoint (`https://api.you.com/mcp`), and, when an operator opts in, Keenable's MCP endpoint (`https://api.keenable.ai/mcp`). Every configured provider takes part. On each search they are put in a random order, and each is tried in turn until one returns results; a provider that answers with nothing usable, or fails, hands the search to the next one. The whole cascade shares one 15-second budget, and each attempt gets the remaining budget divided by the number of providers still untried and not paused, so a provider that hangs cannot use up the time the others need. A single search can therefore reach more than one provider, one after the other. `docker-compose.yml` passes only `HOST`, `PORT`, `BASIC_SSL` and `HMR_PORT` into the development container, so these variables are not carried by the compose `environment` list; set them in `.env`, which `vite.config.ts` loads, inside the container as well as outside it. `vite.config.ts` reads `.env.example` after `.env`, so anything still set there acts as a default: the real API keys belong in `.env`, never in `.env.example`, which is committed. +When SearXNG fails on a text search, the server can retry that search against second providers: `search.parallel.ai` (Parallel), You.com's MCP endpoint (`https://api.you.com/mcp`), and Keenable's MCP endpoint (`https://api.keenable.ai/mcp`). Every configured provider takes part. On each search they are put in a random order, and each is tried in turn until one returns results; a provider that answers with nothing usable, or fails, hands the search to the next one. The whole cascade shares one 15-second budget, and each attempt gets the remaining budget divided by the number of providers still untried and not paused, so a provider that hangs cannot use up the time the others need. A single search can therefore reach more than one provider, one after the other. `docker-compose.yml` passes only `HOST`, `PORT`, `BASIC_SSL` and `HMR_PORT` into the development container, so these variables are not carried by the compose `environment` list; set them in `.env`, which `vite.config.ts` loads, inside the container as well as outside it. `vite.config.ts` reads `.env.example` after `.env`, so anything still set there acts as a default: the real API keys belong in `.env`, never in `.env.example`, which is committed. | Variable | Default | Description | | ---------------------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `SEARCH_FALLBACK_ENABLED` | `false` | Serve text results from the fallback providers when SearXNG has failed (an HTTP error, a network error, every engine unresponsive, or an open circuit), under one 15-second budget for the whole cascade. Only `true` or `1` turns it on, and changing it takes a restart, since a process keeps the environment it was started with. Image searches never use it, and a fallback that returns nothing usable is still an HTTP 200 with no results rather than an outage | -| `SEARCH_FALLBACK_PROVIDERS` | `''` (all providers) | Comma-separated list of the providers to try: `parallel`, `youcom`, `keenable`, or any mix. Names are trimmed and lowercased, and empty items are ignored. Unset or empty means Parallel and You.com, plus Keenable only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set. With `SEARCH_FALLBACK_ENABLED` on, an unknown name, or a list with no names at all (such as `,`), stops the server at start with an error that names the valid values | +| `SEARCH_FALLBACK_PROVIDERS` | `''` (all providers) | Comma-separated list of the providers to try: `parallel`, `youcom`, `keenable`, or any mix. Names are trimmed and lowercased, and empty items are ignored. Unset or empty means all three: Parallel, You.com and Keenable. With `SEARCH_FALLBACK_ENABLED` on, an unknown name, or a list with no names at all (such as `,`), stops the server at start with an error that names the valid values | | `SEARCH_FALLBACK_PARALLEL_API_KEY` | `''` | Optional API key for Parallel, sent as a Bearer token. Without it the fallback calls Parallel's keyless tier. With `SEARCH_FALLBACK_ENABLED` on, a key with a control character inside it (such as a pasted line break) stops the server at start, since the HTTP client would quote it in its error | | `SEARCH_FALLBACK_YOUCOM_API_KEY` | `''` | Optional API key for You.com, sent as a Bearer token. Without it the fallback calls the keyless `https://api.you.com/mcp?profile=free` endpoint. A key with a control character inside it stops the server at start, like the Parallel key | -| `SEARCH_FALLBACK_KEENABLE_API_KEY` | `''` | Optional API key for Keenable, sent as `X-API-Key` to `https://api.keenable.ai/mcp`. Setting it adds Keenable to the default list. Without it Keenable is tried only when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, and then on the keyless `https://api.keenable.ai/mcp-public` endpoint. Every request names the app in `X-Keenable-Title: MiniSearch`. A key with a control character inside it stops the server at start, like the other keys | +| `SEARCH_FALLBACK_KEENABLE_API_KEY` | `''` | Optional API key for Keenable, sent as `X-API-Key` to `https://api.keenable.ai/mcp`. Without it Keenable uses the keyless `https://api.keenable.ai/mcp-public` endpoint, like the other keyless tiers. Every request names the app in `X-Keenable-Title: MiniSearch`. A key with a control character inside it stops the server at start, like the other keys | `SEARCH_FALLBACK_PROVIDER` and `SEARCH_FALLBACK_API_KEY` are gone. If either is still set to a non-empty value while `SEARCH_FALLBACK_ENABLED` is on, the server stops at start with an error that names the variable to use instead, so an upgrade cannot silently drop a key: move the key to `SEARCH_FALLBACK_PARALLEL_API_KEY` or `SEARCH_FALLBACK_YOUCOM_API_KEY`, and the provider choice to `SEARCH_FALLBACK_PROVIDERS`. @@ -405,7 +415,8 @@ Client-facing configuration (access keys, inference type, internal API settings) "internalApiEnabled": true, "internalApiName": "Internal API", "defaultInferenceType": "browser", - "searchToken": "" + "searchToken": "", + "parentWindowOrigins": ["https://huggingface.co"] } ``` @@ -421,6 +432,7 @@ Client-facing configuration (access keys, inference type, internal API settings) | `WLLAMA_DEFAULT_GPU_MODEL_ID` | Runtime | Read from `/api/config` | | `INTERNAL_OPENAI_COMPATIBLE_API_*` | Runtime | Read from `/api/config` (except `API_KEY` which is server-only) | | `DEFAULT_INFERENCE_TYPE` | Runtime | Read from `/api/config` | +| `PARENT_WINDOW_ORIGINS` | Runtime | Read from `/api/config` | | Search token | Runtime | Read from `/api/config`, so a reload picks up the token of whichever server answers | ### Security Considerations diff --git a/docs/overview.md b/docs/overview.md index cfa00afa2f035d22c9c127bd6348007fc694ab09..e276c5a0ef421e5241fd34ed79f4ac22751dfec7 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -323,6 +323,7 @@ is counted at all (see `docs/page-content.md`): | `skipped.redirectLimit` | number | `MAX_REDIRECTS` | | `skipped.timedOut` | number | `REQUEST_TIMEOUT_MS` | | `skipped.tooLittleText` | number | `MIN_USEFUL_CHARS`, and the extractor's selectors | +| `skipped.unparsable` | number | A served document that could not be parsed (a locked PDF); never boxes a host | | `skipped.failed` | number | Nothing; the residue worth watching for a pattern | | `grounding.requests` | number | Nothing; the denominator for the two below | | `grounding.withContent` | number | Nothing; requests where at least one page yielded text | @@ -372,28 +373,28 @@ pays for it running out. `/inference`. Nothing about the conversation is kept, so the questions it can answer are about the upstream and about the wait, not about what was asked: -| Field | Type | Says | -| ------------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `requests` | number | Requests that passed token verification; the denominator for the rest | -| `streamed` | number | Answers that finished normally | -| `streamedRate` | number | `streamed` as a percentage of `requests` | -| `averageTimeToFirstTokenMs` | number | The wait the user actually feels, over the answers that produced a token | -| `averageDurationMs` | number | Whole-request duration over every outcome, so a 2 ms rejected body and a 25 s answer land in the same average | -| `averageAttempts` | number | Models tried, over the requests that reached the model loop; above 1 means the pool is carrying failures | -| `modelFallbacks` | number | Times a retry moved to another model | -| `modelsRefetched` | number | Times the model pool was re-listed mid-retry | -| `streamsEndedWithoutFinish` | number | Attempts whose stream closed with no finish part, counted per attempt because the retry can still succeed | -| `attemptFailures` | object | Failed attempts by reason: `rateLimited` (429), `serverError` (5xx), `otherHttpError`, `stalled` (no part within the idle timeout) and `other` | -| `failed.failedBeforeFirstToken` | number | Every model failed before a token was sent, answered 503 | -| `failed.failedMidStream` | number | The answer broke after content was already sent, so no retry was possible | -| `failed.abandoned` | number | The client was gone before or during the answer; the only outcome with no response to observe it by | -| `failed.badRequest` | number | Body too large, unparsable, or failing the schema | -| `failed.notConfigured` | number | `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` or its key is missing | -| `failed.modelListUnavailable` | number | The upstream's model list could not be fetched | -| `failed.noModelAvailable` | number | The list was fetched and held nothing usable | -| `failed.internalError` | number | Anything the handler did not expect | -| `failed.unclassified` | number | Should always be zero; a non-zero value means a path stopped reporting its outcome | -| `byModel` | object | `attempted`, `streamed`, `failed` and `abandoned` per model id, which is how a dead member of the pool becomes visible. `attempted` equals the other three added up | +| Field | Type | Says | +| ------------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `requests` | number | Requests that passed token verification; the denominator for the rest | +| `streamed` | number | Answers that finished normally | +| `streamedRate` | number | `streamed` as a percentage of `requests` | +| `averageTimeToFirstTokenMs` | number | The wait the user actually feels, over the answers that produced a token | +| `averageDurationMs` | number | Whole-request duration over every outcome, so a 2 ms rejected body and a 25 s answer land in the same average | +| `averageAttempts` | number | Models tried, over the requests that reached the model loop; above 1 means the pool is carrying failures | +| `modelFallbacks` | number | Times a retry moved to another model | +| `modelsRefetched` | number | Times the model pool was re-listed mid-retry | +| `streamsEndedWithoutFinish` | number | Attempts whose stream closed with no finish part, counted per attempt because the retry can still succeed | +| `attemptFailures` | object | Failed attempts by reason: `rateLimited` (429), `serverError` (5xx), `otherHttpError`, `stalled` (no part within the idle timeout) and `other` | +| `failed.failedBeforeFirstToken` | number | Every model failed before a token was sent, answered 503 | +| `failed.failedMidStream` | number | The answer broke after content was already sent, so no retry was possible | +| `failed.abandoned` | number | The client was gone before or during the answer; the only outcome with no response to observe it by | +| `failed.badRequest` | number | Body too large, unparsable, or failing the schema | +| `failed.notConfigured` | number | `INTERNAL_OPENAI_COMPATIBLE_API_BASE_URL` or its key is missing | +| `failed.modelListUnavailable` | number | The upstream's model list could not be fetched | +| `failed.noModelAvailable` | number | The list was fetched and held nothing usable | +| `failed.internalError` | number | Anything the handler did not expect | +| `failed.unclassified` | number | Should always be zero; a non-zero value means a path stopped reporting its outcome | +| `byModel` | array | One entry per model with `attempted`, `streamed`, `failed` and `abandoned`; `attempted` equals the other three added up. Names are not published, since `/status` needs no token: with `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` set, entry _i_ is the model at position _i_ of that list (zero-filled if untried), and with the random pool entries follow first-seen order. That is still how a dead member of the pool becomes visible | `streamed` plus every `failed` entry sums to `requests`. A request refused at token verification is not counted here, since `authorization` above already diff --git a/docs/page-content.md b/docs/page-content.md index 3dd739791a8dd69e42964d66bc64da2439519ed9..692282e0431f495805c56b812485f6273496439a 100644 --- a/docs/page-content.md +++ b/docs/page-content.md @@ -334,13 +334,15 @@ in the same batch gets one probe, not two. What counts as a refusal is the host's doing and nothing else: 401, 403 and 429 (`httpForbidden`), any other non-ok status (`httpOtherError`), a read that -hit the deadline (`timedOut`), and a connection that was refused or dropped -(`failed`). A dead link (`httpNotFound`) is the host answering, a page with too -little text is the page's fault, and a blocked address never reached the host, +hit the deadline (`timedOut`), and a connection that was refused or dropped, or +a redirect to an address that is not a URL (`failed`). A dead link +(`httpNotFound`) is the host answering, a page with too little text is the +page's fault, a document the host served but that could not be parsed +(`unparsable`) is the document's, and a blocked address never reached the host, so none of those count, and any of them ends a run of refusals the way a read -that worked does. A redirect counts for the host that sent it as an answer; -the chain is then judged again at the host it lands on, and stops there if that -host is boxed. +that worked does. A redirect counts for the host that sent it as an +answer; the chain is then judged again at the host it lands on, and stops there +if that host is boxed. The circuit is keyed on `url.host` once `resolvePublicUrl` has cleared it, so the breaker only ever holds hosts the instance was going to fetch from. Its @@ -377,6 +379,7 @@ this limit set where it should be", not "who read what": | `averageReadMs` | Is a 6 s deadline generous or stingy | | `skipped.timedOut` | How much is being lost to that deadline | | `skipped.tooLittleText` | Is the 200-character floor discarding real pages, or is the extractor missing their text | +| `skipped.unparsable` | How many documents arrive that cannot be read. Kept apart from `failed` so they never box a host | | `skipped.notADocument` | Are useful content types being turned away | | `skipped.blocked` | Are callers aiming at private space, deliberately or otherwise | | `skipped.httpForbidden` | How often bot walls or rate limits turn the instance away (401, 403, 429) | @@ -412,6 +415,7 @@ grounded on before: | Other HTTP error (5xx, other non-ok status) | That page is skipped (`httpOtherError`) | | Host refused the last three reads | That page is skipped without a request for five minutes, then one read probes the host (`skippedByBreaker`) | | Page yields less than 200 characters | That page is skipped (`tooLittleText`) | +| Document cannot be parsed (a locked PDF) | That page is skipped (`unparsable`); the host is not boxed for it | | `/page-content` fails or times out | Answer falls back to snippets | | Setting turned off, or AI responses off | No page is ever read | | A newer search starts while pages are still being read | The late result is dropped instead of grounding the new answer | diff --git a/docs/search-history.md b/docs/search-history.md index 0429973596b74d1025eb43704c3ba606dc51e014..ef2299f5a26f67a51bf63d268cb03d31e557aa91 100644 --- a/docs/search-history.md +++ b/docs/search-history.md @@ -12,6 +12,8 @@ The `HistoryDatabase` Dexie instance stores three related tables: 2. `llmResponses` – snapshot of every AI answer tied to its originating search run, enabling restoration of the assistant output. 3. `chatHistory` – chronological record of chat turns (user/assistant roles) scoped by `conversationId` (the `searchRunId`). +A pinned search carries `pinned: true` and a `pinnedAt` timestamp, and `togglePin` writes both in one update. Schema version 3 indexes `pinnedAt` in place of `pinned`: IndexedDB does not index boolean values, so the `pinned` index never held an entry, while an entry without `pinnedAt` simply stays out of its index. The version 3 upgrade gives searches pinned before it a `pinnedAt` equal to their own `timestamp`, since their real pin time is unknown. + All three tables share a `searchRunId` foreign key so restoring a specific run can bring back the search results, saved AI response, and chat transcript atomically. ## Disabled History @@ -34,6 +36,7 @@ Cleanup is gated by `historyAutoCleanup`, so advanced users can opt out. These k - Fetches recent searches (optionally paginated) and exposes filtered/grouped views. - Provides fuzzy search, pin toggling, delete/clear operations, and error retry helpers. +- With `includeAllPinned`, also loads every pinned entry through `getPinnedSearches()` and keeps it in the filtered list past `limit`, however many newer searches exist. Cleanup never deletes a pinned entry, so a recent-only window would hide old ones for good. The read uses the `pinnedAt` index, which holds pinned entries only, so it does not grow with the history; only the History Drawer, which mounts while open, asks for it. - Keeps derived state such as grouped sections (Today/Yesterday/etc.) in sync with the settings flag `historyGroupByDate`. - Refreshes itself on an interval so the History UI stays live even if other tabs mutate the DB. @@ -41,7 +44,7 @@ Because the hook writes via Dexie directly, any component can call `addSearchToH ## UI Surfaces -- **History Drawer** – wraps the hook data in a drawer with filtering, pin/delete affordances, grouped stacks, and an Analytics tab powered by `SearchStats` in compact mode. The drawer guards against disabled history settings and mirrors the hook filtered list in real time. +- **History Drawer** – wraps the hook data in a drawer with filtering, pin/delete affordances, grouped stacks, and an Analytics tab powered by `SearchStats` in compact mode. The drawer guards against disabled history settings, mirrors the hook filtered list in real time, and lists every pinned search in its Pinned section, however old. - **History Button** – lazy-loads the drawer and logs open/close events for observability. - **History Restore** – the `useHistoryRestore` hook recreates full search state (query string, search results, AI response, and chat transcript) when a user replays an entry. diff --git a/docs/security.md b/docs/security.md index ccc91eb2087c4c23a99c7f18361b9a40867eac97..24e3f648e4030aeb3eae09663d74f9c55eaf94b8 100644 --- a/docs/security.md +++ b/docs/security.md @@ -15,6 +15,7 @@ 4. On success: key hash is stored in localStorage with timestamp 5. On subsequent loads, `useAccessKeyValidation` in `App.tsx` calls `verifyStoredAccessKey()` to check if the cached key is still valid 6. If expired (based on `ACCESS_KEY_TIMEOUT_HOURS`), user is prompted to re-enter +7. The stored hash is deleted only when it has expired, cannot be read, or the server answers `{"valid":false}`. When the server gives no verdict (it is unreachable, rate-limits the call, or a proxy answers with an error page), the hash is kept and the check is repeated on the next load, so a passing outage does not make the user retype a key that is still good. Access stays closed for that load either way. Whether access keys are enabled is read at runtime from `/api/config`. When that request fails, the app shell refuses to render rather than assuming access keys @@ -45,10 +46,10 @@ Every HTTP request from client to backend carries a `token` query parameter for - **Local-First Storage**: All data stored in IndexedDB, no cloud sync - **No Tracking**: No telemetry, analytics, or user tracking - **SearXNG Integration**: All web searches routed through privacy-focused metasearch, which holds for every search as long as `SEARCH_FALLBACK_ENABLED` is off (the default); with it on, a text search that found SearXNG failed goes to the fallback providers instead, and an image search never does -- **The Fallback Sends The Query To A Third Party When It Is On**: With `SEARCH_FALLBACK_ENABLED` on (off by default), a text query whose SearXNG search failed is sent to the providers `SEARCH_FALLBACK_PROVIDERS` lists (Parallel and You.com when it is empty, plus Keenable when its key is set): `search.parallel.ai` (Parallel), You.com's MCP endpoint (`https://api.you.com/mcp`) and Keenable's MCP endpoint (`https://api.keenable.ai/mcp`, or `/mcp-public` without a key). They are tried one after the other, in a random order, until one returns results, so a single search can reach more than one provider. Each provider that is tried sees the query text and the server's IP address. The user's IP address is never sent, because the request leaves from the server rather than from the browser. The query is still never written to the server log, and neither is any provider's error text; what `/status` publishes for this feature is the two counts `searchesServedByFallback` and `searchesFailedOnFallback` and the per-provider counters under `searches.fallbackProviders`, none of which carries a query. The provider names there are configured infrastructure, not anything a user typed +- **The Fallback Sends The Query To A Third Party When It Is On**: With `SEARCH_FALLBACK_ENABLED` on (off by default), a text query whose SearXNG search failed is sent to the providers `SEARCH_FALLBACK_PROVIDERS` lists (all three when it is empty: Parallel, You.com and Keenable): `search.parallel.ai` (Parallel), You.com's MCP endpoint (`https://api.you.com/mcp`) and Keenable's MCP endpoint (`https://api.keenable.ai/mcp`, or `/mcp-public` without a key). They are tried one after the other, in a random order, until one returns results, so a single search can reach more than one provider. Each provider that is tried sees the query text and the server's IP address. The user's IP address is never sent, because the request leaves from the server rather than from the browser. The query is still never written to the server log, and neither is any provider's error text; what `/status` publishes for this feature is the two counts `searchesServedByFallback` and `searchesFailedOnFallback` and the per-provider counters under `searches.fallbackProviders`, none of which carries a query. The provider names there are configured infrastructure, not anything a user typed - **Browser-Only Mode Still Downloads Models From HuggingFace**: The instance sends no telemetry and no analytics. But browser-only mode is not fully offline: wllama (for both the chat models and the dictation model) and the local text-to-speech engine fetch their models from `huggingface.co` (served from `us.aws.cdn.hf.co`), so that host sees the user's IP. The text-to-speech engine's full host list is in the Reading Answers Aloud bullet below. - **Page Reading Is On By Default, And Reversible**: `enablePageContentFetch` ships on and the user can turn it off under AI Settings; nothing is read until AI responses are enabled, and the server (never the browser) requests the top result pages, so those sites see the instance and no user cookies or IP -- **Search And Page Reading Leave No Query In The Log**: The search query is never written to the server log, and neither is the URL of a page read for grounding; how often searches come back empty, fail on unresponsive engines, are fully discarded, are served by the fallback or lose the fallback too, and how page reads ended, are counted instead and reported on `/status` (`searchesWithoutResults`, `searchesWithUnresponsiveEngines`, `searchesWithAllResultsDiscarded`, `searchesServedByFallback`, `searchesFailedOnFallback`, `pageReads`). `searches.unresponsiveEngines` names the engines behind those failures, which is configured infrastructure rather than anything a user typed, the same basis on which `inference.byModel` names model ids. What each failed with is published as one of `blocked`, `timeout` or `other`, never SearXNG's own wording: `/status` needs no token, and an upstream engine is free to build its error text out of the request URL, and so out of the query. The raw string stays in the server log and in the thrown error the search endpoint catches; the 502 it answers with carries a fixed message, so the string never leaves the server. The page reader's per-host circuit breaker (`server/pageReadHostBreaker.ts`) holds the hosts it has boxed in memory, since it needs them to know which host to skip; a page-read host comes from the search results, downstream of the query, so unlike an engine name it is never published: `/status` reports how many reads were skipped and how often a host was boxed, as counts only. Anything in front of the instance keeps its own access log, where `?q=` appears in full +- **Search And Page Reading Leave No Query In The Log**: The search query is never written to the server log, and neither is the URL of a page read for grounding; how often searches come back empty, fail on unresponsive engines, are fully discarded, are served by the fallback or lose the fallback too, and how page reads ended, are counted instead and reported on `/status` (`searchesWithoutResults`, `searchesWithUnresponsiveEngines`, `searchesWithAllResultsDiscarded`, `searchesServedByFallback`, `searchesFailedOnFallback`, `pageReads`). `searches.unresponsiveEngines` names the engines behind those failures, which is configured infrastructure rather than anything a user typed. Model ids are not published at all: `inference.byModel` is an array in the order of `INTERNAL_OPENAI_COMPATIBLE_API_MODEL` (first-seen order with the random pool), because `/status` needs no token and naming the internal pool would tell whoever probes it which upstream models to target. What each failed with is published as one of `blocked`, `timeout` or `other`, never SearXNG's own wording: `/status` needs no token, and an upstream engine is free to build its error text out of the request URL, and so out of the query. The raw string stays in the server log and in the thrown error the search endpoint catches; the 502 it answers with carries a fixed message, so the string never leaves the server. The page reader's per-host circuit breaker (`server/pageReadHostBreaker.ts`) holds the hosts it has boxed in memory, since it needs them to know which host to skip; a page-read host comes from the search results, downstream of the query, so unlike an engine name it is never published: `/status` reports how many reads were skipped and how often a host was boxed, as counts only. Anything in front of the instance keeps its own access log, where `?q=` appears in full - **Dictation: Which Engine Runs, And Where The Audio Goes**: The dictation button, which sits inside the search field and inside the chat follow-up field, has two engines. The on-device engine records the microphone in the page and, once the user stops, transcribes the recording with the Qwen3-ASR 0.6B model running in wllama; the audio never leaves the device. The browser engine is the browser's own `SpeechRecognition`, which sends audio to the browser vendor. Which one runs is decided by `enableLocalDictationModel`, which defaults to on. The preference reorders the engines and never removes one: on browsers without `SpeechRecognition` the on-device model runs regardless. When the preferred engine cannot run, the switch from on-device to browser happens only while the local model is on, and a notification announces it because the audio's destination changed; the reverse never happens, so a user who turned the model off never gets a surprise ~700 MB download after a recognizer failure. A denied microphone is never retried on the browser engine, since that is the user's answer rather than an engine that cannot run. Nothing loads until the button is pressed, so a user who never dictates pays nothing for the feature. The model is fetched from `huggingface.co` the same way the chat models are, from a URL pinned to one commit of the repository, so an upstream re-upload cannot change what users download; wllama keeps it in the origin's private file system, and that host sees the user's IP until one download completes; a press abandoned mid-download aborts it, and the next press starts it over. The microphone opens only after the model has loaded, so a first-run download never lights the browser's recording indicator. The browser asks for microphone permission on the first press; a denied permission shows a notification instead of failing quietly, on either engine. On the browser engine the denial arrives after the session has started, so it is reported through the same notification rather than the press simply failing. When neither engine is available, or the page is not in a secure context, the button hides. Users can turn the feature off with `enableDictation` in the Voice settings @@ -87,25 +88,25 @@ The full trust model lives in [`.github/SECURITY.md`](../.github/SECURITY.md) (" ## Server-Side Security Modules -| Module | Purpose | -| ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `server/searchToken.ts` | Generates the CSRF token per process and records it in `{tempdir}/minisearch-token` | -| `server/verifiedTokens.ts` | In-memory `Set` of verified session tokens | -| `server/rejectedTokens.ts` | Bounded in-memory set of tokens that already failed a completed verification, so a replay skips the second argon2 check | -| `server/searchesSinceLastRestart.ts` | In-memory counters for aggregate search outcomes (text/image search totals, and how often searches came back empty or were fully discarded), plus per-engine failure counts, reported on `/status`; records no query, URL, host, or per-search timestamp, and stores a failure kind classified by `server/webSearchService.ts` rather than SearXNG's reason string | -| `server/pageReadsSinceLastRestart.ts` | In-memory aggregate counters for pages read for grounding (outcomes, durations, passage ratios), reported on `/status`; records no query, URL, host, or per-read timestamp | -| `server/pageReadHostBreaker.ts` | Per-host circuit breaker for page reads: a host that refused the last three reads is skipped for five minutes, then probed with one read; holds host names in memory only, reset on restart, and reports counts alone | -| `server/searchExcerptStore.ts` | Holds the excerpts a fallback provider sent with its results for five minutes (at most 500), under a SHA-256 of the query and the URL, so `/page-content` uses them instead of reading those pages; holds no query or URL in clear text | -| `server/searchEndpointServerHook.ts` | Proxies text/image search to SearXNG after token verification (via `handleTokenVerification`), and serves fallback text results when SearXNG has failed and `SEARCH_FALLBACK_ENABLED` is on | -| `server/fallbackSearchService.ts` | Second text-search source, consulted only after SearXNG has failed: reads `SEARCH_FALLBACK_ENABLED`, `SEARCH_FALLBACK_PROVIDERS` and the per-provider keys at call time, and refuses to start on an unknown provider name or a removed variable; runs the JSON-RPC exchange against `search.parallel.ai`, You.com's MCP endpoint and, when opted in, Keenable's MCP endpoint in a random order per search, one after the other until one returns results, under one shared 15-second budget; pauses a provider that answered 429 until its `Retry-After`; and maps the reply into the tuples the SearXNG path produces; records no query | -| `server/verifyTokenAndRateLimit.ts` | Verifies the Argon2 token hash and enforces rate limiting (10 requests per 10 seconds, shared by the search, page-content and inference endpoints; a separate 60-per-10-seconds budget for `/thumbnail`) | -| `server/handleTokenVerification.ts` | Middleware bridge that calls `verifyTokenAndRateLimit` and writes 400/401/429 error responses for the search, page-content, thumbnail and inference endpoints | -| `server/configEndpointServerHook.ts` | Serves the non-secret runtime config at `/api/config`, including whether access keys are enabled | -| `server/utils/publicUrl.ts` | Rejects non-HTTP schemes and hosts resolving into private, loopback, link-local or reserved ranges before the server fetches a client-supplied URL; `resolvePublicUrlAndAddress` also hands back the vetted IP so the caller can pin the connection to it | -| `server/utils/pinnedFetch.ts` | Fetches a vetted URL over a socket pinned to the vetted IP, with the original hostname preserved for TLS SNI, certificate verification and the `Host` header, so the address checked is the address reached (closes the DNS-rebinding window between check and connect) | -| `server/utils/requestUrl.ts` | Parses the request URL against a fixed base instead of the `Host` header, and answers 400 to a `Host` that is present but malformed. Without it, one unauthenticated request with `Host: bad host` made the search, page-content, thumbnail and inference hooks throw inside async middleware, which exits the process | -| `server/pageContentEndpointServerHook.ts` | Reads result pages at `/page-content` after token verification, capped at 6 URLs per request | -| `server/thumbnailEndpointServerHook.ts` | Serves one search-result thumbnail at a time at `/thumbnail` after token verification, connecting only to the vetted pinned address, with an in-process LRU in front of the upstream host | +| Module | Purpose | +| ----------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `server/searchToken.ts` | Generates the CSRF token per process and records it in `{tempdir}/minisearch-token` | +| `server/verifiedTokens.ts` | In-memory `Set` of verified session tokens | +| `server/rejectedTokens.ts` | Bounded in-memory set of tokens that already failed a completed verification, so a replay skips the second argon2 check | +| `server/searchesSinceLastRestart.ts` | In-memory counters for aggregate search outcomes (text/image search totals, and how often searches came back empty or were fully discarded), plus per-engine failure counts, reported on `/status`; records no query, URL, host, or per-search timestamp, and stores a failure kind classified by `server/webSearchService.ts` rather than SearXNG's reason string | +| `server/pageReadsSinceLastRestart.ts` | In-memory aggregate counters for pages read for grounding (outcomes, durations, passage ratios), reported on `/status`; records no query, URL, host, or per-read timestamp | +| `server/pageReadHostBreaker.ts` | Per-host circuit breaker for page reads: a host that refused the last three reads is skipped for five minutes, then probed with one read; holds host names in memory only, reset on restart, and reports counts alone | +| `server/searchExcerptStore.ts` | Holds the excerpts a fallback provider sent with its results for five minutes (at most 500), under a SHA-256 of the query and the URL, so `/page-content` uses them instead of reading those pages; holds no query or URL in clear text | +| `server/searchEndpointServerHook.ts` | Proxies text/image search to SearXNG after token verification (via `handleTokenVerification`), and serves fallback text results when SearXNG has failed and `SEARCH_FALLBACK_ENABLED` is on | +| `server/fallbackSearchService.ts` | Second text-search source, consulted only after SearXNG has failed: reads `SEARCH_FALLBACK_ENABLED`, `SEARCH_FALLBACK_PROVIDERS` and the per-provider keys at call time, and refuses to start on an unknown provider name or a removed variable; runs the JSON-RPC exchange against `search.parallel.ai`, You.com's MCP endpoint and Keenable's MCP endpoint in a random order per search, one after the other until one returns results, under one shared 15-second budget; pauses a provider that answered 429 until its `Retry-After`; and maps the reply into the tuples the SearXNG path produces; records no query | +| `server/verifyTokenAndRateLimit.ts` | Verifies the Argon2 token hash and enforces rate limiting (10 requests per 10 seconds, shared by the search, page-content and inference endpoints; a separate 60-per-10-seconds budget for `/thumbnail`) | +| `server/handleTokenVerification.ts` | Middleware bridge that calls `verifyTokenAndRateLimit` and writes 400/401/429 error responses for the search, page-content, thumbnail and inference endpoints | +| `server/configEndpointServerHook.ts` | Serves the non-secret runtime config at `/api/config`, including whether access keys are enabled | +| `server/utils/publicUrl.ts` | Rejects non-HTTP schemes and hosts resolving into private, loopback, link-local or reserved ranges before the server fetches a client-supplied URL; `resolvePublicUrlAndAddress` also hands back the vetted IP so the caller can pin the connection to it | +| `server/utils/pinnedFetch.ts` | Fetches a vetted URL over a socket pinned to the vetted IP, with the original hostname preserved for TLS SNI, certificate verification and the `Host` header, so the address checked is the address reached (closes the DNS-rebinding window between check and connect) | +| `server/utils/requestUrl.ts` | Parses the request URL against a fixed base instead of the `Host` header, and answers 400 to a `Host` that is present but malformed. Without it, one unauthenticated request with `Host: bad host` made the search, page-content, thumbnail and inference hooks throw inside async middleware, which exits the process | +| `server/pageContentEndpointServerHook.ts` | Reads result pages at `/page-content` after token verification, capped at 6 URLs per request | +| `server/thumbnailEndpointServerHook.ts` | Serves one search-result thumbnail at a time at `/thumbnail` after token verification, connecting only to the vetted pinned address, with an in-process LRU in front of the upstream host | ### Server-Side Fetching of Client-Supplied URLs @@ -173,7 +174,7 @@ pin and keeps the old rebinding residual. ## Threat Model - **Local Environment**: Assumes trusted local execution -- **Network Requests**: All external requests go through SearXNG proxy, except a text search whose SearXNG search failed, which goes to the fallback providers `SEARCH_FALLBACK_PROVIDERS` lists (`search.parallel.ai`, You.com's MCP endpoint and, when opted in, Keenable's MCP endpoint, one after the other until one returns results, so possibly more than one per search), and only when `SEARCH_FALLBACK_ENABLED` is on (off by default) +- **Network Requests**: All external requests go through SearXNG proxy, except a text search whose SearXNG search failed, which goes to the fallback providers `SEARCH_FALLBACK_PROVIDERS` lists (`search.parallel.ai`, You.com's MCP endpoint and Keenable's MCP endpoint, one after the other until one returns results, so possibly more than one per search), and only when `SEARCH_FALLBACK_ENABLED` is on (off by default) - **AI Models**: Models run locally or through trusted providers - **Data Exfiltration**: Prevented by local-first architecture