diff --git a/.env.example b/.env.example index 88b759a0da7fa4fc5672395b5a1888d9f1dfb1cb..ed6f446fd372b2ecfedd99f3bdb7ae2f272d74bc 100644 --- a/.env.example +++ b/.env.example @@ -32,7 +32,7 @@ DEFAULT_INFERENCE_TYPE="browser" # Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on. SEARCH_FALLBACK_ENABLED="false" -# Comma-separated list of the second search providers to try: "parallel", "youcom", or both. Empty means all of them. 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 Parallel and You.com, plus Keenable when its key is set. With the fallback enabled, an unknown name stops the server at start. SEARCH_FALLBACK_PROVIDERS="" # The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use. @@ -41,5 +41,8 @@ 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. +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. SEARCH_OFFICIAL_LANE_ENABLED="false" diff --git a/.github/workflows/reusable-check-docker.yml b/.github/workflows/reusable-check-docker.yml index 331ba1c7a1dc95b7deb39f96d360429fde883675..829ca965de46923381e4d3aa7e42011ba49a4cc2 100644 --- a/.github/workflows/reusable-check-docker.yml +++ b/.github/workflows/reusable-check-docker.yml @@ -17,7 +17,7 @@ jobs: - run: docker compose -f docker-compose.production.yml up -d - name: Check if main page is available run: until curl -s -o /dev/null -w "%{http_code}" localhost:"$PORT" | grep 200; do sleep 1; done - timeout-minutes: 1 + timeout-minutes: 3 - uses: actions/setup-node@v7 with: diff --git a/agents.md b/agents.md index f73126665576cdc5515272d3a2bdfc9bd10b9e7d..0767fc2539da3482bc4ba1977f6024ce50e4c0a5 100644 --- a/agents.md +++ b/agents.md @@ -82,7 +82,7 @@ Need to: ### Entry Points - `client/index.tsx` - React app initialization -- `vite.config.ts` - Vite dev server with hooks +- `vite.config.ts` - Vite dev server with hooks. There is no standalone server entry point: every `server/*ServerHook.ts` is a connect middleware this file mounts through `configureServer` (dev) and/or `configurePreviewServer` (preview and production). To exercise an endpoint locally, run `npm run dev`, or `npm run build && npm run preview`; the Docker image serves `npm start`, which is `vite preview`. - `Dockerfile` - Single-stage container build ### Business Logic Modules @@ -161,14 +161,16 @@ Need to: - `server/statusEndpointServerHook.ts` - `/status` health check endpoint - `server/configEndpointServerHook.ts` - `/api/config` runtime client configuration - `server/rerankerServiceHook.ts` - Reranker model lifecycle management +- `server/biEncoderServiceHook.ts` - Starts and stops the bi-encoder service with the server; the bi-encoder scores query-passage relevance for page reading (`server/pageContentService.ts`) - `server/compressionServerHook.ts` - gzip/brotli compression for responses - `server/crossOriginServerHook.ts` - COOP/COEP headers for SharedArrayBuffer - `server/cacheServerHook.ts` - Cache-Control headers (preview server only) - `server/webSearchService.ts` - SearXNG integration with circuit breaker and retry logic -- `server/fallbackSearchService.ts` - Fallback text-search cascade over Parallel and You.com for when SearXNG fails and `SEARCH_FALLBACK_ENABLED` is on, with a per-provider pause after a 429 +- `server/fallbackSearchService.ts` - Fallback text-search cascade over Parallel, You.com and opt-in Keenable for when SearXNG fails and `SEARCH_FALLBACK_ENABLED` is on, with a per-provider pause after a 429 - `server/pageContentService.ts` - Reads result pages and extracts query-relevant passages - `server/pageReadHostBreaker.ts` - Per-host circuit breaker for page reads: skips a host that refused the last three reads, then probes it once - `server/utils/publicUrl.ts` - Blocks private and reserved addresses before a server-side fetch +- `server/utils/requestUrl.ts` - Parses a request URL against a fixed base and refuses a malformed `Host` header, so the endpoint hooks cannot crash on one - `server/rerankerService.ts` - Reranker service (ONNX Runtime inference) - `server/rankSearchResults.ts` - Score-based filtering and result reordering - `server/searchToken.ts` - CSRF token generation and storage @@ -183,6 +185,7 @@ Need to: - `client/hooks/useSearchHistory.ts` - Search history management from IndexedDB - `client/hooks/useHistoryRestore.ts` - Restores full search state from history - `client/hooks/useDrawerState.ts` - Drawer open/close state with logging +- `client/hooks/useSettingsForm.ts` - Mantine form over a list of settings keys that writes only the keys that changed - `client/hooks/useScreenWakeLock.ts` - Keeps the screen awake while a response is generating ## Common Tasks Quick Reference @@ -199,7 +202,7 @@ Need to: ### Add a new setting 1. Add to `client/modules/settings.ts` default object -2. Add UI in `client/components/Pages/Main/Menu/` +2. Add UI in `client/components/Pages/Main/Menu/`, and add its key to that form's `useSettingsForm` keys 3. Update `docs/configuration.md` settings table ### Modify search behavior @@ -226,11 +229,12 @@ Before any change: ```bash npm run lint +npx vitest run ``` -Inside the dev container, the same command is `docker compose exec development-server npm run lint`. +Inside the dev container, prefix either command with `docker compose exec development-server`. -This runs: +`npm run lint` runs: - Biome (formatting/linting) - TypeScript (type checking) @@ -251,6 +255,19 @@ The project is split across three TypeScript configs, and the default one covers So `npx tsc --noEmit` reports success while type errors sit in `server/` or `eval/`, and CI then fails on a change that looked clean locally. Only `npm run lint` runs all three configs. Never treat a bare `tsc` as a green typecheck. +### node_modules can be stale relative to the lockfile + +When you verify behavior by reading a dependency's source in `node_modules`, check the installed version against the lockfile first: + +```bash +node -p "require('./node_modules//package.json').version" +node -p "require('./package-lock.json').packages['node_modules/'].version" +``` + +A checkout can lag the lockfile by a major version, and the behavior you read is then not the behavior CI runs. Run `npm ci` when the two disagree. + +Some dependencies also ship their own `AGENTS.md` (for example `node_modules/@wllama/wllama/AGENTS.md`). That is the dependency's contributor guide, not this repository's. Ignore it. + ## Agent-First Principles **Repository as System of Record:** diff --git a/changelog.md b/changelog.md index 174d5b5aedcfd408634e6b3f0dad60f75ba90a5f..3faac405341a244155103dfb6ddf7ed1915f3191 100644 --- a/changelog.md +++ b/changelog.md @@ -2,10 +2,61 @@ Notable changes, grouped by date, most recent first. +## 2026-11-24 + +- Changing a setting in one section of the menu no longer undoes a change made in another. The AI, Search, Interface, History and Voice forms each kept a copy of every setting from the moment the menu opened and wrote the whole copy back on each change, so turning off Text Search and then switching Enter to Submit switched Text Search back on, and a model the app had fallen back to during a search was replaced by the one the menu opened with. Each form now writes only the settings it changed. +- The search fallback can use Keenable as a third provider. It is opt-in: it joins the default list only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set, or when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, in which case its keyless endpoint is used without a key. Instances that already run the fallback keep Parallel and You.com as before. +- Removing a search from the history now removes its AI answer and chat with it. Automatic cleanup, by age or by the entry limit, and deleting a single entry used to delete only the search, so its answer and chat stayed in the browser's storage for good, out of reach of the History drawer. Follow-up question suggestions also no longer write chat rows that nothing reads, and the rows that earlier versions left behind are removed once, the first time the app opens after this update. Pinned searches keep everything. +- A search that fails now says why in the log. A timeout while the results were still arriving was reported as a JSON parsing error, and a dropped connection got no network label in any browser, because the check looked for the word "network" and Chrome, Firefox and Safari each word it differently. Both are now named where they happen, so the log shows a timeout as a timeout and a network failure as one, also on the line that says it served results from a previous search. +- An AI Horde answer no longer fails, or submits extra jobs, because of a passing rate limit or server error while it waits. A 429 or 5xx on a status check was read as "Generation not possible with the selected model", and in automatic mode that sent two fresh jobs to any model, doubling the kudos spent. Such a check is now retried, waiting a little longer each time, and the answer fails only after five in a row, with the server's reason and without the extra jobs. A job that is gone ends right away with Horde's message, a finished job with no text says "No text generated", and a refused API key now shows Horde's reason instead of "Failed to start generation". +- A page whose address lookup never comes back no longer holds up page reads past their 6 second limit. The lookup ran outside that limit, once per redirect, so a stuck DNS resolver could stretch a single page read to tens of seconds and delay the AI answer waiting on the batch. The lookup now counts against the same 6 seconds, the read is counted as timed out instead of blocked, and three of them in a row make the server skip that site for a while, as it already does for sites that time out. +- Editing a question or regenerating the last answer now works when an earlier AI answer in the chat is empty. An empty answer, which is saved when a response stream ends with no text, shifted the positions the chat used, so the Re-generate button disappeared from the last answer and Edit on a later question loaded a different, earlier question and cut the chat back to it. +- A collapsed citation link in an AI answer now shows the right first character. A link whose text is bold or code, such as **Reuters**, showed `[` instead of `R`, and a link starting with an emoji showed `οΏ½`. The pill now takes the first visible character, and keeps an emoji, a flag or a combined emoji such as πŸ‘©β€πŸ’» whole. +- Daily Average in the History analytics now counts days by your local calendar, like Most Active Hour and the activity heatmap. It used to split days at UTC midnight, so outside UTC, searches made late at night or early in the morning could land on a different day, lower the average and disagree with the heatmap's active days. +- Image results hosted on Wikimedia (`upload.wikimedia.org`) now show their thumbnails. The server fetched thumbnails without saying who it was, and Wikimedia refuses such requests, so those results showed the site's name instead of the picture. Thumbnail requests now identify themselves as MiniSearch, the same way page reads already did. +- An image-result thumbnail larger than 500 KB is no longer shown cut off. The server used to send the first 500 KB of it as if it were the whole image and keep that copy for an hour, so the tile showed a damaged picture (a JPEG lost everything below the cut, other formats could fail to show at all). Such a thumbnail is now refused, and the tile shows the site's name, like other thumbnails that cannot be loaded. +- Turning off "Enable Search History" now stops saving searches. After a reload with the setting off, every search, its results, the AI answer and follow-up chat messages were still written to the browser's storage, while the History drawer that could show or delete them stayed hidden. Nothing is read from or written to the history while the setting is off. +- Clearing the context length, CPU threads, history max entries or history retention field no longer saves an empty value. It now falls back to the default number, and an empty value already saved in the browser is repaired when the app loads, so AI answers keep their token budget and history cleanup keeps running. +- Requests to an OpenAI-compatible backend and to the internal API no longer ask for an answer as long as the whole context window. `max_tokens` used to be the full Context Length, so prompt plus answer could not fit, and backends that check the sum rejected the request or cut the answer short. It is now what the window has left after the prompt, at least 64 tokens, measured against the same window the page excerpts and chat history use. +- A bi-encoder worker that stays alive but stops answering no longer stalls page content reads. Its scoring requests waited with no deadline, so every later read queued behind it, AI answers waited out the browser's 20 second timeout and lost their page excerpts until the server restarted. A scoring request now gets 10 seconds, after which the passages are ranked lexically, as when the model is not loaded, and the log says so. +- Restoring a saved search that has no saved results and no saved answer (a failed search, a search with zero results and AI answers off, an abandoned search) no longer appends a duplicate entry to the history nor starts a new live search. The same happened when Regenerate was clicked, or the "enable AI response" prompt accepted, after restoring an entry. The restored query is now treated as handled, like a submitted or auto-searched one. +- When the browser blocks site data (for example Safari "Block All Cookies" or Chrome "sites can't save data"), the app no longer crashes on load with a blank page. Settings and other persisted values stay in memory for the session and simply do not write through. + +- Search results, page contents, AI answers, the status report and access key checks are now sent with `Cache-Control: no-store`, errors included, so a shared cache or proxy in front of the server can no longer keep them. In production the access key and AI answer responses used to be marked as publicly cacheable for 24 hours, and the search, page content and status responses carried no caching directive at all. The AI answer stream changes from `no-cache` to `no-store`. +- "Clear all data" now finishes resetting and reloads the page even when Cache Storage is unavailable (such as on a plain HTTP LAN deployment) or when clearing a cache or the in-browser AI model cache fails. It also releases the temporary Wllama worker after clearing the model cache instead of leaving it alive until the reload. +- A failed or empty conversation summary fold no longer erases the summary already built for a long chat. When summarizing older turns fails and the fallback returns empty (for example after dropping a very long message) or the model returns an empty summary, MiniSearch keeps the existing stored summary and includes it in the prompt for the current turn. +- Restoring a saved search from history no longer turns off follow-up question suggestions for the rest of the session. Sending a chat message in the restored conversation or starting a new search now generates follow-up suggestions again, restoring an entry with no saved answer no longer suppresses them, and a follow-up question still generating from a previous search is cancelled so it cannot land in the restored session. +- A missing file under `/assets/` is no longer sent with a one-year immutable cache header. During a partial deploy, or for an outdated link, the server answered such a request with the app page or a 404 marked immutable, so browsers could keep that wrong answer for the asset's URL for a year. Only files that exist in the build are now marked immutable; anything else under `/assets/` gets `no-cache`. +- A search that found nothing is no longer reported as failed when the query has no keywords. A query made only of common words, such as "how about that", used to be retried with its keywords after finding no results; with none left, the retry sent an empty query, which was rejected, so the search showed as failed and, with AI answers on, ran the image fallback meant for outages. The retry is now skipped and the search completes with no results. A query over 2000 characters with no keywords is now searched without its surrounding spaces when that fits, and otherwise completes with no results instead of failing. A failed text search now also leaves a log entry with its error. +- A relative date in a search query is now recognised the way people type it. "next year’s champion" with a curly apostrophe, the default on iPhone and Mac, no longer gets a year added, and a non-breaking or double space no longer hides "next year". A date the query already carries in another spelling ("2026 December", "Dec 2026", "2026-12") is not appended again, and a year inside a longer number such as "120265" is no longer taken for one. A follow-up search that is only a year no longer starts with a space, which gave the same search two cache entries. + ## 2026-11-23 +- A request with a malformed `Host` header, such as `Host: bad host`, no longer shuts the server down. The search, page content, thumbnail and AI inference endpoints used to build the request URL from that header, so one unauthenticated request made the server exit; they now answer 400 and keep serving. The thumbnail endpoint answered 500 for the same request before. The `/status` endpoint also answers a 500 instead of exiting when the build's commit hash define is malformed. +- Saved searches in the History drawer can now be restored with the keyboard. The query used to be a plain card that only a click could activate, so Tab skipped it; it is now a button that Enter and Space activate, separate from the pin and delete buttons. +- When the in-browser AI model fails during its warm-up, the model and its worker are now released, so the failed start no longer keeps the model's memory allocated until the page is reloaded. The original error is still the one reported, and the log says if the release itself failed. +- When the access key cannot be checked because the server is unreachable, the access page now says "Could not reach the server. Please try again." instead of "Invalid access key", so a network problem no longer looks like a wrong key. Access still stays closed until the key is checked. +- With the AI Horde engine, the answer card and its Stop button now appear as soon as the request is queued, instead of a loading skeleton for the whole wait, which can take minutes. Stop now works during that wait, and it also cancels the queued job on the Horde, so a stopped answer no longer keeps spending kudos. +- The search box placeholder now always shows a suggestion. When the suggestion list could not be loaded, came back empty, or held empty entries in the browser's storage, the placeholder could end up blank; it now falls back to "Anything you need!". The log now names why the list failed to load and how many suggestions were actually stored. +- The "Clear all data" confirmation now says everything it deletes: besides resetting the settings and the cached files (including downloaded AI models), it permanently deletes the saved searches, AI responses and chat messages. It used to mention only the settings and the cache. The note under the button says the same. +- A saved AI backend that the server no longer offers is now switched to one it does. When an operator removed the internal API, a profile that had picked it kept routing answers there, so they failed, and the AI settings showed no backend selected and no way to tell why. The saved choice now moves to the server's default backend, or to running in the browser if the server's default is gone too, and the log says what changed. A choice the server still offers stays as it is, and so does any choice when the server's settings could not be loaded. +- With "Enter to submit" turned off in the interface settings, Shift+Enter now submits the search, as the setting's description says. It used to do nothing, so the search could only be sent with the Search button. The suggested follow-up question in the chat box follows the same setting: Shift+Enter sends it when the setting is off, and Enter adds a new line instead. +- Chat replies now always see the question being asked. When the search results, page excerpts and conversation summary used up the room set aside for the chat, the newest question was folded into the summary with the older messages and the model answered without it, from the summary alone and with no error. With the default settings that happened to any message longer than about 300 tokens, such as a pasted log, and with a large Context Length in the OpenAI-compatible settings it could happen on every turn. Now the question is always sent and only older messages are summarized, the chat history is measured against the configured Context Length instead of always 4096, and a message larger than the whole context fails with an error instead of a reply that ignores it. Follow-up question suggestions no longer overwrite the chat's summary with their own prompt either. +- A follow-up question typed with more than 2000 characters now searches with its first 2000 characters. It used to send the whole text, which the server rejects, so the follow-up got no new search results and only a line in the log. The same limit now also holds for the keyword search the first question falls back to. +- The "Thinking" indicator of the reasoning section no longer keeps animating after an answer stops while the model is still reasoning, for example when you interrupt it, it reaches the token limit or the connection drops. The unfinished reasoning now shows as a collapsed "Thought Process", as do older chat messages that end the same way. +- The in-app log now keeps the newest 1000 entries and drops older ones. It used to grow for as long as the tab stayed open, copying the whole log on every new line, so a long session slowed down logging and the Logs window. The download from the Logs window holds those 1000 entries. +- The AI settings panel no longer crashes when AI Horde answers the user lookup with incomplete data, such as a username without kudos. The answer is now logged as malformed and the API key field shows the anonymous-access hint, as it does for the default key. +- A local model that declares stop strings now has its answer cut at the stop string. Before, the answer was trimmed by the stop string's length from the end of the text, so `abcdefghijklSTOPxyz` with the stop string `STOP` came out as `abcdefghijklSTO`: three characters of the marker stayed in and the text after it was lost. No bundled model declares stop strings yet, so nobody saw this. +- Page bodies of exactly 1,500,000 bytes are no longer counted as truncated in `/status`'s `pageReads.bodiesTruncated`. The text was always complete, only the counter was wrong. +- `ACCESS_KEYS` and `ALLOWED_HOSTS` now ignore spaces around each entry and empty entries, so `key1, key2,` works as written. Before, a key after a comma and a space was never accepted, `ALLOWED_HOSTS="localhost, example.com"` blocked `example.com`, and `ACCESS_KEYS=","` made the app ask every visitor for an access key that no one could enter. +- `/inference`, `/status` and `/thumbnail` now answer only on their exact path. Before, any path that started with the route, such as `/inferences`, `/statuses` or `/thumbnails`, was claimed by the endpoint instead of falling through to the app. +- Search result snippets now reach the AI prompt exactly as written. Before, the prompt's own template rules rewrote them: LaTeX like `$$x^2$$` lost a dollar sign, and a crafted page could inject text that looked like the app's own instructions. Custom prompts that repeat a placeholder now fill every occurrence too. +- The Context Length field in the OpenAI-compatible settings now accepts values below 4096, down to 512, so a model with a 2048-token context can be set up. It used to snap any smaller value back to 4096 when the field lost focus. Its arrows now move in steps of 1024 instead of 4096. The default stays 4096. +- The numpad Enter key now submits the search and sends chat messages, like the main Enter key. Before, it inserted a new line into the text box instead, because the Enter check looked at the physical key (`event.code`) and numpad Enter reports `NumpadEnter`. Shift+Enter behaves the same way for both keys. +- When SearXNG fails and the fallback search answers, the server log now gets two lines instead of four: the engines that failed, and the provider that served the search. A failed thumbnail download is now logged with a timestamp, like the other lines. The log still never names the image's host, since it comes from the search results. - The Docker image now switches on Mojeek in its SearXNG settings. Since the last SearXNG update, the Brave web engine is off by default, which left DuckDuckGo and Google CSE as the only general web engines, and DuckDuckGo often answers a CAPTCHA to servers. Mojeek runs its own index: in a test run it returned 10 results on each of 10 queries, and 7 to 9 of them per query came from no other engine. To keep the old engine set, replace the settings file as described in "Tuning the Search Engines" in `docs/configuration.md`. - When SearXNG fails and the fallback search answers through Parallel, the AI answer now grounds on the text Parallel already sent with each result instead of downloading those pages. Parallel picks excerpts that match the query, a median of about 2,500 characters per result (measured over 30 results), and the result's snippet showed only 400 of them. So those answers wait for no page downloads, and they no longer lose the pages that refuse the server (on the public demo, 48% of page reads failed). `/status` counts these pages under `pageReads.servedFromSearchExcerpts`. +- Reopening a search from history now restores its saved images even when the entry also contains text results. Image-only searches and older history entries still restore as before. ## 2026-11-22 diff --git a/client/components/AiResponse/AiResponseContent.test.tsx b/client/components/AiResponse/AiResponseContent.test.tsx index a42849e6fff511ef16f4919b63b663bfb854382b..4acc5de936f2a33c2794faae78bc4571a86e2803 100644 --- a/client/components/AiResponse/AiResponseContent.test.tsx +++ b/client/components/AiResponse/AiResponseContent.test.tsx @@ -17,8 +17,19 @@ vi.mock("@/modules/textToSpeech", () => ({ })); vi.mock("./FormattedMarkdown", () => ({ - default: ({ children }: { children: string }) => ( -
{children}
+ default: ({ + children, + isGenerating, + }: { + children: string; + isGenerating?: boolean; + }) => ( +
+ {children} +
), })); @@ -70,6 +81,22 @@ describe("AiResponseContent", () => { expect(liveRegion).toHaveAttribute("aria-busy", "false"); }); + it.each([ + ["generating", "true"], + ["interrupted", "false"], + ["completed", "false"], + ])( + "tells the markdown whether the response is generating (%s)", + (state, expected) => { + renderContent(state); + + expect(screen.getByTestId("formatted-markdown")).toHaveAttribute( + "data-generating", + expected, + ); + }, + ); + it("gives the toolbar action icons accessible names while generating", () => { renderContent("generating"); expect( diff --git a/client/components/AiResponse/AiResponseContent.tsx b/client/components/AiResponse/AiResponseContent.tsx index 4d59b934e7ea76fc2edfcd0932bc92444955a2dd..252482ccd4254c92d8d3602f759db286fc23ecca 100644 --- a/client/components/AiResponse/AiResponseContent.tsx +++ b/client/components/AiResponse/AiResponseContent.tsx @@ -160,7 +160,9 @@ export default function AiResponseContent({ - {response} + + {response} + {textGenerationState === "failed" && ( diff --git a/client/components/AiResponse/ChatInputArea.test.tsx b/client/components/AiResponse/ChatInputArea.test.tsx index ec318bd6ba7a47e821cd4541cac9e6b63544b2b2..a577e10a7a51c0ed6d51e25d0f6bbc84a21bcfa7 100644 --- a/client/components/AiResponse/ChatInputArea.test.tsx +++ b/client/components/AiResponse/ChatInputArea.test.tsx @@ -3,7 +3,13 @@ import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useSyncExternalStore } from "react"; import ChatInputArea from "@/components/AiResponse/ChatInputArea"; -import { chatGenerationStatePubSub, chatInputPubSub } from "@/modules/pubSub"; +import { + chatGenerationStatePubSub, + chatInputPubSub, + followUpQuestionPubSub, + settingsPubSub, +} from "@/modules/pubSub"; +import { defaultSettings } from "@/modules/settings"; import { getDictationEngine, startDictation } from "@/modules/speechToText"; vi.mock("@/modules/speechToText", async () => { @@ -145,3 +151,39 @@ it("stops a running session when a response starts generating", async () => { // input the user cannot see or correct. await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1)); }); + +describe("sending the suggested follow-up question", () => { + afterEach(() => { + followUpQuestionPubSub[0](""); + settingsPubSub[0]({ ...defaultSettings }); + }); + + it.each([ + [true, "{Enter}", true], + [true, "{Shift>}{Enter}{/Shift}", false], + [false, "{Shift>}{Enter}{/Shift}", true], + [false, "{Enter}", false], + ])( + "with enterToSubmit %s, pressing %s sends it: %s", + async (enterToSubmit, keys, sends) => { + settingsPubSub[0]({ ...defaultSettings, enterToSubmit }); + followUpQuestionPubSub[0]("What happened next?"); + const handleSend = vi.fn(); + const user = userEvent.setup(); + render( + + {}} handleSend={handleSend} /> + , + ); + + await user.click(screen.getByRole("textbox")); + await user.keyboard(keys); + + if (sends) { + expect(handleSend).toHaveBeenCalledWith("What happened next?"); + } else { + expect(handleSend).not.toHaveBeenCalled(); + } + }, + ); +}); diff --git a/client/components/AiResponse/ChatInputArea.tsx b/client/components/AiResponse/ChatInputArea.tsx index d2cbc173c09ccc14f3f1d02d81e15406e5d138dd..1dca679321c7f169a25e9f95183a2d781676e365 100644 --- a/client/components/AiResponse/ChatInputArea.tsx +++ b/client/components/AiResponse/ChatInputArea.tsx @@ -4,12 +4,14 @@ import { usePubSub } from "create-pubsub/react"; import DictationButton, { dictationButtonWidth, } from "@/components/DictationButton"; +import { handleEnterKeyDown } from "@/modules/keyboard"; import { chatGenerationStatePubSub, chatInputPubSub, followUpQuestionPubSub, getChatInput, isRestoringFromHistoryPubSub, + settingsPubSub, suppressNextFollowUpPubSub, } from "@/modules/pubSub"; @@ -34,6 +36,7 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { const [followUpQuestion] = usePubSub(followUpQuestionPubSub); const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub); + const [settings] = usePubSub(settingsPubSub); const isGenerating = generationState.isGeneratingResponse && @@ -51,23 +54,17 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) { const handleKeyDownWithPlaceholder = ( event: React.KeyboardEvent, ) => { - // Same IME guard as handleEnterKeyDown: the Enter that confirms a - // composition candidate must not fire the follow-up question while the - // composition text has not reached the input value yet. - const isComposing = event.nativeEvent.isComposing || event.keyCode === 229; - + // With an empty input the suggested follow-up question is sent on the + // same keys that submit typed text, so the Enter setting and the IME + // guard both apply; handleEnterKeyDown prevents the default when it sends. if ( input.trim() === "" && followUpQuestion && !isRestoringFromHistory && - !suppressNextFollowUp && - !isComposing + !suppressNextFollowUp ) { - if (event.key === "Enter" && !event.shiftKey) { - event.preventDefault(); - handleSend(followUpQuestion); - return; - } + handleEnterKeyDown(event, settings, () => handleSend(followUpQuestion)); + if (event.defaultPrevented) return; } onKeyDown(event); diff --git a/client/components/AiResponse/ChatInterface.test.tsx b/client/components/AiResponse/ChatInterface.test.tsx index 1ef952f1b8c634305cc0eb7aaca317c38f33db5f..34b92b8b9d42556095a74beaedb83fc166329313 100644 --- a/client/components/AiResponse/ChatInterface.test.tsx +++ b/client/components/AiResponse/ChatInterface.test.tsx @@ -5,6 +5,7 @@ import { chatGenerationStatePubSub, chatInputPubSub, followUpQuestionPubSub, + getSuppressNextFollowUp, suppressNextFollowUpPubSub, } from "@/modules/pubSub"; import type { ChatMessage } from "@/modules/types"; @@ -689,4 +690,50 @@ describe("ChatInterface generation state", () => { ); expect(generateFollowUpQuestion).toHaveBeenCalled(); }); + + it("clears suppressNextFollowUp after skipping the restored answer's follow-up so later sends generate one", async () => { + updateSuppressNextFollowUp(true); + + renderChatInterface({ suppressInitialFollowUp: false }); + + await act(async () => {}); + + expect(generateFollowUpQuestion).not.toHaveBeenCalled(); + expect(getSuppressNextFollowUp()).toBe(false); + + await act(async () => { + await sendMessage("Tell me more about wake locks"); + }); + + expect(generateFollowUpQuestion).toHaveBeenCalledTimes(1); + expect(getFollowUpQuestion()).toBe("A question?"); + }); + + it("drops an in-flight follow-up question when a restore suppresses follow-ups", async () => { + const inFlightQuestion = deferred(); + vi.mocked(generateFollowUpQuestion).mockReturnValueOnce( + inFlightQuestion.promise, + ); + + renderChatInterface({ suppressInitialFollowUp: false }); + + await act(async () => {}); + + expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true); + + await act(async () => { + updateSuppressNextFollowUp(true); + }); + + expect(getSuppressNextFollowUp()).toBe(false); + expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false); + expect(getFollowUpQuestion()).toBe(""); + + await act(async () => { + inFlightQuestion.resolve("Question from the previous search?"); + }); + + expect(getFollowUpQuestion()).toBe(""); + expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false); + }); }); diff --git a/client/components/AiResponse/ChatInterface.tsx b/client/components/AiResponse/ChatInterface.tsx index 4ba2a53b7d3574e7c22153d2fd4dbff3fb95e4e0..3588defcd4e0f0c8fca708288c33224f05a5daad 100644 --- a/client/components/AiResponse/ChatInterface.tsx +++ b/client/components/AiResponse/ChatInterface.tsx @@ -65,7 +65,9 @@ export default function ChatInterface({ const [textSearchResults] = usePubSub(textSearchResultsPubSub); const [imageSearchResults] = usePubSub(imageSearchResultsPubSub); const [currentQuery] = usePubSub(queryPubSub); - const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub); + const [suppressNextFollowUp, setSuppressNextFollowUp] = usePubSub( + suppressNextFollowUpPubSub, + ); const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState< string[] >([]); @@ -190,6 +192,13 @@ export default function ChatInterface({ useEffect(() => { if (suppressNextFollowUp) { hasInitialized.current = true; + followUpInvocationRef.current += 1; + setFollowUpQuestion(""); + setGenerationState({ + ...getChatGenerationState(), + isGeneratingFollowUpQuestion: false, + }); + setSuppressNextFollowUp(false); return; } if (suppressInitialFollowUp) return; @@ -214,6 +223,9 @@ export default function ChatInterface({ initialMessages, messages, regenerateFollowUpQuestion, + setFollowUpQuestion, + setGenerationState, + setSuppressNextFollowUp, suppressInitialFollowUp, suppressNextFollowUp, ]); diff --git a/client/components/AiResponse/ExpandableLink.test.tsx b/client/components/AiResponse/ExpandableLink.test.tsx index db78cc976267be37e6d4ab854365957c35d01f2c..1bf732aea1d5bb1b6e923cc38693a2c520498af1 100644 --- a/client/components/AiResponse/ExpandableLink.test.tsx +++ b/client/components/AiResponse/ExpandableLink.test.tsx @@ -37,6 +37,14 @@ function renderLink(label = "Example Domain", href = "https://example.com") { ); } +function getPill() { + const pill = screen + .getByRole("link") + .querySelectorAll('[aria-hidden="true"]'); + expect(pill).toHaveLength(1); + return pill[0]; +} + function getFullText() { return screen.getByTestId("expandable-link-full"); } @@ -208,4 +216,43 @@ describe("ExpandableLink", () => { expect(fullText).toHaveTextContent("Example Domain"); expect(fullText.style.visibility).not.toBe("hidden"); }); + + it("shows the first character of plain link text in the pill", () => { + renderLink("Example Domain"); + + expect(getPill().textContent).toBe("E"); + }); + + it("shows the first visible character of formatted link text in the pill", () => { + render( + + + Reuters + + , + ); + + expect(getPill().textContent).toBe("R"); + }); + + it.each([ + ["πŸ˜€ Emoji Site", "πŸ˜€"], + ["πŸ‡¨πŸ‡­ Swiss Site", "πŸ‡¨πŸ‡­"], + ["πŸ‘©β€πŸ’» Dev Site", "πŸ‘©β€πŸ’»"], + ])("keeps the leading emoji of %s whole in the pill", (label, expected) => { + renderLink(label); + + expect(getPill().textContent).toBe(expected); + }); + + it("falls back to the first code point without Intl.Segmenter", () => { + vi.stubGlobal( + "Intl", + Object.assign(Object.create(Intl), { Segmenter: undefined }), + ); + + renderLink("πŸ˜€ Emoji Site"); + + expect(getPill().textContent).toBe("πŸ˜€"); + }); }); diff --git a/client/components/AiResponse/ExpandableLink.tsx b/client/components/AiResponse/ExpandableLink.tsx index 41defb43374a229f0d6c0a382abe059a560cb9ab..b5608adb4dd19a2d7aed956a1011ad28ea67a999 100644 --- a/client/components/AiResponse/ExpandableLink.tsx +++ b/client/components/AiResponse/ExpandableLink.tsx @@ -54,6 +54,35 @@ function registerResizeListener( }; } +/** + * Collects the visible text of React children. Formatted link text such as + * `**Reuters**` arrives as elements, whose `toString()` is "[object Object]". + */ +function getTextContent(node: React.ReactNode): string { + if (typeof node === "string" || typeof node === "number") { + return String(node); + } + if (Array.isArray(node)) { + return node.map(getTextContent).join(""); + } + if (React.isValidElement<{ children?: React.ReactNode }>(node)) { + return getTextContent(node.props.children); + } + return ""; +} + +/** + * Returns the first user-perceived character, so an emoji, a flag or a ZWJ + * sequence is never split into a lone surrogate or a partial glyph. + */ +function getFirstGrapheme(text: string): string { + if (typeof Intl.Segmenter === "function") { + const [first] = new Intl.Segmenter().segment(text); + return first?.segment ?? ""; + } + return Array.from(text)[0] ?? ""; +} + /** * Citation link that collapses to a first-character pill and reveals the full * link text on hover/focus, auto-collapsing after 3 s. @@ -68,8 +97,7 @@ export default function ExpandableLink({ href, children, }: ExpandableLinkProps) { - const childContent = children?.toString() || ""; - const firstChar = childContent.charAt(0); + const firstChar = getFirstGrapheme(getTextContent(children)); const [isExpanded, setIsExpanded] = React.useState(true); const timerRef = React.useRef(null); const anchorRef = React.useRef(null); diff --git a/client/components/AiResponse/FormattedMarkdown.tsx b/client/components/AiResponse/FormattedMarkdown.tsx index 7a0455f4721dfae21e6c1fc0df0164c8715286c2..2f8a89c2cd6b14d091a16506fd9b4705832f9417 100644 --- a/client/components/AiResponse/FormattedMarkdown.tsx +++ b/client/components/AiResponse/FormattedMarkdown.tsx @@ -7,15 +7,20 @@ interface FormattedMarkdownProps { children: string; className?: string; enableCopy?: boolean; + /** Whether this response is still being generated. */ + isGenerating?: boolean; } export default function FormattedMarkdown({ children, className = "", enableCopy = true, + isGenerating: isResponseGenerating = false, }: FormattedMarkdownProps) { - const { reasoningContent, mainContent, isGenerating } = - useReasoningContent(children); + const { reasoningContent, mainContent, isGenerating } = useReasoningContent( + children, + isResponseGenerating, + ); if (!children && !reasoningContent) { return null; diff --git a/client/components/AiResponse/MarkdownRenderer.test.tsx b/client/components/AiResponse/MarkdownRenderer.test.tsx index 87897e9717ed904773fe0e6bb8927e18a06d3a02..a3b6af4a4b6e3bd183f5979fd98d347d3fc93c20 100644 --- a/client/components/AiResponse/MarkdownRenderer.test.tsx +++ b/client/components/AiResponse/MarkdownRenderer.test.tsx @@ -80,6 +80,19 @@ describe("MarkdownRenderer rendered output", () => { expect(link?.getAttribute("rel")).toContain("nofollow"); }); + it.each([ + ["[**Reuters**](https://www.reuters.com/)", "R"], + ["[`npm`](https://www.npmjs.com/)", "n"], + ])( + "collapses the formatted link %s to its first visible character", + (markdown, expected) => { + const { container } = renderMarkdown(markdown); + + const pill = container.querySelector('a [aria-hidden="true"]'); + expect(pill?.textContent).toBe(expected); + }, + ); + it("renders a fenced code block through CodeHighlight with its language", () => { const { getByTestId } = renderMarkdown("```js\nconst x = 1;\n```"); diff --git a/client/components/AiResponse/MessageList.test.tsx b/client/components/AiResponse/MessageList.test.tsx index 524e5463c1b21c337c50bbce9e45a8a80cd2fe0e..4cf1fd075ced853496b0380eda1c24094907c440 100644 --- a/client/components/AiResponse/MessageList.test.tsx +++ b/client/components/AiResponse/MessageList.test.tsx @@ -1,5 +1,5 @@ import { MantineProvider } from "@mantine/core"; -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import type { ChatMessage } from "@/modules/types"; import MessageList from "./MessageList"; @@ -53,4 +53,76 @@ describe("MessageList", () => { ); expect(renderedQuestions).toHaveLength(2); }); + + describe("an empty answer earlier in the chat", () => { + // An empty answer is saved when the stream ends with no content. + const messages: ChatMessage[] = [ + { role: "user", content: "system instructions" }, + { role: "assistant", content: "Ok!" }, + { role: "user", content: "Q1" }, + { role: "assistant", content: "" }, + { role: "user", content: "Q2" }, + { role: "assistant", content: "" }, + { role: "user", content: "Q3" }, + { role: "assistant", content: "A3" }, + ]; + + it("edits each question at its position in the chat", () => { + const onEditMessage = vi.fn(); + renderMessageList({ messages, onEditMessage }); + + const editButtons = screen.getAllByLabelText("Edit message"); + expect(editButtons).toHaveLength(3); + for (const button of editButtons) fireEvent.click(button); + + expect(onEditMessage.mock.calls).toEqual([[2], [4], [6]]); + }); + + it("keeps the Re-generate button on the last answer", () => { + const onRegenerate = vi.fn(); + renderMessageList({ messages, onRegenerate }); + + fireEvent.click(screen.getByLabelText("Re-generate response")); + + expect(onRegenerate).toHaveBeenCalledTimes(1); + }); + + it("renders no bubble for the empty answers", () => { + renderMessageList({ messages }); + + expect(screen.getAllByText(/^(Q1|Q2|Q3|A3)$/)).toHaveLength(4); + expect(document.querySelectorAll(".mantine-Paper-root")).toHaveLength(4); + }); + }); + + describe("unterminated reasoning", () => { + const messages: ChatMessage[] = [ + { role: "user", content: "system instructions" }, + { role: "assistant", content: "Ok!" }, + { role: "user", content: "why?" }, + { role: "assistant", content: "cut off mid-thought" }, + ]; + + it("shows no Thinking loader on a message that is not being generated", () => { + renderMessageList({ messages, isGenerating: false }); + + expect(screen.queryByText("Thinking")).toBeNull(); + expect(screen.getByText("Thought Process")).toBeInTheDocument(); + }); + + it("shows the Thinking loader on the last assistant message while it is generated", () => { + renderMessageList({ messages, isGenerating: true }); + + expect(screen.getByText("Thinking")).toBeInTheDocument(); + }); + + it("shows no Thinking loader on an older message while a later one is generated", () => { + renderMessageList({ + messages: [...messages, { role: "user", content: "and then?" }], + isGenerating: true, + }); + + expect(screen.queryByText("Thinking")).toBeNull(); + }); + }); }); diff --git a/client/components/AiResponse/MessageList.tsx b/client/components/AiResponse/MessageList.tsx index 7e9f9d92da9144735de2867bf56cf9871c289c4c..f37536913658be43b9766104d59dd50268cc80c7 100644 --- a/client/components/AiResponse/MessageList.tsx +++ b/client/components/AiResponse/MessageList.tsx @@ -13,7 +13,6 @@ interface MessageListProps { interface MessageProps { message: ChatMessage; - index: number; absoluteIndex: number; isLastAssistant: boolean; isGenerating: boolean; @@ -24,7 +23,6 @@ interface MessageProps { const Message = memo( ({ message, - index, absoluteIndex, isLastAssistant, isGenerating, @@ -58,13 +56,15 @@ const Message = memo( )} - {message.content} + + {message.content} + {canRegenerate && ( @@ -100,27 +100,27 @@ const MessageList = memo(function MessageList({ return ( - {messages - .slice(2) - .filter((message) => message.content.length > 0) - .map((message, index) => { - const absoluteIndex = index + 2; - const isLastAssistant = - absoluteIndex === messages.length - 1 && - message.role === "assistant"; - return ( - - ); - })} + {messages.map((message, absoluteIndex) => { + // The index is the message's position in `messages`, which is what + // editing and regenerating act on. The first two messages are the + // system prompt and its acknowledgement, and an empty message has + // nothing to show, so neither renders, but both keep their position. + if (absoluteIndex < 2 || message.content.length === 0) return null; + const isLastAssistant = + absoluteIndex === messages.length - 1 && message.role === "assistant"; + return ( + + ); + })} ); }); diff --git a/client/components/AiResponse/hooks/useReasoningContent.test.ts b/client/components/AiResponse/hooks/useReasoningContent.test.ts index b695dc51e1c280342486172051128533495bd02d..13e96d6d92eb3fe9579cc4cbe8af51ff14bbb183 100644 --- a/client/components/AiResponse/hooks/useReasoningContent.test.ts +++ b/client/components/AiResponse/hooks/useReasoningContent.test.ts @@ -16,6 +16,7 @@ describe("useReasoningContent hook", () => { const { result } = renderHook(() => useReasoningContent( "Let me think about this\nHere is the answer.", + false, ), ); @@ -29,13 +30,13 @@ describe("useReasoningContent hook", () => { ["whitespace-only text", " "], ["no text at all", null as unknown as string], ])("should report nothing to show for %s", (_, content) => { - const { result } = renderHook(() => useReasoningContent(content)); + const { result } = renderHook(() => useReasoningContent(content, false)); expectEmptyState(result); }); it("should return text as main content when no markers present", () => { const { result } = renderHook(() => - useReasoningContent("This is a normal response."), + useReasoningContent("This is a normal response.", false), ); expect(result.current.reasoningContent).toBe(""); @@ -45,12 +46,22 @@ describe("useReasoningContent hook", () => { it("should detect generating state when end marker is missing", () => { const { result } = renderHook(() => - useReasoningContent("I'm still thinking"), + useReasoningContent("I'm still thinking", true), ); expect(result.current.reasoningContent).toBe("I'm still thinking"); expect(result.current.mainContent).toBe(""); expect(result.current.isGenerating).toBe(true); }); + + it("should treat a missing end marker as a finished thought once generation stops", () => { + const { result } = renderHook(() => + useReasoningContent("I was interrupted", false), + ); + + expect(result.current.reasoningContent).toBe("I was interrupted"); + expect(result.current.mainContent).toBe(""); + expect(result.current.isGenerating).toBe(false); + }); }); }); diff --git a/client/components/AiResponse/hooks/useReasoningContent.ts b/client/components/AiResponse/hooks/useReasoningContent.ts index 74d95909461538902683f00589f2dd21a7135d47..500f0d6f58da628bfa9f22b3d7b38ff2950f68a2 100644 --- a/client/components/AiResponse/hooks/useReasoningContent.ts +++ b/client/components/AiResponse/hooks/useReasoningContent.ts @@ -4,10 +4,15 @@ import { settingsPubSub } from "@/modules/pubSub"; /** * Splits a streamed AI response into the part between the reasoning markers - * and the rest, flagging `isGenerating` while the closing marker has not - * arrived yet. + * and the rest. `isGenerating` is reported only while the closing marker has + * not arrived yet and `isResponseGenerating` says the response is still being + * written; once generation stops (finished, interrupted, truncated), an + * unterminated reasoning block is a finished thought. */ -export function useReasoningContent(text: string) { +export function useReasoningContent( + text: string, + isResponseGenerating: boolean, +) { const [settings] = usePubSub(settingsPubSub); const extractReasoningAndMainContent = useCallback( @@ -27,7 +32,7 @@ export function useReasoningContent(text: string) { return { reasoningContent: trimmedText.slice(startIndex + startMarker.length), mainContent: "", - isGenerating: true, + isGenerating: isResponseGenerating, }; } @@ -40,7 +45,7 @@ export function useReasoningContent(text: string) { isGenerating: false, }; }, - [], + [isResponseGenerating], ); if (text && text.trim() === "") { diff --git a/client/components/Analytics/SearchStats.test.tsx b/client/components/Analytics/SearchStats.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0c74402d399a5bb771ca978e6f1660d8e97a190f --- /dev/null +++ b/client/components/Analytics/SearchStats.test.tsx @@ -0,0 +1,85 @@ +import { MantineProvider } from "@mantine/core"; +import { render, screen } from "@testing-library/react"; +import { useSearchHistory } from "@/hooks/useSearchHistory"; +import type { SearchEntry } from "@/modules/history"; +import SearchStats from "./SearchStats"; + +vi.mock("@/hooks/useSearchHistory", () => ({ + useSearchHistory: vi.fn(), +})); + +/** The hook mock has to return the full shape the real hook returns. */ +const mockHistory = (recentSearches: SearchEntry[]) => { + const noop = vi.fn(async (): Promise => {}); + vi.mocked(useSearchHistory).mockReturnValue({ + recentSearches, + llmResponseCount: 0, + chatMessageCount: 0, + filteredSearches: recentSearches, + groupedSearches: {}, + isLoading: false, + error: null, + currentPage: 0, + totalPages: 0, + hasNextPage: false, + hasPreviousPage: false, + retryLastOperation: noop, + clearError: vi.fn(), + searchHistory: vi.fn(), + addToHistory: noop, + togglePin: noop, + deleteEntry: noop, + clearAll: noop, + refreshHistory: noop, + nextPage: vi.fn(), + previousPage: vi.fn(), + goToPage: vi.fn(), + }); +}; + +/** Metric cards print the value below the label; the heatmap above it. */ +const valueBelow = (label: string) => + screen.getByText(label).nextElementSibling?.textContent; +const valueAbove = (label: string) => + screen.getByText(label).previousElementSibling?.textContent; + +describe("SearchStats", () => { + let originalTimeZone: string | undefined; + + beforeEach(() => { + originalTimeZone = process.env.TZ; + }); + + afterEach(() => { + vi.useRealTimers(); + if (originalTimeZone === undefined) delete process.env.TZ; + else process.env.TZ = originalTimeZone; + }); + + it("buckets the Daily Average by local day, like the heatmap", () => { + process.env.TZ = "Europe/Zurich"; // UTC+1 in January + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(new Date(2026, 0, 15, 12)); + + // 00:30 and 01:30 local are 23:30 and 00:30 UTC: one local day, two UTC + // days. The UTC check makes a silent no-op of the zone change fail loudly + // instead of passing vacuously. + const first = new Date(2026, 0, 15, 0, 30).getTime(); + const second = new Date(2026, 0, 15, 1, 30).getTime(); + 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 }, + ]); + render( + + + , + ); + + expect(valueBelow("Daily Average")).toBe("2"); + expect(valueAbove("Active days")).toBe("1"); + }); +}); diff --git a/client/components/Analytics/SearchStats.tsx b/client/components/Analytics/SearchStats.tsx index 83bb303c18d511fae19638313f0fd103da2922c5..cd976fdc9ef6a1625f5ed86409d22b764ac8536b 100644 --- a/client/components/Analytics/SearchStats.tsx +++ b/client/components/Analytics/SearchStats.tsx @@ -14,7 +14,7 @@ import { IconSearch } from "@tabler/icons-react"; import { useMemo } from "react"; import { useSearchHistory } from "@/hooks/useSearchHistory"; import type { SearchEntry } from "@/modules/history"; -import { buildActivity } from "@/modules/searchActivity"; +import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity"; import { formatRelativeTime } from "@/modules/stringFormatters"; import ActivityHeatmap from "./ActivityHeatmap"; @@ -96,7 +96,8 @@ export default function SearchStats({ const dateCounts = new Map(); filteredSearches.forEach((search) => { - const date = new Date(search.timestamp).toISOString().split("T")[0]; + // Local day, like the hour math below and the heatmap's active days. + const date = localKey(startOfDay(search.timestamp)); dateCounts.set(date, (dateCounts.get(date) || 0) + 1); }); diff --git a/client/components/Pages/AccessPage.test.tsx b/client/components/Pages/AccessPage.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7107704ca01e839da779430f0ee6f4f3f8d477d9 --- /dev/null +++ b/client/components/Pages/AccessPage.test.tsx @@ -0,0 +1,65 @@ +import { MantineProvider } from "@mantine/core"; +import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { type AccessKeyResult, validateAccessKey } from "@/modules/accessKey"; +import AccessPage from "./AccessPage"; + +vi.mock("@/modules/accessKey", () => ({ + validateAccessKey: vi.fn(), +})); + +vi.mock("@/modules/logEntries", () => ({ + addLogEntry: vi.fn(), +})); + +async function submitKey(result: AccessKeyResult) { + vi.mocked(validateAccessKey).mockResolvedValueOnce(result); + const onAccessKeyValid = vi.fn(); + const user = userEvent.setup(); + render( + + + , + ); + + await user.type( + screen.getByPlaceholderText("Enter your access key to continue"), + "some-key{Enter}", + ); + + return onAccessKeyValid; +} + +describe("AccessPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("says the key is wrong when the server rejects it", async () => { + await submitKey("invalid"); + + expect(await screen.findByText("Invalid access key")).toBeInTheDocument(); + }); + + it("says the server could not be reached instead of blaming the key", async () => { + await submitKey("unreachable"); + + expect( + await screen.findByText("Could not reach the server. Please try again."), + ).toBeInTheDocument(); + expect(screen.queryByText("Invalid access key")).toBeNull(); + }); + + it("shows no field error when rate-limited", async () => { + const onAccessKeyValid = await submitKey("rateLimited"); + + expect(screen.queryByText("Invalid access key")).toBeNull(); + expect(onAccessKeyValid).not.toHaveBeenCalled(); + }); + + it("lets the user in with a valid key", async () => { + const onAccessKeyValid = await submitKey("valid"); + + expect(onAccessKeyValid).toHaveBeenCalled(); + }); +}); diff --git a/client/components/Pages/AccessPage.tsx b/client/components/Pages/AccessPage.tsx index 0552ebccb971b322869f769691b7c9a25719c248..28a3c844f4e602851af0fd7ccc289d3df9d11063 100644 --- a/client/components/Pages/AccessPage.tsx +++ b/client/components/Pages/AccessPage.tsx @@ -21,21 +21,22 @@ export default function AccessPage({ const handleSubmit = async (formEvent: FormEvent) => { formEvent.preventDefault(); setState((prev) => ({ ...prev, error: "" })); - try { - const isValid = await validateAccessKey(state.accessKey); - if (isValid === "valid") { - addLogEntry("Valid access key entered"); - onAccessKeyValid(); - } else if (isValid === "rateLimited") { - // The module already raised the refusal notice; no wrong-key error. - addLogEntry("Access key validation rate-limited"); - } else { - setState((prev) => ({ ...prev, error: "Invalid access key" })); - addLogEntry("Invalid access key attempt"); - } - } catch (error) { - setState((prev) => ({ ...prev, error: "Error validating access key" })); - addLogEntry(`Error validating access key: ${error}`); + // validateAccessKey never rejects: every failure comes back as a result. + const result = await validateAccessKey(state.accessKey); + if (result === "valid") { + addLogEntry("Valid access key entered"); + onAccessKeyValid(); + } else if (result === "rateLimited") { + // The module already raised the refusal notice; no wrong-key error. + addLogEntry("Access key validation rate-limited"); + } else if (result === "unreachable") { + setState((prev) => ({ + ...prev, + error: "Could not reach the server. Please try again.", + })); + } else { + setState((prev) => ({ ...prev, error: "Invalid access key" })); + addLogEntry("Invalid access key attempt"); } }; diff --git a/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx b/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx index a8c4206093372a4d708f43c834be897c0e78858e..b4af06f0b84884109d759fde7e5fafbfb1bc4e1e 100644 --- a/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx +++ b/client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx @@ -1,8 +1,8 @@ import { Select, Stack, Switch, Text, TextInput } from "@mantine/core"; -import { useForm } from "@mantine/form"; import { notifications } from "@mantine/notifications"; import { usePubSub } from "create-pubsub/react"; import { useEffect, useState } from "react"; +import { useSettingsForm } from "@/hooks/useSettingsForm"; import { FALLBACK_CONFIG, getConfig } from "@/modules/config"; import { requestNotificationPermission } from "@/modules/notifications"; import { settingsPubSub } from "@/modules/pubSub"; @@ -15,8 +15,26 @@ import { useHordeModels } from "./hooks/useHordeModels"; import { useHordeUserInfo } from "./hooks/useHordeUserInfo"; import { useOpenAiModels } from "./hooks/useOpenAiModels"; +const SETTINGS_KEYS = [ + "enableAiResponse", + "enableNotificationOnAiComplete", + "enablePageContentFetch", + "inferenceType", + "openAiApiBaseUrl", + "openAiApiKey", + "openAiApiModel", + "openAiContextLength", + "hordeApiKey", + "hordeModel", + "wllamaModelId", + "cpuThreads", + "systemPrompt", + "reasoningStartMarker", + "reasoningEndMarker", +] as const; + export default function AISettingsForm() { - const [settings, setSettings] = usePubSub(settingsPubSub); + const [settings] = usePubSub(settingsPubSub); const { openAiModels, useTextInput } = useOpenAiModels(settings); const hordeModels = useHordeModels(settings); const hordeUserInfo = useHordeUserInfo(settings); @@ -29,10 +47,7 @@ export default function AISettingsForm() { .then(setServerConfig); }, []); - const form = useForm({ - initialValues: settings, - onValuesChange: setSettings, - }); + const form = useSettingsForm(SETTINGS_KEYS); const handleNotificationToggle = async ( event: React.ChangeEvent, diff --git a/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx index aca882ecf1d97ac8a38d7b954e33c432d7ba6281..e9f37b682d7a9dd4695ba31b51d0f9318cd1bf23 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx @@ -8,7 +8,9 @@ const WllamaModelSelect = lazy( ); interface BrowserSettingsProps { - form: UseFormReturnType; + form: UseFormReturnType< + Pick + >; } /** Browser inference settings: the model to run (lazy-loaded) and its CPU threads. */ diff --git a/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx index 3467b9e8c70a65207b4bd24e1844472e3318f9fc..fa312a1255ebb119484978df58e367af1dfa823d 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx @@ -5,7 +5,9 @@ import { aiHordeDefaultApiKey } from "@/modules/textGenerationWithHorde"; import type { HordeUserInfo, ModelOption } from "../types"; interface HordeSettingsProps { - form: UseFormReturnType; + form: UseFormReturnType< + Pick + >; hordeUserInfo: HordeUserInfo | null; hordeModels: ModelOption[]; } diff --git a/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsx b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..af84dcaa7561695ee64067914187f4fac5c5f44d --- /dev/null +++ b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsx @@ -0,0 +1,40 @@ +import { MantineProvider } from "@mantine/core"; +import { useForm } from "@mantine/form"; +import { fireEvent, render, screen } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import { defaultSettings } from "@/modules/settings"; +import { OpenAISettings } from "./OpenAISettings"; + +function Harness({ + onValuesChange, +}: { + onValuesChange: (values: typeof defaultSettings) => void; +}) { + const form = useForm({ + initialValues: defaultSettings, + onValuesChange, + }); + + return ; +} + +describe("OpenAISettings", () => { + it("keeps a context length below the default after blur", () => { + const onValuesChange = vi.fn(); + render( + + + , + ); + const input = screen.getByRole("textbox", { name: "Context Length" }); + + fireEvent.change(input, { target: { value: "2048" } }); + fireEvent.blur(input); + + expect(input).toHaveValue("2048"); + expect(onValuesChange).toHaveBeenLastCalledWith( + expect.objectContaining({ openAiContextLength: 2048 }), + expect.anything(), + ); + }); +}); diff --git a/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx index 7397b326dc805f5784c845f82503022d68bcf12a..868e6bd5c8c4142aefd9ec2dec01016bfe4c8d38 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx @@ -5,7 +5,15 @@ import { defaultSettings } from "@/modules/settings"; import type { ModelOption } from "../types"; interface OpenAISettingsProps { - form: UseFormReturnType; + form: UseFormReturnType< + Pick< + typeof defaultSettings, + | "openAiApiBaseUrl" + | "openAiApiKey" + | "openAiApiModel" + | "openAiContextLength" + > + >; openAiModels: ModelOption[]; useTextInput: boolean; } @@ -60,8 +68,8 @@ export const OpenAISettings = ({ description={`Maximum number of tokens the model can consider. Defaults to ${defaultSettings.openAiContextLength}.`} defaultValue={defaultSettings.openAiContextLength} {...form.getInputProps("openAiContextLength")} - step={defaultSettings.openAiContextLength} - min={defaultSettings.openAiContextLength} + step={1024} + min={512} /> ); diff --git a/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx b/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx index 7ea622ede4d772d4abd1a2f39345396995cb3b75..d5bd7da280f072220dbaac1292799a72518ad15f 100644 --- a/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx +++ b/client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx @@ -3,7 +3,7 @@ import type { UseFormReturnType } from "@mantine/form"; import { defaultSettings } from "@/modules/settings"; interface SystemPromptInputProps { - form: UseFormReturnType; + form: UseFormReturnType>; } /** Custom system prompt editor, with an inline action to restore the default. */ diff --git a/client/components/Pages/Main/Menu/ClearDataButton.test.tsx b/client/components/Pages/Main/Menu/ClearDataButton.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6eea9f730161a047cfe04fa205e3c126eae2f74a --- /dev/null +++ b/client/components/Pages/Main/Menu/ClearDataButton.test.tsx @@ -0,0 +1,170 @@ +import { MantineProvider } from "@mantine/core"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import Dexie from "dexie"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { addLogEntry } from "@/modules/logEntries"; +import { clearWllamaCache } from "@/modules/wllama"; +import ClearDataButton from "./ClearDataButton"; + +const mockNavigate = vi.fn(); + +vi.mock("wouter", () => ({ + useLocation: vi.fn(() => ["/", mockNavigate]), +})); + +vi.mock("@/modules/logEntries", () => ({ + addLogEntry: vi.fn(), +})); + +vi.mock("@/modules/wllama", () => ({ + clearWllamaCache: vi.fn(), +})); + +function renderClearDataButton() { + return render( + + + , + ); +} + +describe("ClearDataButton", () => { + const originalLocation = self.location; + const originalCachesDescriptor = Object.getOwnPropertyDescriptor( + self, + "caches", + ); + let reloadMock: ReturnType; + + beforeEach(() => { + vi.clearAllMocks(); + reloadMock = vi.fn(); + Object.defineProperty(self, "location", { + configurable: true, + value: { ...originalLocation, reload: reloadMock }, + }); + vi.spyOn(self, "confirm").mockReturnValue(true); + vi.spyOn(Dexie, "getDatabaseNames").mockResolvedValue(["minisearch-db"]); + vi.spyOn(Dexie, "delete").mockResolvedValue(undefined); + vi.mocked(clearWllamaCache).mockResolvedValue(undefined); + localStorage.setItem("sample-key", "sample-value"); + }); + + afterEach(() => { + cleanup(); + Object.defineProperty(self, "location", { + configurable: true, + value: originalLocation, + }); + if (originalCachesDescriptor) { + Object.defineProperty(self, "caches", originalCachesDescriptor); + } else { + Reflect.deleteProperty(self, "caches"); + } + vi.restoreAllMocks(); + }); + + it("completes the teardown and reloads when self.caches is undefined", async () => { + Object.defineProperty(self, "caches", { + configurable: true, + value: undefined, + }); + + const user = userEvent.setup(); + renderClearDataButton(); + + await user.click(screen.getByRole("button", { name: "Clear all data" })); + + await waitFor(() => { + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + expect(localStorage.getItem("sample-key")).toBeNull(); + expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db"); + expect(clearWllamaCache).toHaveBeenCalledTimes(1); + expect(addLogEntry).toHaveBeenCalledWith("All data cleared successfully"); + expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true }); + expect( + screen.getByRole("button", { name: "Data cleared" }), + ).not.toHaveAttribute("data-loading"); + }); + + it("logs the failure, clears the spinner, and still reloads when clearWllamaCache rejects", async () => { + Object.defineProperty(self, "caches", { + configurable: true, + value: undefined, + }); + vi.mocked(clearWllamaCache).mockRejectedValueOnce( + new Error("OPFS unavailable"), + ); + + const user = userEvent.setup(); + renderClearDataButton(); + + await user.click(screen.getByRole("button", { name: "Clear all data" })); + + await waitFor(() => { + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + expect(addLogEntry).toHaveBeenCalledWith( + "Error clearing data: OPFS unavailable", + ); + expect(addLogEntry).not.toHaveBeenCalledWith( + "All data cleared successfully", + ); + expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true }); + expect( + screen.getByRole("button", { name: "Clear all data" }), + ).not.toHaveAttribute("data-loading"); + }); + + it("deletes all caches and continues when one caches.delete call rejects", async () => { + const deleteMock = vi + .fn<(cacheName: string) => Promise>() + .mockRejectedValueOnce(new Error("locked cache")) + .mockResolvedValueOnce(true); + const keysMock = vi.fn().mockResolvedValue(["cache-a", "cache-b"]); + + Object.defineProperty(self, "caches", { + configurable: true, + value: { + keys: keysMock, + delete: deleteMock, + }, + }); + + const user = userEvent.setup(); + renderClearDataButton(); + + await user.click(screen.getByRole("button", { name: "Clear all data" })); + + await waitFor(() => { + expect(reloadMock).toHaveBeenCalledTimes(1); + }); + + expect(keysMock).toHaveBeenCalledTimes(1); + expect(deleteMock).toHaveBeenCalledWith("cache-a"); + expect(deleteMock).toHaveBeenCalledWith("cache-b"); + expect(addLogEntry).toHaveBeenCalledWith( + "Error deleting cache cache-a: locked cache", + ); + expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db"); + expect(clearWllamaCache).toHaveBeenCalledTimes(1); + expect(addLogEntry).toHaveBeenCalledWith("All data cleared successfully"); + }); + + it("does nothing when confirmation is cancelled", async () => { + vi.spyOn(self, "confirm").mockReturnValue(false); + + const user = userEvent.setup(); + renderClearDataButton(); + + await user.click(screen.getByRole("button", { name: "Clear all data" })); + + expect(localStorage.getItem("sample-key")).toBe("sample-value"); + expect(clearWllamaCache).not.toHaveBeenCalled(); + expect(reloadMock).not.toHaveBeenCalled(); + }); +}); diff --git a/client/components/Pages/Main/Menu/ClearDataButton.tsx b/client/components/Pages/Main/Menu/ClearDataButton.tsx index e7fbd6a0fde9da935399b631e5e3be0c198dfba9..fb1ce0f03bdfc45048914c8d4208fa3fd60e0c4d 100644 --- a/client/components/Pages/Main/Menu/ClearDataButton.tsx +++ b/client/components/Pages/Main/Menu/ClearDataButton.tsx @@ -18,7 +18,7 @@ export default function ClearDataButton() { const handleClearDataButtonClick = async () => { const sureToDelete = self.confirm( - "Are you sure you want to reset the settings and delete all files in cache?", + "Are you sure you want to clear all data? This resets the settings, deletes the cached files (including downloaded AI models) and permanently deletes all your saved searches, AI responses and chat messages. This cannot be undone.", ); if (!sureToDelete) return; @@ -27,42 +27,71 @@ export default function ClearDataButton() { setState((prev) => ({ ...prev, isClearingData: true })); - self.localStorage.clear(); - - for (const cacheName of await self.caches.keys()) { - await self.caches.delete(cacheName); - } + let clearedSuccessfully = false; try { - const dbNames = await Dexie.getDatabaseNames(); + self.localStorage.clear(); + + if (self.caches) { + try { + for (const cacheName of await self.caches.keys()) { + try { + await self.caches.delete(cacheName); + } catch (error) { + addLogEntry( + `Error deleting cache ${cacheName}: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } + } catch (error) { + addLogEntry( + `Error listing caches: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + } + } - for (const dbName of dbNames) { - await Dexie.delete(dbName); - addLogEntry(`Deleted database: ${dbName}`); + try { + const dbNames = await Dexie.getDatabaseNames(); + + for (const dbName of dbNames) { + await Dexie.delete(dbName); + addLogEntry(`Deleted database: ${dbName}`); + } + } catch (error) { + addLogEntry( + `Error deleting databases: ${ + error instanceof Error ? error.message : String(error) + }`, + ); } + + const { clearWllamaCache } = await import("../../../../modules/wllama"); + + await clearWllamaCache(); + + clearedSuccessfully = true; + addLogEntry("All data cleared successfully"); } catch (error) { addLogEntry( - `Error deleting databases: ${ + `Error clearing data: ${ error instanceof Error ? error.message : String(error) }`, ); - } - - const { clearWllamaCache } = await import("../../../../modules/wllama"); - - await clearWllamaCache(); + } finally { + setState((prev) => ({ + ...prev, + isClearingData: false, + hasClearedData: clearedSuccessfully, + })); - setState((prev) => ({ - ...prev, - isClearingData: false, - hasClearedData: true, - })); + navigate("/", { replace: true }); - addLogEntry("All data cleared successfully"); - - navigate("/", { replace: true }); - - self.location.reload(); + self.location.reload(); + } }; return ( @@ -77,7 +106,8 @@ export default function ClearDataButton() { {state.hasClearedData ? "Data cleared" : "Clear all data"} - Reset settings and delete all files in cache to free up space. + Reset settings, delete cached files and erase your search and chat + history. ); diff --git a/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx b/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx index 5322b8ce0aabe57815cd903696353ee1315a6276..a9f9140e07c64a9a4e7705539ad48a096e42b1ea 100644 --- a/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx @@ -4,16 +4,12 @@ import { useComputedColorScheme, useMantineColorScheme, } from "@mantine/core"; -import { useForm } from "@mantine/form"; -import { usePubSub } from "create-pubsub/react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { useSettingsForm } from "@/hooks/useSettingsForm"; + +const SETTINGS_KEYS = ["enterToSubmit"] as const; export default function InterfaceSettingsForm() { - const [settings, setSettings] = usePubSub(settingsPubSub); - const form = useForm({ - initialValues: settings, - onValuesChange: setSettings, - }); + const form = useSettingsForm(SETTINGS_KEYS); const { setColorScheme } = useMantineColorScheme(); const computedColorScheme = useComputedColorScheme("light"); diff --git a/client/components/Pages/Main/Menu/SearchSettingsForm.tsx b/client/components/Pages/Main/Menu/SearchSettingsForm.tsx index ca8884674ca017cc0a2569a0318054a0b25753a9..801a111437ffb98e57dbd16339be155040508f5c 100644 --- a/client/components/Pages/Main/Menu/SearchSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/SearchSettingsForm.tsx @@ -1,14 +1,14 @@ import { Slider, Stack, Switch, Text } from "@mantine/core"; -import { useForm } from "@mantine/form"; -import { usePubSub } from "create-pubsub/react"; -import { settingsPubSub } from "@/modules/pubSub"; +import { useSettingsForm } from "@/hooks/useSettingsForm"; + +const SETTINGS_KEYS = [ + "searchResultsLimit", + "enableTextSearch", + "enableImageSearch", +] as const; export default function SearchSettingsForm() { - const [settings, setSettings] = usePubSub(settingsPubSub); - const form = useForm({ - initialValues: settings, - onValuesChange: setSettings, - }); + const form = useSettingsForm(SETTINGS_KEYS); return ( diff --git a/client/components/Pages/Main/Menu/SettingsForms.test.tsx b/client/components/Pages/Main/Menu/SettingsForms.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..75610daab5761c9cd8c7597ae06c28a20d60335b --- /dev/null +++ b/client/components/Pages/Main/Menu/SettingsForms.test.tsx @@ -0,0 +1,60 @@ +import { MantineProvider } from "@mantine/core"; +import { act, fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { settingsPubSub } from "@/modules/pubSub"; +import { defaultSettings } from "@/modules/settings"; +import AISettingsForm from "./AISettings/AISettingsForm"; +import InterfaceSettingsForm from "./InterfaceSettingsForm"; +import SearchSettingsForm from "./SearchSettingsForm"; + +vi.mock("@/modules/config", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getConfig: async () => actual.FALLBACK_CONFIG }; +}); + +const [updateSettings, , getSettings] = settingsPubSub; + +function toggle(name: RegExp) { + fireEvent.click(screen.getByRole("switch", { name })); +} + +describe("the menu's settings forms", () => { + beforeEach(() => { + updateSettings(defaultSettings); + }); + + it("keep a change made in one section when another section changes", () => { + render( + + + + , + ); + + toggle(/Text Search/); + toggle(/Enter to Submit/); + + expect(getSettings()).toMatchObject({ + enableTextSearch: false, + enterToSubmit: false, + }); + }); + + it("keep a setting another writer changed while the AI form is open", () => { + render( + + + , + ); + + act(() => + updateSettings({ ...getSettings(), wllamaModelId: "another-model" }), + ); + toggle(/AI Response/); + + expect(getSettings()).toMatchObject({ + enableAiResponse: true, + wllamaModelId: "another-model", + }); + }); +}); diff --git a/client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx b/client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx index d47bb7b5041bfff100fa1e8f6e7687b41f24de0d..6da7b91e11d0bd0017b087511c1c9351ebdc56c1 100644 --- a/client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx +++ b/client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx @@ -168,7 +168,6 @@ describe("VoiceSettingsForm", () => { expect(setSettings).toHaveBeenCalledWith( expect.objectContaining({ enableLocalDictationModel: false }), - expect.anything(), ); }); @@ -189,7 +188,6 @@ describe("VoiceSettingsForm", () => { textToSpeechEngine: "system", selectedVoiceId: "", }), - expect.anything(), ); expect((voiceInput() as HTMLInputElement).value).toBe(""); }); diff --git a/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx b/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx index b966aaee24f9e671a658e3f805df1720f821bd21..263b44600d92b8a8d982e78949c4fde435e9aa0a 100644 --- a/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx +++ b/client/components/Pages/Main/Menu/VoiceSettingsForm.tsx @@ -6,10 +6,10 @@ import { Switch, Text, } from "@mantine/core"; -import { useForm } from "@mantine/form"; import getUnicodeFlagIcon from "country-flag-icons/unicode"; import { usePubSub } from "create-pubsub/react"; import { useCallback, useEffect, useState } from "react"; +import { useSettingsForm } from "@/hooks/useSettingsForm"; import { settingsPubSub } from "@/modules/pubSub"; import { listVoices, @@ -17,8 +17,15 @@ import { type VoiceOption, } from "@/modules/textToSpeech"; +const SETTINGS_KEYS = [ + "enableDictation", + "enableLocalDictationModel", + "textToSpeechEngine", + "selectedVoiceId", +] as const; + export default function VoiceSettingsForm() { - const [settings, setSettings] = usePubSub(settingsPubSub); + const [settings] = usePubSub(settingsPubSub); const [voiceOptions, setVoiceOptions] = useState([]); const getCountryFlag = useCallback((langCode: string) => { @@ -33,10 +40,7 @@ export default function VoiceSettingsForm() { } }, []); - const form = useForm({ - initialValues: settings, - onValuesChange: setSettings, - }); + const form = useSettingsForm(SETTINGS_KEYS); useEffect(() => { let cancelled = false; diff --git a/client/components/Search/Form/SearchForm.restore.test.tsx b/client/components/Search/Form/SearchForm.restore.test.tsx new file mode 100644 index 0000000000000000000000000000000000000000..f8046d1112131af7ff988ba72e8b92d952bfa9c8 --- /dev/null +++ b/client/components/Search/Form/SearchForm.restore.test.tsx @@ -0,0 +1,161 @@ +import { MantineProvider } from "@mantine/core"; +import { act, render, screen, waitFor } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import SearchForm from "@/components/Search/Form/SearchForm"; +import { resetHandledQuery } from "@/modules/autoSearch"; +import type { SearchEntry } from "@/modules/history"; +import { + isRestoringFromHistoryPubSub, + updateResponse, + updateTextSearchResults, + updateTextSearchState, +} from "@/modules/pubSub"; +import { sleep } from "@/modules/sleep"; +import { searchAndRespond } from "@/modules/textGeneration"; + +const addToHistory = vi.fn(); +const navigate = vi.fn((path: string) => { + window.history.replaceState({}, "", path); +}); + +/** The entry the history button hands to `restoreSearch` when clicked. */ +let entryToRestore: SearchEntry = { query: "", timestamp: 0 }; + +vi.mock("wouter", () => ({ + useLocation: () => ["/", navigate], +})); + +vi.mock("@/hooks/useSearchHistory", () => ({ + useSearchHistory: () => ({ addToHistory }), +})); + +vi.mock("../History/HistoryButton", () => ({ + default: function HistoryButton({ + onSearchSelect, + }: { + onSearchSelect: (entry: SearchEntry) => void; + }) { + return ( + + ); + }, +})); + +vi.mock("@/modules/textGeneration", () => ({ + searchAndRespond: vi.fn(), +})); + +vi.mock("@/modules/querySuggestions", () => ({ + DEFAULT_QUERY_SUGGESTION: "Anything you need!", + getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"), +})); + +vi.mock("@/modules/history", async (importOriginal) => ({ + ...(await importOriginal()), + getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null), + getChatMessagesForQuery: vi.fn().mockResolvedValue([]), +})); + +vi.mock("@/components/DictationButton", () => ({ + dictationButtonWidth: 34, + default: () => null, +})); + +function renderSearchForm(query = "") { + const updateQuery = vi.fn(); + render( + + + , + ); + return updateQuery; +} + +/** + * Clicks the history button, waits for the restore to finish and flushes the + * `sleepUntilIdle` tick the auto-search effect takes before acting. + */ +async function restore(entry: SearchEntry) { + entryToRestore = entry; + await userEvent + .setup() + .click(screen.getByRole("button", { name: "Restore" })); + await waitFor(() => expect(isRestoringFromHistoryPubSub[2]()).toBe(false)); + await act(() => sleep(0)); +} + +describe("SearchForm with the real history restore", () => { + beforeEach(() => { + addToHistory.mockClear(); + navigate.mockClear(); + vi.mocked(searchAndRespond).mockClear(); + resetHandledQuery(); + updateTextSearchResults([]); + updateTextSearchState("idle"); + updateResponse(""); + window.history.replaceState({}, "", "/"); + }); + + it("does not add a history entry or search when an empty entry is restored", async () => { + renderSearchForm(); + await screen.findByRole("textbox"); + + await restore({ query: "failed search", timestamp: 1 }); + + expect(window.location.search).toBe("?q=failed%20search"); + expect(screen.getByRole("textbox")).toHaveValue("failed search"); + expect(addToHistory).not.toHaveBeenCalled(); + expect(searchAndRespond).not.toHaveBeenCalled(); + }); + + it("does not re-run the auto-search when results and response are cleared after a restore", async () => { + renderSearchForm(); + await screen.findByRole("textbox"); + await restore({ + query: "saved search", + timestamp: 1, + textResults: { + type: "text", + items: [{ title: "Saved", snippet: "Saved", url: "https://e.com" }], + }, + }); + + // Regenerate and "enable AI response" start by clearing the response and + // the results while the URL still holds the restored query. + act(() => { + updateResponse(""); + updateTextSearchResults([]); + }); + await act(() => sleep(0)); + + expect(addToHistory).not.toHaveBeenCalled(); + expect(searchAndRespond).not.toHaveBeenCalled(); + }); + + it("still adds one entry and runs one search when the restored query is submitted", async () => { + renderSearchForm(); + await screen.findByRole("textbox"); + await restore({ query: "failed search", timestamp: 1 }); + + await userEvent + .setup() + .click(screen.getByRole("button", { name: /search/i })); + await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1)); + + expect(addToHistory).toHaveBeenCalledTimes(1); + expect(addToHistory).toHaveBeenCalledWith("failed search", { + type: "text", + items: [], + }); + }); + + it("still auto-searches a fresh URL query once", async () => { + window.history.replaceState({}, "", "/?q=fresh+load"); + renderSearchForm("fresh load"); + + await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1)); + expect(addToHistory).toHaveBeenCalledTimes(1); + }); +}); diff --git a/client/components/Search/Form/SearchForm.test.tsx b/client/components/Search/Form/SearchForm.test.tsx index 1d1b841cb85cff9e86793f243bfed80c94bc8e11..be9678f6112153086cd3d6fac2a2b0a2871bc4fe 100644 --- a/client/components/Search/Form/SearchForm.test.tsx +++ b/client/components/Search/Form/SearchForm.test.tsx @@ -1,9 +1,10 @@ import { MantineProvider } from "@mantine/core"; import { act, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import SearchForm, { - resetAutoSearchedQuery, -} from "@/components/Search/Form/SearchForm"; +import SearchForm from "@/components/Search/Form/SearchForm"; +import { resetHandledQuery } from "@/modules/autoSearch"; +import { settingsPubSub } from "@/modules/pubSub"; +import { defaultSettings } from "@/modules/settings"; import { searchAndRespond } from "@/modules/textGeneration"; vi.mock("create-pubsub/react", () => ({ @@ -48,6 +49,7 @@ vi.mock("../../../modules/textGeneration", () => ({ })); vi.mock("../../../modules/querySuggestions", () => ({ + DEFAULT_QUERY_SUGGESTION: "Anything you need!", getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"), })); @@ -88,7 +90,7 @@ const waitForPlaceholder = async () => { describe("SearchForm component", () => { beforeEach(() => { vi.mocked(searchAndRespond).mockClear(); - resetAutoSearchedQuery(); + resetHandledQuery(); window.history.replaceState({}, "", "/"); }); @@ -98,6 +100,37 @@ describe("SearchForm component", () => { await waitForPlaceholder(); }); + describe("Enter and Shift+Enter", () => { + afterEach(() => { + settingsPubSub[0]({ ...defaultSettings }); + }); + + it.each([ + [true, "{Enter}", true], + [true, "{Shift>}{Enter}{/Shift}", false], + [false, "{Shift>}{Enter}{/Shift}", true], + [false, "{Enter}", false], + ])( + "with enterToSubmit %s, pressing %s submits: %s", + async (enterToSubmit, keys, submits) => { + settingsPubSub[0]({ ...defaultSettings, enterToSubmit }); + const mockUpdate = vi.fn(); + const user = userEvent.setup(); + renderSearchForm("", mockUpdate); + + const textarea = await waitForPlaceholder(); + await user.type(textarea, "test query"); + await user.keyboard(keys); + + if (submits) { + expect(mockUpdate).toHaveBeenCalledWith("test query"); + } else { + expect(mockUpdate).not.toHaveBeenCalled(); + } + }, + ); + }); + it("calls updateQuery on submit", async () => { const mockUpdate = vi.fn(); const user = userEvent.setup(); diff --git a/client/components/Search/Form/SearchForm.tsx b/client/components/Search/Form/SearchForm.tsx index 331f99151aea17fedb5a2bb3d7b2a4009698223e..e1914ea941945211c2636ded91db118ca552a6c1 100644 --- a/client/components/Search/Form/SearchForm.tsx +++ b/client/components/Search/Form/SearchForm.tsx @@ -16,18 +16,16 @@ import DictationButton, { } from "@/components/DictationButton"; import { useHistoryRestore } from "@/hooks/useHistoryRestore"; import { useSearchHistory } from "@/hooks/useSearchHistory"; +import { isQueryHandled, markQueryAsHandled } from "@/modules/autoSearch"; import { resetSearchRunId } from "@/modules/history"; import { handleEnterKeyDown } from "@/modules/keyboard"; import { addLogEntry } from "@/modules/logEntries"; import { postMessageToParentWindow } from "@/modules/parentWindow"; +import { isRestoringFromHistoryPubSub, settingsPubSub } from "@/modules/pubSub"; import { - imageSearchResultsPubSub, - isRestoringFromHistoryPubSub, - responsePubSub, - settingsPubSub, - textSearchResultsPubSub, -} from "@/modules/pubSub"; -import { getRandomQuerySuggestion } from "@/modules/querySuggestions"; + DEFAULT_QUERY_SUGGESTION, + getRandomQuerySuggestion, +} from "@/modules/querySuggestions"; import { sleepUntilIdle } from "@/modules/sleep"; import { searchAndRespond } from "@/modules/textGeneration"; import HistoryButton from "../History/HistoryButton"; @@ -39,20 +37,6 @@ function getUrlQuery() { return new URLSearchParams(window.location.search).get("q"); } -/** - * The query whose auto-search already ran. Module-level so it survives - * the remount when MainPage swaps HomePage for SearchForm as the query - * goes from empty to non-empty. Kept as a single slot (not a Set) so it - * suppresses only the most recent auto-search, matching the behavior the - * user expects when navigating back to a previously searched query. - */ -let autoSearchedQuery: string | null = null; - -/** Exposed for tests to reset module state between runs. */ -export function resetAutoSearchedQuery(): void { - autoSearchedQuery = null; -} - interface SearchFormState { textAreaValue: string; suggestedQuery: string; @@ -81,18 +65,14 @@ export default memo(function SearchForm({ useEffect(() => { pendingDictationRef.current = null; }); - const defaultSuggestedQuery = "Anything you need!"; const [state, setState] = useState({ textAreaValue: query, - suggestedQuery: defaultSuggestedQuery, + suggestedQuery: DEFAULT_QUERY_SUGGESTION, }); const [, navigate] = useLocation(); const [pubSubSettings] = usePubSub(settingsPubSub); const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); - const [textSearchResults] = usePubSub(textSearchResultsPubSub); - const [imageSearchResults] = usePubSub(imageSearchResultsPubSub); - const [responseValue] = usePubSub(responsePubSub); const { addToHistory } = useSearchHistory(); const { restoreSearch } = useHistoryRestore((newQuery) => { setState((prev) => ({ ...prev, textAreaValue: newQuery })); @@ -102,7 +82,7 @@ export default memo(function SearchForm({ try { return await getRandomQuerySuggestion(); } catch { - return defaultSuggestedQuery; + return DEFAULT_QUERY_SUGGESTION; } }, []); @@ -112,17 +92,12 @@ export default memo(function SearchForm({ const normalizedUrlQuery = urlQuery?.trim(); if ( + urlQuery && normalizedUrlQuery && - normalizedUrlQuery !== autoSearchedQuery && + !isQueryHandled(normalizedUrlQuery) && !isRestoringFromHistory ) { - const hasRestoredResults = - textSearchResults.length > 0 || imageSearchResults.length > 0; - const hasRestoredResponse = responseValue.trim().length > 0; - if (hasRestoredResults || hasRestoredResponse) return; - - if (!urlQuery) return; - autoSearchedQuery = normalizedUrlQuery; + markQueryAsHandled(normalizedUrlQuery); updateQuery(urlQuery); setState((prevState) => ({ ...prevState, @@ -145,14 +120,7 @@ export default memo(function SearchForm({ }; void initializeComponent(); - }, [ - updateQuery, - isRestoringFromHistory, - textSearchResults.length, - imageSearchResults.length, - responseValue, - addToHistory, - ]); + }, [updateQuery, isRestoringFromHistory, addToHistory]); useEffect(() => { if (state.textAreaValue.length === 0) { @@ -163,7 +131,7 @@ export default memo(function SearchForm({ .catch(() => { setState((prev) => ({ ...prev, - suggestedQuery: defaultSuggestedQuery, + suggestedQuery: DEFAULT_QUERY_SUGGESTION, })); }); } @@ -182,7 +150,7 @@ export default memo(function SearchForm({ addLogEntry("Failed to get query suggestion"); setState((prev) => ({ ...prev, - suggestedQuery: defaultSuggestedQuery, + suggestedQuery: DEFAULT_QUERY_SUGGESTION, })); } } @@ -220,7 +188,7 @@ export default memo(function SearchForm({ const normalizedQuery = queryToEncode.trim(); if (normalizedQuery.length > 0) { - autoSearchedQuery = normalizedQuery; + markQueryAsHandled(normalizedQuery); } setState((prev) => ({ ...prev, textAreaValue: queryToEncode })); @@ -260,9 +228,7 @@ export default memo(function SearchForm({ }; const handleKeyDown = (event: KeyboardEvent) => { - if (event.key === "Enter" && !event.shiftKey) { - handleEnterKeyDown(event, pubSubSettings, startSearching); - } + handleEnterKeyDown(event, pubSubSettings, startSearching); }; return ( diff --git a/client/components/Search/History/HistoryDrawer.test.tsx b/client/components/Search/History/HistoryDrawer.test.tsx index 22281ef4d9a5eeaf0bb23cb1a39aee8d4214b9f5..3ce6e2b7c45c7940344959fcb52b446ebfbf8334 100644 --- a/client/components/Search/History/HistoryDrawer.test.tsx +++ b/client/components/Search/History/HistoryDrawer.test.tsx @@ -141,6 +141,44 @@ describe("HistoryDrawer component", () => { expect(onSearchSelect).toHaveBeenCalledWith(entry); }); + it("selects an entry once when its query is clicked", async () => { + const onSearchSelect = vi.fn(); + const entry = makeEntry(1, "quantum tunneling"); + mockHistory({ filteredSearches: [entry] }); + + const user = userEvent.setup(); + renderDrawer(onSearchSelect); + await user.click( + await screen.findByRole("button", { name: /quantum tunneling/ }), + ); + + expect(onSearchSelect).toHaveBeenCalledTimes(1); + expect(onSearchSelect).toHaveBeenCalledWith(entry); + }); + + it("selects an entry from the keyboard", async () => { + const onSearchSelect = vi.fn(); + const entry = makeEntry(1, "quantum tunneling"); + mockHistory({ filteredSearches: [entry] }); + + const user = userEvent.setup(); + renderDrawer(onSearchSelect); + const queryButton = await screen.findByRole("button", { + name: /quantum tunneling/, + }); + + for (let i = 0; i < 10 && document.activeElement !== queryButton; i++) { + await user.tab(); + } + expect(queryButton).toHaveFocus(); + + await user.keyboard("{Enter}"); + await user.keyboard(" "); + + expect(onSearchSelect).toHaveBeenCalledTimes(2); + expect(onSearchSelect).toHaveBeenCalledWith(entry); + }); + it("pins an entry without selecting it", async () => { const onSearchSelect = vi.fn(); const entry = makeEntry(1, "quantum tunneling"); diff --git a/client/components/Search/History/HistoryDrawer.tsx b/client/components/Search/History/HistoryDrawer.tsx index 53547b1db98ef0e90304f814e5f80e8f65a59403..20556086f95f412b225e476db495b6ebb2b63c16 100644 --- a/client/components/Search/History/HistoryDrawer.tsx +++ b/client/components/Search/History/HistoryDrawer.tsx @@ -12,6 +12,7 @@ import { Text, TextInput, Tooltip, + UnstyledButton, } from "@mantine/core"; import { useReducedMotion } from "@mantine/hooks"; import { @@ -95,22 +96,30 @@ export default function HistoryDrawer({ onClick={() => handleSearchSelect(search)} > - - - - {search.query} - - + { + e.stopPropagation(); + handleSearchSelect(search); + }} + style={{ flex: 1, minWidth: 0, textAlign: "left" }} + > + + + + {search.query} + + - - - {formatRelativeTime(search.timestamp)} - - + + + {formatRelativeTime(search.timestamp)} + + + void; } +const SETTINGS_KEYS = [ + "enableHistory", + "historyMaxEntries", + "historyAutoCleanup", + "historyRetentionDays", +] as const; + export default function HistorySettings({ onClose }: HistorySettingsProps) { - const [settings, setSettings] = usePubSub(settingsPubSub); const { recentSearches, llmResponseCount, chatMessageCount, clearAll } = useSearchHistory(); const [showClearConfirm, setShowClearConfirm] = useState(false); @@ -30,20 +34,7 @@ export default function HistorySettings({ onClose }: HistorySettingsProps) { const hasHistory = recentSearches.length > 0 || llmResponseCount > 0 || chatMessageCount > 0; - const form = useForm({ - initialValues: { - enableHistory: settings.enableHistory, - historyMaxEntries: settings.historyMaxEntries, - historyAutoCleanup: settings.historyAutoCleanup, - historyRetentionDays: settings.historyRetentionDays, - }, - onValuesChange: (values) => { - setSettings({ - ...settings, - ...values, - }); - }, - }); + const form = useSettingsForm(SETTINGS_KEYS); const handleClearHistory = async () => { try { diff --git a/client/hooks/useHistoryRestore.test.ts b/client/hooks/useHistoryRestore.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..9df477333eba01642dcc820b8878a1a617c40496 --- /dev/null +++ b/client/hooks/useHistoryRestore.test.ts @@ -0,0 +1,153 @@ +import { act, cleanup, renderHook } from "@testing-library/react"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import type { ImageResults, SearchEntry, TextResults } from "@/modules/history"; +import { getLatestLlmResponseForEntry } from "@/modules/history"; +import { + getLlmTextSearchResults, + getSuppressNextFollowUp, + imageSearchResultsPubSub, + imageSearchStatePubSub, + textSearchResultsPubSub, + updateImageSearchResults, + updateSuppressNextFollowUp, +} from "@/modules/pubSub"; +import { useHistoryRestore } from "./useHistoryRestore"; + +vi.mock("wouter", () => ({ + useLocation: () => ["/", vi.fn()], +})); + +vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() })); + +vi.mock("@/modules/history", async (importOriginal) => ({ + ...(await importOriginal()), + getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null), + getChatMessagesForQuery: vi.fn().mockResolvedValue([]), +})); + +const textResults: TextResults = { + type: "text", + items: [ + { + title: "Saved text", + snippet: "Saved snippet", + url: "https://example.com/text", + }, + ], +}; + +const imageResults: ImageResults = { + type: "image", + items: [ + { + title: "Saved image", + url: "https://example.com/image.png", + thumbnail: "https://example.com/thumbnail.png", + sourceUrl: "https://example.com/source", + }, + { + title: "Image without a source", + url: "https://example.com/other.png", + thumbnail: "https://example.com/other-thumbnail.png", + }, + ], +}; + +const expectedImages = [ + [ + "Saved image", + "https://example.com/image.png", + "https://example.com/thumbnail.png", + "https://example.com/source", + ], + [ + "Image without a source", + "https://example.com/other.png", + "https://example.com/other-thumbnail.png", + "", + ], +]; + +beforeEach(() => { + vi.useFakeTimers(); + vi.mocked(getLatestLlmResponseForEntry).mockResolvedValue(null); + updateSuppressNextFollowUp(false); + updateImageSearchResults([ + ["Previous image", "old.png", "old-thumb.png", ""], + ]); +}); + +afterEach(() => { + cleanup(); + vi.runOnlyPendingTimers(); + vi.useRealTimers(); +}); + +async function restoreEntry(payload: Partial) { + const { result } = renderHook(() => useHistoryRestore(vi.fn())); + await act(async () => { + await result.current.restoreSearch({ + query: "saved search", + timestamp: 1, + ...payload, + }); + }); +} + +describe("useHistoryRestore", () => { + it("restores both text and images from the same search", async () => { + await restoreEntry({ results: textResults, textResults, imageResults }); + + expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages); + const expectedText = [ + ["Saved text", "Saved snippet", "https://example.com/text"], + ]; + expect(textSearchResultsPubSub[2]()).toEqual(expectedText); + expect(getLlmTextSearchResults()).toEqual(expectedText); + expect(imageSearchStatePubSub[2]()).toBe("completed"); + }); + + it.each([ + { name: "image-only entry", payload: { imageResults } }, + { name: "legacy image-only entry", payload: { results: imageResults } }, + { + name: "legacy images alongside newer text results", + payload: { textResults, results: imageResults }, + }, + { + name: "newer images alongside an empty legacy image payload", + payload: { + imageResults, + results: { type: "image", items: [] } as ImageResults, + }, + }, + ])("restores $name", async ({ payload }) => { + await restoreEntry(payload); + + expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages); + expect(imageSearchStatePubSub[2]()).toBe("completed"); + }); + + it("clears previous images when the saved search has none", async () => { + await restoreEntry({ textResults }); + + expect(imageSearchResultsPubSub[2]()).toEqual([]); + expect(imageSearchStatePubSub[2]()).toBe("completed"); + }); + + it("leaves suppressNextFollowUp false when the restored entry has no saved response", async () => { + await restoreEntry({ textResults }); + + expect(getSuppressNextFollowUp()).toBe(false); + }); + + it("sets suppressNextFollowUp true when the restored entry has a saved response", async () => { + vi.mocked(getLatestLlmResponseForEntry).mockResolvedValueOnce( + "Saved AI answer.", + ); + + await restoreEntry({ textResults }); + + expect(getSuppressNextFollowUp()).toBe(true); + }); +}); diff --git a/client/hooks/useHistoryRestore.ts b/client/hooks/useHistoryRestore.ts index cfb1cdd521a9769d662fa2bd4f05e7d99ecf004d..a4e6af2e5de87c3c464e1af9538e3e0e000f7144 100644 --- a/client/hooks/useHistoryRestore.ts +++ b/client/hooks/useHistoryRestore.ts @@ -1,5 +1,6 @@ import { useCallback } from "react"; import { useLocation } from "wouter"; +import { markQueryAsHandled } from "../modules/autoSearch"; import type { SearchEntry } from "../modules/history"; import { getChatMessagesForQuery, @@ -38,13 +39,17 @@ export function useHistoryRestore( const restoreSearch = useCallback( async (entry: SearchEntry) => { const selectedQuery = entry.query; + // The URL is about to hold this query; without the mark, an entry that + // restores empty would fall through to the URL auto-search once + // isRestoringFromHistory flips back, appending a duplicate history + // entry and starting a live search. + markQueryAsHandled(selectedQuery); updateQuery(selectedQuery); const searchRunId = entry.searchRunId || entry.query; setCurrentSearchRunId(searchRunId); updateIsRestoringFromHistory(true); - updateSuppressNextFollowUp(true); // Excerpts belong to the search that fetched them; a follow-up on the // restored entry must not be grounded on the live search's pages. updatePageContents({}); @@ -81,7 +86,9 @@ export function useHistoryRestore( } if (hasImageResults(entry)) { - const results = getResultsFromEntry(entry); + const results = + entry.imageResults ?? + (entry.results?.type === "image" ? entry.results : null); if (results && results.type === "image") { const imageTuples: ImageSearchResults = results.items.map((it) => [ it.title, @@ -102,9 +109,11 @@ export function useHistoryRestore( const savedResponse = await getLatestLlmResponseForEntry(entry); if (savedResponse && savedResponse.trim().length > 0) { + updateSuppressNextFollowUp(true); updateResponse(savedResponse); updateTextGenerationState("completed"); } else { + updateSuppressNextFollowUp(false); updateResponse(""); updateTextGenerationState("idle"); } diff --git a/client/hooks/useSearchHistory.test.ts b/client/hooks/useSearchHistory.test.ts index 909a436e5d5c65126f9decd8798102a7722bb672..0b52fdaa675b4f87de652b77ea4912b6beb88c1a 100644 --- a/client/hooks/useSearchHistory.test.ts +++ b/client/hooks/useSearchHistory.test.ts @@ -7,6 +7,7 @@ import { type SearchEntry, type TextResults, } from "@/modules/history"; +import { getSettings } from "@/modules/pubSub"; import * as stringFormatters from "@/modules/stringFormatters"; import { FILTER_DEBOUNCE_MS, @@ -83,6 +84,33 @@ async function settle() { } describe("useSearchHistory", () => { + it("leaves IndexedDB alone while history is turned off", async () => { + const settingsMock = vi.mocked(getSettings); + const historyOn = settingsMock.getMockImplementation(); + settingsMock.mockImplementation( + () => + ({ + ...historyOn?.(), + enableHistory: false, + }) as ReturnType, + ); + const readSpy = vi.spyOn(historyModule, "getRecentSearches"); + + try { + const { result } = renderHook(() => useSearchHistory({ limit: 100 })); + await settle(); + await act(async () => { + await vi.advanceTimersByTimeAsync(REFRESH_INTERVAL_MS); + }); + + expect(readSpy).not.toHaveBeenCalled(); + expect(result.current.isLoading).toBe(false); + expect(result.current.recentSearches).toEqual([]); + } finally { + if (historyOn) settingsMock.mockImplementation(historyOn); + } + }); + it("reads IndexedDB only on load, never while typing", async () => { const readSpy = vi.spyOn(historyModule, "getRecentSearches"); @@ -223,6 +251,58 @@ describe("useSearchHistory", () => { expect(result.current.filteredSearches).toHaveLength(SEEDED_QUERIES.length); }); + it("deletes an entry's answer and chat with it and leaves the other entries' rows", async () => { + // Seeding shares one search run; give each entry its own, as separate + // searches have, with an answer and a chat turn stored under it. + const entries = await historyDatabase.searches.toArray(); + for (const entry of entries) { + const runId = `run-${entry.id}`; + await historyDatabase.searches.update(entry.id as number, { + searchRunId: runId, + }); + await historyDatabase.llmResponses.add({ + searchRunId: runId, + searchId: entry.id, + prompt: entry.query, + response: "answer", + model: "m", + timestamp: Date.now(), + }); + await historyDatabase.chatHistory.add({ + role: "user", + content: "chat", + timestamp: Date.now(), + conversationId: runId, + }); + } + const { result } = renderHook(() => useSearchHistory({ limit: 100 })); + await settle(); + + const [target] = entries; + await act(async () => { + await result.current.deleteEntry(target.id as number); + }); + + const targetRun = `run-${target.id}`; + expect(await historyDatabase.searches.get(target.id as number)).toBe( + undefined, + ); + expect( + await historyDatabase.llmResponses + .where("searchRunId") + .equals(targetRun) + .count(), + ).toBe(0); + expect( + await historyDatabase.chatHistory + .where("conversationId") + .equals(targetRun) + .count(), + ).toBe(0); + expect(await historyDatabase.llmResponses.count()).toBe(entries.length - 1); + expect(await historyDatabase.chatHistory.count()).toBe(entries.length - 1); + }); + it("paginates from memory: page changes and queries trigger no reads", async () => { await addSearchToHistory("wine tasting porto", textResults); vi.advanceTimersByTime(1000); diff --git a/client/hooks/useSearchHistory.ts b/client/hooks/useSearchHistory.ts index 2badb6eb4d0ef80539505c9e3fe1429e24fd20d7..d345d439434171599e46b52e8ca259a0561d53d9 100644 --- a/client/hooks/useSearchHistory.ts +++ b/client/hooks/useSearchHistory.ts @@ -5,6 +5,7 @@ import { getRecentSearches, historyDatabase, type ImageResults, + isHistoryEnabled, type SearchEntry, type TextResults, } from "../modules/history"; @@ -94,6 +95,15 @@ export function useSearchHistory( setIsLoading(true); setError(null); + // Reading would open the database too, so a disabled history is shown + // as empty without touching IndexedDB. + if (!isHistoryEnabled()) { + setLlmResponseCount(0); + setChatMessageCount(0); + setEntries([]); + return; + } + const searches = await getRecentSearches( enablePagination ? 1000 : limit * 2, ); @@ -234,7 +244,9 @@ export function useSearchHistory( async (searchId: number) => { try { const search = await historyDatabase.searches.get(searchId); - await historyDatabase.searches.delete(searchId); + if (search) { + await historyDatabase.deleteSearchesWithChildren([search]); + } await refreshHistory(); if (search) { diff --git a/client/hooks/useSettingsForm.test.ts b/client/hooks/useSettingsForm.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..1bc9b9ca8183937a144c16335b1132b0921114e5 --- /dev/null +++ b/client/hooks/useSettingsForm.test.ts @@ -0,0 +1,90 @@ +import { act, renderHook } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { settingsPubSub } from "@/modules/pubSub"; +import { defaultSettings } from "@/modules/settings"; +import { useSettingsForm } from "./useSettingsForm"; + +const [updateSettings, onSettingsChange, getSettings] = settingsPubSub; + +describe("useSettingsForm", () => { + beforeEach(() => { + updateSettings(defaultSettings); + }); + + it("holds only the keys it was given", () => { + const { result } = renderHook(() => + useSettingsForm(["enterToSubmit", "enableTextSearch"]), + ); + + expect(result.current.values).toEqual({ + enterToSubmit: true, + enableTextSearch: true, + }); + }); + + it("writes a changed key into the settings", () => { + const { result } = renderHook(() => useSettingsForm(["enterToSubmit"])); + + act(() => result.current.setFieldValue("enterToSubmit", false)); + + expect(getSettings()).toEqual({ ...defaultSettings, enterToSubmit: false }); + }); + + it("keeps a value another writer changed after the form was opened", () => { + const { result } = renderHook(() => useSettingsForm(["enterToSubmit"])); + + act(() => + updateSettings({ + ...getSettings(), + enableTextSearch: false, + wllamaModelId: "another-model", + }), + ); + act(() => result.current.setFieldValue("enterToSubmit", false)); + + expect(getSettings()).toEqual({ + ...defaultSettings, + enableTextSearch: false, + wllamaModelId: "another-model", + enterToSubmit: false, + }); + }); + + it("writes every key of one change in a single update", () => { + updateSettings({ + ...defaultSettings, + textToSpeechEngine: "local", + selectedVoiceId: "piper:voice", + }); + const { result } = renderHook(() => + useSettingsForm(["textToSpeechEngine", "selectedVoiceId"]), + ); + const onChange = vi.fn(); + const unsubscribe = onSettingsChange(onChange); + + act(() => + result.current.setValues({ + textToSpeechEngine: "system", + selectedVoiceId: "", + }), + ); + unsubscribe(); + + expect(onChange).toHaveBeenCalledTimes(1); + expect(getSettings()).toMatchObject({ + textToSpeechEngine: "system", + selectedVoiceId: "", + }); + }); + + it("does not write when no value changed", () => { + const { result } = renderHook(() => useSettingsForm(["enterToSubmit"])); + const onChange = vi.fn(); + const unsubscribe = onSettingsChange(onChange); + + act(() => result.current.setFieldValue("enterToSubmit", true)); + unsubscribe(); + + expect(onChange).not.toHaveBeenCalled(); + }); +}); diff --git a/client/hooks/useSettingsForm.ts b/client/hooks/useSettingsForm.ts new file mode 100644 index 0000000000000000000000000000000000000000..91350d5ade1f7b37ef25b44a1a9cba1d28a2a821 --- /dev/null +++ b/client/hooks/useSettingsForm.ts @@ -0,0 +1,32 @@ +import { useForm } from "@mantine/form"; +import { usePubSub } from "create-pubsub/react"; +import { settingsPubSub } from "@/modules/pubSub"; +import type { defaultSettings } from "@/modules/settings"; + +type Settings = typeof defaultSettings; + +function pick(source: T, keys: readonly K[]): Pick { + const picked = {} as Pick; + for (const key of keys) picked[key] = source[key]; + return picked; +} + +/** + * A form over the settings in `keys`. Each change writes only the keys that + * changed, merged into the settings as they are at that moment, so a form that + * has been open for a while cannot put back a value another writer changed. + */ +export function useSettingsForm(keys: readonly K[]) { + const [settings, setSettings] = usePubSub(settingsPubSub); + const [, , getSettings] = settingsPubSub; + + return useForm>({ + initialValues: pick(settings, keys), + onValuesChange: (values, previous) => { + const changed = keys.filter((key) => values[key] !== previous[key]); + if (changed.length === 0) return; + + setSettings({ ...getSettings(), ...pick(values, changed) }); + }, + }); +} diff --git a/client/modules/accessKey.test.ts b/client/modules/accessKey.test.ts index c35cc653a82b52f35dac65d52f48720ab7e5d0ff..4f78b55ee3d277b79fa3b05e82fac054b2a1ccfb 100644 --- a/client/modules/accessKey.test.ts +++ b/client/modules/accessKey.test.ts @@ -71,12 +71,24 @@ describe("Access Key Module", () => { expect(result).toBe("invalid"); }); - it("should return invalid on network error", async () => { + it("should return unreachable on network error", async () => { const { validateAccessKey } = await import("./accessKey"); mockFetch.mockRejectedValue(new Error("Network error")); const result = await validateAccessKey("test-key"); - expect(result).toBe("invalid"); + expect(result).toBe("unreachable"); + }); + + it("should return unreachable when the server reply is not JSON", async () => { + const { validateAccessKey } = await import("./accessKey"); + mockFetch.mockResolvedValue({ + ok: false, + status: 502, + json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token <")), + }); + + const result = await validateAccessKey("test-key"); + expect(result).toBe("unreachable"); }); it("should send a hash the server can verify against the access key", async () => { diff --git a/client/modules/accessKey.ts b/client/modules/accessKey.ts index ac3448b83e552d8fb9bb3d3cf5888f1b0318a4ed..1644e90295365b5e17b46d976e37f6313949b50b 100644 --- a/client/modules/accessKey.ts +++ b/client/modules/accessKey.ts @@ -26,7 +26,11 @@ async function hashAccessKey(accessKey: string): Promise { * Validates the key against the server; on success the hash is stored locally * so later loads can go through `verifyStoredAccessKey`. */ -export type AccessKeyResult = "valid" | "invalid" | "rateLimited"; +export type AccessKeyResult = + | "valid" + | "invalid" + | "rateLimited" + | "unreachable"; export async function validateAccessKey( accessKey: string, @@ -66,6 +70,8 @@ export async function validateAccessKey( return "invalid"; } catch (error) { + // The server never judged the key (no connection, or a reply that is not + // the expected JSON), so access stays closed without calling it wrong. addLogEntry(`Error validating access key: ${error}`); notifications.show({ title: "Error validating access key", @@ -73,7 +79,7 @@ export async function validateAccessKey( color: "red", position: "top-right", }); - return "invalid"; + return "unreachable"; } } diff --git a/client/modules/autoSearch.ts b/client/modules/autoSearch.ts new file mode 100644 index 0000000000000000000000000000000000000000..bf73fb7ed8aa0b0e9101f934404128c436ace75c --- /dev/null +++ b/client/modules/autoSearch.ts @@ -0,0 +1,22 @@ +/** + * The query the URL currently belongs to: the one whose auto-search already + * ran, or that was just submitted or restored from history. Module-level so + * it survives the remount when MainPage swaps HomePage for SearchForm as the + * query goes from empty to non-empty. Kept as a single slot (not a Set) so it + * suppresses only the most recent auto-search, matching the behavior the + * user expects when navigating back to a previously searched query. + */ +let handledQuery: string | null = null; + +export function markQueryAsHandled(query: string): void { + handledQuery = query.trim(); +} + +export function isQueryHandled(query: string): boolean { + return query.trim() === handledQuery; +} + +/** Exposed for tests to reset module state between runs. */ +export function resetHandledQuery(): void { + handledQuery = null; +} diff --git a/client/modules/chatHelpers.test.ts b/client/modules/chatHelpers.test.ts index 612751dcfa02f42933b915fd5719cb12fdb0a38e..7373f6f1e95c07ad251ff947614faf4662da4018 100644 --- a/client/modules/chatHelpers.test.ts +++ b/client/modules/chatHelpers.test.ts @@ -337,6 +337,22 @@ describe("runFollowUpSearch", () => { expect(mockSearchText).toHaveBeenCalled(); }); + it("searches with at most 2000 characters when the chat input is longer", async () => { + const longInput = "x".repeat(2001); + mockSearchText.mockResolvedValueOnce({ results: [], stale: false }); + + await runFollowUpSearch( + [{ role: "user", content: longInput }], + longInput, + makeSettings({ enableImageSearch: false }), + [], + [], + ); + + const [query] = mockSearchText.mock.calls[0]; + expect(query.length).toBeLessThanOrEqual(2000); + }); + it("skips text search when disabled", async () => { await runFollowUpSearch( [{ role: "user", content: "hello" }], diff --git a/client/modules/followUpQuestions.test.ts b/client/modules/followUpQuestions.test.ts index 95cf3cdfcbe035ebba02f31036529b0feb5449ae..33a29119e3208ace3f2e1907fe9e1807287629f6 100644 --- a/client/modules/followUpQuestions.test.ts +++ b/client/modules/followUpQuestions.test.ts @@ -1,23 +1,16 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import { generateFollowUpQuestion } from "./followUpQuestions"; -vi.mock("./pubSub", () => ({ - getSuppressNextFollowUp: vi.fn(() => false), -})); - vi.mock("./textGeneration", () => ({ generateChatResponse: vi.fn(), })); -import { getSuppressNextFollowUp } from "./pubSub"; import { generateChatResponse } from "./textGeneration"; const mockedGenerateChatResponse = vi.mocked(generateChatResponse); -const mockedGetSuppressNextFollowUp = vi.mocked(getSuppressNextFollowUp); beforeEach(() => { vi.clearAllMocks(); - mockedGetSuppressNextFollowUp.mockReturnValue(false); }); describe("generateFollowUpQuestion", () => { @@ -79,16 +72,19 @@ describe("generateFollowUpQuestion", () => { expect(question).toBe(""); }); +}); - it("returns an empty string when follow-up questions are suppressed", async () => { - mockedGetSuppressNextFollowUp.mockReturnValue(true); +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?"); - const question = await generateFollowUpQuestion({ + await generateFollowUpQuestion({ topic: "cats", currentContent: "Cats are independent.", }); - expect(mockedGenerateChatResponse).not.toHaveBeenCalled(); - expect(question).toBe(""); + expect(await historyDatabase.chatHistory.count()).toBe(before); }); }); diff --git a/client/modules/followUpQuestions.ts b/client/modules/followUpQuestions.ts index e926693ebce4b3dcd70cbceb2f43514c1aea0775..a0cb63034be5fc6cabbfbd0b4f6f2eacbba592ef 100644 --- a/client/modules/followUpQuestions.ts +++ b/client/modules/followUpQuestions.ts @@ -1,25 +1,7 @@ -import { historyDatabase } from "./history"; import { addLogEntry } from "./logEntries"; -import { getSuppressNextFollowUp } from "./pubSub"; import { generateChatResponse } from "./textGeneration"; import type { ChatMessage } from "./types"; -async function saveChatHistoryEntry( - role: "user" | "assistant", - content: string, -) { - await historyDatabase.chatHistory - .add({ - role, - content, - timestamp: Date.now(), - conversationId: `follow-up-${Date.now()}`, - }) - .catch((error) => { - addLogEntry(`Error saving chat history: ${error}`); - }); -} - interface FollowUpQuestionParams { topic: string; currentContent: string; @@ -32,14 +14,8 @@ export async function generateFollowUpQuestion({ previousQuestions = [], }: FollowUpQuestionParams): Promise { try { - if (getSuppressNextFollowUp()) { - return ""; - } - addLogEntry("Generating a follow-up question"); - await saveChatHistoryEntry("user", topic); - const promptMessages: ChatMessage[] = [ { role: "user", @@ -84,8 +60,6 @@ Respond with just the question, no additional text or explanations.`, const response = await generateChatResponse(promptMessages, () => {}); - await saveChatHistoryEntry("assistant", response); - const lines = response .trim() .split("\n") @@ -109,8 +83,6 @@ Respond with just the question, no additional text or explanations.`, addLogEntry("Generated follow-up question successfully"); - await saveChatHistoryEntry("assistant", questionLine); - return questionLine; } catch (error) { addLogEntry(`Error generating follow-up question: ${error}`); diff --git a/client/modules/history.test.ts b/client/modules/history.test.ts index 88d2d5189a4ab642acf5d1fb39636065f4037fe0..6fe89543c6179532e56186fff0afaee0b3b0d38b 100644 --- a/client/modules/history.test.ts +++ b/client/modules/history.test.ts @@ -1,4 +1,6 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import Dexie from "dexie"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { getSettings } from "./pubSub"; // Pin auto-cleanup off and avoid pubSub's module-level localStorage reads. vi.mock("./pubSub", () => ({ @@ -607,3 +609,300 @@ describe("History Module - Dexie CRUD", () => { }); }); }); + +describe("History Module - Enable Search History off", () => { + const settingsMock = vi.mocked(getSettings); + const historyOn = settingsMock.getMockImplementation(); + const textResults = { + type: "text" as const, + items: [{ title: "T", url: "https://t.com", snippet: "S" }], + }; + + beforeEach(async () => { + const { historyDatabase } = await import("./history"); + await historyDatabase.searches.clear(); + await historyDatabase.llmResponses.clear(); + await historyDatabase.chatHistory.clear(); + settingsMock.mockImplementation( + () => + ({ + ...historyOn?.(), + enableHistory: false, + }) as ReturnType, + ); + }); + + afterEach(async () => { + if (historyOn) settingsMock.mockImplementation(historyOn); + const { historyDatabase } = await import("./history"); + if (!historyDatabase.isOpen()) await historyDatabase.open(); + }); + + it("writes no search, result, answer or chat message", async () => { + const { + addSearchToHistory, + getCurrentSearchRunId, + historyDatabase, + saveChatMessageForQuery, + saveLlmResponseForQuery, + updateSearchResults, + } = await import("./history"); + + const id = await addSearchToHistory("private query", textResults); + await updateSearchResults(getCurrentSearchRunId(), textResults); + await saveLlmResponseForQuery("private query", "answer", "m"); + await saveChatMessageForQuery("private query", "user", "follow-up"); + + expect(id).toBeUndefined(); + expect(await historyDatabase.searches.count()).toBe(0); + expect(await historyDatabase.llmResponses.count()).toBe(0); + expect(await historyDatabase.chatHistory.count()).toBe(0); + }); + + it("does not open a database the app never opened", async () => { + // The state at startup with history off: index.tsx skips open(), and + // Dexie would open the database on the first query. + const { addSearchToHistory, historyDatabase } = await import("./history"); + historyDatabase.close({ disableAutoOpen: false }); + + await addSearchToHistory("private query", textResults); + + expect(historyDatabase.isOpen()).toBe(false); + }); +}); + +describe("History Module - a search takes its answers and chats with it", () => { + const settingsMock = vi.mocked(getSettings); + const historyOn = settingsMock.getMockImplementation(); + + function enableCleanup( + overrides: { + historyRetentionDays?: number; + historyMaxEntries?: number; + } = {}, + ) { + settingsMock.mockImplementation( + () => + ({ + ...historyOn?.(), + historyAutoCleanup: true, + historyRetentionDays: 30, + historyMaxEntries: 500, + ...overrides, + }) as ReturnType, + ); + } + + /** A search plus the answer and chat turn stored under its key. */ + async function seedSearch({ + key, + ageMs = 0, + pinned = false, + legacy = false, + }: { + key: string; + ageMs?: number; + pinned?: boolean; + legacy?: boolean; + }) { + const { historyDatabase } = await import("./history"); + const timestamp = Date.now() - ageMs; + const searchId = await historyDatabase.searches.add({ + ...(legacy ? {} : { searchRunId: key }), + query: key, + timestamp, + pinned, + source: "user", + }); + await historyDatabase.llmResponses.add({ + searchRunId: key, + searchId: searchId as number, + prompt: key, + response: `answer for ${key}`, + model: "m", + timestamp, + }); + await historyDatabase.chatHistory.add({ + role: "user", + content: `chat for ${key}`, + timestamp, + conversationId: key, + }); + return searchId as number; + } + + async function counts() { + const { historyDatabase } = await import("./history"); + return { + searches: await historyDatabase.searches.count(), + llmResponses: await historyDatabase.llmResponses.count(), + chatHistory: await historyDatabase.chatHistory.count(), + }; + } + + /** The search, answer and chat stored under `key` are the only rows left. */ + async function expectOnlyRowsOf(key: string) { + const { historyDatabase } = await import("./history"); + const searches = await historyDatabase.searches.toArray(); + const answers = await historyDatabase.llmResponses.toArray(); + const chats = await historyDatabase.chatHistory.toArray(); + expect(searches.map((search) => search.searchRunId)).toEqual([key]); + expect(answers.map((answer) => answer.searchRunId)).toEqual([key]); + expect(chats.map((chat) => chat.conversationId)).toEqual([key]); + } + + const sixtyDays = 60 * 24 * 60 * 60 * 1000; + + beforeEach(async () => { + const { historyDatabase } = await import("./history"); + await historyDatabase.searches.clear(); + await historyDatabase.llmResponses.clear(); + await historyDatabase.chatHistory.clear(); + }); + + afterEach(() => { + if (historyOn) settingsMock.mockImplementation(historyOn); + }); + + it("removes an expired search's answer and chat with it", async () => { + enableCleanup(); + await seedSearch({ key: "old", ageMs: sixtyDays }); + await seedSearch({ key: "recent" }); + + const { historyDatabase } = await import("./history"); + await historyDatabase.runCleanup(); + + await expectOnlyRowsOf("recent"); + }); + + it("keeps a pinned search's answer and chat", async () => { + enableCleanup(); + await seedSearch({ key: "pinned", ageMs: sixtyDays, pinned: true }); + + const { historyDatabase } = await import("./history"); + await historyDatabase.runCleanup(); + + await expectOnlyRowsOf("pinned"); + }); + + it("trims answers and chats with the searches over the entry limit", async () => { + enableCleanup({ historyRetentionDays: 0, historyMaxEntries: 10 }); + for (let i = 0; i < 15; i++) { + await seedSearch({ key: `run-${i}`, ageMs: (15 - i) * 1000 }); + } + + const { historyDatabase } = await import("./history"); + await historyDatabase.runCleanup(); + + expect(await counts()).toEqual({ + searches: 10, + llmResponses: 10, + chatHistory: 10, + }); + }); + + it("finds a legacy search's answer and chat by its query", async () => { + enableCleanup(); + await seedSearch({ key: "legacy query", ageMs: sixtyDays, legacy: true }); + + const { historyDatabase } = await import("./history"); + await historyDatabase.runCleanup(); + + expect(await counts()).toEqual({ + searches: 0, + llmResponses: 0, + chatHistory: 0, + }); + }); + + it("keeps the rows of a key another search still reads", async () => { + enableCleanup(); + // Two searches of one run share the key their answer is stored under. + await seedSearch({ key: "shared-run", ageMs: sixtyDays }); + const { historyDatabase } = await import("./history"); + await historyDatabase.searches.add({ + searchRunId: "shared-run", + query: "second search of the run", + timestamp: Date.now(), + pinned: false, + source: "user", + }); + + await historyDatabase.runCleanup(); + + await expectOnlyRowsOf("shared-run"); + }); + + it("deletes one search with its answer and chat and leaves the others", async () => { + const target = await seedSearch({ key: "delete-me" }); + await seedSearch({ key: "keep-me" }); + + const { historyDatabase } = await import("./history"); + const entry = await historyDatabase.searches.get(target); + if (!entry) throw new Error("seeded search is missing"); + await historyDatabase.deleteSearchesWithChildren([entry]); + + await expectOnlyRowsOf("keep-me"); + }); + + it("drops the rows no search owns when a version 1 database is upgraded", async () => { + const { historyDatabase } = await import("./history"); + historyDatabase.close({ disableAutoOpen: false }); + await Dexie.delete("History"); + + const v1 = new Dexie("History"); + v1.version(1).stores({ + searches: "++id, searchRunId, query, timestamp, source, pinned, results", + llmResponses: "++id, searchId, searchRunId, timestamp, model", + chatHistory: + "++id, conversationId, timestamp, [conversationId+timestamp]", + }); + const now = Date.now(); + await v1.table("searches").add({ + searchRunId: "live", + query: "live", + timestamp: now, + pinned: false, + }); + await v1.table("llmResponses").bulkAdd([ + { + searchRunId: "live", + prompt: "p", + response: "kept", + model: "m", + timestamp: now, + }, + { + searchRunId: "gone", + prompt: "p", + response: "orphan", + model: "m", + timestamp: now, + }, + ]); + await v1.table("chatHistory").bulkAdd([ + { role: "user", content: "kept", timestamp: now, conversationId: "live" }, + { + role: "user", + content: "orphan", + timestamp: now, + conversationId: "gone", + }, + { + role: "user", + content: "follow-up", + timestamp: now, + conversationId: "follow-up-1", + }, + ]); + v1.close(); + + await historyDatabase.open(); + + const answers = await historyDatabase.llmResponses.toArray(); + const chats = await historyDatabase.chatHistory.toArray(); + expect(answers.map((row) => row.response)).toEqual(["kept"]); + expect(chats.map((row) => row.content)).toEqual(["kept"]); + expect(await historyDatabase.searches.count()).toBe(1); + }); +}); diff --git a/client/modules/history.ts b/client/modules/history.ts index f4cfd4d3e9beb4b9d23654ad7453f62c0417d1e0..9c2a1a1a1189180a767aafe69b76e341ced41034 100644 --- a/client/modules/history.ts +++ b/client/modules/history.ts @@ -1,5 +1,6 @@ -import Dexie, { type Table } from "dexie"; +import Dexie, { type Table, type Transaction } from "dexie"; import { addLogEntry } from "./logEntries"; +import { getSettings } from "./pubSub"; let currentSearchRunId: string | null = null; @@ -14,6 +15,17 @@ export function getCurrentSearchRunId(): string { return currentSearchRunId; } +/** + * History is on unless the user turned it off. The check guards every read and + * write instead of relying on the database being closed: Dexie opens a + * database that was never opened on its first query, so skipping `open()` at + * startup does not keep searches out of IndexedDB. Settings saved before the + * toggle existed have no value, which counts as on, like the default. + */ +export function isHistoryEnabled(): boolean { + return getSettings().enableHistory !== false; +} + export function setCurrentSearchRunId(id: string): void { currentSearchRunId = id; } @@ -104,6 +116,43 @@ interface ChatHistoryMessage { metadata?: Record; } +/** + * The key a search's answers and chat turns are stored under. Entries written + * before `searchRunId` existed use their query, as the readers in + * `getLatestLlmResponseForEntry` and `useHistoryRestore` do. + */ +function childKeyOf(search: SearchEntry): string { + return search.searchRunId || search.query; +} + +/** + * Version 1 never removed a search's answers or chat turns with it, and + * follow-up questions wrote chat rows under `follow-up-*` ids that nothing + * reads, so an existing install carries rows that no search owns. They are + * dropped once, on the upgrade. Rows that a search still reads stay. + */ +async function dropRowsNoSearchOwns(tx: Transaction): Promise { + const searches = await tx.table("searches").toArray(); + const liveKeys = new Set(searches.map(childKeyOf)); + await tx + .table("chatHistory") + .filter((message) => !liveKeys.has(message.conversationId)) + .delete(); + await tx + .table("llmResponses") + .filter( + (response) => + !response.searchRunId || !liveKeys.has(response.searchRunId), + ) + .delete(); +} + +const historySchema = { + searches: "++id, searchRunId, query, timestamp, source, pinned, results", + llmResponses: "++id, searchId, searchRunId, timestamp, model", + chatHistory: "++id, conversationId, timestamp, [conversationId+timestamp]", +}; + class HistoryDatabase extends Dexie { searches!: Table; llmResponses!: Table; @@ -112,12 +161,55 @@ class HistoryDatabase extends Dexie { constructor() { super("History"); - this.version(1).stores({ - searches: "++id, searchRunId, query, timestamp, source, pinned, results", - llmResponses: "++id, searchId, searchRunId, timestamp, model", - chatHistory: - "++id, conversationId, timestamp, [conversationId+timestamp]", - }); + this.version(1).stores(historySchema); + this.version(2).stores(historySchema).upgrade(dropRowsNoSearchOwns); + } + + /** + * Deletes searches together with their answers and chat turns, in one + * transaction, so a pruned search never leaves rows behind that the UI can + * no longer reach. A key that a surviving search still uses (two searches + * of one run, or two legacy searches with the same query) keeps its rows, + * because that search reads them. + */ + async deleteSearchesWithChildren(searches: SearchEntry[]): Promise { + const ids = searches + .map((search) => search.id) + .filter((id): id is number => id !== undefined); + if (ids.length === 0) return; + const keys = [...new Set(searches.map(childKeyOf))]; + + await this.transaction( + "rw", + this.searches, + this.llmResponses, + this.chatHistory, + async () => { + await this.searches.bulkDelete(ids); + + const survivors = [ + ...(await this.searches.where("searchRunId").anyOf(keys).toArray()), + ...(await this.searches + .where("query") + .anyOf(keys) + .filter((search) => !search.searchRunId) + .toArray()), + ]; + const keysInUse = new Set(survivors.map(childKeyOf)); + const ownedKeys = keys.filter((key) => !keysInUse.has(key)); + + await this.llmResponses.where("searchRunId").anyOf(ownedKeys).delete(); + await this.llmResponses + .where("searchId") + .anyOf(ids) + .filter((response) => !response.searchRunId) + .delete(); + await this.chatHistory + .where("conversationId") + .anyOf(ownedKeys) + .delete(); + }, + ); } private cleanupInFlight: Promise | null = null; @@ -131,7 +223,6 @@ class HistoryDatabase extends Dexie { async performCleanup(): Promise { try { - const { getSettings } = await import("./pubSub"); const globalSettings = getSettings(); const settings = { autoCleanup: globalSettings.historyAutoCleanup, @@ -152,11 +243,7 @@ class HistoryDatabase extends Dexie { .toArray(); if (oldSearches.length > 0) { - await this.searches.bulkDelete( - oldSearches - .map((s) => s.id) - .filter((id): id is number => id !== undefined), - ); + await this.deleteSearchesWithChildren(oldSearches); addLogEntry(`Cleaned up ${oldSearches.length} old search entries`); } } @@ -171,11 +258,7 @@ class HistoryDatabase extends Dexie { .toArray(); if (excess.length > 0) { - await this.searches.bulkDelete( - excess - .map((s) => s.id) - .filter((id): id is number => id !== undefined), - ); + await this.deleteSearchesWithChildren(excess); addLogEntry(`Removed ${excess.length} excess search entries`); } } @@ -213,6 +296,7 @@ export async function updateSearchResults( searchRunId: string, results: TextResults | ImageResults, ): Promise { + if (!isHistoryEnabled()) return; try { await measurePerformance("Update search results", async () => { const latest = await historyDatabase.searches @@ -240,6 +324,7 @@ export async function addSearchToHistory( results: TextResults | ImageResults, source: "user" | "followup" | "suggestion" = "user", ): Promise { + if (!isHistoryEnabled()) return undefined; try { const id = await measurePerformance("Add search to history", async () => { return await historyDatabase.searches.add({ @@ -282,6 +367,7 @@ export async function saveLlmResponseForQuery( response: string, model: string = "", ): Promise { + if (!isHistoryEnabled()) return; try { const searchRunId = getCurrentSearchRunId(); const latest = await historyDatabase.searches @@ -329,6 +415,7 @@ export async function saveChatMessageForQuery( role: "user" | "assistant", content: string, ): Promise { + if (!isHistoryEnabled()) return; try { const searchRunId = getCurrentSearchRunId(); await historyDatabase.chatHistory.add({ diff --git a/client/modules/keyboard.test.ts b/client/modules/keyboard.test.ts index a7be16c728a922a4afc439a67c97a417a89c1c53..9bf9e937e7a69909b8baf34ef7fd6ce221662db0 100644 --- a/client/modules/keyboard.test.ts +++ b/client/modules/keyboard.test.ts @@ -4,13 +4,16 @@ import { handleEnterKeyDown } from "./keyboard"; function mockEvent( shift: boolean, + overrides: { key?: string; code?: string } = {}, ): Partial> { return { + key: "Enter", code: "Enter", shiftKey: shift, keyCode: 13, preventDefault: vi.fn(), nativeEvent: { isComposing: false }, + ...overrides, } as unknown as Partial>; } @@ -63,6 +66,30 @@ describe("handleEnterKeyDown", () => { expect(onSubmit).not.toHaveBeenCalled(); }); + it("submits on numpad Enter when enterToSubmit is true", () => { + const onSubmit = vi.fn(); + const event = mockEvent(false, { code: "NumpadEnter" }); + handleEnterKeyDown( + event as KeyboardEvent, + { enterToSubmit: true }, + onSubmit, + ); + expect(event.preventDefault).toHaveBeenCalled(); + expect(onSubmit).toHaveBeenCalled(); + }); + + it("submits on Shift+numpad Enter when enterToSubmit is false", () => { + const onSubmit = vi.fn(); + const event = mockEvent(true, { code: "NumpadEnter" }); + handleEnterKeyDown( + event as KeyboardEvent, + { enterToSubmit: false }, + onSubmit, + ); + expect(event.preventDefault).toHaveBeenCalled(); + expect(onSubmit).toHaveBeenCalled(); + }); + it("does not submit when Enter confirms an IME composition candidate", () => { const onSubmit = vi.fn(); const event = { diff --git a/client/modules/keyboard.ts b/client/modules/keyboard.ts index 893c68057579359a36154376124639d4907b2234..070e651c206fafe5559b6fff7528d7a573c968b8 100644 --- a/client/modules/keyboard.ts +++ b/client/modules/keyboard.ts @@ -17,8 +17,8 @@ export const handleEnterKeyDown = ( } if ( - (event.code === "Enter" && !event.shiftKey && settings.enterToSubmit) || - (event.code === "Enter" && event.shiftKey && !settings.enterToSubmit) + (event.key === "Enter" && !event.shiftKey && settings.enterToSubmit) || + (event.key === "Enter" && event.shiftKey && !settings.enterToSubmit) ) { event.preventDefault(); onSubmit(); diff --git a/client/modules/logEntries.test.ts b/client/modules/logEntries.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..fea32b17b0e4dee0a02f877891c3c6d52c6383a7 --- /dev/null +++ b/client/modules/logEntries.test.ts @@ -0,0 +1,42 @@ +import { beforeEach, describe, expect, it } from "vitest"; +import { addLogEntry, logEntriesPubSub, MAX_LOG_ENTRIES } from "./logEntries"; + +const [updateLogEntries, , getLogEntries] = logEntriesPubSub; + +describe("addLogEntry", () => { + beforeEach(() => { + updateLogEntries([]); + }); + + it("appends entries in order below the cap", () => { + addLogEntry("first"); + addLogEntry("second"); + + expect(getLogEntries().map((entry) => entry.message)).toEqual([ + "first", + "second", + ]); + }); + + it("keeps only the newest entries once the cap is exceeded", () => { + for (let i = 0; i < MAX_LOG_ENTRIES + 5; i++) { + addLogEntry(`entry ${i}`); + } + + const entries = getLogEntries(); + expect(entries).toHaveLength(MAX_LOG_ENTRIES); + expect(entries[0].message).toBe("entry 5"); + expect(entries.at(-1)?.message).toBe(`entry ${MAX_LOG_ENTRIES + 4}`); + }); + + it("publishes a new array on every append", () => { + for (let i = 0; i < MAX_LOG_ENTRIES; i++) { + addLogEntry(`entry ${i}`); + } + const before = getLogEntries(); + + addLogEntry("one more"); + + expect(getLogEntries()).not.toBe(before); + }); +}); diff --git a/client/modules/logEntries.ts b/client/modules/logEntries.ts index a8c920adb696169c375600d4af04c7df7b80f3c7..66f452c95048dce189565c4adcd9ad31cd5ca91d 100644 --- a/client/modules/logEntries.ts +++ b/client/modules/logEntries.ts @@ -10,10 +10,13 @@ export const logEntriesPubSub = createPubSub([]); const [updateLogEntries, , getLogEntries] = logEntriesPubSub; -/** Appends a timestamped entry to the in-app log. */ +/** The in-app log keeps only this many of the newest entries. */ +export const MAX_LOG_ENTRIES = 1000; + +/** Appends a timestamped entry to the in-app log, dropping the oldest past the cap. */ export function addLogEntry(message: string) { updateLogEntries([ - ...getLogEntries(), + ...getLogEntries().slice(-(MAX_LOG_ENTRIES - 1)), { timestamp: new Date().toISOString(), message, diff --git a/client/modules/pubSub.test.ts b/client/modules/pubSub.test.ts index 9aa9908d715bfd205061fd7ddbf5a35427b0128b..cf27fbd9b2d68e5a88aae0877e48accabd0f8042 100644 --- a/client/modules/pubSub.test.ts +++ b/client/modules/pubSub.test.ts @@ -83,3 +83,88 @@ describe("PubSub localStorage persistence", () => { ); }); }); + +describe("numeric settings never hold an empty string", () => { + it("clearing the context length stores the default number", async () => { + const { updateSettings, getSettings } = await import("./pubSub"); + const { defaultSettings } = await import("./settings"); + updateSettings({ + ...getSettings(), + openAiContextLength: "" as unknown as number, + }); + expect(getSettings().openAiContextLength).toBe( + defaultSettings.openAiContextLength, + ); + const stored = JSON.parse(localStorage.getItem("settings") as string); + expect(stored.openAiContextLength).toBe( + defaultSettings.openAiContextLength, + ); + }); + + it("clearing CPU threads, max entries or retention days stores the default number", async () => { + const { updateSettings, getSettings } = await import("./pubSub"); + const { defaultSettings } = await import("./settings"); + updateSettings({ + ...getSettings(), + cpuThreads: "" as unknown as number, + historyMaxEntries: "" as unknown as number, + historyRetentionDays: "" as unknown as number, + }); + expect(getSettings().cpuThreads).toBe(defaultSettings.cpuThreads); + expect(getSettings().historyMaxEntries).toBe( + defaultSettings.historyMaxEntries, + ); + expect(getSettings().historyRetentionDays).toBe( + defaultSettings.historyRetentionDays, + ); + }); + + it("keeps history retention cleanup enabled when a stored retention is empty", async () => { + const { defaultSettings } = await import("./settings"); + localStorage.setItem( + "settings", + JSON.stringify({ ...defaultSettings, historyRetentionDays: "" }), + ); + const { getSettings } = await import("./pubSub"); + expect(getSettings().historyRetentionDays).toBeGreaterThan(0); + }); + + it("repairs a stored empty string on load without a migration", async () => { + const { defaultSettings } = await import("./settings"); + localStorage.setItem( + "settings", + JSON.stringify({ + ...defaultSettings, + openAiContextLength: "", + cpuThreads: "", + historyMaxEntries: "", + }), + ); + const { getSettings } = await import("./pubSub"); + expect(getSettings()).toMatchObject({ + openAiContextLength: defaultSettings.openAiContextLength, + cpuThreads: defaultSettings.cpuThreads, + historyMaxEntries: defaultSettings.historyMaxEntries, + }); + }); + + it("sends the default max_tokens and sizes the excerpt budget from the default when a stored context length is empty", async () => { + const { defaultSettings } = await import("./settings"); + localStorage.setItem( + "settings", + JSON.stringify({ + ...defaultSettings, + inferenceType: "openai", + openAiContextLength: "", + }), + ); + const { + getDefaultChatCompletionCreateParamsStreaming, + getEffectiveContextSize, + } = await import("./textGenerationUtilities"); + expect(getDefaultChatCompletionCreateParamsStreaming([]).max_tokens).toBe( + defaultSettings.openAiContextLength, + ); + expect(getEffectiveContextSize()).toBe(defaultSettings.openAiContextLength); + }); +}); diff --git a/client/modules/pubSub.ts b/client/modules/pubSub.ts index fbe5e5fd84b317cc638e33c9ca6d9a350206d37e..6c37a5a6f206ce46269629d4e8bf5ef4a26d1e7e 100644 --- a/client/modules/pubSub.ts +++ b/client/modules/pubSub.ts @@ -1,7 +1,12 @@ import { createPubSub } from "create-pubsub"; import throttle from "throttleit"; import { addLogEntry } from "./logEntries"; -import { defaultSettings, SETTINGS_STORAGE_KEY } from "./settings"; +import * as safeStorage from "./safeStorage"; +import { + coerceNumericSettings, + defaultSettings, + SETTINGS_STORAGE_KEY, +} from "./settings"; import type { ImageSearchResults, PageContents, @@ -26,8 +31,12 @@ function isSameJsonKind(value: unknown, reference: unknown): boolean { return typeof value === typeof reference; } -function createLocalStoragePubSub(localStorageKey: string, defaultValue: T) { - const localStorageValue = localStorage.getItem(localStorageKey); +function createLocalStoragePubSub( + localStorageKey: string, + defaultValue: T, + normalize?: (value: T) => T, +) { + const localStorageValue = safeStorage.getItem(localStorageKey); let initialValue: T = defaultValue; if (localStorageValue !== null) { let parsed: unknown; @@ -37,12 +46,12 @@ function createLocalStoragePubSub(localStorageKey: string, defaultValue: T) { parsed = undefined; } if (parsed !== undefined && isSameJsonKind(parsed, defaultValue)) { - initialValue = parsed as T; + initialValue = normalize ? normalize(parsed as T) : (parsed as T); } else { // Runs at module load, so an unparseable or wrong-type stored value must // not crash the app. Remove it (so the fallback doesn't repeat on every // load) and log it for the in-app log panel. - localStorage.removeItem(localStorageKey); + safeStorage.removeItem(localStorageKey); addLogEntry( `Discarded an unusable stored value for '${localStorageKey}'`, ); @@ -50,13 +59,20 @@ function createLocalStoragePubSub(localStorageKey: string, defaultValue: T) { } const localStoragePubSub = createPubSub(initialValue); - const [, onValueChange] = localStoragePubSub; + const [updateValue, onValueChange, getValue] = localStoragePubSub; onValueChange((value) => - localStorage.setItem(localStorageKey, JSON.stringify(value)), + safeStorage.setItem(localStorageKey, JSON.stringify(value)), ); - return localStoragePubSub; + if (!normalize) return localStoragePubSub; + // Every write goes through the same rule as hydration, so no path can store + // a value the consumers would misread. + return [ + (value: T) => updateValue(normalize(value)), + onValueChange, + getValue, + ] as typeof localStoragePubSub; } const querySuggestionsPubSub = createLocalStoragePubSub( @@ -115,6 +131,7 @@ export const [updateModelLoadingProgress] = modelLoadingProgressPubSub; export const settingsPubSub = createLocalStoragePubSub( SETTINGS_STORAGE_KEY, defaultSettings, + coerceNumericSettings, ); export const [updateSettings, listenToSettingsChanges, getSettings] = diff --git a/client/modules/querySuggestions.test.ts b/client/modules/querySuggestions.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..2d49894ce0069a9f6348ad98d09e2da44fb14fd5 --- /dev/null +++ b/client/modules/querySuggestions.test.ts @@ -0,0 +1,80 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { addLogEntry } from "./logEntries"; +import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub"; +import { + DEFAULT_QUERY_SUGGESTION, + getRandomQuerySuggestion, +} from "./querySuggestions"; + +vi.mock("./logEntries", () => ({ + addLogEntry: vi.fn(), +})); + +const mockFetch = vi.fn(); +vi.stubGlobal("fetch", mockFetch); + +function jsonResponse(data: unknown, status = 200) { + return new Response(JSON.stringify(data), { status }); +} + +describe("getRandomQuerySuggestion", () => { + beforeEach(() => { + vi.clearAllMocks(); + updateQuerySuggestions([]); + }); + + it("returns a stored suggestion without fetching", async () => { + updateQuerySuggestions(["first", "second"]); + + await expect(getRandomQuerySuggestion()).resolves.toBe("second"); + expect(getQuerySuggestions()).toEqual(["first"]); + expect(mockFetch).not.toHaveBeenCalled(); + }); + + it("returns the default when the fetched list is empty", async () => { + mockFetch.mockResolvedValueOnce(jsonResponse([])); + + await expect(getRandomQuerySuggestion()).resolves.toBe( + DEFAULT_QUERY_SUGGESTION, + ); + }); + + it("skips stored entries that are not non-empty strings", async () => { + updateQuerySuggestions([null, "", " "] as unknown as string[]); + mockFetch.mockResolvedValueOnce(jsonResponse(["fetched"])); + + await expect(getRandomQuerySuggestion()).resolves.toBe("fetched"); + }); + + it("drops unusable entries from the fetched list", async () => { + mockFetch.mockResolvedValueOnce(jsonResponse([null, "", 42, "usable"])); + + await expect(getRandomQuerySuggestion()).resolves.toBe("usable"); + expect(getQuerySuggestions()).toEqual([]); + }); + + it("logs how many suggestions the refill actually stored", async () => { + mockFetch.mockResolvedValueOnce(jsonResponse(["a", "b", "c"])); + + await getRandomQuerySuggestion(); + + expect(addLogEntry).toHaveBeenCalledWith( + "Query suggestions refilled with 3 suggestions", + ); + }); + + it.each([ + ["a 404 response", () => new Response("Not found", { status: 404 })], + ["invalid JSON", () => new Response("not json", { status: 200 })], + ["a body that is not a list", () => jsonResponse({ suggestions: [] })], + ])("returns the default and logs on %s", async (_, response) => { + mockFetch.mockResolvedValueOnce(response()); + + await expect(getRandomQuerySuggestion()).resolves.toBe( + DEFAULT_QUERY_SUGGESTION, + ); + expect(addLogEntry).toHaveBeenCalledWith( + expect.stringContaining("Failed to refill query suggestions"), + ); + }); +}); diff --git a/client/modules/querySuggestions.ts b/client/modules/querySuggestions.ts index ae0195c94931d85c8b1a4b0436d510acb650ce2d..63a00bc4aa4a134b77ee99090d70d7f9fc3a8f8a 100644 --- a/client/modules/querySuggestions.ts +++ b/client/modules/querySuggestions.ts @@ -1,31 +1,66 @@ import { addLogEntry } from "./logEntries"; import { getQuerySuggestions, updateQuerySuggestions } from "./pubSub"; -export async function getRandomQuerySuggestion() { - if (getQuerySuggestions().length === 0) await refillQuerySuggestions(25); +/** Shown in the search box when no stored or fetched suggestion is usable. */ +export const DEFAULT_QUERY_SUGGESTION = "Anything you need!"; - const querySuggestions = getQuerySuggestions(); +/** Keeps the non-empty strings of a list read from storage or the network. */ +function toNonEmptyStrings(value: unknown): string[] { + if (!Array.isArray(value)) return []; + return value.filter( + (entry): entry is string => + typeof entry === "string" && entry.trim().length > 0, + ); +} + +/** 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); - const randomQuerySuggestion = querySuggestions.pop() as string; + const randomQuerySuggestion = querySuggestions.pop(); updateQuerySuggestions(querySuggestions); - return randomQuerySuggestion; + return randomQuerySuggestion ?? DEFAULT_QUERY_SUGGESTION; } -async function refillQuerySuggestions(limit?: number) { +async function refillQuerySuggestions(limit: number): Promise { const querySuggestionsFileUrl = new URL( "/query-suggestions.json", self.location.origin, ); - const fetchResponse = await fetch(querySuggestionsFileUrl.toString()); + try { + const fetchResponse = await fetch(querySuggestionsFileUrl.toString()); - const querySuggestionsList: string[] = await fetchResponse.json(); + if (!fetchResponse.ok) { + throw new Error(`HTTP ${fetchResponse.status}`); + } - updateQuerySuggestions( - querySuggestionsList.sort(() => Math.random() - 0.5).slice(0, limit), - ); + const body: unknown = await fetchResponse.json(); + + if (!Array.isArray(body)) { + throw new Error("the response is not a list"); + } + + const querySuggestionsList = toNonEmptyStrings(body) + .sort(() => Math.random() - 0.5) + .slice(0, limit); + + addLogEntry( + `Query suggestions refilled with ${querySuggestionsList.length} suggestions`, + ); - addLogEntry(`Query suggestions refilled with ${limit} suggestions`); + return querySuggestionsList; + } catch (error) { + addLogEntry( + `Failed to refill query suggestions: ${ + error instanceof Error ? error.message : String(error) + }`, + ); + return []; + } } diff --git a/client/modules/safeStorage.test.ts b/client/modules/safeStorage.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..349afb398bf9a81b7238aa307c7ea62c59b7180e --- /dev/null +++ b/client/modules/safeStorage.test.ts @@ -0,0 +1,45 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import * as safeStorage from "./safeStorage"; + +describe("safeStorage", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("returns null from getItem when localStorage throws SecurityError", () => { + vi.stubGlobal("localStorage", { + getItem: () => { + throw new DOMException("Access is denied", "SecurityError"); + }, + setItem: () => { + throw new DOMException("Access is denied", "SecurityError"); + }, + removeItem: () => { + throw new DOMException("Access is denied", "SecurityError"); + }, + }); + + expect(safeStorage.getItem("settings")).toBeNull(); + expect(() => safeStorage.setItem("settings", "{}")).not.toThrow(); + expect(() => safeStorage.removeItem("settings")).not.toThrow(); + }); + + it("delegates to localStorage when access is allowed", () => { + const store = new Map(); + vi.stubGlobal("localStorage", { + getItem: (key: string) => store.get(key) ?? null, + setItem: (key: string, value: string) => { + store.set(key, value); + }, + removeItem: (key: string) => { + store.delete(key); + }, + }); + + expect(safeStorage.getItem("k")).toBeNull(); + safeStorage.setItem("k", "v"); + expect(safeStorage.getItem("k")).toBe("v"); + safeStorage.removeItem("k"); + expect(safeStorage.getItem("k")).toBeNull(); + }); +}); diff --git a/client/modules/safeStorage.ts b/client/modules/safeStorage.ts new file mode 100644 index 0000000000000000000000000000000000000000..cab8e7590ffb90f90d367be9e55085db3d7bcef0 --- /dev/null +++ b/client/modules/safeStorage.ts @@ -0,0 +1,29 @@ +/** + * localStorage accessors that never throw. Browsers that block site data + * (Safari "Block All Cookies", Chrome "sites can't save data") raise + * SecurityError on any property access; callers get a soft failure instead + * of a blank page. + */ +export function getItem(key: string): string | null { + try { + return localStorage.getItem(key); + } catch { + return null; + } +} + +export function setItem(key: string, value: string): void { + try { + localStorage.setItem(key, value); + } catch { + // Persistence is best-effort when storage is blocked. + } +} + +export function removeItem(key: string): void { + try { + localStorage.removeItem(key); + } catch { + // Same as setItem: ignore when storage is unavailable. + } +} diff --git a/client/modules/search.test.ts b/client/modules/search.test.ts index c58900195c56b546b17ff47f4da7afd4053f7244..a71d648a993464ef640923e6df9c0583e2eb70d3 100644 --- a/client/modules/search.test.ts +++ b/client/modules/search.test.ts @@ -221,9 +221,8 @@ describe("Search Module", () => { expect(mockFetch).toHaveBeenCalledTimes(1); }); - // Each row has to reach the branch it is named for. A plain Error matches - // neither `AbortError` nor the lowercase "network" the wrapper looks for, - // so a row that rejects with one only watches a raw error propagate. + // Each row has to reach the branch it is named for. A network failure is a + // TypeError in every browser, each with its own wording. it.each([ [ "wraps a body it cannot parse", @@ -237,9 +236,22 @@ describe("Search Module", () => { "JSON parsing error: Unexpected token", ], [ - "labels a network failure", - () => mockFetch.mockRejectedValue(new Error("network is unreachable")), - "Network error: network is unreachable", + "labels a Chrome network failure", + () => mockFetch.mockRejectedValue(new TypeError("Failed to fetch")), + "Network error: Failed to fetch", + ], + [ + "labels a Firefox network failure", + () => + mockFetch.mockRejectedValue( + new TypeError("NetworkError when attempting to fetch resource."), + ), + "Network error: NetworkError when attempting to fetch resource.", + ], + [ + "labels a Safari network failure", + () => mockFetch.mockRejectedValue(new TypeError("Load failed")), + "Network error: Load failed", ], [ "labels an aborted request as a timeout", @@ -261,6 +273,39 @@ describe("Search Module", () => { ), ).rejects.toThrow(expected); }); + + it("labels a timeout that fires while the body is still arriving", async () => { + // The headers came back in time, then the body stalled until the + // request timer aborted it. + mockFetch.mockImplementation( + async (_url: string, init: { signal: AbortSignal }) => ({ + ok: true, + json: () => + new Promise((_resolve, reject) => { + init.signal.addEventListener("abort", () => + reject( + new DOMException("The user aborted a request.", "AbortError"), + ), + ); + }), + }), + ); + vi.useFakeTimers(); + try { + const search = searchModule.searchServiceInstance + .performSearch("text", "test") + .catch((caught: Error) => caught); + await vi.advanceTimersByTimeAsync(30 * 1000); + + const error = await search; + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe( + "Request timeout - server did not respond within 30 seconds", + ); + } finally { + vi.useRealTimers(); + } + }); }); // A restart, a second instance or a dev-server reload mints a new search diff --git a/client/modules/search.ts b/client/modules/search.ts index 6393d11edca5161192b82361f0d79f27be89dd6d..228e2fab166b0e6230b3dc463a0d36b87a600f1a 100644 --- a/client/modules/search.ts +++ b/client/modules/search.ts @@ -208,6 +208,33 @@ async function buildSearchUrl( return searchUrl; } +/** + * Names a failed request at the point of failure, where the cause is still + * known. The timer is the only thing that aborts the controller, so an aborted + * signal is a timeout whatever rejected, the fetch before the headers or + * `json()` mid-body. The Fetch spec rejects a network failure with a + * TypeError in every browser, whatever the wording, and a body that is not + * JSON fails with a SyntaxError. + */ +function labelSearchFailure(error: unknown, signal: AbortSignal): Error { + if ( + signal.aborted || + (error instanceof Error && error.name === "AbortError") + ) { + return new Error( + "Request timeout - server did not respond within 30 seconds", + { cause: error }, + ); + } + if (error instanceof SyntaxError) { + return new Error(`JSON parsing error: ${error.message}`, { cause: error }); + } + if (error instanceof TypeError) { + return new Error(`Network error: ${error.message}`, { cause: error }); + } + return error instanceof Error ? error : new Error(String(error)); +} + /** * One request, with the timeout covering the body as well as the response, so * a server that answers and then stalls mid-stream still aborts. @@ -228,13 +255,9 @@ async function attemptSearch(searchUrl: URL): Promise> { return { ok: false, status: response.status }; } - try { - return { ok: true, results: (await response.json()) as T }; - } catch (parseError) { - throw new Error( - `JSON parsing error: ${parseError instanceof Error ? parseError.message : String(parseError)}`, - ); - } + return { ok: true, results: (await response.json()) as T }; + } catch (error) { + throw labelSearchFailure(error, controller.signal); } finally { clearTimeout(timeoutId); } @@ -450,44 +473,30 @@ const searchService = { ); } - try { - let attempt = await attemptSearch( + let attempt = await attemptSearch( + await buildSearchUrl(endpoint, query, limit), + ); + + // Every server process mints its own search token, so a restart leaves + // this page hashing one the server never issued. Drop the cached config, + // take the token the server is handing out now, and try once more. The + // retry runs once per request: a second rejection is a real one, and is + // reported as the failure it is. + if (!attempt.ok && attempt.status === UNAUTHORIZED_STATUS) { + addLogEntry( + "Search token was rejected; refreshing it and retrying the search", + ); + invalidateConfig(); + attempt = await attemptSearch( await buildSearchUrl(endpoint, query, limit), ); + } - // Every server process mints its own search token, so a restart leaves - // this page hashing one the server never issued. Drop the cached config, - // take the token the server is handing out now, and try once more. The - // retry runs once per request: a second rejection is a real one, and is - // reported as the failure it is. - if (!attempt.ok && attempt.status === UNAUTHORIZED_STATUS) { - addLogEntry( - "Search token was rejected; refreshing it and retrying the search", - ); - invalidateConfig(); - attempt = await attemptSearch( - await buildSearchUrl(endpoint, query, limit), - ); - } - - if (!attempt.ok) { - throw new Error(`HTTP error! status: ${attempt.status}`); - } - - return attempt.results; - } catch (error) { - if (error instanceof Error) { - if (error.name === "AbortError") { - throw new Error( - "Request timeout - server did not respond within 30 seconds", - ); - } - if (error.message.includes("network")) { - throw new Error(`Network error: ${error.message}`); - } - } - throw error; + if (!attempt.ok) { + throw new Error(`HTTP error! status: ${attempt.status}`); } + + return attempt.results; }, async searchText( diff --git a/client/modules/searchActivity.ts b/client/modules/searchActivity.ts index 0751c43e93c1991ea9d1dd238f41fe8990dd22db..809ab9b766338a536ee5b4259d538cc054cadd11 100644 --- a/client/modules/searchActivity.ts +++ b/client/modules/searchActivity.ts @@ -53,13 +53,13 @@ export interface ActivityData { weeks: number; } -function startOfDay(ts: number): Date { +export function startOfDay(ts: number): Date { const d = new Date(ts); d.setHours(0, 0, 0, 0); return d; } -function localKey(d: Date): string { +export function localKey(d: Date): string { const month = `${d.getMonth() + 1}`.padStart(2, "0"); const day = `${d.getDate()}`.padStart(2, "0"); return `${d.getFullYear()}-${month}-${day}`; diff --git a/client/modules/settings.test.ts b/client/modules/settings.test.ts index 589b8180975dd07adfd53dd40e4cc0186ffa47fd..4ebd0e814dc75e6f874cfc4eafd17e47691b8912 100644 --- a/client/modules/settings.test.ts +++ b/client/modules/settings.test.ts @@ -3,7 +3,7 @@ import { DEFAULT_SYSTEM_PROMPT, } from "@shared/defaultSystemPrompt"; import { describe, expect, it, vi } from "vitest"; -import type { ServerConfig } from "./config"; +import { FALLBACK_CONFIG, type ServerConfig } from "./config"; import { applyServerConfig, defaultSettings, @@ -84,6 +84,7 @@ describe("Settings Module", () => { const config = { ...mockConfig, wllamaDefaultModelId: "custom-model", + internalApiEnabled: true, defaultInferenceType: "internal", }; const applied = applyServerConfig(defaultSettings, config, false, false); @@ -131,6 +132,76 @@ describe("Settings Module", () => { expect(applied.wllamaModelId).toBe(defaultSettings.wllamaModelId); expect(applied.inferenceType).toBe(defaultSettings.inferenceType); }); + + describe("an inference type the server no longer offers", () => { + const storedInternal = { ...defaultSettings, inferenceType: "internal" }; + + it("switches a stored type to the server default", () => { + const config = { ...mockConfig, defaultInferenceType: "openai" }; + const applied = applyServerConfig(storedInternal, config, true, true); + expect(applied.inferenceType).toBe("openai"); + expect(applied.wllamaModelId).toBe(storedInternal.wllamaModelId); + }); + + it("uses the shipped default when the server default is not offered either", () => { + // DEFAULT_INFERENCE_TYPE=internal left in place after the internal API + // was removed: the server still names "internal" as its default. + const config = { ...mockConfig, defaultInferenceType: "internal" }; + expect( + applyServerConfig(storedInternal, config, true, true).inferenceType, + ).toBe("browser"); + expect( + applyServerConfig(defaultSettings, config, false, true).inferenceType, + ).toBe("browser"); + }); + + it("keeps a stored type the server still offers", () => { + const config = { ...mockConfig, internalApiEnabled: true }; + expect(applyServerConfig(storedInternal, config, true, true)).toBe( + storedInternal, + ); + }); + + it("keeps a stored type when the server config could not be loaded", () => { + // The fallback is not the server's answer, so it must not overwrite a + // choice that the next successful load may confirm. + expect( + applyServerConfig(storedInternal, FALLBACK_CONFIG, true, true), + ).toBe(storedInternal); + }); + + it("always leaves the settings select with a matching option", () => { + for (const internalApiEnabled of [true, false]) { + for (const defaultInferenceType of ["browser", "internal", "unknown"]) { + for (const stored of [ + "browser", + "openai", + "horde", + "internal", + "gone", + ]) { + const config = { + ...mockConfig, + internalApiEnabled, + defaultInferenceType, + }; + const offered = getInferenceTypes(config).map( + (t) => t.value as string, + ); + for (const wasStored of [true, false]) { + const applied = applyServerConfig( + { ...defaultSettings, inferenceType: stored }, + config, + wasStored, + true, + ); + expect(offered).toContain(applied.inferenceType); + } + } + } + } + }); + }); }); describe("legacy voice migration", () => { diff --git a/client/modules/settings.ts b/client/modules/settings.ts index f5dcb2ecc441f339dbe0b201e0a960f79563dc1a..42924706508654d1f6351b11a71ee2e96f1022b2 100644 --- a/client/modules/settings.ts +++ b/client/modules/settings.ts @@ -8,7 +8,9 @@ import { DEFAULT_WLLAMA_MODEL_ID, type ServerConfig, } from "@shared/serverConfig"; +import { FALLBACK_CONFIG } from "./config"; import { addLogEntry } from "./logEntries"; +import * as safeStorage from "./safeStorage"; export const SETTINGS_STORAGE_KEY = "settings"; @@ -19,7 +21,7 @@ export const SETTINGS_STORAGE_KEY = "settings"; * that happens to equal a default. */ export const hasStoredUserSettings = - localStorage.getItem(SETTINGS_STORAGE_KEY) !== null; + safeStorage.getItem(SETTINGS_STORAGE_KEY) !== null; /** * Whether this profile picked an OS voice before the local engine existed. @@ -30,7 +32,7 @@ export const hasStoredUserSettings = const hasLegacySystemVoice = (() => { try { const stored: unknown = JSON.parse( - localStorage.getItem(SETTINGS_STORAGE_KEY) ?? "{}", + safeStorage.getItem(SETTINGS_STORAGE_KEY) ?? "{}", ); if (typeof stored !== "object" || stored === null) return false; const { selectedVoiceId, textToSpeechEngine } = stored as Record< @@ -101,6 +103,30 @@ export const defaultSettings = { enablePageContentFetch: true, }; +/** + * Returns the settings with every numeric setting that holds something other + * than a finite number replaced by its default. A cleared Mantine NumberInput + * emits `""`, which `??` does not catch and `> 0` reads as false, so it would + * otherwise reach consumers as a `max_tokens` of `""` or a retention that + * silently stops cleanup. Keys whose default is not a number are left alone. + */ +export function coerceNumericSettings( + settings: typeof defaultSettings, +): typeof defaultSettings { + const coerced: Record = { ...settings }; + for (const key of Object.keys(defaultSettings) as Array< + keyof typeof defaultSettings + >) { + const fallback = defaultSettings[key]; + if (typeof fallback !== "number") continue; + const value: unknown = settings[key]; + if (typeof value !== "number" || !Number.isFinite(value)) { + coerced[key] = fallback; + } + } + return coerced as typeof defaultSettings; +} + addLogEntry( `Number of logical processors in CPU: ${ navigator.hardwareConcurrency ?? "unknown" @@ -144,11 +170,30 @@ export function upgradeUntouchedSystemPrompt( : settings; } +/** + * The inference type to use in place of one this server does not offer: the + * server's default, unless that is not offered either (`DEFAULT_INFERENCE_TYPE` + * still names a backend whose config was removed), then the shipped default, + * which is always offered. + */ +function offeredInferenceType(requested: string, config: ServerConfig): string { + const offered: string[] = getInferenceTypes(config).map(({ value }) => value); + if (offered.includes(requested)) return requested; + return offered.includes(config.defaultInferenceType) + ? config.defaultInferenceType + : DEFAULT_INFERENCE_TYPE; +} + /** * These are defaults, not overrides: they seed a profile that has never been * saved and are ignored once the user has settings of their own, since a stored * value is a choice even when it matches what the code ships with. * + * The one stored value that is checked is the inference type: when the server + * no longer offers it (the operator removed the internal API, say), the AI + * settings select has no matching option and generation keeps routing to the + * missing backend, so it moves to one the server offers. + * * The Wllama model default depends on `hasWebGpu`, because a model that * answers quickly on a GPU can take minutes per answer on the CPU. */ @@ -158,13 +203,26 @@ export function applyServerConfig( userSettingsWereStored: boolean, hasWebGpu: boolean, ): typeof defaultSettings { - if (userSettingsWereStored) return settings; + if (userSettingsWereStored) { + // The fallback is not the server's answer: it changes nothing, so a choice + // survives a failed config fetch and is checked on the next load. + if (config === FALLBACK_CONFIG) return settings; + const inferenceType = offeredInferenceType(settings.inferenceType, config); + if (inferenceType === settings.inferenceType) return settings; + addLogEntry( + `Inference type "${settings.inferenceType}" is not offered by this server; switched to "${inferenceType}"`, + ); + return { ...settings, inferenceType }; + } return { ...settings, wllamaModelId: hasWebGpu ? config.wllamaDefaultGpuModelId || DEFAULT_WLLAMA_GPU_MODEL_ID : config.wllamaDefaultModelId || DEFAULT_WLLAMA_MODEL_ID, - inferenceType: config.defaultInferenceType || DEFAULT_INFERENCE_TYPE, + inferenceType: offeredInferenceType( + config.defaultInferenceType || DEFAULT_INFERENCE_TYPE, + config, + ), }; } diff --git a/client/modules/systemPrompt.test.ts b/client/modules/systemPrompt.test.ts index 7ffca2445f2bde589a2aa7b2c0ec2a38ab95080e..d840c2d19fe0ab79d5b9d912fd3c22d3165b3fc3 100644 --- a/client/modules/systemPrompt.test.ts +++ b/client/modules/systemPrompt.test.ts @@ -52,4 +52,28 @@ describe("systemPrompt", () => { const result = getSystemPrompt(""); expect(result).toBe(""); }); + + it("should insert search results containing dollar patterns verbatim without expansion", () => { + mockGetSettings.mockReturnValue({ + systemPrompt: "BEFORE {{searchResults}} AFTER", + }); + const result = getSystemPrompt("a $& b $` c $' d $$ e $1 f"); + expect(result).toBe("BEFORE a $& b $` c $' d $$ e $1 f AFTER"); + }); + + it("should replace multiple searchResults occurrences", () => { + mockGetSettings.mockReturnValue({ + systemPrompt: "{{searchResults}} and {{searchResults}}", + }); + const result = getSystemPrompt("RESULT"); + expect(result).toBe("RESULT and RESULT"); + }); + + it("should not expand placeholders appearing inside search results", () => { + mockGetSettings.mockReturnValue({ + systemPrompt: "Prompt: {{searchResults}}", + }); + const result = getSystemPrompt("snippet with {{currentDate}} inside"); + expect(result).toBe("Prompt: snippet with {{currentDate}} inside"); + }); }); diff --git a/client/modules/systemPrompt.ts b/client/modules/systemPrompt.ts index 51657fed92557ff325006b29d1dd3826d6a58a92..d8049aefd78664d5557ced1516c1d1afbf8c18aa 100644 --- a/client/modules/systemPrompt.ts +++ b/client/modules/systemPrompt.ts @@ -1,5 +1,7 @@ import { getSettings } from "./pubSub"; +const PLACEHOLDERS = /\{\{(searchResults|currentDate|dateTime)\}\}/g; + /** Replaces the `{{searchResults}}` and date placeholders in the configured prompt. */ export function getSystemPrompt(searchResults: string) { const currentDate = new Intl.DateTimeFormat("en-CA", { @@ -8,7 +10,7 @@ export function getSystemPrompt(searchResults: string) { day: "2-digit", }).format(new Date()); - return getSettings() - .systemPrompt.replace("{{searchResults}}", searchResults) - .replace(/{{dateTime}}|{{currentDate}}/g, currentDate); + return getSettings().systemPrompt.replace(PLACEHOLDERS, (_match, name) => + name === "searchResults" ? searchResults : currentDate, + ); } diff --git a/client/modules/textGeneration.chatBudget.test.ts b/client/modules/textGeneration.chatBudget.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..84fc24c26f8911a56de055c4a6cc27677f6a7eaa --- /dev/null +++ b/client/modules/textGeneration.chatBudget.test.ts @@ -0,0 +1,255 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const state = vi.hoisted(() => ({ + settings: { inferenceType: "browser" } as { + inferenceType: string; + openAiContextLength?: number; + }, + systemPrompt: "", +})); + +vi.mock("./pubSub", () => ({ + getConversationSummary: vi.fn(() => ({ conversationId: "", summary: "" })), + getQuery: vi.fn(() => ""), + getResponse: vi.fn(() => ""), + getSettings: vi.fn(() => state.settings), + getTextGenerationState: vi.fn(() => "idle"), + listenToSettingsChanges: vi.fn(() => vi.fn()), + updateChatMessages: vi.fn(), + updateConversationSummary: vi.fn(), + updateImageSearchResults: vi.fn(), + updateImageSearchState: vi.fn(), + updateLlmTextSearchResults: vi.fn(), + updateResponse: vi.fn(), + updateSearchPromise: vi.fn(), + updateTextGenerationState: vi.fn(), + updateTextSearchResults: vi.fn(), + updateTextSearchState: vi.fn(), +})); +vi.mock("./history", () => ({ + getCurrentSearchRunId: vi.fn(() => "run-1"), + saveLlmResponseForQuery: vi.fn(() => Promise.resolve()), + updateSearchResults: vi.fn(() => Promise.resolve()), +})); +vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() })); +vi.mock("./notifications", () => ({ showAiCompleteNotification: vi.fn() })); +vi.mock("./search", () => ({ + searchImages: vi.fn(() => Promise.resolve([])), + searchText: vi.fn(() => Promise.resolve([])), +})); +// The system prompt stands in for everything that fills it (instructions, +// search results, page excerpts), so its length sets how much of the window +// is left for the conversation. +vi.mock("./systemPrompt", () => ({ + getSystemPrompt: vi.fn(() => state.systemPrompt), +})); +vi.mock("./textGenerationUtilities", async (importOriginal) => ({ + ...(await importOriginal()), + getFormattedSearchResults: vi.fn(() => Promise.resolve("")), +})); +// One token per character keeps the budget arithmetic readable. +vi.mock("gpt-tokenizer", () => ({ + default: { encode: vi.fn((text: string) => Array.from(text, () => 1)) }, +})); +vi.mock("pretty-ms", () => ({ default: vi.fn(() => "100ms") })); +vi.mock("./textGenerationWithWllama", () => ({ + generateTextWithWllama: vi.fn(() => Promise.resolve()), + generateChatWithWllama: vi.fn(), +})); +vi.mock("./textGenerationWithOpenAi", () => ({ + generateTextWithOpenAi: vi.fn(() => Promise.resolve()), + generateChatWithOpenAi: vi.fn(), +})); + +import { getConversationSummary, updateConversationSummary } from "./pubSub"; +import { generateChatResponse } from "./textGeneration"; +import { generateChatWithOpenAi } from "./textGenerationWithOpenAi"; +import { generateChatWithWllama } from "./textGenerationWithWllama"; +import type { ChatMessage } from "./types"; + +const summarizerInstruction = "You are the conversation memory manager."; + +function mockGenerateChat(generateChat: typeof generateChatWithWllama) { + vi.mocked(generateChat).mockImplementation(async (messages) => + messages[0].content.startsWith(summarizerInstruction) + ? "folded summary" + : "the answer", + ); +} + +function callsTo(generateChat: typeof generateChatWithWllama) { + const calls = vi + .mocked(generateChat) + .mock.calls.map(([messages]) => messages); + return { + summarizer: calls.filter((messages) => + messages[0].content.startsWith(summarizerInstruction), + ), + answer: calls.filter( + (messages) => !messages[0].content.startsWith(summarizerInstruction), + ), + }; +} + +const earlierTurns: ChatMessage[] = [ + { role: "user", content: "first question" }, + { role: "assistant", content: "first answer" }, +]; + +describe("generateChatResponse context budget", () => { + beforeEach(() => { + vi.clearAllMocks(); + state.settings = { inferenceType: "browser" }; + state.systemPrompt = ""; + mockGenerateChat(generateChatWithWllama); + mockGenerateChat(generateChatWithOpenAi); + }); + + it("sends the newest question when the budget is exhausted", async () => { + // 3500 tokens of system prompt against a 4096 * 0.75 = 3072 history + // budget leaves nothing for the conversation. + state.systemPrompt = "s".repeat(3500); + const question: ChatMessage = { role: "user", content: "q".repeat(500) }; + + await generateChatResponse([...earlierTurns, question], () => {}); + + const { answer } = callsTo(generateChatWithWllama); + expect(answer).toHaveLength(1); + expect(answer[0].at(-1)).toEqual(question); + }); + + it("folds only the turns before the current question into the summary", async () => { + state.systemPrompt = "s".repeat(3500); + const question = "the current question ".repeat(20); + + await generateChatResponse( + [...earlierTurns, { role: "user", content: question }], + () => {}, + ); + + const { summarizer } = callsTo(generateChatWithWllama); + expect(summarizer).toHaveLength(1); + expect(summarizer[0][0].content).toContain("first question"); + expect(summarizer[0][0].content).not.toContain(question); + }); + + it("measures the budget against the configured OpenAI context", async () => { + state.settings = { inferenceType: "openai", openAiContextLength: 32768 }; + // Excerpts sized from a 32768 window overflow a 4096-based budget, but fit + // easily in 32768 * 0.75. + state.systemPrompt = "s".repeat(11468); + const messages: ChatMessage[] = [ + ...earlierTurns, + { role: "user", content: "follow-up question" }, + ]; + + await generateChatResponse(messages, () => {}); + + const { answer, summarizer } = callsTo(generateChatWithOpenAi); + expect(summarizer).toHaveLength(0); + expect(answer[0].slice(2)).toEqual(messages); + expect(updateConversationSummary).not.toHaveBeenCalled(); + }); + + it("rejects before any generation when the newest message alone exceeds the window", async () => { + const question: ChatMessage = { role: "user", content: "q".repeat(5000) }; + + await expect( + generateChatResponse([...earlierTurns, question], () => {}), + ).rejects.toThrow("The newest message alone does not fit the context"); + + expect(generateChatWithWllama).not.toHaveBeenCalled(); + expect(updateConversationSummary).not.toHaveBeenCalled(); + }); + + it("answers a single long prompt without writing a conversation summary", async () => { + // The follow-up question generator sends one synthetic message that embeds + // the whole answer; it must not be folded into the chat's summary slot. + state.systemPrompt = "s".repeat(2500); + const prompt: ChatMessage = { role: "user", content: "a".repeat(1000) }; + + await generateChatResponse([prompt], () => {}); + + const { answer, summarizer } = callsTo(generateChatWithWllama); + expect(summarizer).toHaveLength(0); + expect(answer[0].at(-1)).toEqual(prompt); + expect(updateConversationSummary).not.toHaveBeenCalled(); + }); + + it("lets older turns share what the newest question leaves, starting on a user turn", async () => { + // Budget 3072 - 2000 - 3 ("Ok!") = 1069; the question takes 300, leaving + // 769 for older turns: the newest two (200) fit, the 600-token answer + // before them does not. + state.systemPrompt = "s".repeat(2000); + const messages: ChatMessage[] = [ + { role: "user", content: "u".repeat(600) }, + { role: "assistant", content: "a".repeat(600) }, + { role: "user", content: "v".repeat(100) }, + { role: "assistant", content: "b".repeat(100) }, + { role: "user", content: "w".repeat(300) }, + ]; + + await generateChatResponse(messages, () => {}); + + const { answer, summarizer } = callsTo(generateChatWithWllama); + expect(answer[0].slice(2)).toEqual(messages.slice(2)); + expect(summarizer).toHaveLength(1); + expect(summarizer[0][0].content).toContain("u".repeat(600)); + expect(summarizer[0][0].content).not.toContain("w".repeat(300)); + }); + + it("keeps the stored summary when the summarizer rejects and the fallback returns empty", async () => { + state.systemPrompt = "s".repeat(3500); + const messages: ChatMessage[] = [ + { role: "user", content: "first question" }, + { role: "assistant", content: "x".repeat(900) }, + { role: "user", content: "follow-up question" }, + ]; + vi.mocked(getConversationSummary).mockReturnValue({ + conversationId: "first question", + summary: "S1", + }); + vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => { + if (chat[0].content.startsWith(summarizerInstruction)) { + throw new Error("summarizer unavailable"); + } + return "the answer"; + }); + + await generateChatResponse(messages, () => {}); + + expect(updateConversationSummary).toHaveBeenCalledWith({ + conversationId: "first question", + summary: "S1", + }); + const { answer } = callsTo(generateChatWithWllama); + expect(answer).toHaveLength(1); + expect(answer[0][0].content).toContain("S1"); + }); + + it("keeps the stored summary when the summarizer resolves to an empty string", async () => { + state.systemPrompt = "s".repeat(3500); + const messages: ChatMessage[] = [ + { role: "user", content: "first question" }, + { role: "assistant", content: "x".repeat(900) }, + { role: "user", content: "follow-up question" }, + ]; + vi.mocked(getConversationSummary).mockReturnValue({ + conversationId: "first question", + summary: "S1", + }); + vi.mocked(generateChatWithWllama).mockImplementation(async (chat) => + chat[0].content.startsWith(summarizerInstruction) ? "" : "the answer", + ); + + await generateChatResponse(messages, () => {}); + + expect(updateConversationSummary).toHaveBeenCalledWith({ + conversationId: "first question", + summary: "S1", + }); + const { answer } = callsTo(generateChatWithWllama); + expect(answer).toHaveLength(1); + expect(answer[0][0].content).toContain("S1"); + }); +}); diff --git a/client/modules/textGeneration.degradation.test.ts b/client/modules/textGeneration.degradation.test.ts index e216483c45d5f50c5e5da17c4a1fa5286ba921f9..99c7b0b6bc9f2bbeb6802ad682efa8d80bd6725f 100644 --- a/client/modules/textGeneration.degradation.test.ts +++ b/client/modules/textGeneration.degradation.test.ts @@ -11,6 +11,7 @@ const harness = vi.hoisted(() => { pageContents: {} as Record, searchRunId: "run-1", staleFlag: false, + suppressNextFollowUp: false, searchPromise: Promise.resolve({}) as Promise, settings: { inferenceType: "internal", @@ -58,6 +59,9 @@ vi.mock("./pubSub", () => ({ updateSearchPromise: (promise: Promise) => { harness.state.searchPromise = promise; }, + updateSuppressNextFollowUp: (value: boolean) => { + harness.state.suppressNextFollowUp = value; + }, updateTextGenerationState: (value: string) => { harness.state.textGenerationState = value; harness.stateTransitions.push(value); @@ -240,6 +244,51 @@ describe("search degradation", () => { expect(harness.state.textSearchState).toBe("completed"); }); + it("completes with no results when a stopword-only query leaves no keywords to retry with", async () => { + harness.state.query = "how about that"; + vi.mocked(searchText).mockImplementation(async (query) => { + if (!query.trim()) { + throw new Error("Query cannot be empty or whitespace only"); + } + return { results: [], stale: false }; + }); + + await searchAndRespond(); + await harness.state.searchPromise; + + expect(searchText).toHaveBeenCalledTimes(1); + expect(harness.state.textSearchResults).toEqual([]); + expect(harness.state.textSearchState).toBe("completed"); + }); + + it("completes without searching when an over-long query has no keywords", async () => { + harness.state.query = "that ".repeat(401); + vi.mocked(searchText).mockImplementation(async (query) => { + if (!query.trim()) { + throw new Error("Query cannot be empty or whitespace only"); + } + return { results: [], stale: false }; + }); + + await searchAndRespond(); + await harness.state.searchPromise; + + expect(searchText).not.toHaveBeenCalled(); + expect(harness.state.textSearchState).toBe("completed"); + }); + + it("searches the trimmed query when an over-long query has no keywords but fits once trimmed", async () => { + harness.state.query = `how about that${" ".repeat(2000)}`; + vi.mocked(searchText).mockResolvedValue({ results: [], stale: false }); + + await searchAndRespond(); + await harness.state.searchPromise; + + expect(searchText).toHaveBeenCalledTimes(1); + expect(vi.mocked(searchText).mock.calls[0][0]).toBe("how about that"); + expect(harness.state.textSearchState).toBe("completed"); + }); + it("grounds the LLM on image results when the text search fails", async () => { vi.mocked(searchText).mockRejectedValue( new Error("HTTP error! status: 502"), @@ -430,6 +479,15 @@ describe("search degradation", () => { expect(harness.state.llmTextSearchResults).toEqual([]); expect(harness.state.textSearchState).toBe("failed"); }); + + it("resets suppressNextFollowUp so a prior restore does not suppress the next search", async () => { + harness.state.suppressNextFollowUp = true; + + await searchAndRespond(); + await harness.state.searchPromise; + + expect(harness.state.suppressNextFollowUp).toBe(false); + }); }); describe("page content grounding", () => { diff --git a/client/modules/textGeneration.test.ts b/client/modules/textGeneration.test.ts index bb208d1c9c627b8c118386e9eb7df9a137c9b066..09dcff7f10625617a9a1f381ca9f3f0cbccac60e 100644 --- a/client/modules/textGeneration.test.ts +++ b/client/modules/textGeneration.test.ts @@ -29,6 +29,7 @@ vi.mock("./pubSub", () => ({ updateImageSearchState: vi.fn(), updateChatMessages: vi.fn(), updateLlmTextSearchResults: vi.fn(), + updateSuppressNextFollowUp: vi.fn(), })); vi.mock("./history", () => ({ diff --git a/client/modules/textGeneration.ts b/client/modules/textGeneration.ts index b2225eb137e32019ac91845aca667bc950a733b2..4bbe6c67aa830e32bb6f0bf9d096d13e396d1af8 100644 --- a/client/modules/textGeneration.ts +++ b/client/modules/textGeneration.ts @@ -24,6 +24,7 @@ import { updatePageContents, updateResponse, updateSearchPromise, + updateSuppressNextFollowUp, updateTextGenerationState, updateTextSearchResults, updateTextSearchStale, @@ -35,6 +36,7 @@ import { getSystemPrompt } from "./systemPrompt"; import { ChatGenerationError, defaultContextSize, + getEffectiveContextSize, getFormattedSearchResults, imageResultTag, searchResultsToConsider, @@ -256,6 +258,8 @@ export async function searchAndRespond() { updateChatMessages([]); + updateSuppressNextFollowUp(false); + updatePageContents({}); updateSearchPromise(startTextSearch(getQuery(), invocation)); @@ -327,6 +331,12 @@ async function buildSystemPromptContent(summary: string): Promise { return content; } +/** Share of the context window that the conversation itself may occupy. */ +const historyBudgetRatio = 0.75; + +const newestMessageTooLongMessage = + "The newest message alone does not fit the context"; + function keepNewestMessagesWithinBudget( messages: ChatMessage[], tokenBudget: number, @@ -360,11 +370,11 @@ export async function generateReplyToMessages( ): Promise { const keptMessages = keepNewestMessagesWithinBudget( messages, - defaultContextSize * 0.75, + defaultContextSize * historyBudgetRatio, ); if (keptMessages.length === 0) { - throw new Error("The newest message alone does not fit the context"); + throw new Error(newestMessageTooLongMessage); } const strategy = await getCurrentInferenceStrategy(); @@ -378,6 +388,18 @@ export async function generateChatResponse( let response = ""; try { + const contextSize = getEffectiveContextSize(); + // The newest message is the question being answered. It always goes out, + // so the one case with no usable prompt is a question larger than the + // whole window; that fails here, before anything is generated. + const question = newMessages.at(-1); + const questionTokens = question + ? gptTokenizer.encode(question.content).length + : 0; + if (questionTokens > contextSize) { + throw new Error(newestMessageTooLongMessage); + } + const conversationId = getConversationId(newMessages); const existingSummary = loadConversationSummary(conversationId); const systemPromptContent = await buildSystemPromptContent(existingSummary); @@ -392,19 +414,30 @@ export async function generateChatResponse( initialResponse.content, ).length; const reservedTokens = systemPromptTokens + initialResponseTokens; - const availableTokenBudget = defaultContextSize * 0.75 - reservedTokens; - const processedMessages = keepNewestMessagesWithinBudget( - newMessages, - availableTokenBudget, + // Only the turns before the question compete for what the system prompt + // and the question leave. Search results, page excerpts and the summary + // can outgrow the history's share, so the budget is clamped at zero: + // then every earlier turn is folded into the summary, never the question. + const earlierTurnsBudget = Math.max( + 0, + contextSize * historyBudgetRatio - reservedTokens - questionTokens, ); + const processedMessages = question + ? [ + ...keepNewestMessagesWithinBudget( + newMessages.slice(0, -1), + earlierTurnsBudget, + ), + question, + ] + : []; if (newMessages.length > processedMessages.length) { const droppedCount = newMessages.length - processedMessages.length; const droppedMessages = newMessages.slice(0, droppedCount); - const updatedSummary = await createLlmSummary( - droppedMessages, - existingSummary, - ); + const updatedSummary = + (await createLlmSummary(droppedMessages, existingSummary)) || + existingSummary; saveConversationSummary(updatedSummary, conversationId); systemPrompt = { role: "user", @@ -434,6 +467,18 @@ async function getKeywords(text: string, limit?: number) { .slice(0, limit); } +/** + * The text to search for a query over the server's 2000-character limit: its + * keywords, or the trimmed query when it has none (stopwords only) and fits. + * Empty when neither works. + */ +async function getLongQuerySearchText(query: string) { + const keywords = (await getKeywords(query, 20)).join(" "); + if (keywords) return keywords; + const trimmed = query.trim(); + return trimmed.length <= 2000 ? trimmed : ""; +} + /** * Reads the pages behind the top results so the answer is grounded on their * text instead of on search snippets alone. Awaited by the search promise, so @@ -480,7 +525,7 @@ async function startTextSearch(query: string, invocation: number) { const asOf = new Date(); const searchQuery = normalizeRelativeDates( - query.length > 2000 ? (await getKeywords(query, 20)).join(" ") : query, + query.length > 2000 ? await getLongQuerySearchText(query) : query, asOf, // The server rejects a longer query outright, so the anchor has to fit. { maxLength: 2000 }, @@ -494,21 +539,27 @@ async function startTextSearch(query: string, invocation: number) { updateTextSearchState("running"); try { - let { results: textResults, stale } = await searchText( - searchQuery, - getSettings().searchResultsLimit, - ); + // A query with no keywords left has nothing to send, which is an empty + // result set rather than a failed search. + let { results: textResults, stale } = searchQuery + ? await searchText(searchQuery, getSettings().searchResultsLimit) + : { results: [] as TextSearchResults, stale: false }; if (textResults.length === 0) { - const queryKeywords = await getKeywords(query, 10); - const keywordOutcome = await searchText( - normalizeRelativeDates(queryKeywords.join(" "), asOf, { - maxLength: 2000, - }).searchQuery, - getSettings().searchResultsLimit, - ); - textResults = keywordOutcome.results; - stale = keywordOutcome.stale; + const keywordQuery = normalizeRelativeDates( + (await getKeywords(query, 10)).join(" "), + asOf, + { maxLength: 2000 }, + ).searchQuery; + + if (keywordQuery) { + const keywordOutcome = await searchText( + keywordQuery, + getSettings().searchResultsLimit, + ); + textResults = keywordOutcome.results; + stale = keywordOutcome.stale; + } } results.textResults = textResults; @@ -535,7 +586,8 @@ async function startTextSearch(query: string, invocation: number) { // Started here but awaited last: only the AI answer waits on it, while // image search and the history write carry on. pageContentsRead = readPageContents(searchQuery, resultsForLlm); - } catch { + } catch (error) { + addLogEntry(`Text search failed: ${error}`); updateTextSearchStale(false); updateTextSearchState("failed"); textSearchFailed = true; diff --git a/client/modules/textGenerationUtilities.test.ts b/client/modules/textGenerationUtilities.test.ts index caeff1229a0f98a50491feab64d32a982774a28c..586d4d3e7280bd170324f7d2405aa9ac753e67e1 100644 --- a/client/modules/textGenerationUtilities.test.ts +++ b/client/modules/textGenerationUtilities.test.ts @@ -1,3 +1,4 @@ +import gptTokenizer from "gpt-tokenizer"; import { beforeEach, describe, expect, it, vi } from "vitest"; import { handleExcerptRequest } from "./pageExcerptWorker"; import type { @@ -36,9 +37,14 @@ vi.mock("./systemPrompt", () => ({ })); import { + getDefaultChatCompletionCreateParamsStreaming, + getDefaultChatMessages, + getEffectiveContextSize, getFormattedSearchResults, + minimumOutputTokens, setWorkerFactory, } from "./textGenerationUtilities"; +import type { ChatMessage } from "./types"; const results: TextSearchResults = [ ["First", "first snippet", "https://a.example/"], @@ -318,6 +324,91 @@ describe("getFormattedSearchResults", () => { }); }); +describe("getEffectiveContextSize", () => { + it("follows the configured context on the OpenAI-compatible backend", () => { + state.settings = { inferenceType: "openai", openAiContextLength: 32768 }; + + expect(getEffectiveContextSize()).toBe(32768); + }); + + it("stays at the default on every other backend, whatever the setting says", () => { + for (const inferenceType of ["browser", "horde", "internal"]) { + state.settings = { inferenceType, openAiContextLength: 32768 }; + + expect(getEffectiveContextSize()).toBe(4096); + } + }); + + it("falls back to the default when the setting cannot size a window", () => { + // A cleared numeric input can persist as an empty string. + for (const openAiContextLength of [undefined, 0, -1, "" as never]) { + state.settings = { inferenceType: "openai", openAiContextLength }; + + expect(getEffectiveContextSize()).toBe(4096); + } + }); +}); + +describe("getDefaultChatCompletionCreateParamsStreaming", () => { + function countPromptTokens(messages: ChatMessage[]) { + return messages.reduce( + (total, message) => total + gptTokenizer.encode(message.content).length, + 0, + ); + } + + /** Search results of `tokens` tokens, the way excerpts fill them. */ + function searchResultsOf(tokens: number) { + const text = Array.from({ length: tokens }, (_, i) => `word${i}`).join(" "); + return gptTokenizer.decode(gptTokenizer.encode(text).slice(0, tokens)); + } + + beforeEach(() => { + state.settings = { inferenceType: "openai", openAiContextLength: 4096 }; + }); + + it("leaves the prompt room in the window instead of asking for all of it", () => { + const messages = getDefaultChatMessages(searchResultsOf(2500)); + const promptTokens = countPromptTokens(messages); + expect(promptTokens).toBeGreaterThan(2000); + + const { max_tokens } = + getDefaultChatCompletionCreateParamsStreaming(messages); + + expect(promptTokens + max_tokens).toBeLessThanOrEqual(4096); + expect(max_tokens).toBeGreaterThan(1000); + }); + + it("still asks for a short answer when the prompt nearly fills the window", () => { + const messages = getDefaultChatMessages(searchResultsOf(4090)); + + expect( + getDefaultChatCompletionCreateParamsStreaming(messages).max_tokens, + ).toBe(minimumOutputTokens); + }); + + it("sizes the budget from the configured context on the OpenAI-compatible backend", () => { + state.settings = { inferenceType: "openai", openAiContextLength: 32768 }; + const messages = getDefaultChatMessages(searchResultsOf(8000)); + + const { max_tokens } = + getDefaultChatCompletionCreateParamsStreaming(messages); + + expect(max_tokens).toBeGreaterThan(20000); + expect(countPromptTokens(messages) + max_tokens).toBeLessThanOrEqual(32768); + }); + + it("sizes the budget from the default context on the internal API", () => { + state.settings = { inferenceType: "internal", openAiContextLength: 32768 }; + const messages = getDefaultChatMessages(searchResultsOf(1000)); + + const { max_tokens } = + getDefaultChatCompletionCreateParamsStreaming(messages); + + expect(countPromptTokens(messages) + max_tokens).toBeLessThanOrEqual(4096); + }); +}); + describe("worker handoff", () => { beforeEach(() => { state.searchResults = results; diff --git a/client/modules/textGenerationUtilities.ts b/client/modules/textGenerationUtilities.ts index c329d7f105386c0d5a46af5c93c65f196ad50bad..01cb4899dc93188b9959e48d0566c747a46eb832 100644 --- a/client/modules/textGenerationUtilities.ts +++ b/client/modules/textGenerationUtilities.ts @@ -1,3 +1,4 @@ +import gptTokenizer from "gpt-tokenizer"; import { addLogEntry } from "./logEntries"; import { allocatePageExcerpts } from "./pageExcerptAllocation"; import type { @@ -35,18 +36,29 @@ export class ChatGenerationError extends Error { */ const pageContentTokenBudgetRatio = 0.35; -function getPageContentTokenBudget() { +/** + * The context window, in tokens, of the selected backend. Every budget carved + * out of the prompt (page excerpts, chat history) measures against this one + * number, so the parts are sized for the same window and fit together. + */ +export function getEffectiveContextSize() { const { inferenceType, openAiContextLength } = getSettings(); // `openAiContextLength` describes one backend's endpoint. Every other one // runs at `defaultContextSize` (the browser models are built with it), and // the setting outlives a switch between them, so it only counts where it - // applies. - const contextSize = - inferenceType === "openai" - ? (openAiContextLength ?? defaultContextSize) - : defaultContextSize; + // applies. A value that is not a positive number cannot size a window. + if ( + inferenceType === "openai" && + typeof openAiContextLength === "number" && + openAiContextLength > 0 + ) { + return openAiContextLength; + } + return defaultContextSize; +} - return Math.floor(contextSize * pageContentTokenBudgetRatio); +function getPageContentTokenBudget() { + return Math.floor(getEffectiveContextSize() * pageContentTokenBudgetRatio); } let workerFactory = () => @@ -243,11 +255,47 @@ export async function canStartResponding() { await getSearchPromise(); } -export function getDefaultChatCompletionCreateParamsStreaming() { - const settings = getSettings(); +/** + * The smallest answer budget a request asks for. A prompt that nearly fills + * the window still gets room for a short answer instead of a zero or negative + * `max_tokens`, which backends reject outright. + */ +export const minimumOutputTokens = 64; + +/** + * Tokens each message spends on its role and delimiters in the chat template, + * on top of its content (ChatML's `<|im_start|>role\n...<|im_end|>\n`). + */ +const tokensPerMessageOverhead = 4; + +/** + * The output budget left in the window once the prompt is in it. Backends + * count `max_tokens` on top of the prompt, so asking for the whole window + * overflows it on every request and gets rejected or truncated. The count + * uses the same tokenizer as the other prompt budgets; the model's own may + * differ a little either way. + */ +function getMaxOutputTokens(messages: ChatMessage[]) { + const contextSize = getEffectiveContextSize(); + const promptTokens = messages.reduce( + (total, message) => + total + + gptTokenizer.encode(message.content).length + + tokensPerMessageOverhead, + 0, + ); + return Math.min( + contextSize, + Math.max(minimumOutputTokens, contextSize - promptTokens), + ); +} + +export function getDefaultChatCompletionCreateParamsStreaming( + messages: ChatMessage[], +) { return { stream: true, - max_tokens: settings.openAiContextLength ?? defaultContextSize, + max_tokens: getMaxOutputTokens(messages), temperature: 0.35, top_p: 1.0, min_p: 0.0, diff --git a/client/modules/textGenerationWithHorde.test.ts b/client/modules/textGenerationWithHorde.test.ts index a60864084813c3b78d29515a9ec37885207b610a..6857b15054e380477ad47656a969645f034454a0 100644 --- a/client/modules/textGenerationWithHorde.test.ts +++ b/client/modules/textGenerationWithHorde.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { addLogEntry } from "./logEntries"; import { getSettings, @@ -9,7 +9,7 @@ import { import { defaultSettings } from "./settings"; import { sleep } from "./sleep"; import { canStartResponding } from "./textGenerationUtilities"; -import type { ChatMessage } from "./types"; +import type { ChatMessage, TextGenerationState } from "./types"; vi.mock("./logEntries", () => ({ addLogEntry: vi.fn(), @@ -81,9 +81,16 @@ describe("textGenerationWithHorde", () => { await generateTextWithHorde(); expect(canStartResponding).toHaveBeenCalled(); - expect(updateTextGenerationState).toHaveBeenCalledWith( - "preparingToGenerate", - ); + expect(vi.mocked(updateTextGenerationState).mock.calls).toEqual([ + ["preparingToGenerate"], + ["generating"], + ]); + // "generating" is entered before the first status poll, so the Stop + // button is there for the whole queue wait. + const generatingOrder = vi.mocked(updateTextGenerationState).mock + .invocationCallOrder[1]; + const firstStatusPollOrder = mockFetch.mock.invocationCallOrder[1]; + expect(generatingOrder).toBeLessThan(firstStatusPollOrder); expect(updateResponse).toHaveBeenCalledWith("Hello world"); const [startUrl, startInit] = mockFetch.mock.calls[0]; @@ -143,6 +150,36 @@ describe("textGenerationWithHorde", () => { expect(sleep).toHaveBeenCalled(); }); + it("can be interrupted once it is generating, and cancels the queued job", async () => { + // The UI only offers Stop while the state is "generating", so the + // interrupt can only happen after the engine has entered it. + let state: TextGenerationState = "idle"; + vi.mocked(updateTextGenerationState).mockImplementation((next) => { + state = next; + }); + vi.mocked(getTextGenerationState).mockImplementation(() => + state === "generating" ? "interrupted" : state, + ); + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-queued" })) + .mockResolvedValueOnce( + jsonResponse({ done: false, is_possible: true, generations: [] }), + ) + .mockResolvedValueOnce(jsonResponse({})); + + await expect(generateTextWithHorde()).rejects.toThrow( + "Generation interrupted", + ); + + const [cancelUrl, cancelInit] = mockFetch.mock.calls[2]; + expect(cancelUrl).toContain("/generate/text/status/gen-queued"); + expect(cancelInit.method).toBe("DELETE"); + }); + it("includes the configured model in the generation request body", async () => { mockSettings({ hordeModel: "custom-model" }); const { generateTextWithHorde } = await import( @@ -164,6 +201,124 @@ describe("textGenerationWithHorde", () => { const [, startInit] = mockFetch.mock.calls[0]; expect(JSON.parse(startInit.body).models).toEqual(["custom-model"]); }); + + describe("status poll failures", () => { + // clearAllMocks keeps queued responses and implementations, and a poll + // that stops early would leave them for the next test. + afterEach(() => { + mockFetch.mockReset(); + }); + + const done = (text: string) => + jsonResponse({ + done: true, + is_possible: true, + generations: [{ text, model: "chosen-model" }], + }); + + it("keeps polling through a rate limit and finishes the generation", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-rate" })) + .mockResolvedValueOnce( + jsonResponse({ message: "Too many requests" }, 429), + ) + .mockResolvedValueOnce(done("After the rate limit")); + + await generateTextWithHorde(); + + expect(updateResponse).toHaveBeenCalledWith("After the rate limit"); + }); + + it("recovers when a gateway answers a poll with an HTML error page", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-gateway" })) + .mockResolvedValueOnce( + new Response("502 Bad Gateway", { + status: 502, + }), + ) + .mockResolvedValueOnce(done("After the gateway error")); + + await generateTextWithHorde(); + + expect(updateResponse).toHaveBeenCalledWith("After the gateway error"); + }); + + it("gives up on a status check that keeps failing without calling the model impossible", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-down" })) + .mockImplementation(async () => + jsonResponse({ message: "Service unavailable" }, 503), + ); + + const error = await generateTextWithHorde().catch( + (caught: Error) => caught, + ); + + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toContain("Service unavailable"); + expect((error as Error).message).not.toContain( + "Generation not possible", + ); + // One submit, then the polls up to the consecutive-failure cap. + expect(mockFetch).toHaveBeenCalledTimes(6); + }); + + it("stops at once when the job is gone, with the server's message", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-gone" })) + .mockResolvedValueOnce( + jsonResponse({ message: "Generation not found" }, 404), + ); + + await expect(generateTextWithHorde()).rejects.toThrow( + "Generation not found", + ); + expect(mockFetch).toHaveBeenCalledTimes(2); + }); + + it("rejects a finished generation that carries no text", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch + .mockResolvedValueOnce(jsonResponse({ id: "gen-empty" })) + .mockResolvedValueOnce( + jsonResponse({ done: true, is_possible: true, generations: [] }), + ); + + const error = await generateTextWithHorde().catch( + (caught: Error) => caught, + ); + + expect((error as Error).message).toContain("No text generated"); + expect((error as Error).message).not.toContain("TypeError"); + }); + }); + + it("reports the server's reason when the job is refused at submit", async () => { + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + mockFetch.mockResolvedValueOnce( + jsonResponse({ message: "Invalid API key" }, 401), + ); + + await expect(generateTextWithHorde()).rejects.toThrow("Invalid API key"); + expect(mockFetch).toHaveBeenCalledTimes(1); + }); }); describe("generateChatWithHorde", () => { @@ -190,6 +345,7 @@ describe("textGenerationWithHorde", () => { expect(onUpdate).toHaveBeenCalledWith("Chat response"); expect(canStartResponding).not.toHaveBeenCalled(); expect(updateResponse).not.toHaveBeenCalled(); + expect(updateTextGenerationState).not.toHaveBeenCalled(); }); }); @@ -229,7 +385,8 @@ describe("textGenerationWithHorde", () => { if (init?.method === "DELETE") { return jsonResponse({}); } - return jsonResponse(statusResponder(pollCounter++)); + const reply = statusResponder(pollCounter++); + return reply instanceof Response ? reply : jsonResponse(reply); }, ); } @@ -349,6 +506,23 @@ describe("textGenerationWithHorde", () => { ); }); + it("does not submit a second round when the status checks keep failing", async () => { + routeHordeFetch({ + workers: [{ models: ["m-a"], max_length: 1024 }], + monthStats: { "m-a": 10 }, + statusResponder: () => + jsonResponse({ message: "Too many requests" }, 429), + }); + + const { generateTextWithHorde } = await import( + "./textGenerationWithHorde" + ); + await expect(generateTextWithHorde()).rejects.toThrow( + "Too many requests", + ); + expect(generationRequestBodies()).toHaveLength(2); + }); + it("does not retry when the generation faults", async () => { routeHordeFetch({ workers: [{ models: ["m-a"], max_length: 1024 }], @@ -467,6 +641,24 @@ describe("textGenerationWithHorde", () => { const [, init] = mockFetch.mock.calls[0]; expect(init.headers.apikey).toBe("test-api-key"); }); + + it.each([ + ["kudos is missing", { username: "bob" }], + ["username is missing", { kudos: 1000 }], + ["kudos is not a number", { username: "bob", kudos: "1000" }], + ["the body is null", null], + ])("returns null and logs when %s", async (_, body) => { + const { fetchHordeUserInfo } = await import("./textGenerationWithHorde"); + + mockFetch.mockResolvedValueOnce(jsonResponse(body)); + + const userInfo = await fetchHordeUserInfo("test-api-key"); + + expect(userInfo).toBeNull(); + expect(addLogEntry).toHaveBeenCalledWith( + expect.stringContaining("malformed user info"), + ); + }); }); it("logs a message that names the model used once generation completes", async () => { diff --git a/client/modules/textGenerationWithHorde.ts b/client/modules/textGenerationWithHorde.ts index 420d712943aa9d86f232a6f94756060b0ef64c05..2a7256f362ec98389f286e7f4306824f5d3f0578 100644 --- a/client/modules/textGenerationWithHorde.ts +++ b/client/modules/textGenerationWithHorde.ts @@ -88,6 +88,65 @@ const HORDE_RANKING_FETCH_TIMEOUT_MS = 10 * 1000; const GENERATION_NOT_POSSIBLE_MESSAGE = "Generation not possible with the selected model"; +// A status check that fails this many times in a row ends the generation. +// Until then a rate limit or a gateway hiccup is retried, waiting 1 s, 2 s, +// 4 s and so on, up to the cap. +const MAX_CONSECUTIVE_POLL_FAILURES = 5; +const MAX_POLL_RETRY_DELAY_MS = 8 * 1000; + +/** + * A non-ok answer from the AI Horde API. The status is kept so a poll can + * tell a passing rate limit from a job that is gone. + */ +class HordeHttpError extends Error { + readonly status: number; + + constructor(status: number, message: string) { + super(message); + this.name = "HordeHttpError"; + this.status = status; + } +} + +/** + * Reads a Horde JSON body, or throws with the server's own message when the + * response is not ok. Horde explains a refusal (a bad key, a rate limit) in + * the body, and that reason is what the user needs to see. + */ +async function readHordeJson( + response: Response, + fallbackMessage: string, +): Promise { + if (response.ok) return (await response.json()) as T; + + let message = fallbackMessage; + try { + const body = (await response.json()) as { message?: unknown }; + if (typeof body.message === "string" && body.message) { + message = body.message; + } + } catch { + // A gateway error page is HTML, not JSON, and the status says enough. + } + throw new HordeHttpError( + response.status, + `${message} (HTTP ${response.status})`, + ); +} + +/** + * A status poll is an idempotent GET, so anything that can pass on its own is + * worth another try: a rate limit, a server error, a body that is not JSON + * (an HTML error page from a gateway) and a dropped connection. Any other + * HTTP error, such as a 404 for an expired job, will not get better. + */ +function isTransientPollFailure(error: unknown): boolean { + if (error instanceof HordeHttpError) { + return error.status === 429 || error.status >= 500; + } + return error instanceof SyntaxError || error instanceof TypeError; +} + function getEffectiveHordeApiKey( settings: ReturnType = getSettings(), ) { @@ -129,7 +188,10 @@ async function startGeneration( }), }); - const data = (await response.json()) as HordeResponse; + const data = await readHordeJson( + response, + "Failed to start generation", + ); if (!data.id) { throw new Error("Failed to start generation"); } @@ -146,54 +208,88 @@ async function handleGenerationStatus( let lastText = ""; try { - let status: HordeStatusResponse; + // Only read after a poll that answered, which is the only way out of the + // loop other than a throw. + let status: HordeStatusResponse = {}; + let consecutivePollFailures = 0; - do { + while (true) { if (signal?.aborted) { throw new Error("Request was aborted"); } - const response = await fetch( - buildHordeUrl(`/generate/text/status/${generationId}`), - { - method: "GET", - signal, - headers: { - [HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent, - [HTTP_HEADERS.CONTENT_TYPE]: "application/json", - [HTTP_HEADERS.API_KEY]: aiHordeApiKey, + let polled: HordeStatusResponse | undefined; + try { + const response = await fetch( + buildHordeUrl(`/generate/text/status/${generationId}`), + { + method: "GET", + signal, + headers: { + [HTTP_HEADERS.CLIENT_AGENT]: aiHordeClientAgent, + [HTTP_HEADERS.CONTENT_TYPE]: "application/json", + [HTTP_HEADERS.API_KEY]: aiHordeApiKey, + }, }, - }, - ); + ); + polled = await readHordeJson( + response, + "Failed to check generation status", + ); + consecutivePollFailures = 0; + } catch (error) { + consecutivePollFailures++; + // Never a ChatGenerationError: "not possible" has to stay reserved for + // a real is_possible: false, since it makes the automatic mode submit + // a second round of jobs. + if ( + signal?.aborted || + !isTransientPollFailure(error) || + consecutivePollFailures >= MAX_CONSECUTIVE_POLL_FAILURES + ) { + throw error; + } + addLogEntry(`AI Horde status check failed, retrying: ${error}`); + } - status = await response.json(); - - if ( - status.generations?.[0]?.text && - status.generations[0].text !== lastText - ) { - lastText = status.generations[0].text; - if (status.generations[0].model) { - addLogEntry( - `AI Horde completed the generation using the model "${status.generations[0].model}"`, - ); + if (polled) { + status = polled; + const generation = status.generations?.[0]; + if (generation?.text && generation.text !== lastText) { + lastText = generation.text; + if (generation.model) { + addLogEntry( + `AI Horde completed the generation using the model "${generation.model}"`, + ); + } + onUpdate(lastText.split(userMarker)[0]); } - onUpdate(lastText.split(userMarker)[0]); } - if (!status.done && !status.faulted && status.is_possible) { - await sleep(1000); + const pending = + polled === undefined || + (!polled.done && !polled.faulted && polled.is_possible); + + if (pending) { + await sleep( + polled + ? 1000 + : Math.min( + 1000 * 2 ** (consecutivePollFailures - 1), + MAX_POLL_RETRY_DELAY_MS, + ), + ); } if (getTextGenerationState() === "interrupted") { + // Stop only ends the polling here; without a cancel the queued job + // would keep running on the Horde and keep spending kudos. + await cancelGeneration(generationId).catch(() => {}); throw new ChatGenerationError("Generation interrupted"); } - } while ( - !status.done && - !status.faulted && - status.is_possible && - !signal?.aborted - ); + + if (!pending || signal?.aborted) break; + } if (signal?.aborted) { throw new Error("Request was aborted"); @@ -207,7 +303,7 @@ async function handleGenerationStatus( throw new ChatGenerationError(GENERATION_NOT_POSSIBLE_MESSAGE); } - const generatedText = status.generations?.[0].text; + const generatedText = status.generations?.[0]?.text; if (!generatedText) { throw new Error("No text generated"); @@ -358,7 +454,7 @@ async function getTopHordeModels(): Promise { export async function fetchHordeUserInfo( apiKey: string, -): Promise { +): Promise { const response = await fetch(buildHordeUrl("/find_user"), { headers: { [HTTP_HEADERS.API_KEY]: apiKey, @@ -371,6 +467,13 @@ export async function fetchHordeUserInfo( } const data = await response.json(); + if (typeof data?.username !== "string" || typeof data?.kudos !== "number") { + addLogEntry( + "AI Horde returned a malformed user info response; treating the key as anonymous", + ); + return null; + } + return { username: data.username, kudos: data.kudos, @@ -383,6 +486,11 @@ export async function generateTextWithHorde() { const messages = getDefaultChatMessages( await getFormattedSearchResults(true), ); + // Horde answers only once the queued job is done, so the first text + // arrives on the poll that ends the loop. Entering "generating" before the + // job is submitted shows the response card and its Stop button for the + // whole queue wait, which is what makes an interrupt possible at all. + updateTextGenerationState("generating"); await executeHordeGeneration(messages, (text) => { updateResponse(text); }); diff --git a/client/modules/textGenerationWithInternalApi.ts b/client/modules/textGenerationWithInternalApi.ts index 6a8ff6062ece0e920f9a5c6d3ed07e9503e538d0..5855682da697da290f2051afcd8be6cb29b72441 100644 --- a/client/modules/textGenerationWithInternalApi.ts +++ b/client/modules/textGenerationWithInternalApi.ts @@ -67,7 +67,7 @@ async function processStreamResponse( "Content-Type": "application/json", }, body: JSON.stringify({ - ...getDefaultChatCompletionCreateParamsStreaming(), + ...getDefaultChatCompletionCreateParamsStreaming(messages), messages, }), }); diff --git a/client/modules/textGenerationWithOpenAi.ts b/client/modules/textGenerationWithOpenAi.ts index 1af0114ddcb177c7bb1414f8ff798ab996466ab5..5c0daaab061370e52a515f3293d519ac05600371 100644 --- a/client/modules/textGenerationWithOpenAi.ts +++ b/client/modules/textGenerationWithOpenAi.ts @@ -47,7 +47,7 @@ async function createOpenAiStream({ apiKey: settings.openAiApiKey, }); - const params = getDefaultChatCompletionCreateParamsStreaming(); + const params = getDefaultChatCompletionCreateParamsStreaming(messages); let effectiveModel = settings.openAiApiModel; let availableModels: { id: string }[] = []; diff --git a/client/modules/textGenerationWithWllama.test.ts b/client/modules/textGenerationWithWllama.test.ts index bfa7955100b5076d2ec1be52340a66e778ee6ec3..c6ffeb8ca670c46db27ccd28421d18d74c0d82c8 100644 --- a/client/modules/textGenerationWithWllama.test.ts +++ b/client/modules/textGenerationWithWllama.test.ts @@ -8,6 +8,7 @@ import { } from "./pubSub"; import { composeStreamedText, + generateChatWithWllama, generateTextWithWllama, } from "./textGenerationWithWllama"; import { initializeWllama } from "./wllama"; @@ -71,6 +72,16 @@ vi.mock("./wllama", () => ({ shouldIncludeUrlsOnPrompt: false, getSampling: () => ({}), }, + "stop-model": { + label: "Stop Model", + hfRepoId: "repo", + hfFilePath: "stop.gguf", + contextSize: 512, + fileSizeInMegabytes: 1, + shouldIncludeUrlsOnPrompt: false, + getSampling: () => ({}), + stopStrings: ["STOP", "<|end|>"], + }, }, })); @@ -147,6 +158,72 @@ describe("generateTextWithWllama", () => { }); }); +describe("stop strings", () => { + async function streamWithStopModel(chunks: string[]) { + const savedSettings = getSettings(); + vi.mocked(getSettings).mockReturnValue({ + ...savedSettings, + wllamaModelId: "stop-model", + }); + vi.mocked(initializeWllama).mockImplementation( + async () => + ({ + createChatCompletion: vi.fn().mockResolvedValue( + (async function* () { + for (const content of chunks) { + yield { choices: [{ delta: { content } }] }; + } + })(), + ), + exit: vi.fn().mockResolvedValue(undefined), + // biome-ignore lint/suspicious/noExplicitAny: minimal Wllama stub + }) as any, + ); + const onUpdate = vi.fn(); + + try { + const result = await generateChatWithWllama( + [{ role: "user", content: "hi" }], + onUpdate, + ); + return { result, onUpdate }; + } finally { + vi.mocked(getSettings).mockReturnValue(savedSettings); + } + } + + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("cuts at the stop string when text follows it in the same chunk", async () => { + const { result, onUpdate } = await streamWithStopModel([ + "abcdefghijklSTOPxyz", + ]); + + expect(result).toBe("abcdefghijkl"); + expect(onUpdate).toHaveBeenLastCalledWith("abcdefghijkl"); + }); + + it("removes a stop string that ends the text", async () => { + const { result } = await streamWithStopModel(["Hello ", "world", "STOP"]); + + expect(result).toBe("Hello world"); + }); + + it("cuts at the stop string that is found, not at the first one in the list", async () => { + const { result } = await streamWithStopModel(["answer<|end|>tail"]); + + expect(result).toBe("answer"); + }); + + it("leaves the text alone when no stop string appears", async () => { + const { result } = await streamWithStopModel(["no stop ", "here"]); + + expect(result).toBe("no stop here"); + }); +}); + describe("composeStreamedText", () => { it("returns the answer unchanged when the model does not think", () => { expect(composeStreamedText("", "The answer.")).toBe("The answer."); diff --git a/client/modules/textGenerationWithWllama.ts b/client/modules/textGenerationWithWllama.ts index 060f2544ab8a0a1d7ff140f29235fc886eacc6f6..cba20c713ead9b39aef2cbdf3eb4fe51e4394dde 100644 --- a/client/modules/textGenerationWithWllama.ts +++ b/client/modules/textGenerationWithWllama.ts @@ -266,18 +266,16 @@ function handleWllamaCompletion( return currentText; } - const stopIndex = model.stopStrings.findIndex((stopString) => - currentText.slice(-(stopString.length * 2)).includes(stopString), - ); + for (const stopString of model.stopStrings) { + const windowStart = Math.max(0, currentText.length - stopString.length * 2); + const stopPosition = currentText.indexOf(stopString, windowStart); - if (stopIndex !== -1) { - abortSignal(); - const cleanedText = currentText.slice( - 0, - -model.stopStrings[stopIndex].length, - ); - onUpdate(cleanedText); - return cleanedText; + if (stopPosition !== -1) { + abortSignal(); + const cleanedText = currentText.slice(0, stopPosition); + onUpdate(cleanedText); + return cleanedText; + } } onUpdate(currentText); diff --git a/client/modules/wllama.initialize.test.ts b/client/modules/wllama.initialize.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..93018200720ec1a37df654b7c25957b95f5578c7 --- /dev/null +++ b/client/modules/wllama.initialize.test.ts @@ -0,0 +1,68 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { addLogEntry } from "./logEntries"; +import { initializeWllama } from "./wllama"; + +const instance = vi.hoisted(() => ({ + loadModelFromHF: vi.fn(), + createChatCompletion: vi.fn(), + exit: vi.fn(), +})); + +vi.mock("@wllama/wllama", () => ({ + // A constructor that returns an object hands that object to `new`. + Wllama: vi.fn(function Wllama() { + return instance; + }), +})); +vi.mock("./logEntries", () => ({ addLogEntry: vi.fn() })); +vi.mock("./textGenerationUtilities", () => ({ defaultContextSize: 4096 })); + +const warmupReply = { choices: [{ message: { content: "a" } }] }; + +describe("initializeWllama", () => { + beforeEach(() => { + vi.clearAllMocks(); + instance.loadModelFromHF.mockResolvedValue(undefined); + instance.createChatCompletion.mockResolvedValue(warmupReply); + instance.exit.mockResolvedValue(undefined); + }); + + it("returns the loaded instance and releases it only between the two loads", async () => { + const result = await initializeWllama("repo", "file.gguf"); + + expect(result).toBe(instance); + expect(instance.loadModelFromHF).toHaveBeenCalledTimes(2); + expect(instance.exit).toHaveBeenCalledTimes(1); + expect(instance.exit.mock.invocationCallOrder[0]).toBeGreaterThan( + instance.loadModelFromHF.mock.invocationCallOrder[0], + ); + expect(instance.exit.mock.invocationCallOrder[0]).toBeLessThan( + instance.loadModelFromHF.mock.invocationCallOrder[1], + ); + }); + + it("releases the instance when the warm-up fails", async () => { + const warmupError = new Error("wasm abort"); + instance.createChatCompletion.mockRejectedValue(warmupError); + + await expect(initializeWllama("repo", "file.gguf")).rejects.toBe( + warmupError, + ); + + expect(instance.exit).toHaveBeenCalledTimes(1); + }); + + it("rethrows the original error when releasing the instance also fails", async () => { + const warmupError = new Error("wasm abort"); + instance.createChatCompletion.mockRejectedValue(warmupError); + instance.exit.mockRejectedValue(new Error("worker already gone")); + + await expect(initializeWllama("repo", "file.gguf")).rejects.toBe( + warmupError, + ); + + expect(addLogEntry).toHaveBeenCalledWith( + "Failed to release Wllama after initialization failed: worker already gone", + ); + }); +}); diff --git a/client/modules/wllama.ts b/client/modules/wllama.ts index 1a4ff3f5962a63fa19863966e56764fb9b0d5977..140101d319c2e025ea4e9d49b6c65c8b99a84da2 100644 --- a/client/modules/wllama.ts +++ b/client/modules/wllama.ts @@ -42,8 +42,10 @@ export async function initializeWllama( ): Promise { addLogEntry("Initializing Wllama"); + let wllama: Wllama | undefined; + try { - const wllama = await createWllamaInstance(config?.wllama); + wllama = await createWllamaInstance(config?.wllama); await wllama.loadModelFromHF( { repo: hfRepoId, file: hfFilePath }, @@ -98,18 +100,31 @@ export async function initializeWllama( error instanceof Error ? error.message : "Unknown error" }`, ); + + // The caller never receives the instance when this throws, so release the + // worker and the model memory here. A failed cleanup must not hide the + // original error. + await wllama?.exit().catch((exitError: unknown) => { + addLogEntry( + `Failed to release Wllama after initialization failed: ${ + exitError instanceof Error ? exitError.message : "Unknown error" + }`, + ); + }); + throw error; } } -export async function clearWllamaCache(): Promise { +export async function clearWllamaCache(): Promise { addLogEntry("Clearing Wllama cache"); + let wllama: Wllama | undefined; + try { - const wllama = await createWllamaInstance(); + wllama = await createWllamaInstance(); await wllama.cacheManager.clear(); addLogEntry("Wllama cache cleared successfully"); - return wllama; } catch (error) { addLogEntry( `Failed to clear Wllama cache: ${ @@ -117,6 +132,14 @@ export async function clearWllamaCache(): Promise { }`, ); throw error; + } finally { + await wllama?.exit().catch((exitError: unknown) => { + addLogEntry( + `Failed to release Wllama after clearing cache: ${ + exitError instanceof Error ? exitError.message : "Unknown error" + }`, + ); + }); } } diff --git a/docs/api.md b/docs/api.md index 6d4792270611ebbcf044a3ede18b234d924cc7be..0131997b81d506b1182fedf20704d1bc08bce58d 100644 --- a/docs/api.md +++ b/docs/api.md @@ -68,6 +68,7 @@ below are the same on every token-gated endpoint: | Status | Body | When | | ------ | -------------------------------- | ---------------------------------------------------- | | `429` | `{"error":"Too many requests."}` | The bucket for this client is empty | +| `400` | `{"error":"Malformed request"}` | Malformed `Host` header, checked before the token | | `400` | `{"error":"Missing token."}` | No `token` parameter | | `401` | `{"error":"Invalid token."}` | The hash does not verify against this server's token | @@ -117,6 +118,11 @@ identity. ## Endpoints +Every response from `/search/text`, `/search/images`, `/page-content`, `/inference`, +`/status`, `/api/config` and `/api/validate-access-key`, errors included, carries +`Cache-Control: no-store`, so no shared cache keeps a result, a token verdict or a +rate-limit answer. `/thumbnail` sets its own headers, described below. + ### `GET /search/text` Query parameters: @@ -276,15 +282,19 @@ because it would be a scriptable document on this origin. Responses carry and `Cache-Control: private, max-age=3600`. The fetch is bounded by a 3 s deadline covering DNS and every hop, at most 3 -redirects, each of them re-validated, and 500 KB of body. Successful fetches are -held in an in-process LRU (100 entries, 50 MB); failures never are. +redirects, each of them re-validated, and 500 KB of body; a larger image is +refused rather than served cut off. Successful fetches are held in an +in-process LRU (100 entries, 50 MB); failures never are. The upstream request +carries the same `User-Agent` as page reads (name, version and repository URL +from `package.json`), since some image hosts, such as `upload.wikimedia.org`, +answer a request without one with 403. | Status | Body | When | | ------ | ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `400` | `{"error":"Missing thumbnail URL"}` | `u` missing | | `400` | `{"error":"Thumbnail URL too long"}` | `u` over 2048 characters | | `403` | `{"error":"Refusing to fetch a thumbnail from a non-public or unresolvable address"}` | The host is in private space, does not resolve, or `u` is not a parseable `http`/`https` URL. `/page-content` answers `400` for that last case; this endpoint does not distinguish it | -| `502` | `{"error":"Thumbnail could not be fetched"}` | Upstream failed, timed out, redirected more than 3 times, answered with a type outside the list, or sent an empty body | +| `502` | `{"error":"Thumbnail could not be fetched"}` | Upstream failed, timed out, redirected more than 3 times, answered with a type outside the list, or sent an empty body or one over 500 KB | | `500` | `{"error":"Internal server error"}` | Anything the hook itself threw, caught so Vite's connect stack does not see an unhandled rejection | Error responses carry `Cache-Control: no-store`, since neither a refusal nor an @@ -334,7 +344,7 @@ written the status line is already sent, so a later failure arrives as a data frame carrying an `error` field, followed by `[DONE]`, rather than as a status code. -The stream carries `Content-Type: text/event-stream`, `Cache-Control: no-cache` +The stream carries `Content-Type: text/event-stream`, `Cache-Control: no-store` and `Connection: keep-alive`. Failures before the stream starts: @@ -353,8 +363,7 @@ Failures before the stream starts: ### `GET /status` -The hook claims the `/status` prefix, so `/status/anything` answers the same -way. +The path is matched exactly, so `/status/anything` falls through. Unauthenticated and not rate-limited: uptime, the counters accumulated since the last restart, and the health of the reranker, the bi-encoder and SearXNG. diff --git a/docs/configuration.md b/docs/configuration.md index d91edb642385a02710400807c5def14093d08b9f..99fb293477c6ac7e3cbe5f11f8274037427308ba 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -88,18 +88,19 @@ These variables control the Vite development/preview server behavior: | `BASIC_SSL` | `false` | Enable basic SSL for HTTPS support during development | | `TRUST_PROXY` | `false` | Trust `X-Forwarded-For`/`X-Real-IP` for the per-client rate-limit key. Enable **only** behind a reverse proxy that sets the rightmost `X-Forwarded-For` entry. Leave off when the instance is exposed directly - otherwise clients could forge the header to evade rate limiting. | -These defaults are provided by `docker-compose.yml`/`docker-compose.production.yml` (e.g. `PORT=${PORT:-7860}`), not by the application itself - `vite.config.ts` reads these variables with no fallback, so when running directly via `npm run dev`/`vite preview` without Docker, unset variables fall through to Vite's own built-in defaults. +These defaults are provided by `docker-compose.yml`/`docker-compose.production.yml` (e.g. `PORT=${PORT:-7860}`), not by the application itself - `vite.config.ts` reads these variables with no fallback, so when running directly via `npm run dev`/`vite preview` without Docker, unset variables fall through to Vite's own built-in defaults, except `ALLOWED_HOSTS`, which allows any host when unset. In the comma-separated lists (`ACCESS_KEYS` and `ALLOWED_HOSTS`), spaces around an entry and empty entries are ignored. ### 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`). 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) 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. | 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`, or both. Names are trimmed and lowercased, and empty items are ignored. Unset or empty means every built-in provider. 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 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_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_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`. @@ -107,6 +108,7 @@ Each provider has its own terms, and each operator is responsible for following - **Parallel**: Parallel describes its keyless tier as for exploration and light use, and asks for an account and an API key for production use ([docs.parallel.ai](https://docs.parallel.ai/integrations/mcp/search-mcp)). - **You.com**: the keyless `profile=free` endpoint allows 100 queries per day ([you.com](https://you.com/docs/build-with-agents/mcp-server)). Its API acceptable use policy asks integrations to honor 429 responses ([you.com](https://you.com/acceptable-use-policy-may-2026)). +- **Keenable**: the keyless endpoint allows 1,000 requests an hour and 10 a second per IP address ([docs.keenable.ai](https://docs.keenable.ai/guides/keyless-access)). Keenable logs requests with or without a key on its default data policy ([docs.keenable.ai](https://docs.keenable.ai/data-privacy)). That is why a provider that answers HTTP 429 is paused: the cascade skips it, without a network call, until its `Retry-After` has passed (60 seconds when the header is missing or invalid, and never more than an hour or less than a second). A public instance should set a key for each provider. @@ -150,7 +152,7 @@ Settings are stored in browser localStorage and can be changed via the Settings | `openAiApiBaseUrl` | string | `''` | Base URL for the OpenAI-compatible API | | `openAiApiKey` | string | `''` | API key for the OpenAI-compatible API | | `openAiApiModel` | string | `''` | Model identifier for the OpenAI-compatible API | -| `openAiContextLength` | number | `4096` | Context window size for OpenAI-compatible models, sent as `max_tokens` | +| `openAiContextLength` | number | `4096` | Context window size for OpenAI-compatible models; `max_tokens` is what is left of it after the prompt (at least 64) | ### Model Selection diff --git a/docs/design.md b/docs/design.md index 7531888de7ed9ef1a97934215722fc4fe5a29720..74695f6ed149825443c479b15b3ea58aea4f2289 100644 --- a/docs/design.md +++ b/docs/design.md @@ -21,7 +21,7 @@ ### Performance -- Lazy loading for routes and components with React.lazy() +- Lazy loading with `React.lazy()` for code not needed on first paint (`AccessPage`, result and AI sections inside `MainPage`, drawers, modals, and `WllamaModelSelect`); `MainPage` is a static import - Optimized bundle size using Vite 8 build optimizations - Efficient state management with create-pubsub - Caching strategies for search results and AI responses diff --git a/docs/development-commands.md b/docs/development-commands.md index 0432c1f2d29156d03d0e85eb1fc49a1f4bde729e..f106c487cfa2cb7218cf91f386d44f7400a09a93 100644 --- a/docs/development-commands.md +++ b/docs/development-commands.md @@ -114,7 +114,7 @@ The repository uses nine GitHub Actions workflows for continuous integration, de Used by both `on-push-to-main` and `on-pull-request-to-main` to run the production container smoke test: -1. **check-docker-container** - Builds and starts the production container with `docker compose -f docker-compose.production.yml up -d`, then verifies the main page returns HTTP 200 within 60 seconds +1. **check-docker-container** - Builds and starts the production container with `docker compose -f docker-compose.production.yml up -d`, then verifies the main page returns HTTP 200 within 3 minutes ### Docker Image Builds diff --git a/docs/failure-injection.md b/docs/failure-injection.md index 6d18237e28b171bb5e411b5072322ef7c8f1e794..1c2f3bf6468989276edb26dc2ea6e7a045efa2e4 100644 --- a/docs/failure-injection.md +++ b/docs/failure-injection.md @@ -46,7 +46,7 @@ needed. | Thumbnail redirects into a private range | Redirect not followed, HTTP 403 | `server/thumbnailEndpointServerHook.test.ts` | | Thumbnail redirect carries a malformed Location | Not followed, HTTP 502, no unhandled rejection | `server/thumbnailEndpointServerHook.test.ts` | | Thumbnail upstream answers with a non-raster or an empty body (SVG included) | `/thumbnail` answers HTTP 502, the tile shows the host name | `server/thumbnailEndpointServerHook.test.ts` | -| Thumbnail body exceeds the byte cap | Body truncated at the cap and served | `server/thumbnailEndpointServerHook.test.ts` | +| Thumbnail body exceeds the byte cap | Not served or cached; `/thumbnail` answers HTTP 502, the tile shows the host name | `server/thumbnailEndpointServerHook.test.ts` | | Thumbnail upstream refuses once, then recovers | The failure is not cached; the next tile load fetches again and serves | `server/thumbnailEndpointServerHook.test.ts` | | `/thumbnail` budget is spent | HTTP 429 for the tiles only; the search budget is a separate limiter | `server/handleTokenVerification.test.ts`, `server/thumbnailEndpointServerHook.test.ts` | | A tile's `/thumbnail` request fails in the browser | That tile shows the host name, the rest of the grid is untouched | `client/components/Search/Results/Graphical/ImageResultsList.test.tsx` | diff --git a/docs/overview.md b/docs/overview.md index 30e900efc84526b04b970cd14cd288b7845ae610..cfa00afa2f035d22c9c127bd6348007fc694ab09 100644 --- a/docs/overview.md +++ b/docs/overview.md @@ -104,7 +104,7 @@ The system executes two parallel flows when a user submits a query: ### AI Generation Flow 1. `textGeneration.ts` orchestrates response generation after search completes -2. State machine transitions: `idle` -> `loadingModel`/`preparingToGenerate` -> `awaitingSearchResults` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `loadingModel` only occurs on the browser/Wllama path, other backends use `preparingToGenerate`) +2. State machine transitions: `idle` -> `awaitingModelDownloadAllowance` -> `loadingModel` -> `awaitingSearchResults` -> `preparingToGenerate` -> `generating` -> `completed`/`failed`/`interrupted` (see Text Generation States below; `awaitingModelDownloadAllowance` and `loadingModel` only occur on the browser/Wllama path, while every backend transitions through `awaitingSearchResults` and then `preparingToGenerate`) 3. Search results are formatted and injected into system prompt via `{{searchResults}}` placeholder. With `enablePageContentFetch` on, the pages behind the top results are read through `/page-content` first and their excerpts are appended to each result (see `docs/page-content.md`) 4. LLM generates response with streaming tokens 5. Response updates throttled to ~12 updates/sec via `throttleit` to prevent React render overload @@ -150,7 +150,7 @@ MiniSearch uses a PubSub-based architecture where state flows through independen - `awaitingModelDownloadAllowance` - Waiting for user consent to download a browser model - `loadingModel` - Downloading or initializing the browser (Wllama) model - `awaitingSearchResults` - Waiting for search to complete before generating -- `preparingToGenerate` - Building the prompt/request just before calling the inference backend (OpenAI-compatible, Internal API, and AI Horde paths) +- `preparingToGenerate` - Building the prompt/request after search results arrive, just before calling the inference backend (all backends, including browser/Wllama) - `generating` - Streaming response tokens - `interrupted` - Generation was cancelled by the user - `completed` - Full response received @@ -231,6 +231,8 @@ The `cacheServerHook` sets Cache-Control headers on every response: | `/` or `*.html` | `no-cache` | HTML must always check for updates | | Everything else | `public, max-age=86400, must-revalidate` | 24-hour cache with revalidation | +The dynamic endpoints (`/search/*`, `/page-content`, `/inference`, `/status`, `/api/config` and `/api/validate-access-key`) set `Cache-Control: no-store` themselves, which overrides this hook where it runs first. `/thumbnail` sets `private, max-age=3600` on success and `no-store` on errors. + ### Status Endpoint The `/status` endpoint returns a JSON object: @@ -441,7 +443,7 @@ way `pageReads` does: | `reranker.skippedUnhealthy` | number | Nothing; searches served in SearXNG's own order because the model was not loaded | | `reranker.failed` | number | Nothing; the same, because reranking threw | | `thumbnails.requested` | number | Nothing; the denominator for the two below; every verified `/thumbnail` request, cache hits included. Before the endpoint existed this counted image results in a search response, so the served share cannot be trended across that deploy | -| `thumbnails.dropped` | number | Every request that did not serve a tile: timeout, a non-raster or empty answer, or an address the guard refused (`MAX_THUMBNAIL_BYTES` is not one of these, a capped body is truncated and served): each is a tile the user saw as a placeholder | +| `thumbnails.dropped` | number | Every request that did not serve a tile: timeout, a non-raster or empty answer, a body over `MAX_THUMBNAIL_BYTES`, or an address the guard refused: each is a tile the user saw as a placeholder | | `thumbnails.blocked` | number | The SSRF guard, as the share of thumbnails whose host is in private space or does not resolve | `thumbnails.dropped` includes the blocked ones, so `requested` minus `dropped` diff --git a/docs/page-content.md b/docs/page-content.md index ac91f3bbd4a667cef203655db6f24c2b516b784e..3dd739791a8dd69e42964d66bc64da2439519ed9 100644 --- a/docs/page-content.md +++ b/docs/page-content.md @@ -138,7 +138,9 @@ the existing per-page character cap and cross-page duplicate suppression. Pools above 256 passages keep the exact lexical ranking of the whole pool; they are not truncated to a shortlist. An unloaded model (empty dense scores) -or a scoring error also keeps lexical ranking. Errors log a fixed diagnostic +or a scoring error also keeps lexical ranking, and so does a scoring request +the worker has not answered within 10 seconds (`SCORE_TIMEOUT_MS`), so a worker +that is alive but stuck cannot hold page-content reads. Errors log a fixed diagnostic without query, URL, passage text or model error details. Dense scoring runs in a worker thread (`server/biEncoderWorker.ts`), not on diff --git a/docs/project-structure.md b/docs/project-structure.md index 5144ea774c544000bb33225bd7924aa2340dba55..5875584e24db3a12ecd5067a6c39a59fe0053d62 100644 --- a/docs/project-structure.md +++ b/docs/project-structure.md @@ -44,6 +44,7 @@ The `client/modules/` directory contains core business logic organized by domain | `textGeneration.ts` | AI response generation and chat handling | | `textGenerationWith*.ts` | Provider-specific inference implementations (Wllama, OpenAI, Horde, Internal API) | | `history.ts` | IndexedDB persistence for searches and chat | +| `autoSearch.ts` | The query the URL belongs to (auto-searched, submitted or restored), so the URL auto-search runs once | | `settings.ts` | Default settings and inference type definitions | | `followUpQuestions.ts` | Generates contextual follow-up questions | | `relatedSearchQuery.ts` | Creates related search queries from conversation | diff --git a/docs/search-history.md b/docs/search-history.md index 9638f4668059655d0c9612bb1e179a92fa802ded..0429973596b74d1025eb43704c3ba606dc51e014 100644 --- a/docs/search-history.md +++ b/docs/search-history.md @@ -14,6 +14,10 @@ The `HistoryDatabase` Dexie instance stores three related tables: 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 + +When `enableHistory` is off, `isHistoryEnabled()` makes every history write (`addSearchToHistory`, `updateSearchResults`, `saveLlmResponseForQuery`, `saveChatMessageForQuery`, the follow-up question chat entries) and the `useSearchHistory` reads return without touching IndexedDB. Skipping `historyDatabase.open()` at startup is not enough on its own: Dexie opens a database that was never opened on its first query, so the setting, not the open state, decides. + ## Cleanup Guarantees To keep IndexedDB lean, inserts trigger `performCleanup()`, which enforces: diff --git a/docs/security.md b/docs/security.md index 22f0caf54d033299937e66c618ed34d346695dc6..ccc91eb2087c4c23a99c7f18361b9a40867eac97 100644 --- a/docs/security.md +++ b/docs/security.md @@ -45,7 +45,7 @@ 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 (all of them when it is empty): `search.parallel.ai` (Parallel) and You.com's MCP endpoint (`https://api.you.com/mcp`). 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 (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 - **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 @@ -87,24 +87,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` and You.com'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/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, 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 | ### Server-Side Fetching of Client-Supplied URLs @@ -157,7 +158,7 @@ the issue's checklist, answered from the code: | Only HTTP/HTTPS schemes | Yes | `resolvePublicUrlAndAddress` | | Redirects safe (no redirect to a private IP) | Yes | followed by hand in `fetchThumbnail`; every hop re-validated under one shared deadline | | Content-Type checked to be an image | Yes | raster-only allowlist in `thumbnailEndpointServerHook.ts`; SVG is excluded because served same-origin it is a script-carrying document | -| Response size limited | Yes | `MAX_THUMBNAIL_BYTES` (500 KB) via `readCappedStream` | +| Response size limited | Yes | `MAX_THUMBNAIL_BYTES` (500 KB) via `readCappedStream`; a larger body is refused, not served cut off | | Timeout configured | Yes | `THUMBNAIL_TIMEOUT_MS` (3 s), shared across DNS and every hop | | Rate limited per client | Yes | `thumbnailRateLimiter`, a dedicated 60-per-10-seconds budget keyed on client IP | | Global rate limit | No, by design | the per-client limiter plus the shared token gate bound the total; a global cap would let one caller's grid starve every other user's tiles | @@ -172,7 +173,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` and You.com'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, 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) - **AI Models**: Models run locally or through trusted providers - **Data Exfiltration**: Prevented by local-first architecture diff --git a/docs/ui-components.md b/docs/ui-components.md index 7e2ec6420ca6cc1f22ff92d55bb49b1f98352563..9dfd92a7149eb4fc7a5b1cd8202f80af518c4333 100644 --- a/docs/ui-components.md +++ b/docs/ui-components.md @@ -88,7 +88,7 @@ All state channels are defined in `client/modules/pubSub.ts`: | `chatGenerationStatePubSub` | `{isGeneratingResponse, isGeneratingFollowUpQuestion}` | Chat generation states. Each flag has one owner: the send and regenerate handlers write `isGeneratingResponse`, `regenerateFollowUpQuestion` writes `isGeneratingFollowUpQuestion`, and every writer merges `getChatGenerationState()` so a concurrent flow is not clobbered. A boolean cannot represent two follow-up calls at once, so each carries an invocation token, and a completion that is no longer the current one writes nothing. Unmounting is the exception to the merge: it replaces both flags outright, bumps the token, and stops the response writers touching the channel at all, so an orphaned flow cannot write into the instance that replaced it | ChatInterface | | `conversationSummaryPubSub` | `{id, summary}` | Rolling conversation summary | TextGeneration module | | `followUpQuestionPubSub` | `string` | Generated follow-up question | AiResponseSection | -| `suppressNextFollowUpPubSub` | `boolean` | Flag to skip next follow-up | FollowUpQuestions module | +| `suppressNextFollowUpPubSub` | `boolean` | One-shot flag set when restoring a saved AI response from history so the restored answer skips follow-up generation; cleared on first read by `ChatInterface` (cancelling any in-flight follow-up) and reset by `searchAndRespond` | ChatInterface, ChatInputArea | | `isRestoringFromHistoryPubSub` | `boolean` | History restoration in progress | SearchForm, components | | `menuExpandedAccordionsPubSub` | `string[]` | Expanded menu accordion IDs | MenuDrawer | | `querySuggestionsPubSub` | `string[]` | Query suggestions history | SearchForm | @@ -149,10 +149,16 @@ App **Responsibility:** Query input and search initiation +**Props:** + +- `query: string` β€” Current query passed from `MainPage` / `HomePage` +- `updateQuery: (query: string) => void` β€” Publishes to `queryPubSub` on submit, URL auto-search, and history restore (typing only updates local `textAreaValue` state) +- `additionalButtons?: ReactNode` β€” Optional buttons rendered in the action row (e.g. `MenuButton`) + **PubSub:** -- **Subscribes:** `queryPubSub`, `textSearchStatePubSub` -- **Updates:** `queryPubSub` (on type), triggers `searchAndRespond()` (on submit) +- **Subscribes:** `settingsPubSub`, `isRestoringFromHistoryPubSub` +- **Updates:** calls `updateQuery(...)` on submit, URL auto-search, and history restore; triggers `searchAndRespond()` on submit and URL auto-search The query field is wrapped in its own `position: relative` element so `DictationButton` anchors to the field rather than to the form, and stays put @@ -161,20 +167,33 @@ when the row of buttons below the field changes height. **Logic:** ```typescript -function SearchForm() { - const [query, setQuery] = usePubSub(queryPubSub); - const [searchState] = usePubSub(textSearchStatePubSub); - - const handleSubmit = () => { - searchAndRespond(); +function SearchForm({ query, updateQuery, additionalButtons }: SearchFormProps) { + const [state, setState] = useState({ + textAreaValue: query, + suggestedQuery: DEFAULT_QUERY_SUGGESTION, + }); + const [pubSubSettings] = usePubSub(settingsPubSub); + const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub); + const [textSearchResults] = usePubSub(textSearchResultsPubSub); + const [imageSearchResults] = usePubSub(imageSearchResultsPubSub); + const [responseValue] = usePubSub(responsePubSub); + + const handleSubmit = (event: React.FormEvent) => { + event.preventDefault(); + // Publishes to queryPubSub via updateQuery, updates URL & history, then runs searchAndRespond() + startSearching(); }; - + return (
- setQuery(e.target.value)} /> - +