Spaces:
Running
Running
Sync from felladrin/MiniSearch@757fca5
Browse filesThis view is limited to 50 files because it contains too many changes. ย See raw diff
Files changed (50)
- .env.example+4-1
- .github/workflows/reusable-check-docker.yml+1-1
- agents.md+22-5
- changelog.md+51
- client/components/AiResponse/AiResponseContent.test.tsx+29-2
- client/components/AiResponse/AiResponseContent.tsx+3-1
- client/components/AiResponse/ChatInputArea.test.tsx+43-1
- client/components/AiResponse/ChatInputArea.tsx+9-12
- client/components/AiResponse/ChatInterface.test.tsx+47
- client/components/AiResponse/ChatInterface.tsx+13-1
- client/components/AiResponse/ExpandableLink.test.tsx+47
- client/components/AiResponse/ExpandableLink.tsx+30-2
- client/components/AiResponse/FormattedMarkdown.tsx+7-2
- client/components/AiResponse/MarkdownRenderer.test.tsx+13
- client/components/AiResponse/MessageList.test.tsx+73-1
- client/components/AiResponse/MessageList.tsx+25-25
- client/components/AiResponse/hooks/useReasoningContent.test.ts+14-3
- client/components/AiResponse/hooks/useReasoningContent.ts+10-5
- client/components/Analytics/SearchStats.test.tsxAdded+85
- client/components/Analytics/SearchStats.tsx+3-2
- client/components/Pages/AccessPage.test.tsxAdded+65
- client/components/Pages/AccessPage.tsx+16-15
- client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx+21-6
- client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx+3-1
- client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx+3-1
- client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsxAdded+40
- client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx+11-3
- client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx+1-1
- client/components/Pages/Main/Menu/ClearDataButton.test.tsxAdded+170
- client/components/Pages/Main/Menu/ClearDataButton.tsx+57-27
- client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx+4-8
- client/components/Pages/Main/Menu/SearchSettingsForm.tsx+8-8
- client/components/Pages/Main/Menu/SettingsForms.test.tsxAdded+60
- client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx-2
- client/components/Pages/Main/Menu/VoiceSettingsForm.tsx+10-6
- client/components/Search/Form/SearchForm.restore.test.tsxAdded+161
- client/components/Search/Form/SearchForm.test.tsx+37-4
- client/components/Search/Form/SearchForm.tsx+15-49
- client/components/Search/History/HistoryDrawer.test.tsx+38
- client/components/Search/History/HistoryDrawer.tsx+24-15
- client/components/Settings/HistorySettings.tsx+9-18
- client/hooks/useHistoryRestore.test.tsAdded+153
- client/hooks/useHistoryRestore.ts+11-2
- client/hooks/useSearchHistory.test.ts+80
- client/hooks/useSearchHistory.ts+13-1
- client/hooks/useSettingsForm.test.tsAdded+90
- client/hooks/useSettingsForm.tsAdded+32
- client/modules/accessKey.test.ts+14-2
- client/modules/accessKey.ts+8-2
- client/modules/autoSearch.tsAdded+22
31 unmodified lines323334353637382 unmodified lines414243444531 unmodified lines# 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.SEARCH_FALLBACK_PROVIDERS=""# The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.2 unmodified lines# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.SEARCH_FALLBACK_YOUCOM_API_KEY=""# 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"31 unmodified lines323334353637382 unmodified lines414243444546474831 unmodified lines# Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on.SEARCH_FALLBACK_ENABLED="false"# Comma-separated list of the second search providers to try: "parallel", "youcom", "keenable", or any mix. Empty means Parallel and You.com, plus Keenable when its key is set. With the fallback enabled, an unknown name stops the server at start.SEARCH_FALLBACK_PROVIDERS=""# The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.2 unmodified lines# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.SEARCH_FALLBACK_YOUCOM_API_KEY=""# The API key for Keenable (api.keenable.ai), sent as X-API-Key. Keenable is opt-in: it joins the default list only when this key is set, or when SEARCH_FALLBACK_PROVIDERS names "keenable", in which case its keyless endpoint is used without a key.SEARCH_FALLBACK_KEENABLE_API_KEY=""# Whether a search that asks for an official page may run a second, "site:"-scoped query to reach the official site itself. Off by default, since it sends the engines a second request; only "true" or "1" turn it on.SEARCH_OFFICIAL_LANE_ENABLED="false"
16 unmodified lines1718192021222316 unmodified lines- run: docker compose -f docker-compose.production.yml up -d- name: Check if main page is availablerun: until curl -s -o /dev/null -w "%{http_code}" localhost:"$PORT" | grep 200; do sleep 1; donetimeout-minutes: 1- uses: actions/setup-node@v7with:16 unmodified lines1718192021222316 unmodified lines- run: docker compose -f docker-compose.production.yml up -d- name: Check if main page is availablerun: until curl -s -o /dev/null -w "%{http_code}" localhost:"$PORT" | grep 200; do sleep 1; donetimeout-minutes: 3- uses: actions/setup-node@v7with:
81 unmodified lines8283848586878872 unmodified lines1611621631641651661671681691701711721731748 unmodified lines18318418518618718810 unmodified lines19920020120220320420520 unmodified lines22622722822923023123223323423523614 unmodified lines25125225325425525681 unmodified lines### Entry Points- `client/index.tsx` - React app initialization- `vite.config.ts` - Vite dev server with hooks- `Dockerfile` - Single-stage container build### Business Logic Modules72 unmodified lines- `server/statusEndpointServerHook.ts` - `/status` health check endpoint- `server/configEndpointServerHook.ts` - `/api/config` runtime client configuration- `server/rerankerServiceHook.ts` - Reranker model lifecycle management- `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/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/rerankerService.ts` - Reranker service (ONNX Runtime inference)- `server/rankSearchResults.ts` - Score-based filtering and result reordering- `server/searchToken.ts` - CSRF token generation and storage8 unmodified lines- `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/useScreenWakeLock.ts` - Keeps the screen awake while a response is generating## Common Tasks Quick Reference10 unmodified lines### Add a new setting1. Add to `client/modules/settings.ts` default object2. Add UI in `client/components/Pages/Main/Menu/`3. Update `docs/configuration.md` settings table### Modify search behavior20 unmodified lines```bashnpm run lint```Inside the dev container, the same command is `docker compose exec development-server npm run lint`.This runs:- Biome (formatting/linting)- TypeScript (type checking)14 unmodified linesSo `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.## Agent-First Principles**Repository as System of Record:**81 unmodified lines8283848586878872 unmodified lines1611621631641651661671681691701711721731741751768 unmodified lines18518618718818919019110 unmodified lines20220320420520620720820 unmodified lines22923023123223323423523623723823924014 unmodified lines25525625725825926026126226326426526626726826927027127227381 unmodified lines### Entry Points- `client/index.tsx` - React app initialization- `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 Modules72 unmodified lines- `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, 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 storage8 unmodified lines- `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 Reference10 unmodified lines### Add a new setting1. Add to `client/modules/settings.ts` default object2. Add UI in `client/components/Pages/Main/Menu/`, and add its key to that form's `useSettingsForm` keys3. Update `docs/configuration.md` settings table### Modify search behavior20 unmodified lines```bashnpm run lintnpx vitest run```Inside the dev container, prefix either command with `docker compose exec development-server`.`npm run lint` runs:- Biome (formatting/linting)- TypeScript (type checking)14 unmodified linesSo `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 lockfileWhen you verify behavior by reading a dependency's source in `node_modules`, check the installed version against the lockfile first:```bashnode -p "require('./node_modules/<dep>/package.json').version"node -p "require('./package-lock.json').packages['node_modules/<dep>'].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:**
1 unmodified line2345678910111 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-23- 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`.## 2026-11-221 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061621 unmodified lineNotable changes, grouped by date, most recent first.## 2026-11-24- Changing a setting in one section of the menu no longer undoes a change made in another. The AI, Search, Interface, History and Voice forms each kept a copy of every setting from the moment the menu opened and wrote the whole copy back on each change, so turning off Text Search and then switching Enter to Submit switched Text Search back on, and a model the app had fallen back to during a search was replaced by the one the menu opened with. Each form now writes only the settings it changed.- The search fallback can use Keenable as a third provider. It is opt-in: it joins the default list only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set, or when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, in which case its keyless endpoint is used without a key. Instances that already run the fallback keep Parallel and You.com as before.- Removing a search from the history now removes its AI answer and chat with it. Automatic cleanup, by age or by the entry limit, and deleting a single entry used to delete only the search, so its answer and chat stayed in the browser's storage for good, out of reach of the History drawer. Follow-up question suggestions also no longer write chat rows that nothing reads, and the rows that earlier versions left behind are removed once, the first time the app opens after this update. Pinned searches keep everything.- 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
16 unmodified lines171819202122232445 unmodified lines70717273747516 unmodified lines}));vi.mock("./FormattedMarkdown", () => ({default: ({ children }: { children: string }) => (<div data-testid="formatted-markdown">{children}</div>),}));45 unmodified linesexpect(liveRegion).toHaveAttribute("aria-busy", "false");});it("gives the toolbar action icons accessible names while generating", () => {renderContent("generating");expect(16 unmodified lines1718192021222324252627282930313233343545 unmodified lines8182838485868788899091929394959697989910010110216 unmodified lines}));vi.mock("./FormattedMarkdown", () => ({default: ({children,isGenerating,}: {children: string;isGenerating?: boolean;}) => (<divdata-testid="formatted-markdown"data-generating={String(Boolean(isGenerating))}>{children}</div>),}));45 unmodified linesexpect(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(
159 unmodified lines160161162163164165166159 unmodified lines<Card.Section withBorder><ConditionalScrollArea><Box aria-live="polite" aria-busy={isGenerating}><FormattedMarkdown>{response}</FormattedMarkdown></Box></ConditionalScrollArea>{textGenerationState === "failed" && (159 unmodified lines160161162163164165166167168159 unmodified lines<Card.Section withBorder><ConditionalScrollArea><Box aria-live="polite" aria-busy={isGenerating}><FormattedMarkdown isGenerating={isGenerating}>{response}</FormattedMarkdown></Box></ConditionalScrollArea>{textGenerationState === "failed" && (
2 unmodified lines3456789135 unmodified lines1451461472 unmodified linesimport userEvent from "@testing-library/user-event";import { useSyncExternalStore } from "react";import ChatInputArea from "@/components/AiResponse/ChatInputArea";import { chatGenerationStatePubSub, chatInputPubSub } from "@/modules/pubSub";import { getDictationEngine, startDictation } from "@/modules/speechToText";vi.mock("@/modules/speechToText", async () => {135 unmodified lines// input the user cannot see or correct.await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));});2 unmodified lines3456789101112131415135 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881892 unmodified linesimport userEvent from "@testing-library/user-event";import { useSyncExternalStore } from "react";import ChatInputArea from "@/components/AiResponse/ChatInputArea";import {chatGenerationStatePubSub,chatInputPubSub,followUpQuestionPubSub,settingsPubSub,} from "@/modules/pubSub";import { defaultSettings } from "@/modules/settings";import { getDictationEngine, startDictation } from "@/modules/speechToText";vi.mock("@/modules/speechToText", async () => {135 unmodified lines// 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(<MantineProvider><ChatInputArea onKeyDown={() => {}} handleSend={handleSend} /></MantineProvider>,);await user.click(screen.getByRole("textbox"));await user.keyboard(keys);if (sends) {expect(handleSend).toHaveBeenCalledWith("What happened next?");} else {expect(handleSend).not.toHaveBeenCalled();}},);});
3 unmodified lines45678910111213141518 unmodified lines34353637383911 unmodified lines51525354555657585960616263646566676869707172733 unmodified linesimport DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";import {chatGenerationStatePubSub,chatInputPubSub,followUpQuestionPubSub,getChatInput,isRestoringFromHistoryPubSub,suppressNextFollowUpPubSub,} from "@/modules/pubSub";18 unmodified linesconst [followUpQuestion] = usePubSub(followUpQuestionPubSub);const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub);const isGenerating =generationState.isGeneratingResponse &&11 unmodified linesconst handleKeyDownWithPlaceholder = (event: React.KeyboardEvent<HTMLTextAreaElement>,) => {// 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;if (input.trim() === "" &&followUpQuestion &&!isRestoringFromHistory &&!suppressNextFollowUp &&!isComposing) {if (event.key === "Enter" && !event.shiftKey) {event.preventDefault();handleSend(followUpQuestion);return;}}onKeyDown(event);3 unmodified lines456789101112131415161718 unmodified lines3637383940414211 unmodified lines54555657585960616263646566676869703 unmodified linesimport DictationButton, {dictationButtonWidth,} from "@/components/DictationButton";import { handleEnterKeyDown } from "@/modules/keyboard";import {chatGenerationStatePubSub,chatInputPubSub,followUpQuestionPubSub,getChatInput,isRestoringFromHistoryPubSub,settingsPubSub,suppressNextFollowUpPubSub,} from "@/modules/pubSub";18 unmodified linesconst [followUpQuestion] = usePubSub(followUpQuestionPubSub);const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub);const [settings] = usePubSub(settingsPubSub);const isGenerating =generationState.isGeneratingResponse &&11 unmodified linesconst handleKeyDownWithPlaceholder = (event: React.KeyboardEvent<HTMLTextAreaElement>,) => {// 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) {handleEnterKeyDown(event, settings, () => handleSend(followUpQuestion));if (event.defaultPrevented) return;}onKeyDown(event);
4 unmodified lines5678910678 unmodified lines6896906916924 unmodified lineschatGenerationStatePubSub,chatInputPubSub,followUpQuestionPubSub,suppressNextFollowUpPubSub,} from "@/modules/pubSub";import type { ChatMessage } from "@/modules/types";678 unmodified lines);expect(generateFollowUpQuestion).toHaveBeenCalled();});});4 unmodified lines567891011678 unmodified lines6906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387394 unmodified lineschatGenerationStatePubSub,chatInputPubSub,followUpQuestionPubSub,getSuppressNextFollowUp,suppressNextFollowUpPubSub,} from "@/modules/pubSub";import type { ChatMessage } from "@/modules/types";678 unmodified lines);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<string>();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);});});
64 unmodified lines65666768697071118 unmodified lines19019119219319419518 unmodified lines21421521621721821964 unmodified linesconst [textSearchResults] = usePubSub(textSearchResultsPubSub);const [imageSearchResults] = usePubSub(imageSearchResultsPubSub);const [currentQuery] = usePubSub(queryPubSub);const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub);const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState<string[]>([]);118 unmodified linesuseEffect(() => {if (suppressNextFollowUp) {hasInitialized.current = true;return;}if (suppressInitialFollowUp) return;18 unmodified linesinitialMessages,messages,regenerateFollowUpQuestion,suppressInitialFollowUp,suppressNextFollowUp,]);64 unmodified lines656667686970717273118 unmodified lines19219319419519619719819920020120220320418 unmodified lines22322422522622722822923023164 unmodified linesconst [textSearchResults] = usePubSub(textSearchResultsPubSub);const [imageSearchResults] = usePubSub(imageSearchResultsPubSub);const [currentQuery] = usePubSub(queryPubSub);const [suppressNextFollowUp, setSuppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub,);const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState<string[]>([]);118 unmodified linesuseEffect(() => {if (suppressNextFollowUp) {hasInitialized.current = true;followUpInvocationRef.current += 1;setFollowUpQuestion("");setGenerationState({...getChatGenerationState(),isGeneratingFollowUpQuestion: false,});setSuppressNextFollowUp(false);return;}if (suppressInitialFollowUp) return;18 unmodified linesinitialMessages,messages,regenerateFollowUpQuestion,setFollowUpQuestion,setGenerationState,setSuppressNextFollowUp,suppressInitialFollowUp,suppressNextFollowUp,]);
36 unmodified lines373839404142165 unmodified lines20820921021136 unmodified lines);}function getFullText() {return screen.getByTestId("expandable-link-full");}165 unmodified linesexpect(fullText).toHaveTextContent("Example Domain");expect(fullText.style.visibility).not.toBe("hidden");});});36 unmodified lines3738394041424344454647484950165 unmodified lines21621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725836 unmodified lines);}function getPill() {const pill = screen.getByRole("link").querySelectorAll<HTMLElement>('[aria-hidden="true"]');expect(pill).toHaveLength(1);return pill[0];}function getFullText() {return screen.getByTestId("expandable-link-full");}165 unmodified linesexpect(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(<MantineProvider><ExpandableLink href="https://www.reuters.com/"><strong>Reuters</strong></ExpandableLink></MantineProvider>,);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("๐");});});
53 unmodified lines5455565758598 unmodified lines686970717273747553 unmodified lines};}/*** Citation link that collapses to a first-character pill and reveals the full* link text on hover/focus, auto-collapsing after 3 s.8 unmodified lineshref,children,}: ExpandableLinkProps) {const childContent = children?.toString() || "";const firstChar = childContent.charAt(0);const [isExpanded, setIsExpanded] = React.useState(true);const timerRef = React.useRef<number | null>(null);const anchorRef = React.useRef<HTMLAnchorElement>(null);53 unmodified lines54555657585960616263646566676869707172737475767778798081828384858687888 unmodified lines97989910010110210353 unmodified lines};}/*** 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.8 unmodified lineshref,children,}: ExpandableLinkProps) {const firstChar = getFirstGrapheme(getTextContent(children));const [isExpanded, setIsExpanded] = React.useState(true);const timerRef = React.useRef<number | null>(null);const anchorRef = React.useRef<HTMLAnchorElement>(null);
6 unmodified lines7891011121314151617181920216 unmodified lineschildren: string;className?: string;enableCopy?: boolean;}export default function FormattedMarkdown({children,className = "",enableCopy = true,}: FormattedMarkdownProps) {const { reasoningContent, mainContent, isGenerating } =useReasoningContent(children);if (!children && !reasoningContent) {return null;6 unmodified lines78910111213141516171819202122232425266 unmodified lineschildren: 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,isResponseGenerating,);if (!children && !reasoningContent) {return null;
79 unmodified lines80818283848579 unmodified linesexpect(link?.getAttribute("rel")).toContain("nofollow");});it("renders a fenced code block through CodeHighlight with its language", () => {const { getByTestId } = renderMarkdown("```js\nconst x = 1;\n```");79 unmodified lines8081828384858687888990919293949596979879 unmodified linesexpect(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```");
1234547 unmodified lines53545556import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { describe, expect, it, vi } from "vitest";import type { ChatMessage } from "@/modules/types";import MessageList from "./MessageList";47 unmodified lines);expect(renderedQuestions).toHaveLength(2);});});1234547 unmodified lines5354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128import { MantineProvider } from "@mantine/core";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";47 unmodified lines);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: "<think>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();});});});
12 unmodified lines131415161718194 unmodified lines2425262728293027 unmodified lines5859606162636465666768697029 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612 unmodified linesinterface MessageProps {message: ChatMessage;index: number;absoluteIndex: number;isLastAssistant: boolean;isGenerating: boolean;4 unmodified linesconst Message = memo(({message,index,absoluteIndex,isLastAssistant,isGenerating,27 unmodified lines)}<Paperkey={`${message.role}-${index}`}shadow="xs"radius="xl"p="sm"style={{ flex: 1, overflow: "auto" }}><FormattedMarkdown>{message.content}</FormattedMarkdown></Paper>{canRegenerate && (29 unmodified linesreturn (<Stack gap="md">{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 (<Messagekey={absoluteIndex}message={message}index={index}absoluteIndex={absoluteIndex}isLastAssistant={isLastAssistant}isGenerating={isGenerating}onEditMessage={onEditMessage}onRegenerate={onRegenerate}/>);})}</Stack>);});12 unmodified lines1314151617184 unmodified lines23242526272827 unmodified lines56575859606162636465666768697029 unmodified lines10010110210310410510610710810911011111211311411511611711811912012112212312412512612 unmodified linesinterface MessageProps {message: ChatMessage;absoluteIndex: number;isLastAssistant: boolean;isGenerating: boolean;4 unmodified linesconst Message = memo(({message,absoluteIndex,isLastAssistant,isGenerating,27 unmodified lines)}<Paperkey={`${message.role}-${absoluteIndex}`}shadow="xs"radius="xl"p="sm"style={{ flex: 1, overflow: "auto" }}><FormattedMarkdown isGenerating={isGenerating && isLastAssistant}>{message.content}</FormattedMarkdown></Paper>{canRegenerate && (29 unmodified linesreturn (<Stack gap="md">{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 (<Message// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identitykey={absoluteIndex}message={message}absoluteIndex={absoluteIndex}isLastAssistant={isLastAssistant}isGenerating={isGenerating}onEditMessage={onEditMessage}onRegenerate={onRegenerate}/>);})}</Stack>);});
15 unmodified lines1617181920217 unmodified lines293031323334353637383940413 unmodified lines45464748495051525354555615 unmodified linesconst { result } = renderHook(() =>useReasoningContent("<think>Let me think about this</think>\nHere is the answer.",),);7 unmodified lines["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));expectEmptyState(result);});it("should return text as main content when no markers present", () => {const { result } = renderHook(() =>useReasoningContent("This is a normal response."),);expect(result.current.reasoningContent).toBe("");3 unmodified linesit("should detect generating state when end marker is missing", () => {const { result } = renderHook(() =>useReasoningContent("<think>I'm still thinking"),);expect(result.current.reasoningContent).toBe("I'm still thinking");expect(result.current.mainContent).toBe("");expect(result.current.isGenerating).toBe(true);});});});15 unmodified lines161718192021227 unmodified lines303132333435363738394041423 unmodified lines4647484950515253545556575859606162636465666715 unmodified linesconst { result } = renderHook(() =>useReasoningContent("<think>Let me think about this</think>\nHere is the answer.",false,),);7 unmodified lines["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, false));expectEmptyState(result);});it("should return text as main content when no markers present", () => {const { result } = renderHook(() =>useReasoningContent("This is a normal response.", false),);expect(result.current.reasoningContent).toBe("");3 unmodified linesit("should detect generating state when end marker is missing", () => {const { result } = renderHook(() =>useReasoningContent("<think>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("<think>I was interrupted", false),);expect(result.current.reasoningContent).toBe("I was interrupted");expect(result.current.mainContent).toBe("");expect(result.current.isGenerating).toBe(false);});});});
3 unmodified lines4567891011121313 unmodified lines272829303132336 unmodified lines404142434445463 unmodified lines/*** 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.*/export function useReasoningContent(text: string) {const [settings] = usePubSub(settingsPubSub);const extractReasoningAndMainContent = useCallback(13 unmodified linesreturn {reasoningContent: trimmedText.slice(startIndex + startMarker.length),mainContent: "",isGenerating: true,};}6 unmodified linesisGenerating: false,};},[],);if (text && text.trim() === "") {3 unmodified lines45678910111213141516171813 unmodified lines323334353637386 unmodified lines454647484950513 unmodified lines/*** Splits a streamed AI response into the part between the reasoning markers* 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,isResponseGenerating: boolean,) {const [settings] = usePubSub(settingsPubSub);const extractReasoningAndMainContent = useCallback(13 unmodified linesreturn {reasoningContent: trimmedText.slice(startIndex + startMarker.length),mainContent: "",isGenerating: isResponseGenerating,};}6 unmodified linesisGenerating: false,};},[isResponseGenerating],);if (text && text.trim() === "") {
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485import { MantineProvider } from "@mantine/core";import { render, screen } from "@testing-library/react";import { useSearchHistory } from "@/hooks/useSearchHistory";import type { SearchEntry } from "@/modules/history";import SearchStats from "./SearchStats";
vi.mock("@/hooks/useSearchHistory", () => ({ useSearchHistory: vi.fn(),}));
/** The hook mock has to return the full shape the real hook returns. */const mockHistory = (recentSearches: SearchEntry[]) => { const noop = vi.fn(async (): Promise<void> => {}); vi.mocked(useSearchHistory).mockReturnValue({ recentSearches, llmResponseCount: 0, chatMessageCount: 0, filteredSearches: recentSearches, groupedSearches: {}, isLoading: false, error: null, currentPage: 0, totalPages: 0, hasNextPage: false, hasPreviousPage: false, retryLastOperation: noop, clearError: vi.fn(), searchHistory: vi.fn(), addToHistory: noop, togglePin: noop, deleteEntry: noop, clearAll: noop, refreshHistory: noop, nextPage: vi.fn(), previousPage: vi.fn(), goToPage: vi.fn(), });};
/** Metric cards print the value below the label; the heatmap above it. */const valueBelow = (label: string) => 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( <MantineProvider> <SearchStats /> </MantineProvider>, );
expect(valueBelow("Daily Average")).toBe("2"); expect(valueAbove("Active days")).toBe("1"); });});13 unmodified lines1415161718192075 unmodified lines9697989910010110213 unmodified linesimport { useMemo } from "react";import { useSearchHistory } from "@/hooks/useSearchHistory";import type { SearchEntry } from "@/modules/history";import { buildActivity } from "@/modules/searchActivity";import { formatRelativeTime } from "@/modules/stringFormatters";import ActivityHeatmap from "./ActivityHeatmap";75 unmodified linesconst dateCounts = new Map<string, number>();filteredSearches.forEach((search) => {const date = new Date(search.timestamp).toISOString().split("T")[0];dateCounts.set(date, (dateCounts.get(date) || 0) + 1);});13 unmodified lines1415161718192075 unmodified lines9697989910010110210313 unmodified linesimport { useMemo } from "react";import { useSearchHistory } from "@/hooks/useSearchHistory";import type { SearchEntry } from "@/modules/history";import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";import { formatRelativeTime } from "@/modules/stringFormatters";import ActivityHeatmap from "./ActivityHeatmap";75 unmodified linesconst dateCounts = new Map<string, number>();filteredSearches.forEach((search) => {// 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);});
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465import { 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( <MantineProvider> <AccessPage onAccessKeyValid={onAccessKeyValid} /> </MantineProvider>, );
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(); });});20 unmodified lines21222324252627282930313233343536373839404120 unmodified linesconst handleSubmit = async (formEvent: FormEvent<HTMLFormElement>) => {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}`);}};20 unmodified lines2122232425262728293031323334353637383940414220 unmodified linesconst handleSubmit = async (formEvent: FormEvent<HTMLFormElement>) => {formEvent.preventDefault();setState((prev) => ({ ...prev, 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");}};
123456786 unmodified lines15161718192021226 unmodified lines29303132333435363738import { 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 { FALLBACK_CONFIG, getConfig } from "@/modules/config";import { requestNotificationPermission } from "@/modules/notifications";import { settingsPubSub } from "@/modules/pubSub";6 unmodified linesimport { useHordeUserInfo } from "./hooks/useHordeUserInfo";import { useOpenAiModels } from "./hooks/useOpenAiModels";export default function AISettingsForm() {const [settings, setSettings] = usePubSub(settingsPubSub);const { openAiModels, useTextInput } = useOpenAiModels(settings);const hordeModels = useHordeModels(settings);const hordeUserInfo = useHordeUserInfo(settings);6 unmodified lines.then(setServerConfig);}, []);const form = useForm({initialValues: settings,onValuesChange: setSettings,});const handleNotificationToggle = async (event: React.ChangeEvent<HTMLInputElement>,123456786 unmodified lines15161718192021222324252627282930313233343536373839406 unmodified lines47484950515253import { Select, Stack, Switch, Text, TextInput } from "@mantine/core";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";6 unmodified linesimport { 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] = usePubSub(settingsPubSub);const { openAiModels, useTextInput } = useOpenAiModels(settings);const hordeModels = useHordeModels(settings);const hordeUserInfo = useHordeUserInfo(settings);6 unmodified lines.then(setServerConfig);}, []);const form = useSettingsForm(SETTINGS_KEYS);const handleNotificationToggle = async (event: React.ChangeEvent<HTMLInputElement>,
7 unmodified lines8910111213147 unmodified lines);interface BrowserSettingsProps {form: UseFormReturnType<typeof defaultSettings>;}/** Browser inference settings: the model to run (lazy-loaded) and its CPU threads. */7 unmodified lines89101112131415167 unmodified lines);interface BrowserSettingsProps {form: UseFormReturnType<Pick<typeof defaultSettings, "wllamaModelId" | "cpuThreads">>;}/** Browser inference settings: the model to run (lazy-loaded) and its CPU threads. */
4 unmodified lines5678910114 unmodified linesimport type { HordeUserInfo, ModelOption } from "../types";interface HordeSettingsProps {form: UseFormReturnType<typeof defaultSettings>;hordeUserInfo: HordeUserInfo | null;hordeModels: ModelOption[];}4 unmodified lines56789101112134 unmodified linesimport type { HordeUserInfo, ModelOption } from "../types";interface HordeSettingsProps {form: UseFormReturnType<Pick<typeof defaultSettings, "hordeApiKey" | "hordeModel">>;hordeUserInfo: HordeUserInfo | null;hordeModels: ModelOption[];}
12345678910111213141516171819202122232425262728293031323334353637383940import { 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 <OpenAISettings form={form} openAiModels={[]} useTextInput={false} />;}
describe("OpenAISettings", () => { it("keeps a context length below the default after blur", () => { const onValuesChange = vi.fn(); render( <MantineProvider> <Harness onValuesChange={onValuesChange} /> </MantineProvider>, ); 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(), ); });});4 unmodified lines56789101148 unmodified lines60616263646566674 unmodified linesimport type { ModelOption } from "../types";interface OpenAISettingsProps {form: UseFormReturnType<typeof defaultSettings>;openAiModels: ModelOption[];useTextInput: boolean;}48 unmodified linesdescription={`Maximum number of tokens the model can consider. Defaults to ${defaultSettings.openAiContextLength}.`}defaultValue={defaultSettings.openAiContextLength}{...form.getInputProps("openAiContextLength")}step={defaultSettings.openAiContextLength}min={defaultSettings.openAiContextLength}/></>);4 unmodified lines567891011121314151617181948 unmodified lines68697071727374754 unmodified linesimport type { ModelOption } from "../types";interface OpenAISettingsProps {form: UseFormReturnType<Pick<typeof defaultSettings,| "openAiApiBaseUrl"| "openAiApiKey"| "openAiApiModel"| "openAiContextLength">>;openAiModels: ModelOption[];useTextInput: boolean;}48 unmodified linesdescription={`Maximum number of tokens the model can consider. Defaults to ${defaultSettings.openAiContextLength}.`}defaultValue={defaultSettings.openAiContextLength}{...form.getInputProps("openAiContextLength")}step={1024}min={512}/></>);
2 unmodified lines34567892 unmodified linesimport { defaultSettings } from "@/modules/settings";interface SystemPromptInputProps {form: UseFormReturnType<typeof defaultSettings>;}/** Custom system prompt editor, with an inline action to restore the default. */2 unmodified lines34567892 unmodified linesimport { defaultSettings } from "@/modules/settings";interface SystemPromptInputProps {form: UseFormReturnType<Pick<typeof defaultSettings, "systemPrompt">>;}/** Custom system prompt editor, with an inline action to restore the default. */
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170import { 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( <MantineProvider> <ClearDataButton /> </MantineProvider>, );}
describe("ClearDataButton", () => { const originalLocation = self.location; const originalCachesDescriptor = Object.getOwnPropertyDescriptor( self, "caches", ); let reloadMock: ReturnType<typeof vi.fn>;
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<boolean>>() .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(); });});17 unmodified lines181920212223242 unmodified lines2728293031323334353637383940414243444546474849505152535455565758596061626364656667688 unmodified lines7778798081828317 unmodified linesconst handleClearDataButtonClick = async () => {const sureToDelete = self.confirm("Are you sure you want to reset the settings and delete all files in cache?",);if (!sureToDelete) return;2 unmodified linessetState((prev) => ({ ...prev, isClearingData: true }));self.localStorage.clear();for (const cacheName of await self.caches.keys()) {await self.caches.delete(cacheName);}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();setState((prev) => ({...prev,isClearingData: false,hasClearedData: true,}));addLogEntry("All data cleared successfully");navigate("/", { replace: true });self.location.reload();};return (8 unmodified lines{state.hasClearedData ? "Data cleared" : "Clear all data"}</Button><Text size="xs" c="dimmed">Reset settings and delete all files in cache to free up space.</Text></Stack>);17 unmodified lines181920212223242 unmodified lines27282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596978 unmodified lines10610710810911011111211317 unmodified linesconst handleClearDataButtonClick = async () => {const sureToDelete = self.confirm("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;2 unmodified linessetState((prev) => ({ ...prev, isClearingData: true }));let clearedSuccessfully = false;try {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)}`,);}}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 clearing data: ${error instanceof Error ? error.message : String(error)}`,);} finally {setState((prev) => ({...prev,isClearingData: false,hasClearedData: clearedSuccessfully,}));navigate("/", { replace: true });self.location.reload();}};return (8 unmodified lines{state.hasClearedData ? "Data cleared" : "Clear all data"}</Button><Text size="xs" c="dimmed">Reset settings, delete cached files and erase your search and chathistory.</Text></Stack>);
3 unmodified lines456789101112131415161718193 unmodified linesuseComputedColorScheme,useMantineColorScheme,} from "@mantine/core";import { useForm } from "@mantine/form";import { usePubSub } from "create-pubsub/react";import { settingsPubSub } from "@/modules/pubSub";export default function InterfaceSettingsForm() {const [settings, setSettings] = usePubSub(settingsPubSub);const form = useForm({initialValues: settings,onValuesChange: setSettings,});const { setColorScheme } = useMantineColorScheme();const computedColorScheme = useComputedColorScheme("light");3 unmodified lines4567891011121314153 unmodified linesuseComputedColorScheme,useMantineColorScheme,} from "@mantine/core";import { useSettingsForm } from "@/hooks/useSettingsForm";const SETTINGS_KEYS = ["enterToSubmit"] as const;export default function InterfaceSettingsForm() {const form = useSettingsForm(SETTINGS_KEYS);const { setColorScheme } = useMantineColorScheme();const computedColorScheme = useComputedColorScheme("light");
1234567891011121314import { Slider, Stack, Switch, Text } from "@mantine/core";import { useForm } from "@mantine/form";import { usePubSub } from "create-pubsub/react";import { settingsPubSub } from "@/modules/pubSub";export default function SearchSettingsForm() {const [settings, setSettings] = usePubSub(settingsPubSub);const form = useForm({initialValues: settings,onValuesChange: setSettings,});return (<Stack gap="md">1234567891011121314import { Slider, Stack, Switch, Text } from "@mantine/core";import { useSettingsForm } from "@/hooks/useSettingsForm";const SETTINGS_KEYS = ["searchResultsLimit","enableTextSearch","enableImageSearch",] as const;export default function SearchSettingsForm() {const form = useSettingsForm(SETTINGS_KEYS);return (<Stack gap="md">
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import { 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<typeof import("@/modules/config")>(); 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( <MantineProvider> <SearchSettingsForm /> <InterfaceSettingsForm /> </MantineProvider>, );
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( <MantineProvider> <AISettingsForm /> </MantineProvider>, );
act(() => updateSettings({ ...getSettings(), wllamaModelId: "another-model" }), ); toggle(/AI Response/);
expect(getSettings()).toMatchObject({ enableAiResponse: true, wllamaModelId: "another-model", }); });});167 unmodified lines16816917017117217317414 unmodified lines189190191192193194195167 unmodified linesexpect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ enableLocalDictationModel: false }),expect.anything(),);});14 unmodified linestextToSpeechEngine: "system",selectedVoiceId: "",}),expect.anything(),);expect((voiceInput() as HTMLInputElement).value).toBe("");});167 unmodified lines16816917017117217314 unmodified lines188189190191192193167 unmodified linesexpect(setSettings).toHaveBeenCalledWith(expect.objectContaining({ enableLocalDictationModel: false }),);});14 unmodified linestextToSpeechEngine: "system",selectedVoiceId: "",}),);expect((voiceInput() as HTMLInputElement).value).toBe("");});
5 unmodified lines67891011121314151 unmodified line17181920212223248 unmodified lines333435363738394041425 unmodified linesSwitch,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 { settingsPubSub } from "@/modules/pubSub";import {listVoices,1 unmodified linetype VoiceOption,} from "@/modules/textToSpeech";export default function VoiceSettingsForm() {const [settings, setSettings] = usePubSub(settingsPubSub);const [voiceOptions, setVoiceOptions] = useState<VoiceOption[]>([]);const getCountryFlag = useCallback((langCode: string) => {8 unmodified lines}}, []);const form = useForm({initialValues: settings,onValuesChange: setSettings,});useEffect(() => {let cancelled = false;5 unmodified lines67891011121314151 unmodified line1718192021222324252627282930318 unmodified lines404142434445465 unmodified linesSwitch,Text,} from "@mantine/core";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,1 unmodified linetype VoiceOption,} from "@/modules/textToSpeech";const SETTINGS_KEYS = ["enableDictation","enableLocalDictationModel","textToSpeechEngine","selectedVoiceId",] as const;export default function VoiceSettingsForm() {const [settings] = usePubSub(settingsPubSub);const [voiceOptions, setVoiceOptions] = useState<VoiceOption[]>([]);const getCountryFlag = useCallback((langCode: string) => {8 unmodified lines}}, []);const form = useSettingsForm(SETTINGS_KEYS);useEffect(() => {let cancelled = false;
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161import { 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 ( <button type="button" onClick={() => onSearchSelect(entryToRestore)}> Restore </button> ); },}));
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<typeof import("@/modules/history")>()), 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( <MantineProvider> <SearchForm query={query} updateQuery={updateQuery} /> </MantineProvider>, ); 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); });});12345678938 unmodified lines48495051525334 unmodified lines888990919293943 unmodified lines9899100101102103import { 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 { searchAndRespond } from "@/modules/textGeneration";vi.mock("create-pubsub/react", () => ({38 unmodified lines}));vi.mock("../../../modules/querySuggestions", () => ({getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"),}));34 unmodified linesdescribe("SearchForm component", () => {beforeEach(() => {vi.mocked(searchAndRespond).mockClear();resetAutoSearchedQuery();window.history.replaceState({}, "", "/");});3 unmodified linesawait waitForPlaceholder();});it("calls updateQuery on submit", async () => {const mockUpdate = vi.fn();const user = userEvent.setup();1234567891038 unmodified lines4950515253545534 unmodified lines909192939495963 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import { 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 { settingsPubSub } from "@/modules/pubSub";import { defaultSettings } from "@/modules/settings";import { searchAndRespond } from "@/modules/textGeneration";vi.mock("create-pubsub/react", () => ({38 unmodified lines}));vi.mock("../../../modules/querySuggestions", () => ({DEFAULT_QUERY_SUGGESTION: "Anything you need!",getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"),}));34 unmodified linesdescribe("SearchForm component", () => {beforeEach(() => {vi.mocked(searchAndRespond).mockClear();resetHandledQuery();window.history.replaceState({}, "", "/");});3 unmodified linesawait 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();
15 unmodified lines1617181920212223242526272829303132335 unmodified lines394041424344454647484950515253545556575822 unmodified lines8182838485868788899091929394959697983 unmodified lines1021031041051061071083 unmodified lines11211311411511611711811912012112212312412512612712816 unmodified lines1451461471481491501511521531541551561571584 unmodified lines16316416516616716816912 unmodified lines18218318418518618718831 unmodified lines22022122222322422522633 unmodified lines26026126226326426526626726815 unmodified lines} from "@/components/DictationButton";import { useHistoryRestore } from "@/hooks/useHistoryRestore";import { useSearchHistory } from "@/hooks/useSearchHistory";import { resetSearchRunId } from "@/modules/history";import { handleEnterKeyDown } from "@/modules/keyboard";import { addLogEntry } from "@/modules/logEntries";import { postMessageToParentWindow } from "@/modules/parentWindow";import {imageSearchResultsPubSub,isRestoringFromHistoryPubSub,responsePubSub,settingsPubSub,textSearchResultsPubSub,} from "@/modules/pubSub";import { getRandomQuerySuggestion } from "@/modules/querySuggestions";import { sleepUntilIdle } from "@/modules/sleep";import { searchAndRespond } from "@/modules/textGeneration";import HistoryButton from "../History/HistoryButton";5 unmodified linesreturn 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;22 unmodified linesuseEffect(() => {pendingDictationRef.current = null;});const defaultSuggestedQuery = "Anything you need!";const [state, setState] = useState<SearchFormState>({textAreaValue: query,suggestedQuery: defaultSuggestedQuery,});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 }));3 unmodified linestry {return await getRandomQuerySuggestion();} catch {return defaultSuggestedQuery;}}, []);3 unmodified linesconst normalizedUrlQuery = urlQuery?.trim();if (normalizedUrlQuery &&normalizedUrlQuery !== autoSearchedQuery &&!isRestoringFromHistory) {const hasRestoredResults =textSearchResults.length > 0 || imageSearchResults.length > 0;const hasRestoredResponse = responseValue.trim().length > 0;if (hasRestoredResults || hasRestoredResponse) return;if (!urlQuery) return;autoSearchedQuery = normalizedUrlQuery;updateQuery(urlQuery);setState((prevState) => ({...prevState,16 unmodified lines};void initializeComponent();}, [updateQuery,isRestoringFromHistory,textSearchResults.length,imageSearchResults.length,responseValue,addToHistory,]);useEffect(() => {if (state.textAreaValue.length === 0) {4 unmodified lines.catch(() => {setState((prev) => ({...prev,suggestedQuery: defaultSuggestedQuery,}));});}12 unmodified linesaddLogEntry("Failed to get query suggestion");setState((prev) => ({...prev,suggestedQuery: defaultSuggestedQuery,}));}}31 unmodified linesconst normalizedQuery = queryToEncode.trim();if (normalizedQuery.length > 0) {autoSearchedQuery = normalizedQuery;}setState((prev) => ({ ...prev, textAreaValue: queryToEncode }));33 unmodified lines};const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {if (event.key === "Enter" && !event.shiftKey) {handleEnterKeyDown(event, pubSubSettings, startSearching);}};return (15 unmodified lines161718192021222324252627282930315 unmodified lines37383940414222 unmodified lines65666768697071727374757677783 unmodified lines828384858687883 unmodified lines929394959697989910010110210316 unmodified lines1201211221231241251264 unmodified lines13113213313413513613712 unmodified lines15015115215315415515631 unmodified lines18818919019119219319433 unmodified lines22822923023123223323415 unmodified lines} 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 {DEFAULT_QUERY_SUGGESTION,getRandomQuerySuggestion,} from "@/modules/querySuggestions";import { sleepUntilIdle } from "@/modules/sleep";import { searchAndRespond } from "@/modules/textGeneration";import HistoryButton from "../History/HistoryButton";5 unmodified linesreturn new URLSearchParams(window.location.search).get("q");}interface SearchFormState {textAreaValue: string;suggestedQuery: string;22 unmodified linesuseEffect(() => {pendingDictationRef.current = null;});const [state, setState] = useState<SearchFormState>({textAreaValue: query,suggestedQuery: DEFAULT_QUERY_SUGGESTION,});const [, navigate] = useLocation();const [pubSubSettings] = usePubSub(settingsPubSub);const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);const { addToHistory } = useSearchHistory();const { restoreSearch } = useHistoryRestore((newQuery) => {setState((prev) => ({ ...prev, textAreaValue: newQuery }));3 unmodified linestry {return await getRandomQuerySuggestion();} catch {return DEFAULT_QUERY_SUGGESTION;}}, []);3 unmodified linesconst normalizedUrlQuery = urlQuery?.trim();if (urlQuery &&normalizedUrlQuery &&!isQueryHandled(normalizedUrlQuery) &&!isRestoringFromHistory) {markQueryAsHandled(normalizedUrlQuery);updateQuery(urlQuery);setState((prevState) => ({...prevState,16 unmodified lines};void initializeComponent();}, [updateQuery, isRestoringFromHistory, addToHistory]);useEffect(() => {if (state.textAreaValue.length === 0) {4 unmodified lines.catch(() => {setState((prev) => ({...prev,suggestedQuery: DEFAULT_QUERY_SUGGESTION,}));});}12 unmodified linesaddLogEntry("Failed to get query suggestion");setState((prev) => ({...prev,suggestedQuery: DEFAULT_QUERY_SUGGESTION,}));}}31 unmodified linesconst normalizedQuery = queryToEncode.trim();if (normalizedQuery.length > 0) {markQueryAsHandled(normalizedQuery);}setState((prev) => ({ ...prev, textAreaValue: queryToEncode }));33 unmodified lines};const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {handleEnterKeyDown(event, pubSubSettings, startSearching);};return (
140 unmodified lines141142143144145146140 unmodified linesexpect(onSearchSelect).toHaveBeenCalledWith(entry);});it("pins an entry without selecting it", async () => {const onSearchSelect = vi.fn();const entry = makeEntry(1, "quantum tunneling");140 unmodified lines141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184140 unmodified linesexpect(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");
11 unmodified lines12131415161777 unmodified lines959697989910010110210310410510610710810911011111211311411511611 unmodified linesText,TextInput,Tooltip,} from "@mantine/core";import { useReducedMotion } from "@mantine/hooks";import {77 unmodified linesonClick={() => handleSearchSelect(search)}><Group justify="space-between" align="flex-start" wrap="nowrap"><Stack gap={2} style={{ flex: 1, minWidth: 0 }}><Tooltip label={search.query} multiline withArrow><Text size="sm" fw={search.pinned ? 600 : 400} truncate>{search.query}</Text></Tooltip><Textsize="xs"c="dimmed"style={{ display: "flex", alignItems: "center", gap: 4 }}><IconClock size={12} />{formatRelativeTime(search.timestamp)}</Text></Stack><Group gap="xs" style={{ flexShrink: 0 }}><ActionIcon11 unmodified lines1213141516171877 unmodified lines9697989910010110210310410510610710810911011111211311411511611711811912012112212312412511 unmodified linesText,TextInput,Tooltip,UnstyledButton,} from "@mantine/core";import { useReducedMotion } from "@mantine/hooks";import {77 unmodified linesonClick={() => handleSearchSelect(search)}><Group justify="space-between" align="flex-start" wrap="nowrap"><UnstyledButtononClick={(e) => {e.stopPropagation();handleSearchSelect(search);}}style={{ flex: 1, minWidth: 0, textAlign: "left" }}><Stack gap={2}><Tooltip label={search.query} multiline withArrow><Text size="sm" fw={search.pinned ? 600 : 400} truncate>{search.query}</Text></Tooltip><Textsize="xs"c="dimmed"style={{ display: "flex", alignItems: "center", gap: 4 }}><IconClock size={12} />{formatRelativeTime(search.timestamp)}</Text></Stack></UnstyledButton><Group gap="xs" style={{ flexShrink: 0 }}><ActionIcon
7 unmodified lines89101112131415161718192021222324252627281 unmodified line30313233343536373839404142434445464748497 unmodified linesSwitch,Text,} from "@mantine/core";import { useForm } from "@mantine/form";import { notifications } from "@mantine/notifications";import { IconInfoCircle } from "@tabler/icons-react";import { usePubSub } from "create-pubsub/react";import { useState } from "react";import { useSearchHistory } from "@/hooks/useSearchHistory";import { addLogEntry } from "@/modules/logEntries";import { settingsPubSub } from "@/modules/pubSub";interface HistorySettingsProps {onClose?: () => void;}export default function HistorySettings({ onClose }: HistorySettingsProps) {const [settings, setSettings] = usePubSub(settingsPubSub);const { recentSearches, llmResponseCount, chatMessageCount, clearAll } =useSearchHistory();const [showClearConfirm, setShowClearConfirm] = useState(false);1 unmodified lineconst 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 handleClearHistory = async () => {try {7 unmodified lines8910111213141516171819202122232425262728293031321 unmodified line343536373839407 unmodified linesSwitch,Text,} from "@mantine/core";import { notifications } from "@mantine/notifications";import { IconInfoCircle } from "@tabler/icons-react";import { useState } from "react";import { useSearchHistory } from "@/hooks/useSearchHistory";import { useSettingsForm } from "@/hooks/useSettingsForm";import { addLogEntry } from "@/modules/logEntries";interface HistorySettingsProps {onClose?: () => void;}const SETTINGS_KEYS = ["enableHistory","historyMaxEntries","historyAutoCleanup","historyRetentionDays",] as const;export default function HistorySettings({ onClose }: HistorySettingsProps) {const { recentSearches, llmResponseCount, chatMessageCount, clearAll } =useSearchHistory();const [showClearConfirm, setShowClearConfirm] = useState(false);1 unmodified lineconst hasHistory =recentSearches.length > 0 || llmResponseCount > 0 || chatMessageCount > 0;const form = useSettingsForm(SETTINGS_KEYS);const handleClearHistory = async () => {try {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153import { 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<typeof import("@/modules/history")>()), 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<SearchEntry>) { 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); });});1234532 unmodified lines3839404142434445464748495030 unmodified lines8182838485868714 unmodified lines102103104105106107108109110import { useCallback } from "react";import { useLocation } from "wouter";import type { SearchEntry } from "../modules/history";import {getChatMessagesForQuery,32 unmodified linesconst restoreSearch = useCallback(async (entry: SearchEntry) => {const selectedQuery = entry.query;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({});30 unmodified lines}if (hasImageResults(entry)) {const results = getResultsFromEntry(entry);if (results && results.type === "image") {const imageTuples: ImageSearchResults = results.items.map((it) => [it.title,14 unmodified linesconst savedResponse = await getLatestLlmResponseForEntry(entry);if (savedResponse && savedResponse.trim().length > 0) {updateResponse(savedResponse);updateTextGenerationState("completed");} else {updateResponse("");updateTextGenerationState("idle");}12345632 unmodified lines394041424344454647484950515253545530 unmodified lines86878889909192939414 unmodified lines109110111112113114115116117118119import { useCallback } from "react";import { useLocation } from "wouter";import { markQueryAsHandled } from "../modules/autoSearch";import type { SearchEntry } from "../modules/history";import {getChatMessagesForQuery,32 unmodified linesconst 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);// 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({});30 unmodified lines}if (hasImageResults(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,14 unmodified linesconst savedResponse = await getLatestLlmResponseForEntry(entry);if (savedResponse && savedResponse.trim().length > 0) {updateSuppressNextFollowUp(true);updateResponse(savedResponse);updateTextGenerationState("completed");} else {updateSuppressNextFollowUp(false);updateResponse("");updateTextGenerationState("idle");}
6 unmodified lines78910111270 unmodified lines838485868788134 unmodified lines2232242252262272286 unmodified linestype SearchEntry,type TextResults,} from "@/modules/history";import * as stringFormatters from "@/modules/stringFormatters";import {FILTER_DEBOUNCE_MS,70 unmodified lines}describe("useSearchHistory", () => {it("reads IndexedDB only on load, never while typing", async () => {const readSpy = vi.spyOn(historyModule, "getRecentSearches");134 unmodified linesexpect(result.current.filteredSearches).toHaveLength(SEEDED_QUERIES.length);});it("paginates from memory: page changes and queries trigger no reads", async () => {await addSearchToHistory("wine tasting porto", textResults);vi.advanceTimersByTime(1000);6 unmodified lines7891011121370 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113114115116134 unmodified lines2512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073086 unmodified linestype SearchEntry,type TextResults,} from "@/modules/history";import { getSettings } from "@/modules/pubSub";import * as stringFormatters from "@/modules/stringFormatters";import {FILTER_DEBOUNCE_MS,70 unmodified lines}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<typeof getSettings>,);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");134 unmodified linesexpect(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);
4 unmodified lines567891083 unmodified lines949596979899134 unmodified lines2342352362372382392404 unmodified linesgetRecentSearches,historyDatabase,type ImageResults,type SearchEntry,type TextResults,} from "../modules/history";83 unmodified linessetIsLoading(true);setError(null);const searches = await getRecentSearches(enablePagination ? 1000 : limit * 2,);134 unmodified linesasync (searchId: number) => {try {const search = await historyDatabase.searches.get(searchId);await historyDatabase.searches.delete(searchId);await refreshHistory();if (search) {4 unmodified lines56789101183 unmodified lines9596979899100101102103104105106107108109134 unmodified lines2442452462472482492502512524 unmodified linesgetRecentSearches,historyDatabase,type ImageResults,isHistoryEnabled,type SearchEntry,type TextResults,} from "../modules/history";83 unmodified linessetIsLoading(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,);134 unmodified linesasync (searchId: number) => {try {const search = await historyDatabase.searches.get(searchId);if (search) {await historyDatabase.deleteSearchesWithChildren([search]);}await refreshHistory();if (search) {
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990import { 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(); });});1234567891011121314151617181920212223242526272829303132import { 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<T, K extends keyof T>(source: T, keys: readonly K[]): Pick<T, K> { const picked = {} as Pick<T, K>; 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<K extends keyof Settings>(keys: readonly K[]) { const [settings, setSettings] = usePubSub(settingsPubSub); const [, , getSettings] = settingsPubSub;
return useForm<Pick<Settings, K>>({ 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) }); }, });}70 unmodified lines71727374757677787980818270 unmodified linesexpect(result).toBe("invalid");});it("should return invalid 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");});it("should send a hash the server can verify against the access key", async () => {70 unmodified lines71727374757677787980818283848586878889909192939470 unmodified linesexpect(result).toBe("invalid");});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("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 () => {
25 unmodified lines2627282930313233 unmodified lines6667686970711 unmodified line7374757677787925 unmodified lines* 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 async function validateAccessKey(accessKey: string,33 unmodified linesreturn "invalid";} catch (error) {addLogEntry(`Error validating access key: ${error}`);notifications.show({title: "Error validating access key",1 unmodified linecolor: "red",position: "top-right",});return "invalid";}}25 unmodified lines262728293031323334353633 unmodified lines70717273747576771 unmodified line7980818283848525 unmodified lines* 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"| "unreachable";export async function validateAccessKey(accessKey: string,33 unmodified linesreturn "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",1 unmodified linecolor: "red",position: "top-right",});return "unreachable";}}
12345678910111213141516171819202122/** * 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;}.env.example+4-1
.github/workflows/reusable-check-docker.yml+1-1
agents.md+22-5
changelog.md+51
client/components/AiResponse/AiResponseContent.test.tsx+29-2
client/components/AiResponse/AiResponseContent.tsx+3-1
client/components/AiResponse/ChatInputArea.test.tsx+43-1
client/components/AiResponse/ChatInputArea.tsx+9-12
client/components/AiResponse/ChatInterface.test.tsx+47
client/components/AiResponse/ChatInterface.tsx+13-1
client/components/AiResponse/ExpandableLink.test.tsx+47
client/components/AiResponse/ExpandableLink.tsx+30-2
client/components/AiResponse/FormattedMarkdown.tsx+7-2
client/components/AiResponse/MarkdownRenderer.test.tsx+13
client/components/AiResponse/MessageList.test.tsx+73-1
client/components/AiResponse/MessageList.tsx+25-25
client/components/AiResponse/hooks/useReasoningContent.test.ts+14-3
client/components/AiResponse/hooks/useReasoningContent.ts+10-5
client/components/Analytics/SearchStats.test.tsxAdded+85
client/components/Analytics/SearchStats.tsx+3-2
client/components/Pages/AccessPage.test.tsxAdded+65
client/components/Pages/AccessPage.tsx+16-15
client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx+21-6
client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx+3-1
client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx+3-1
client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsxAdded+40
client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx+11-3
client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx+1-1
client/components/Pages/Main/Menu/ClearDataButton.test.tsxAdded+170
client/components/Pages/Main/Menu/ClearDataButton.tsx+57-27
client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx+4-8
client/components/Pages/Main/Menu/SearchSettingsForm.tsx+8-8
client/components/Pages/Main/Menu/SettingsForms.test.tsxAdded+60
client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx-2
client/components/Pages/Main/Menu/VoiceSettingsForm.tsx+10-6
client/components/Search/Form/SearchForm.restore.test.tsxAdded+161
client/components/Search/Form/SearchForm.test.tsx+37-4
client/components/Search/Form/SearchForm.tsx+15-49
client/components/Search/History/HistoryDrawer.test.tsx+38
client/components/Search/History/HistoryDrawer.tsx+24-15
client/components/Settings/HistorySettings.tsx+9-18
client/hooks/useHistoryRestore.test.tsAdded+153
client/hooks/useHistoryRestore.ts+11-2
client/hooks/useSearchHistory.test.ts+80
client/hooks/useSearchHistory.ts+13-1
client/hooks/useSettingsForm.test.tsAdded+90
client/hooks/useSettingsForm.tsAdded+32
client/modules/accessKey.test.ts+14-2
client/modules/accessKey.ts+8-2
client/modules/autoSearch.tsAdded+22