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
- .env.example +4 -1
- .github/workflows/reusable-check-docker.yml +1 -1
- agents.md +22 -5
- changelog.md +51 -0
- 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 -0
- client/components/AiResponse/ChatInterface.tsx +13 -1
- client/components/AiResponse/ExpandableLink.test.tsx +47 -0
- client/components/AiResponse/ExpandableLink.tsx +30 -2
- client/components/AiResponse/FormattedMarkdown.tsx +7 -2
- client/components/AiResponse/MarkdownRenderer.test.tsx +13 -0
- 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.tsx +85 -0
- client/components/Analytics/SearchStats.tsx +3 -2
- client/components/Pages/AccessPage.test.tsx +65 -0
- 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.tsx +40 -0
- 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.tsx +170 -0
- 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.tsx +60 -0
- client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx +0 -2
- client/components/Pages/Main/Menu/VoiceSettingsForm.tsx +10 -6
- client/components/Search/Form/SearchForm.restore.test.tsx +161 -0
- 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 -0
- client/components/Search/History/HistoryDrawer.tsx +24 -15
- client/components/Settings/HistorySettings.tsx +9 -18
- client/hooks/useHistoryRestore.test.ts +153 -0
- client/hooks/useHistoryRestore.ts +11 -2
- client/hooks/useSearchHistory.test.ts +80 -0
- client/hooks/useSearchHistory.ts +13 -1
- client/hooks/useSettingsForm.test.ts +90 -0
- client/hooks/useSettingsForm.ts +32 -0
- client/modules/accessKey.test.ts +14 -2
- client/modules/accessKey.ts +8 -2
- client/modules/autoSearch.ts +22 -0
.env.example
CHANGED
|
@@ -32,7 +32,7 @@ DEFAULT_INFERENCE_TYPE="browser"
|
|
| 32 |
# Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on.
|
| 33 |
SEARCH_FALLBACK_ENABLED="false"
|
| 34 |
|
| 35 |
-
# Comma-separated list of the second search providers to try: "parallel", "youcom", or
|
| 36 |
SEARCH_FALLBACK_PROVIDERS=""
|
| 37 |
|
| 38 |
# The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.
|
|
@@ -41,5 +41,8 @@ SEARCH_FALLBACK_PARALLEL_API_KEY=""
|
|
| 41 |
# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.
|
| 42 |
SEARCH_FALLBACK_YOUCOM_API_KEY=""
|
| 43 |
|
|
|
|
|
|
|
|
|
|
| 44 |
# 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.
|
| 45 |
SEARCH_OFFICIAL_LANE_ENABLED="false"
|
|
|
|
| 32 |
# Whether a text search that failed on SearXNG is retried against the second search providers (search.parallel.ai and You.com, tried one after the other in random order until one returns results). Only "true" or "1" turn it on.
|
| 33 |
SEARCH_FALLBACK_ENABLED="false"
|
| 34 |
|
| 35 |
+
# Comma-separated list of the second search providers to try: "parallel", "youcom", "keenable", or any mix. Empty means Parallel and You.com, plus Keenable when its key is set. With the fallback enabled, an unknown name stops the server at start.
|
| 36 |
SEARCH_FALLBACK_PROVIDERS=""
|
| 37 |
|
| 38 |
# The API key for Parallel (search.parallel.ai). Optional; without it the keyless tier is used, which Parallel describes as for exploration and light use.
|
|
|
|
| 41 |
# The API key for You.com. Optional; without it the keyless "profile=free" endpoint is used, which allows 100 queries per day.
|
| 42 |
SEARCH_FALLBACK_YOUCOM_API_KEY=""
|
| 43 |
|
| 44 |
+
# The API key for Keenable (api.keenable.ai), sent as X-API-Key. Keenable is opt-in: it joins the default list only when this key is set, or when SEARCH_FALLBACK_PROVIDERS names "keenable", in which case its keyless endpoint is used without a key.
|
| 45 |
+
SEARCH_FALLBACK_KEENABLE_API_KEY=""
|
| 46 |
+
|
| 47 |
# Whether a search that asks for an official page may run a second, "site:"-scoped query to reach the official site itself. Off by default, since it sends the engines a second request; only "true" or "1" turn it on.
|
| 48 |
SEARCH_OFFICIAL_LANE_ENABLED="false"
|
.github/workflows/reusable-check-docker.yml
CHANGED
|
@@ -17,7 +17,7 @@ jobs:
|
|
| 17 |
- run: docker compose -f docker-compose.production.yml up -d
|
| 18 |
- name: Check if main page is available
|
| 19 |
run: until curl -s -o /dev/null -w "%{http_code}" localhost:"$PORT" | grep 200; do sleep 1; done
|
| 20 |
-
timeout-minutes:
|
| 21 |
|
| 22 |
- uses: actions/setup-node@v7
|
| 23 |
with:
|
|
|
|
| 17 |
- run: docker compose -f docker-compose.production.yml up -d
|
| 18 |
- name: Check if main page is available
|
| 19 |
run: until curl -s -o /dev/null -w "%{http_code}" localhost:"$PORT" | grep 200; do sleep 1; done
|
| 20 |
+
timeout-minutes: 3
|
| 21 |
|
| 22 |
- uses: actions/setup-node@v7
|
| 23 |
with:
|
agents.md
CHANGED
|
@@ -82,7 +82,7 @@ Need to:
|
|
| 82 |
### Entry Points
|
| 83 |
|
| 84 |
- `client/index.tsx` - React app initialization
|
| 85 |
-
- `vite.config.ts` - Vite dev server with hooks
|
| 86 |
- `Dockerfile` - Single-stage container build
|
| 87 |
|
| 88 |
### Business Logic Modules
|
|
@@ -161,14 +161,16 @@ Need to:
|
|
| 161 |
- `server/statusEndpointServerHook.ts` - `/status` health check endpoint
|
| 162 |
- `server/configEndpointServerHook.ts` - `/api/config` runtime client configuration
|
| 163 |
- `server/rerankerServiceHook.ts` - Reranker model lifecycle management
|
|
|
|
| 164 |
- `server/compressionServerHook.ts` - gzip/brotli compression for responses
|
| 165 |
- `server/crossOriginServerHook.ts` - COOP/COEP headers for SharedArrayBuffer
|
| 166 |
- `server/cacheServerHook.ts` - Cache-Control headers (preview server only)
|
| 167 |
- `server/webSearchService.ts` - SearXNG integration with circuit breaker and retry logic
|
| 168 |
-
- `server/fallbackSearchService.ts` - Fallback text-search cascade over Parallel
|
| 169 |
- `server/pageContentService.ts` - Reads result pages and extracts query-relevant passages
|
| 170 |
- `server/pageReadHostBreaker.ts` - Per-host circuit breaker for page reads: skips a host that refused the last three reads, then probes it once
|
| 171 |
- `server/utils/publicUrl.ts` - Blocks private and reserved addresses before a server-side fetch
|
|
|
|
| 172 |
- `server/rerankerService.ts` - Reranker service (ONNX Runtime inference)
|
| 173 |
- `server/rankSearchResults.ts` - Score-based filtering and result reordering
|
| 174 |
- `server/searchToken.ts` - CSRF token generation and storage
|
|
@@ -183,6 +185,7 @@ Need to:
|
|
| 183 |
- `client/hooks/useSearchHistory.ts` - Search history management from IndexedDB
|
| 184 |
- `client/hooks/useHistoryRestore.ts` - Restores full search state from history
|
| 185 |
- `client/hooks/useDrawerState.ts` - Drawer open/close state with logging
|
|
|
|
| 186 |
- `client/hooks/useScreenWakeLock.ts` - Keeps the screen awake while a response is generating
|
| 187 |
|
| 188 |
## Common Tasks Quick Reference
|
|
@@ -199,7 +202,7 @@ Need to:
|
|
| 199 |
### Add a new setting
|
| 200 |
|
| 201 |
1. Add to `client/modules/settings.ts` default object
|
| 202 |
-
2. Add UI in `client/components/Pages/Main/Menu/`
|
| 203 |
3. Update `docs/configuration.md` settings table
|
| 204 |
|
| 205 |
### Modify search behavior
|
|
@@ -226,11 +229,12 @@ Before any change:
|
|
| 226 |
|
| 227 |
```bash
|
| 228 |
npm run lint
|
|
|
|
| 229 |
```
|
| 230 |
|
| 231 |
-
Inside the dev container,
|
| 232 |
|
| 233 |
-
|
| 234 |
|
| 235 |
- Biome (formatting/linting)
|
| 236 |
- TypeScript (type checking)
|
|
@@ -251,6 +255,19 @@ The project is split across three TypeScript configs, and the default one covers
|
|
| 251 |
|
| 252 |
So `npx tsc --noEmit` reports success while type errors sit in `server/` or `eval/`, and CI then fails on a change that looked clean locally. Only `npm run lint` runs all three configs. Never treat a bare `tsc` as a green typecheck.
|
| 253 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 254 |
## Agent-First Principles
|
| 255 |
|
| 256 |
**Repository as System of Record:**
|
|
|
|
| 82 |
### Entry Points
|
| 83 |
|
| 84 |
- `client/index.tsx` - React app initialization
|
| 85 |
+
- `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`.
|
| 86 |
- `Dockerfile` - Single-stage container build
|
| 87 |
|
| 88 |
### Business Logic Modules
|
|
|
|
| 161 |
- `server/statusEndpointServerHook.ts` - `/status` health check endpoint
|
| 162 |
- `server/configEndpointServerHook.ts` - `/api/config` runtime client configuration
|
| 163 |
- `server/rerankerServiceHook.ts` - Reranker model lifecycle management
|
| 164 |
+
- `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`)
|
| 165 |
- `server/compressionServerHook.ts` - gzip/brotli compression for responses
|
| 166 |
- `server/crossOriginServerHook.ts` - COOP/COEP headers for SharedArrayBuffer
|
| 167 |
- `server/cacheServerHook.ts` - Cache-Control headers (preview server only)
|
| 168 |
- `server/webSearchService.ts` - SearXNG integration with circuit breaker and retry logic
|
| 169 |
+
- `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
|
| 170 |
- `server/pageContentService.ts` - Reads result pages and extracts query-relevant passages
|
| 171 |
- `server/pageReadHostBreaker.ts` - Per-host circuit breaker for page reads: skips a host that refused the last three reads, then probes it once
|
| 172 |
- `server/utils/publicUrl.ts` - Blocks private and reserved addresses before a server-side fetch
|
| 173 |
+
- `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
|
| 174 |
- `server/rerankerService.ts` - Reranker service (ONNX Runtime inference)
|
| 175 |
- `server/rankSearchResults.ts` - Score-based filtering and result reordering
|
| 176 |
- `server/searchToken.ts` - CSRF token generation and storage
|
|
|
|
| 185 |
- `client/hooks/useSearchHistory.ts` - Search history management from IndexedDB
|
| 186 |
- `client/hooks/useHistoryRestore.ts` - Restores full search state from history
|
| 187 |
- `client/hooks/useDrawerState.ts` - Drawer open/close state with logging
|
| 188 |
+
- `client/hooks/useSettingsForm.ts` - Mantine form over a list of settings keys that writes only the keys that changed
|
| 189 |
- `client/hooks/useScreenWakeLock.ts` - Keeps the screen awake while a response is generating
|
| 190 |
|
| 191 |
## Common Tasks Quick Reference
|
|
|
|
| 202 |
### Add a new setting
|
| 203 |
|
| 204 |
1. Add to `client/modules/settings.ts` default object
|
| 205 |
+
2. Add UI in `client/components/Pages/Main/Menu/`, and add its key to that form's `useSettingsForm` keys
|
| 206 |
3. Update `docs/configuration.md` settings table
|
| 207 |
|
| 208 |
### Modify search behavior
|
|
|
|
| 229 |
|
| 230 |
```bash
|
| 231 |
npm run lint
|
| 232 |
+
npx vitest run
|
| 233 |
```
|
| 234 |
|
| 235 |
+
Inside the dev container, prefix either command with `docker compose exec development-server`.
|
| 236 |
|
| 237 |
+
`npm run lint` runs:
|
| 238 |
|
| 239 |
- Biome (formatting/linting)
|
| 240 |
- TypeScript (type checking)
|
|
|
|
| 255 |
|
| 256 |
So `npx tsc --noEmit` reports success while type errors sit in `server/` or `eval/`, and CI then fails on a change that looked clean locally. Only `npm run lint` runs all three configs. Never treat a bare `tsc` as a green typecheck.
|
| 257 |
|
| 258 |
+
### node_modules can be stale relative to the lockfile
|
| 259 |
+
|
| 260 |
+
When you verify behavior by reading a dependency's source in `node_modules`, check the installed version against the lockfile first:
|
| 261 |
+
|
| 262 |
+
```bash
|
| 263 |
+
node -p "require('./node_modules/<dep>/package.json').version"
|
| 264 |
+
node -p "require('./package-lock.json').packages['node_modules/<dep>'].version"
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
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.
|
| 268 |
+
|
| 269 |
+
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.
|
| 270 |
+
|
| 271 |
## Agent-First Principles
|
| 272 |
|
| 273 |
**Repository as System of Record:**
|
changelog.md
CHANGED
|
@@ -2,10 +2,61 @@
|
|
| 2 |
|
| 3 |
Notable changes, grouped by date, most recent first.
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
## 2026-11-23
|
| 6 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
- 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`.
|
| 8 |
- 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`.
|
|
|
|
| 9 |
|
| 10 |
## 2026-11-22
|
| 11 |
|
|
|
|
| 2 |
|
| 3 |
Notable changes, grouped by date, most recent first.
|
| 4 |
|
| 5 |
+
## 2026-11-24
|
| 6 |
+
|
| 7 |
+
- Changing a setting in one section of the menu no longer undoes a change made in another. The AI, Search, Interface, History and Voice forms each kept a copy of every setting from the moment the menu opened and wrote the whole copy back on each change, so turning off Text Search and then switching Enter to Submit switched Text Search back on, and a model the app had fallen back to during a search was replaced by the one the menu opened with. Each form now writes only the settings it changed.
|
| 8 |
+
- The search fallback can use Keenable as a third provider. It is opt-in: it joins the default list only when `SEARCH_FALLBACK_KEENABLE_API_KEY` is set, or when `SEARCH_FALLBACK_PROVIDERS` names `keenable`, in which case its keyless endpoint is used without a key. Instances that already run the fallback keep Parallel and You.com as before.
|
| 9 |
+
- Removing a search from the history now removes its AI answer and chat with it. Automatic cleanup, by age or by the entry limit, and deleting a single entry used to delete only the search, so its answer and chat stayed in the browser's storage for good, out of reach of the History drawer. Follow-up question suggestions also no longer write chat rows that nothing reads, and the rows that earlier versions left behind are removed once, the first time the app opens after this update. Pinned searches keep everything.
|
| 10 |
+
- 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.
|
| 11 |
+
- 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".
|
| 12 |
+
- 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.
|
| 13 |
+
- 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.
|
| 14 |
+
- 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.
|
| 15 |
+
- 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.
|
| 16 |
+
- 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.
|
| 17 |
+
- 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.
|
| 18 |
+
- 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.
|
| 19 |
+
- 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.
|
| 20 |
+
- 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.
|
| 21 |
+
- 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.
|
| 22 |
+
- 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.
|
| 23 |
+
- 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.
|
| 24 |
+
|
| 25 |
+
- 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`.
|
| 26 |
+
- "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.
|
| 27 |
+
- 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.
|
| 28 |
+
- 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.
|
| 29 |
+
- A missing file under `/assets/` is no longer sent with a one-year immutable cache header. During a partial deploy, or for an outdated link, the server answered such a request with the app page or a 404 marked immutable, so browsers could keep that wrong answer for the asset's URL for a year. Only files that exist in the build are now marked immutable; anything else under `/assets/` gets `no-cache`.
|
| 30 |
+
- A search that found nothing is no longer reported as failed when the query has no keywords. A query made only of common words, such as "how about that", used to be retried with its keywords after finding no results; with none left, the retry sent an empty query, which was rejected, so the search showed as failed and, with AI answers on, ran the image fallback meant for outages. The retry is now skipped and the search completes with no results. A query over 2000 characters with no keywords is now searched without its surrounding spaces when that fits, and otherwise completes with no results instead of failing. A failed text search now also leaves a log entry with its error.
|
| 31 |
+
- A relative date in a search query is now recognised the way people type it. "next yearโs champion" with a curly apostrophe, the default on iPhone and Mac, no longer gets a year added, and a non-breaking or double space no longer hides "next year". A date the query already carries in another spelling ("2026 December", "Dec 2026", "2026-12") is not appended again, and a year inside a longer number such as "120265" is no longer taken for one. A follow-up search that is only a year no longer starts with a space, which gave the same search two cache entries.
|
| 32 |
+
|
| 33 |
## 2026-11-23
|
| 34 |
|
| 35 |
+
- 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.
|
| 36 |
+
- 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.
|
| 37 |
+
- 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.
|
| 38 |
+
- 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.
|
| 39 |
+
- 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.
|
| 40 |
+
- 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.
|
| 41 |
+
- 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.
|
| 42 |
+
- 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.
|
| 43 |
+
- 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.
|
| 44 |
+
- 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.
|
| 45 |
+
- 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.
|
| 46 |
+
- 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.
|
| 47 |
+
- 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.
|
| 48 |
+
- 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.
|
| 49 |
+
- 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.
|
| 50 |
+
- 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.
|
| 51 |
+
- `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.
|
| 52 |
+
- `/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.
|
| 53 |
+
- 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.
|
| 54 |
+
- 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.
|
| 55 |
+
- 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.
|
| 56 |
+
- 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.
|
| 57 |
- 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`.
|
| 58 |
- 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`.
|
| 59 |
+
- 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.
|
| 60 |
|
| 61 |
## 2026-11-22
|
| 62 |
|
client/components/AiResponse/AiResponseContent.test.tsx
CHANGED
|
@@ -17,8 +17,19 @@ vi.mock("@/modules/textToSpeech", () => ({
|
|
| 17 |
}));
|
| 18 |
|
| 19 |
vi.mock("./FormattedMarkdown", () => ({
|
| 20 |
-
default: ({
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
),
|
| 23 |
}));
|
| 24 |
|
|
@@ -70,6 +81,22 @@ describe("AiResponseContent", () => {
|
|
| 70 |
expect(liveRegion).toHaveAttribute("aria-busy", "false");
|
| 71 |
});
|
| 72 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
it("gives the toolbar action icons accessible names while generating", () => {
|
| 74 |
renderContent("generating");
|
| 75 |
expect(
|
|
|
|
| 17 |
}));
|
| 18 |
|
| 19 |
vi.mock("./FormattedMarkdown", () => ({
|
| 20 |
+
default: ({
|
| 21 |
+
children,
|
| 22 |
+
isGenerating,
|
| 23 |
+
}: {
|
| 24 |
+
children: string;
|
| 25 |
+
isGenerating?: boolean;
|
| 26 |
+
}) => (
|
| 27 |
+
<div
|
| 28 |
+
data-testid="formatted-markdown"
|
| 29 |
+
data-generating={String(Boolean(isGenerating))}
|
| 30 |
+
>
|
| 31 |
+
{children}
|
| 32 |
+
</div>
|
| 33 |
),
|
| 34 |
}));
|
| 35 |
|
|
|
|
| 81 |
expect(liveRegion).toHaveAttribute("aria-busy", "false");
|
| 82 |
});
|
| 83 |
|
| 84 |
+
it.each([
|
| 85 |
+
["generating", "true"],
|
| 86 |
+
["interrupted", "false"],
|
| 87 |
+
["completed", "false"],
|
| 88 |
+
])(
|
| 89 |
+
"tells the markdown whether the response is generating (%s)",
|
| 90 |
+
(state, expected) => {
|
| 91 |
+
renderContent(state);
|
| 92 |
+
|
| 93 |
+
expect(screen.getByTestId("formatted-markdown")).toHaveAttribute(
|
| 94 |
+
"data-generating",
|
| 95 |
+
expected,
|
| 96 |
+
);
|
| 97 |
+
},
|
| 98 |
+
);
|
| 99 |
+
|
| 100 |
it("gives the toolbar action icons accessible names while generating", () => {
|
| 101 |
renderContent("generating");
|
| 102 |
expect(
|
client/components/AiResponse/AiResponseContent.tsx
CHANGED
|
@@ -160,7 +160,9 @@ export default function AiResponseContent({
|
|
| 160 |
<Card.Section withBorder>
|
| 161 |
<ConditionalScrollArea>
|
| 162 |
<Box aria-live="polite" aria-busy={isGenerating}>
|
| 163 |
-
<FormattedMarkdown
|
|
|
|
|
|
|
| 164 |
</Box>
|
| 165 |
</ConditionalScrollArea>
|
| 166 |
{textGenerationState === "failed" && (
|
|
|
|
| 160 |
<Card.Section withBorder>
|
| 161 |
<ConditionalScrollArea>
|
| 162 |
<Box aria-live="polite" aria-busy={isGenerating}>
|
| 163 |
+
<FormattedMarkdown isGenerating={isGenerating}>
|
| 164 |
+
{response}
|
| 165 |
+
</FormattedMarkdown>
|
| 166 |
</Box>
|
| 167 |
</ConditionalScrollArea>
|
| 168 |
{textGenerationState === "failed" && (
|
client/components/AiResponse/ChatInputArea.test.tsx
CHANGED
|
@@ -3,7 +3,13 @@ import { render, screen, waitFor } from "@testing-library/react";
|
|
| 3 |
import userEvent from "@testing-library/user-event";
|
| 4 |
import { useSyncExternalStore } from "react";
|
| 5 |
import ChatInputArea from "@/components/AiResponse/ChatInputArea";
|
| 6 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
import { getDictationEngine, startDictation } from "@/modules/speechToText";
|
| 8 |
|
| 9 |
vi.mock("@/modules/speechToText", async () => {
|
|
@@ -145,3 +151,39 @@ it("stops a running session when a response starts generating", async () => {
|
|
| 145 |
// input the user cannot see or correct.
|
| 146 |
await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
|
| 147 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import userEvent from "@testing-library/user-event";
|
| 4 |
import { useSyncExternalStore } from "react";
|
| 5 |
import ChatInputArea from "@/components/AiResponse/ChatInputArea";
|
| 6 |
+
import {
|
| 7 |
+
chatGenerationStatePubSub,
|
| 8 |
+
chatInputPubSub,
|
| 9 |
+
followUpQuestionPubSub,
|
| 10 |
+
settingsPubSub,
|
| 11 |
+
} from "@/modules/pubSub";
|
| 12 |
+
import { defaultSettings } from "@/modules/settings";
|
| 13 |
import { getDictationEngine, startDictation } from "@/modules/speechToText";
|
| 14 |
|
| 15 |
vi.mock("@/modules/speechToText", async () => {
|
|
|
|
| 151 |
// input the user cannot see or correct.
|
| 152 |
await waitFor(() => expect(cancelFn).toHaveBeenCalledTimes(1));
|
| 153 |
});
|
| 154 |
+
|
| 155 |
+
describe("sending the suggested follow-up question", () => {
|
| 156 |
+
afterEach(() => {
|
| 157 |
+
followUpQuestionPubSub[0]("");
|
| 158 |
+
settingsPubSub[0]({ ...defaultSettings });
|
| 159 |
+
});
|
| 160 |
+
|
| 161 |
+
it.each([
|
| 162 |
+
[true, "{Enter}", true],
|
| 163 |
+
[true, "{Shift>}{Enter}{/Shift}", false],
|
| 164 |
+
[false, "{Shift>}{Enter}{/Shift}", true],
|
| 165 |
+
[false, "{Enter}", false],
|
| 166 |
+
])(
|
| 167 |
+
"with enterToSubmit %s, pressing %s sends it: %s",
|
| 168 |
+
async (enterToSubmit, keys, sends) => {
|
| 169 |
+
settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
|
| 170 |
+
followUpQuestionPubSub[0]("What happened next?");
|
| 171 |
+
const handleSend = vi.fn();
|
| 172 |
+
const user = userEvent.setup();
|
| 173 |
+
render(
|
| 174 |
+
<MantineProvider>
|
| 175 |
+
<ChatInputArea onKeyDown={() => {}} handleSend={handleSend} />
|
| 176 |
+
</MantineProvider>,
|
| 177 |
+
);
|
| 178 |
+
|
| 179 |
+
await user.click(screen.getByRole("textbox"));
|
| 180 |
+
await user.keyboard(keys);
|
| 181 |
+
|
| 182 |
+
if (sends) {
|
| 183 |
+
expect(handleSend).toHaveBeenCalledWith("What happened next?");
|
| 184 |
+
} else {
|
| 185 |
+
expect(handleSend).not.toHaveBeenCalled();
|
| 186 |
+
}
|
| 187 |
+
},
|
| 188 |
+
);
|
| 189 |
+
});
|
client/components/AiResponse/ChatInputArea.tsx
CHANGED
|
@@ -4,12 +4,14 @@ import { usePubSub } from "create-pubsub/react";
|
|
| 4 |
import DictationButton, {
|
| 5 |
dictationButtonWidth,
|
| 6 |
} from "@/components/DictationButton";
|
|
|
|
| 7 |
import {
|
| 8 |
chatGenerationStatePubSub,
|
| 9 |
chatInputPubSub,
|
| 10 |
followUpQuestionPubSub,
|
| 11 |
getChatInput,
|
| 12 |
isRestoringFromHistoryPubSub,
|
|
|
|
| 13 |
suppressNextFollowUpPubSub,
|
| 14 |
} from "@/modules/pubSub";
|
| 15 |
|
|
@@ -34,6 +36,7 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) {
|
|
| 34 |
const [followUpQuestion] = usePubSub(followUpQuestionPubSub);
|
| 35 |
const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);
|
| 36 |
const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub);
|
|
|
|
| 37 |
|
| 38 |
const isGenerating =
|
| 39 |
generationState.isGeneratingResponse &&
|
|
@@ -51,23 +54,17 @@ function ChatInputArea({ onKeyDown, handleSend }: ChatInputAreaProps) {
|
|
| 51 |
const handleKeyDownWithPlaceholder = (
|
| 52 |
event: React.KeyboardEvent<HTMLTextAreaElement>,
|
| 53 |
) => {
|
| 54 |
-
//
|
| 55 |
-
//
|
| 56 |
-
//
|
| 57 |
-
const isComposing = event.nativeEvent.isComposing || event.keyCode === 229;
|
| 58 |
-
|
| 59 |
if (
|
| 60 |
input.trim() === "" &&
|
| 61 |
followUpQuestion &&
|
| 62 |
!isRestoringFromHistory &&
|
| 63 |
-
!suppressNextFollowUp
|
| 64 |
-
!isComposing
|
| 65 |
) {
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
handleSend(followUpQuestion);
|
| 69 |
-
return;
|
| 70 |
-
}
|
| 71 |
}
|
| 72 |
|
| 73 |
onKeyDown(event);
|
|
|
|
| 4 |
import DictationButton, {
|
| 5 |
dictationButtonWidth,
|
| 6 |
} from "@/components/DictationButton";
|
| 7 |
+
import { handleEnterKeyDown } from "@/modules/keyboard";
|
| 8 |
import {
|
| 9 |
chatGenerationStatePubSub,
|
| 10 |
chatInputPubSub,
|
| 11 |
followUpQuestionPubSub,
|
| 12 |
getChatInput,
|
| 13 |
isRestoringFromHistoryPubSub,
|
| 14 |
+
settingsPubSub,
|
| 15 |
suppressNextFollowUpPubSub,
|
| 16 |
} from "@/modules/pubSub";
|
| 17 |
|
|
|
|
| 36 |
const [followUpQuestion] = usePubSub(followUpQuestionPubSub);
|
| 37 |
const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);
|
| 38 |
const [suppressNextFollowUp] = usePubSub(suppressNextFollowUpPubSub);
|
| 39 |
+
const [settings] = usePubSub(settingsPubSub);
|
| 40 |
|
| 41 |
const isGenerating =
|
| 42 |
generationState.isGeneratingResponse &&
|
|
|
|
| 54 |
const handleKeyDownWithPlaceholder = (
|
| 55 |
event: React.KeyboardEvent<HTMLTextAreaElement>,
|
| 56 |
) => {
|
| 57 |
+
// With an empty input the suggested follow-up question is sent on the
|
| 58 |
+
// same keys that submit typed text, so the Enter setting and the IME
|
| 59 |
+
// guard both apply; handleEnterKeyDown prevents the default when it sends.
|
|
|
|
|
|
|
| 60 |
if (
|
| 61 |
input.trim() === "" &&
|
| 62 |
followUpQuestion &&
|
| 63 |
!isRestoringFromHistory &&
|
| 64 |
+
!suppressNextFollowUp
|
|
|
|
| 65 |
) {
|
| 66 |
+
handleEnterKeyDown(event, settings, () => handleSend(followUpQuestion));
|
| 67 |
+
if (event.defaultPrevented) return;
|
|
|
|
|
|
|
|
|
|
| 68 |
}
|
| 69 |
|
| 70 |
onKeyDown(event);
|
client/components/AiResponse/ChatInterface.test.tsx
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
| 5 |
chatGenerationStatePubSub,
|
| 6 |
chatInputPubSub,
|
| 7 |
followUpQuestionPubSub,
|
|
|
|
| 8 |
suppressNextFollowUpPubSub,
|
| 9 |
} from "@/modules/pubSub";
|
| 10 |
import type { ChatMessage } from "@/modules/types";
|
|
@@ -689,4 +690,50 @@ describe("ChatInterface generation state", () => {
|
|
| 689 |
);
|
| 690 |
expect(generateFollowUpQuestion).toHaveBeenCalled();
|
| 691 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 692 |
});
|
|
|
|
| 5 |
chatGenerationStatePubSub,
|
| 6 |
chatInputPubSub,
|
| 7 |
followUpQuestionPubSub,
|
| 8 |
+
getSuppressNextFollowUp,
|
| 9 |
suppressNextFollowUpPubSub,
|
| 10 |
} from "@/modules/pubSub";
|
| 11 |
import type { ChatMessage } from "@/modules/types";
|
|
|
|
| 690 |
);
|
| 691 |
expect(generateFollowUpQuestion).toHaveBeenCalled();
|
| 692 |
});
|
| 693 |
+
|
| 694 |
+
it("clears suppressNextFollowUp after skipping the restored answer's follow-up so later sends generate one", async () => {
|
| 695 |
+
updateSuppressNextFollowUp(true);
|
| 696 |
+
|
| 697 |
+
renderChatInterface({ suppressInitialFollowUp: false });
|
| 698 |
+
|
| 699 |
+
await act(async () => {});
|
| 700 |
+
|
| 701 |
+
expect(generateFollowUpQuestion).not.toHaveBeenCalled();
|
| 702 |
+
expect(getSuppressNextFollowUp()).toBe(false);
|
| 703 |
+
|
| 704 |
+
await act(async () => {
|
| 705 |
+
await sendMessage("Tell me more about wake locks");
|
| 706 |
+
});
|
| 707 |
+
|
| 708 |
+
expect(generateFollowUpQuestion).toHaveBeenCalledTimes(1);
|
| 709 |
+
expect(getFollowUpQuestion()).toBe("A question?");
|
| 710 |
+
});
|
| 711 |
+
|
| 712 |
+
it("drops an in-flight follow-up question when a restore suppresses follow-ups", async () => {
|
| 713 |
+
const inFlightQuestion = deferred<string>();
|
| 714 |
+
vi.mocked(generateFollowUpQuestion).mockReturnValueOnce(
|
| 715 |
+
inFlightQuestion.promise,
|
| 716 |
+
);
|
| 717 |
+
|
| 718 |
+
renderChatInterface({ suppressInitialFollowUp: false });
|
| 719 |
+
|
| 720 |
+
await act(async () => {});
|
| 721 |
+
|
| 722 |
+
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(true);
|
| 723 |
+
|
| 724 |
+
await act(async () => {
|
| 725 |
+
updateSuppressNextFollowUp(true);
|
| 726 |
+
});
|
| 727 |
+
|
| 728 |
+
expect(getSuppressNextFollowUp()).toBe(false);
|
| 729 |
+
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
|
| 730 |
+
expect(getFollowUpQuestion()).toBe("");
|
| 731 |
+
|
| 732 |
+
await act(async () => {
|
| 733 |
+
inFlightQuestion.resolve("Question from the previous search?");
|
| 734 |
+
});
|
| 735 |
+
|
| 736 |
+
expect(getFollowUpQuestion()).toBe("");
|
| 737 |
+
expect(getChatGenerationState().isGeneratingFollowUpQuestion).toBe(false);
|
| 738 |
+
});
|
| 739 |
});
|
client/components/AiResponse/ChatInterface.tsx
CHANGED
|
@@ -65,7 +65,9 @@ export default function ChatInterface({
|
|
| 65 |
const [textSearchResults] = usePubSub(textSearchResultsPubSub);
|
| 66 |
const [imageSearchResults] = usePubSub(imageSearchResultsPubSub);
|
| 67 |
const [currentQuery] = usePubSub(queryPubSub);
|
| 68 |
-
const [suppressNextFollowUp] = usePubSub(
|
|
|
|
|
|
|
| 69 |
const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState<
|
| 70 |
string[]
|
| 71 |
>([]);
|
|
@@ -190,6 +192,13 @@ export default function ChatInterface({
|
|
| 190 |
useEffect(() => {
|
| 191 |
if (suppressNextFollowUp) {
|
| 192 |
hasInitialized.current = true;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
return;
|
| 194 |
}
|
| 195 |
if (suppressInitialFollowUp) return;
|
|
@@ -214,6 +223,9 @@ export default function ChatInterface({
|
|
| 214 |
initialMessages,
|
| 215 |
messages,
|
| 216 |
regenerateFollowUpQuestion,
|
|
|
|
|
|
|
|
|
|
| 217 |
suppressInitialFollowUp,
|
| 218 |
suppressNextFollowUp,
|
| 219 |
]);
|
|
|
|
| 65 |
const [textSearchResults] = usePubSub(textSearchResultsPubSub);
|
| 66 |
const [imageSearchResults] = usePubSub(imageSearchResultsPubSub);
|
| 67 |
const [currentQuery] = usePubSub(queryPubSub);
|
| 68 |
+
const [suppressNextFollowUp, setSuppressNextFollowUp] = usePubSub(
|
| 69 |
+
suppressNextFollowUpPubSub,
|
| 70 |
+
);
|
| 71 |
const [previousFollowUpQuestions, setPreviousFollowUpQuestions] = useState<
|
| 72 |
string[]
|
| 73 |
>([]);
|
|
|
|
| 192 |
useEffect(() => {
|
| 193 |
if (suppressNextFollowUp) {
|
| 194 |
hasInitialized.current = true;
|
| 195 |
+
followUpInvocationRef.current += 1;
|
| 196 |
+
setFollowUpQuestion("");
|
| 197 |
+
setGenerationState({
|
| 198 |
+
...getChatGenerationState(),
|
| 199 |
+
isGeneratingFollowUpQuestion: false,
|
| 200 |
+
});
|
| 201 |
+
setSuppressNextFollowUp(false);
|
| 202 |
return;
|
| 203 |
}
|
| 204 |
if (suppressInitialFollowUp) return;
|
|
|
|
| 223 |
initialMessages,
|
| 224 |
messages,
|
| 225 |
regenerateFollowUpQuestion,
|
| 226 |
+
setFollowUpQuestion,
|
| 227 |
+
setGenerationState,
|
| 228 |
+
setSuppressNextFollowUp,
|
| 229 |
suppressInitialFollowUp,
|
| 230 |
suppressNextFollowUp,
|
| 231 |
]);
|
client/components/AiResponse/ExpandableLink.test.tsx
CHANGED
|
@@ -37,6 +37,14 @@ function renderLink(label = "Example Domain", href = "https://example.com") {
|
|
| 37 |
);
|
| 38 |
}
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
function getFullText() {
|
| 41 |
return screen.getByTestId("expandable-link-full");
|
| 42 |
}
|
|
@@ -208,4 +216,43 @@ describe("ExpandableLink", () => {
|
|
| 208 |
expect(fullText).toHaveTextContent("Example Domain");
|
| 209 |
expect(fullText.style.visibility).not.toBe("hidden");
|
| 210 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 211 |
});
|
|
|
|
| 37 |
);
|
| 38 |
}
|
| 39 |
|
| 40 |
+
function getPill() {
|
| 41 |
+
const pill = screen
|
| 42 |
+
.getByRole("link")
|
| 43 |
+
.querySelectorAll<HTMLElement>('[aria-hidden="true"]');
|
| 44 |
+
expect(pill).toHaveLength(1);
|
| 45 |
+
return pill[0];
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
function getFullText() {
|
| 49 |
return screen.getByTestId("expandable-link-full");
|
| 50 |
}
|
|
|
|
| 216 |
expect(fullText).toHaveTextContent("Example Domain");
|
| 217 |
expect(fullText.style.visibility).not.toBe("hidden");
|
| 218 |
});
|
| 219 |
+
|
| 220 |
+
it("shows the first character of plain link text in the pill", () => {
|
| 221 |
+
renderLink("Example Domain");
|
| 222 |
+
|
| 223 |
+
expect(getPill().textContent).toBe("E");
|
| 224 |
+
});
|
| 225 |
+
|
| 226 |
+
it("shows the first visible character of formatted link text in the pill", () => {
|
| 227 |
+
render(
|
| 228 |
+
<MantineProvider>
|
| 229 |
+
<ExpandableLink href="https://www.reuters.com/">
|
| 230 |
+
<strong>Reuters</strong>
|
| 231 |
+
</ExpandableLink>
|
| 232 |
+
</MantineProvider>,
|
| 233 |
+
);
|
| 234 |
+
|
| 235 |
+
expect(getPill().textContent).toBe("R");
|
| 236 |
+
});
|
| 237 |
+
|
| 238 |
+
it.each([
|
| 239 |
+
["๐ Emoji Site", "๐"],
|
| 240 |
+
["๐จ๐ญ Swiss Site", "๐จ๐ญ"],
|
| 241 |
+
["๐ฉโ๐ป Dev Site", "๐ฉโ๐ป"],
|
| 242 |
+
])("keeps the leading emoji of %s whole in the pill", (label, expected) => {
|
| 243 |
+
renderLink(label);
|
| 244 |
+
|
| 245 |
+
expect(getPill().textContent).toBe(expected);
|
| 246 |
+
});
|
| 247 |
+
|
| 248 |
+
it("falls back to the first code point without Intl.Segmenter", () => {
|
| 249 |
+
vi.stubGlobal(
|
| 250 |
+
"Intl",
|
| 251 |
+
Object.assign(Object.create(Intl), { Segmenter: undefined }),
|
| 252 |
+
);
|
| 253 |
+
|
| 254 |
+
renderLink("๐ Emoji Site");
|
| 255 |
+
|
| 256 |
+
expect(getPill().textContent).toBe("๐");
|
| 257 |
+
});
|
| 258 |
});
|
client/components/AiResponse/ExpandableLink.tsx
CHANGED
|
@@ -54,6 +54,35 @@ function registerResizeListener(
|
|
| 54 |
};
|
| 55 |
}
|
| 56 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
/**
|
| 58 |
* Citation link that collapses to a first-character pill and reveals the full
|
| 59 |
* link text on hover/focus, auto-collapsing after 3 s.
|
|
@@ -68,8 +97,7 @@ export default function ExpandableLink({
|
|
| 68 |
href,
|
| 69 |
children,
|
| 70 |
}: ExpandableLinkProps) {
|
| 71 |
-
const
|
| 72 |
-
const firstChar = childContent.charAt(0);
|
| 73 |
const [isExpanded, setIsExpanded] = React.useState(true);
|
| 74 |
const timerRef = React.useRef<number | null>(null);
|
| 75 |
const anchorRef = React.useRef<HTMLAnchorElement>(null);
|
|
|
|
| 54 |
};
|
| 55 |
}
|
| 56 |
|
| 57 |
+
/**
|
| 58 |
+
* Collects the visible text of React children. Formatted link text such as
|
| 59 |
+
* `**Reuters**` arrives as elements, whose `toString()` is "[object Object]".
|
| 60 |
+
*/
|
| 61 |
+
function getTextContent(node: React.ReactNode): string {
|
| 62 |
+
if (typeof node === "string" || typeof node === "number") {
|
| 63 |
+
return String(node);
|
| 64 |
+
}
|
| 65 |
+
if (Array.isArray(node)) {
|
| 66 |
+
return node.map(getTextContent).join("");
|
| 67 |
+
}
|
| 68 |
+
if (React.isValidElement<{ children?: React.ReactNode }>(node)) {
|
| 69 |
+
return getTextContent(node.props.children);
|
| 70 |
+
}
|
| 71 |
+
return "";
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
/**
|
| 75 |
+
* Returns the first user-perceived character, so an emoji, a flag or a ZWJ
|
| 76 |
+
* sequence is never split into a lone surrogate or a partial glyph.
|
| 77 |
+
*/
|
| 78 |
+
function getFirstGrapheme(text: string): string {
|
| 79 |
+
if (typeof Intl.Segmenter === "function") {
|
| 80 |
+
const [first] = new Intl.Segmenter().segment(text);
|
| 81 |
+
return first?.segment ?? "";
|
| 82 |
+
}
|
| 83 |
+
return Array.from(text)[0] ?? "";
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
/**
|
| 87 |
* Citation link that collapses to a first-character pill and reveals the full
|
| 88 |
* link text on hover/focus, auto-collapsing after 3 s.
|
|
|
|
| 97 |
href,
|
| 98 |
children,
|
| 99 |
}: ExpandableLinkProps) {
|
| 100 |
+
const firstChar = getFirstGrapheme(getTextContent(children));
|
|
|
|
| 101 |
const [isExpanded, setIsExpanded] = React.useState(true);
|
| 102 |
const timerRef = React.useRef<number | null>(null);
|
| 103 |
const anchorRef = React.useRef<HTMLAnchorElement>(null);
|
client/components/AiResponse/FormattedMarkdown.tsx
CHANGED
|
@@ -7,15 +7,20 @@ interface FormattedMarkdownProps {
|
|
| 7 |
children: string;
|
| 8 |
className?: string;
|
| 9 |
enableCopy?: boolean;
|
|
|
|
|
|
|
| 10 |
}
|
| 11 |
|
| 12 |
export default function FormattedMarkdown({
|
| 13 |
children,
|
| 14 |
className = "",
|
| 15 |
enableCopy = true,
|
|
|
|
| 16 |
}: FormattedMarkdownProps) {
|
| 17 |
-
const { reasoningContent, mainContent, isGenerating } =
|
| 18 |
-
|
|
|
|
|
|
|
| 19 |
|
| 20 |
if (!children && !reasoningContent) {
|
| 21 |
return null;
|
|
|
|
| 7 |
children: string;
|
| 8 |
className?: string;
|
| 9 |
enableCopy?: boolean;
|
| 10 |
+
/** Whether this response is still being generated. */
|
| 11 |
+
isGenerating?: boolean;
|
| 12 |
}
|
| 13 |
|
| 14 |
export default function FormattedMarkdown({
|
| 15 |
children,
|
| 16 |
className = "",
|
| 17 |
enableCopy = true,
|
| 18 |
+
isGenerating: isResponseGenerating = false,
|
| 19 |
}: FormattedMarkdownProps) {
|
| 20 |
+
const { reasoningContent, mainContent, isGenerating } = useReasoningContent(
|
| 21 |
+
children,
|
| 22 |
+
isResponseGenerating,
|
| 23 |
+
);
|
| 24 |
|
| 25 |
if (!children && !reasoningContent) {
|
| 26 |
return null;
|
client/components/AiResponse/MarkdownRenderer.test.tsx
CHANGED
|
@@ -80,6 +80,19 @@ describe("MarkdownRenderer rendered output", () => {
|
|
| 80 |
expect(link?.getAttribute("rel")).toContain("nofollow");
|
| 81 |
});
|
| 82 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
it("renders a fenced code block through CodeHighlight with its language", () => {
|
| 84 |
const { getByTestId } = renderMarkdown("```js\nconst x = 1;\n```");
|
| 85 |
|
|
|
|
| 80 |
expect(link?.getAttribute("rel")).toContain("nofollow");
|
| 81 |
});
|
| 82 |
|
| 83 |
+
it.each([
|
| 84 |
+
["[**Reuters**](https://www.reuters.com/)", "R"],
|
| 85 |
+
["[`npm`](https://www.npmjs.com/)", "n"],
|
| 86 |
+
])(
|
| 87 |
+
"collapses the formatted link %s to its first visible character",
|
| 88 |
+
(markdown, expected) => {
|
| 89 |
+
const { container } = renderMarkdown(markdown);
|
| 90 |
+
|
| 91 |
+
const pill = container.querySelector('a [aria-hidden="true"]');
|
| 92 |
+
expect(pill?.textContent).toBe(expected);
|
| 93 |
+
},
|
| 94 |
+
);
|
| 95 |
+
|
| 96 |
it("renders a fenced code block through CodeHighlight with its language", () => {
|
| 97 |
const { getByTestId } = renderMarkdown("```js\nconst x = 1;\n```");
|
| 98 |
|
client/components/AiResponse/MessageList.test.tsx
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
import { MantineProvider } from "@mantine/core";
|
| 2 |
-
import { render, screen } from "@testing-library/react";
|
| 3 |
import { describe, expect, it, vi } from "vitest";
|
| 4 |
import type { ChatMessage } from "@/modules/types";
|
| 5 |
import MessageList from "./MessageList";
|
|
@@ -53,4 +53,76 @@ describe("MessageList", () => {
|
|
| 53 |
);
|
| 54 |
expect(renderedQuestions).toHaveLength(2);
|
| 55 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
});
|
|
|
|
| 1 |
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { fireEvent, render, screen } from "@testing-library/react";
|
| 3 |
import { describe, expect, it, vi } from "vitest";
|
| 4 |
import type { ChatMessage } from "@/modules/types";
|
| 5 |
import MessageList from "./MessageList";
|
|
|
|
| 53 |
);
|
| 54 |
expect(renderedQuestions).toHaveLength(2);
|
| 55 |
});
|
| 56 |
+
|
| 57 |
+
describe("an empty answer earlier in the chat", () => {
|
| 58 |
+
// An empty answer is saved when the stream ends with no content.
|
| 59 |
+
const messages: ChatMessage[] = [
|
| 60 |
+
{ role: "user", content: "system instructions" },
|
| 61 |
+
{ role: "assistant", content: "Ok!" },
|
| 62 |
+
{ role: "user", content: "Q1" },
|
| 63 |
+
{ role: "assistant", content: "" },
|
| 64 |
+
{ role: "user", content: "Q2" },
|
| 65 |
+
{ role: "assistant", content: "" },
|
| 66 |
+
{ role: "user", content: "Q3" },
|
| 67 |
+
{ role: "assistant", content: "A3" },
|
| 68 |
+
];
|
| 69 |
+
|
| 70 |
+
it("edits each question at its position in the chat", () => {
|
| 71 |
+
const onEditMessage = vi.fn();
|
| 72 |
+
renderMessageList({ messages, onEditMessage });
|
| 73 |
+
|
| 74 |
+
const editButtons = screen.getAllByLabelText("Edit message");
|
| 75 |
+
expect(editButtons).toHaveLength(3);
|
| 76 |
+
for (const button of editButtons) fireEvent.click(button);
|
| 77 |
+
|
| 78 |
+
expect(onEditMessage.mock.calls).toEqual([[2], [4], [6]]);
|
| 79 |
+
});
|
| 80 |
+
|
| 81 |
+
it("keeps the Re-generate button on the last answer", () => {
|
| 82 |
+
const onRegenerate = vi.fn();
|
| 83 |
+
renderMessageList({ messages, onRegenerate });
|
| 84 |
+
|
| 85 |
+
fireEvent.click(screen.getByLabelText("Re-generate response"));
|
| 86 |
+
|
| 87 |
+
expect(onRegenerate).toHaveBeenCalledTimes(1);
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
it("renders no bubble for the empty answers", () => {
|
| 91 |
+
renderMessageList({ messages });
|
| 92 |
+
|
| 93 |
+
expect(screen.getAllByText(/^(Q1|Q2|Q3|A3)$/)).toHaveLength(4);
|
| 94 |
+
expect(document.querySelectorAll(".mantine-Paper-root")).toHaveLength(4);
|
| 95 |
+
});
|
| 96 |
+
});
|
| 97 |
+
|
| 98 |
+
describe("unterminated reasoning", () => {
|
| 99 |
+
const messages: ChatMessage[] = [
|
| 100 |
+
{ role: "user", content: "system instructions" },
|
| 101 |
+
{ role: "assistant", content: "Ok!" },
|
| 102 |
+
{ role: "user", content: "why?" },
|
| 103 |
+
{ role: "assistant", content: "<think>cut off mid-thought" },
|
| 104 |
+
];
|
| 105 |
+
|
| 106 |
+
it("shows no Thinking loader on a message that is not being generated", () => {
|
| 107 |
+
renderMessageList({ messages, isGenerating: false });
|
| 108 |
+
|
| 109 |
+
expect(screen.queryByText("Thinking")).toBeNull();
|
| 110 |
+
expect(screen.getByText("Thought Process")).toBeInTheDocument();
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it("shows the Thinking loader on the last assistant message while it is generated", () => {
|
| 114 |
+
renderMessageList({ messages, isGenerating: true });
|
| 115 |
+
|
| 116 |
+
expect(screen.getByText("Thinking")).toBeInTheDocument();
|
| 117 |
+
});
|
| 118 |
+
|
| 119 |
+
it("shows no Thinking loader on an older message while a later one is generated", () => {
|
| 120 |
+
renderMessageList({
|
| 121 |
+
messages: [...messages, { role: "user", content: "and then?" }],
|
| 122 |
+
isGenerating: true,
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
expect(screen.queryByText("Thinking")).toBeNull();
|
| 126 |
+
});
|
| 127 |
+
});
|
| 128 |
});
|
client/components/AiResponse/MessageList.tsx
CHANGED
|
@@ -13,7 +13,6 @@ interface MessageListProps {
|
|
| 13 |
|
| 14 |
interface MessageProps {
|
| 15 |
message: ChatMessage;
|
| 16 |
-
index: number;
|
| 17 |
absoluteIndex: number;
|
| 18 |
isLastAssistant: boolean;
|
| 19 |
isGenerating: boolean;
|
|
@@ -24,7 +23,6 @@ interface MessageProps {
|
|
| 24 |
const Message = memo(
|
| 25 |
({
|
| 26 |
message,
|
| 27 |
-
index,
|
| 28 |
absoluteIndex,
|
| 29 |
isLastAssistant,
|
| 30 |
isGenerating,
|
|
@@ -58,13 +56,15 @@ const Message = memo(
|
|
| 58 |
)}
|
| 59 |
|
| 60 |
<Paper
|
| 61 |
-
key={`${message.role}-${
|
| 62 |
shadow="xs"
|
| 63 |
radius="xl"
|
| 64 |
p="sm"
|
| 65 |
style={{ flex: 1, overflow: "auto" }}
|
| 66 |
>
|
| 67 |
-
<FormattedMarkdown
|
|
|
|
|
|
|
| 68 |
</Paper>
|
| 69 |
|
| 70 |
{canRegenerate && (
|
|
@@ -100,27 +100,27 @@ const MessageList = memo(function MessageList({
|
|
| 100 |
|
| 101 |
return (
|
| 102 |
<Stack gap="md">
|
| 103 |
-
{messages
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
</Stack>
|
| 125 |
);
|
| 126 |
});
|
|
|
|
| 13 |
|
| 14 |
interface MessageProps {
|
| 15 |
message: ChatMessage;
|
|
|
|
| 16 |
absoluteIndex: number;
|
| 17 |
isLastAssistant: boolean;
|
| 18 |
isGenerating: boolean;
|
|
|
|
| 23 |
const Message = memo(
|
| 24 |
({
|
| 25 |
message,
|
|
|
|
| 26 |
absoluteIndex,
|
| 27 |
isLastAssistant,
|
| 28 |
isGenerating,
|
|
|
|
| 56 |
)}
|
| 57 |
|
| 58 |
<Paper
|
| 59 |
+
key={`${message.role}-${absoluteIndex}`}
|
| 60 |
shadow="xs"
|
| 61 |
radius="xl"
|
| 62 |
p="sm"
|
| 63 |
style={{ flex: 1, overflow: "auto" }}
|
| 64 |
>
|
| 65 |
+
<FormattedMarkdown isGenerating={isGenerating && isLastAssistant}>
|
| 66 |
+
{message.content}
|
| 67 |
+
</FormattedMarkdown>
|
| 68 |
</Paper>
|
| 69 |
|
| 70 |
{canRegenerate && (
|
|
|
|
| 100 |
|
| 101 |
return (
|
| 102 |
<Stack gap="md">
|
| 103 |
+
{messages.map((message, absoluteIndex) => {
|
| 104 |
+
// The index is the message's position in `messages`, which is what
|
| 105 |
+
// editing and regenerating act on. The first two messages are the
|
| 106 |
+
// system prompt and its acknowledgement, and an empty message has
|
| 107 |
+
// nothing to show, so neither renders, but both keep their position.
|
| 108 |
+
if (absoluteIndex < 2 || message.content.length === 0) return null;
|
| 109 |
+
const isLastAssistant =
|
| 110 |
+
absoluteIndex === messages.length - 1 && message.role === "assistant";
|
| 111 |
+
return (
|
| 112 |
+
<Message
|
| 113 |
+
// biome-ignore lint/suspicious/noArrayIndexKey: a message's position in the chat is its identity
|
| 114 |
+
key={absoluteIndex}
|
| 115 |
+
message={message}
|
| 116 |
+
absoluteIndex={absoluteIndex}
|
| 117 |
+
isLastAssistant={isLastAssistant}
|
| 118 |
+
isGenerating={isGenerating}
|
| 119 |
+
onEditMessage={onEditMessage}
|
| 120 |
+
onRegenerate={onRegenerate}
|
| 121 |
+
/>
|
| 122 |
+
);
|
| 123 |
+
})}
|
| 124 |
</Stack>
|
| 125 |
);
|
| 126 |
});
|
client/components/AiResponse/hooks/useReasoningContent.test.ts
CHANGED
|
@@ -16,6 +16,7 @@ describe("useReasoningContent hook", () => {
|
|
| 16 |
const { result } = renderHook(() =>
|
| 17 |
useReasoningContent(
|
| 18 |
"<think>Let me think about this</think>\nHere is the answer.",
|
|
|
|
| 19 |
),
|
| 20 |
);
|
| 21 |
|
|
@@ -29,13 +30,13 @@ describe("useReasoningContent hook", () => {
|
|
| 29 |
["whitespace-only text", " "],
|
| 30 |
["no text at all", null as unknown as string],
|
| 31 |
])("should report nothing to show for %s", (_, content) => {
|
| 32 |
-
const { result } = renderHook(() => useReasoningContent(content));
|
| 33 |
expectEmptyState(result);
|
| 34 |
});
|
| 35 |
|
| 36 |
it("should return text as main content when no markers present", () => {
|
| 37 |
const { result } = renderHook(() =>
|
| 38 |
-
useReasoningContent("This is a normal response."),
|
| 39 |
);
|
| 40 |
|
| 41 |
expect(result.current.reasoningContent).toBe("");
|
|
@@ -45,12 +46,22 @@ describe("useReasoningContent hook", () => {
|
|
| 45 |
|
| 46 |
it("should detect generating state when end marker is missing", () => {
|
| 47 |
const { result } = renderHook(() =>
|
| 48 |
-
useReasoningContent("<think>I'm still thinking"),
|
| 49 |
);
|
| 50 |
|
| 51 |
expect(result.current.reasoningContent).toBe("I'm still thinking");
|
| 52 |
expect(result.current.mainContent).toBe("");
|
| 53 |
expect(result.current.isGenerating).toBe(true);
|
| 54 |
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
});
|
| 56 |
});
|
|
|
|
| 16 |
const { result } = renderHook(() =>
|
| 17 |
useReasoningContent(
|
| 18 |
"<think>Let me think about this</think>\nHere is the answer.",
|
| 19 |
+
false,
|
| 20 |
),
|
| 21 |
);
|
| 22 |
|
|
|
|
| 30 |
["whitespace-only text", " "],
|
| 31 |
["no text at all", null as unknown as string],
|
| 32 |
])("should report nothing to show for %s", (_, content) => {
|
| 33 |
+
const { result } = renderHook(() => useReasoningContent(content, false));
|
| 34 |
expectEmptyState(result);
|
| 35 |
});
|
| 36 |
|
| 37 |
it("should return text as main content when no markers present", () => {
|
| 38 |
const { result } = renderHook(() =>
|
| 39 |
+
useReasoningContent("This is a normal response.", false),
|
| 40 |
);
|
| 41 |
|
| 42 |
expect(result.current.reasoningContent).toBe("");
|
|
|
|
| 46 |
|
| 47 |
it("should detect generating state when end marker is missing", () => {
|
| 48 |
const { result } = renderHook(() =>
|
| 49 |
+
useReasoningContent("<think>I'm still thinking", true),
|
| 50 |
);
|
| 51 |
|
| 52 |
expect(result.current.reasoningContent).toBe("I'm still thinking");
|
| 53 |
expect(result.current.mainContent).toBe("");
|
| 54 |
expect(result.current.isGenerating).toBe(true);
|
| 55 |
});
|
| 56 |
+
|
| 57 |
+
it("should treat a missing end marker as a finished thought once generation stops", () => {
|
| 58 |
+
const { result } = renderHook(() =>
|
| 59 |
+
useReasoningContent("<think>I was interrupted", false),
|
| 60 |
+
);
|
| 61 |
+
|
| 62 |
+
expect(result.current.reasoningContent).toBe("I was interrupted");
|
| 63 |
+
expect(result.current.mainContent).toBe("");
|
| 64 |
+
expect(result.current.isGenerating).toBe(false);
|
| 65 |
+
});
|
| 66 |
});
|
| 67 |
});
|
client/components/AiResponse/hooks/useReasoningContent.ts
CHANGED
|
@@ -4,10 +4,15 @@ import { settingsPubSub } from "@/modules/pubSub";
|
|
| 4 |
|
| 5 |
/**
|
| 6 |
* Splits a streamed AI response into the part between the reasoning markers
|
| 7 |
-
* and the rest
|
| 8 |
-
* arrived yet
|
|
|
|
|
|
|
| 9 |
*/
|
| 10 |
-
export function useReasoningContent(
|
|
|
|
|
|
|
|
|
|
| 11 |
const [settings] = usePubSub(settingsPubSub);
|
| 12 |
|
| 13 |
const extractReasoningAndMainContent = useCallback(
|
|
@@ -27,7 +32,7 @@ export function useReasoningContent(text: string) {
|
|
| 27 |
return {
|
| 28 |
reasoningContent: trimmedText.slice(startIndex + startMarker.length),
|
| 29 |
mainContent: "",
|
| 30 |
-
isGenerating:
|
| 31 |
};
|
| 32 |
}
|
| 33 |
|
|
@@ -40,7 +45,7 @@ export function useReasoningContent(text: string) {
|
|
| 40 |
isGenerating: false,
|
| 41 |
};
|
| 42 |
},
|
| 43 |
-
[],
|
| 44 |
);
|
| 45 |
|
| 46 |
if (text && text.trim() === "") {
|
|
|
|
| 4 |
|
| 5 |
/**
|
| 6 |
* Splits a streamed AI response into the part between the reasoning markers
|
| 7 |
+
* and the rest. `isGenerating` is reported only while the closing marker has
|
| 8 |
+
* not arrived yet and `isResponseGenerating` says the response is still being
|
| 9 |
+
* written; once generation stops (finished, interrupted, truncated), an
|
| 10 |
+
* unterminated reasoning block is a finished thought.
|
| 11 |
*/
|
| 12 |
+
export function useReasoningContent(
|
| 13 |
+
text: string,
|
| 14 |
+
isResponseGenerating: boolean,
|
| 15 |
+
) {
|
| 16 |
const [settings] = usePubSub(settingsPubSub);
|
| 17 |
|
| 18 |
const extractReasoningAndMainContent = useCallback(
|
|
|
|
| 32 |
return {
|
| 33 |
reasoningContent: trimmedText.slice(startIndex + startMarker.length),
|
| 34 |
mainContent: "",
|
| 35 |
+
isGenerating: isResponseGenerating,
|
| 36 |
};
|
| 37 |
}
|
| 38 |
|
|
|
|
| 45 |
isGenerating: false,
|
| 46 |
};
|
| 47 |
},
|
| 48 |
+
[isResponseGenerating],
|
| 49 |
);
|
| 50 |
|
| 51 |
if (text && text.trim() === "") {
|
client/components/Analytics/SearchStats.test.tsx
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { render, screen } from "@testing-library/react";
|
| 3 |
+
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
| 4 |
+
import type { SearchEntry } from "@/modules/history";
|
| 5 |
+
import SearchStats from "./SearchStats";
|
| 6 |
+
|
| 7 |
+
vi.mock("@/hooks/useSearchHistory", () => ({
|
| 8 |
+
useSearchHistory: vi.fn(),
|
| 9 |
+
}));
|
| 10 |
+
|
| 11 |
+
/** The hook mock has to return the full shape the real hook returns. */
|
| 12 |
+
const mockHistory = (recentSearches: SearchEntry[]) => {
|
| 13 |
+
const noop = vi.fn(async (): Promise<void> => {});
|
| 14 |
+
vi.mocked(useSearchHistory).mockReturnValue({
|
| 15 |
+
recentSearches,
|
| 16 |
+
llmResponseCount: 0,
|
| 17 |
+
chatMessageCount: 0,
|
| 18 |
+
filteredSearches: recentSearches,
|
| 19 |
+
groupedSearches: {},
|
| 20 |
+
isLoading: false,
|
| 21 |
+
error: null,
|
| 22 |
+
currentPage: 0,
|
| 23 |
+
totalPages: 0,
|
| 24 |
+
hasNextPage: false,
|
| 25 |
+
hasPreviousPage: false,
|
| 26 |
+
retryLastOperation: noop,
|
| 27 |
+
clearError: vi.fn(),
|
| 28 |
+
searchHistory: vi.fn(),
|
| 29 |
+
addToHistory: noop,
|
| 30 |
+
togglePin: noop,
|
| 31 |
+
deleteEntry: noop,
|
| 32 |
+
clearAll: noop,
|
| 33 |
+
refreshHistory: noop,
|
| 34 |
+
nextPage: vi.fn(),
|
| 35 |
+
previousPage: vi.fn(),
|
| 36 |
+
goToPage: vi.fn(),
|
| 37 |
+
});
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
/** Metric cards print the value below the label; the heatmap above it. */
|
| 41 |
+
const valueBelow = (label: string) =>
|
| 42 |
+
screen.getByText(label).nextElementSibling?.textContent;
|
| 43 |
+
const valueAbove = (label: string) =>
|
| 44 |
+
screen.getByText(label).previousElementSibling?.textContent;
|
| 45 |
+
|
| 46 |
+
describe("SearchStats", () => {
|
| 47 |
+
let originalTimeZone: string | undefined;
|
| 48 |
+
|
| 49 |
+
beforeEach(() => {
|
| 50 |
+
originalTimeZone = process.env.TZ;
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
afterEach(() => {
|
| 54 |
+
vi.useRealTimers();
|
| 55 |
+
if (originalTimeZone === undefined) delete process.env.TZ;
|
| 56 |
+
else process.env.TZ = originalTimeZone;
|
| 57 |
+
});
|
| 58 |
+
|
| 59 |
+
it("buckets the Daily Average by local day, like the heatmap", () => {
|
| 60 |
+
process.env.TZ = "Europe/Zurich"; // UTC+1 in January
|
| 61 |
+
vi.useFakeTimers({ toFake: ["Date"] });
|
| 62 |
+
vi.setSystemTime(new Date(2026, 0, 15, 12));
|
| 63 |
+
|
| 64 |
+
// 00:30 and 01:30 local are 23:30 and 00:30 UTC: one local day, two UTC
|
| 65 |
+
// days. The UTC check makes a silent no-op of the zone change fail loudly
|
| 66 |
+
// instead of passing vacuously.
|
| 67 |
+
const first = new Date(2026, 0, 15, 0, 30).getTime();
|
| 68 |
+
const second = new Date(2026, 0, 15, 1, 30).getTime();
|
| 69 |
+
expect(new Date(first).getUTCDate()).toBe(14);
|
| 70 |
+
expect(new Date(second).getUTCDate()).toBe(15);
|
| 71 |
+
|
| 72 |
+
mockHistory([
|
| 73 |
+
{ id: 1, query: "first", timestamp: first },
|
| 74 |
+
{ id: 2, query: "second", timestamp: second },
|
| 75 |
+
]);
|
| 76 |
+
render(
|
| 77 |
+
<MantineProvider>
|
| 78 |
+
<SearchStats />
|
| 79 |
+
</MantineProvider>,
|
| 80 |
+
);
|
| 81 |
+
|
| 82 |
+
expect(valueBelow("Daily Average")).toBe("2");
|
| 83 |
+
expect(valueAbove("Active days")).toBe("1");
|
| 84 |
+
});
|
| 85 |
+
});
|
client/components/Analytics/SearchStats.tsx
CHANGED
|
@@ -14,7 +14,7 @@ import { IconSearch } from "@tabler/icons-react";
|
|
| 14 |
import { useMemo } from "react";
|
| 15 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
| 16 |
import type { SearchEntry } from "@/modules/history";
|
| 17 |
-
import { buildActivity } from "@/modules/searchActivity";
|
| 18 |
import { formatRelativeTime } from "@/modules/stringFormatters";
|
| 19 |
import ActivityHeatmap from "./ActivityHeatmap";
|
| 20 |
|
|
@@ -96,7 +96,8 @@ export default function SearchStats({
|
|
| 96 |
|
| 97 |
const dateCounts = new Map<string, number>();
|
| 98 |
filteredSearches.forEach((search) => {
|
| 99 |
-
|
|
|
|
| 100 |
dateCounts.set(date, (dateCounts.get(date) || 0) + 1);
|
| 101 |
});
|
| 102 |
|
|
|
|
| 14 |
import { useMemo } from "react";
|
| 15 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
| 16 |
import type { SearchEntry } from "@/modules/history";
|
| 17 |
+
import { buildActivity, localKey, startOfDay } from "@/modules/searchActivity";
|
| 18 |
import { formatRelativeTime } from "@/modules/stringFormatters";
|
| 19 |
import ActivityHeatmap from "./ActivityHeatmap";
|
| 20 |
|
|
|
|
| 96 |
|
| 97 |
const dateCounts = new Map<string, number>();
|
| 98 |
filteredSearches.forEach((search) => {
|
| 99 |
+
// Local day, like the hour math below and the heatmap's active days.
|
| 100 |
+
const date = localKey(startOfDay(search.timestamp));
|
| 101 |
dateCounts.set(date, (dateCounts.get(date) || 0) + 1);
|
| 102 |
});
|
| 103 |
|
client/components/Pages/AccessPage.test.tsx
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { render, screen } from "@testing-library/react";
|
| 3 |
+
import userEvent from "@testing-library/user-event";
|
| 4 |
+
import { type AccessKeyResult, validateAccessKey } from "@/modules/accessKey";
|
| 5 |
+
import AccessPage from "./AccessPage";
|
| 6 |
+
|
| 7 |
+
vi.mock("@/modules/accessKey", () => ({
|
| 8 |
+
validateAccessKey: vi.fn(),
|
| 9 |
+
}));
|
| 10 |
+
|
| 11 |
+
vi.mock("@/modules/logEntries", () => ({
|
| 12 |
+
addLogEntry: vi.fn(),
|
| 13 |
+
}));
|
| 14 |
+
|
| 15 |
+
async function submitKey(result: AccessKeyResult) {
|
| 16 |
+
vi.mocked(validateAccessKey).mockResolvedValueOnce(result);
|
| 17 |
+
const onAccessKeyValid = vi.fn();
|
| 18 |
+
const user = userEvent.setup();
|
| 19 |
+
render(
|
| 20 |
+
<MantineProvider>
|
| 21 |
+
<AccessPage onAccessKeyValid={onAccessKeyValid} />
|
| 22 |
+
</MantineProvider>,
|
| 23 |
+
);
|
| 24 |
+
|
| 25 |
+
await user.type(
|
| 26 |
+
screen.getByPlaceholderText("Enter your access key to continue"),
|
| 27 |
+
"some-key{Enter}",
|
| 28 |
+
);
|
| 29 |
+
|
| 30 |
+
return onAccessKeyValid;
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
describe("AccessPage", () => {
|
| 34 |
+
beforeEach(() => {
|
| 35 |
+
vi.clearAllMocks();
|
| 36 |
+
});
|
| 37 |
+
|
| 38 |
+
it("says the key is wrong when the server rejects it", async () => {
|
| 39 |
+
await submitKey("invalid");
|
| 40 |
+
|
| 41 |
+
expect(await screen.findByText("Invalid access key")).toBeInTheDocument();
|
| 42 |
+
});
|
| 43 |
+
|
| 44 |
+
it("says the server could not be reached instead of blaming the key", async () => {
|
| 45 |
+
await submitKey("unreachable");
|
| 46 |
+
|
| 47 |
+
expect(
|
| 48 |
+
await screen.findByText("Could not reach the server. Please try again."),
|
| 49 |
+
).toBeInTheDocument();
|
| 50 |
+
expect(screen.queryByText("Invalid access key")).toBeNull();
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it("shows no field error when rate-limited", async () => {
|
| 54 |
+
const onAccessKeyValid = await submitKey("rateLimited");
|
| 55 |
+
|
| 56 |
+
expect(screen.queryByText("Invalid access key")).toBeNull();
|
| 57 |
+
expect(onAccessKeyValid).not.toHaveBeenCalled();
|
| 58 |
+
});
|
| 59 |
+
|
| 60 |
+
it("lets the user in with a valid key", async () => {
|
| 61 |
+
const onAccessKeyValid = await submitKey("valid");
|
| 62 |
+
|
| 63 |
+
expect(onAccessKeyValid).toHaveBeenCalled();
|
| 64 |
+
});
|
| 65 |
+
});
|
client/components/Pages/AccessPage.tsx
CHANGED
|
@@ -21,21 +21,22 @@ export default function AccessPage({
|
|
| 21 |
const handleSubmit = async (formEvent: FormEvent<HTMLFormElement>) => {
|
| 22 |
formEvent.preventDefault();
|
| 23 |
setState((prev) => ({ ...prev, error: "" }));
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
| 39 |
}
|
| 40 |
};
|
| 41 |
|
|
|
|
| 21 |
const handleSubmit = async (formEvent: FormEvent<HTMLFormElement>) => {
|
| 22 |
formEvent.preventDefault();
|
| 23 |
setState((prev) => ({ ...prev, error: "" }));
|
| 24 |
+
// validateAccessKey never rejects: every failure comes back as a result.
|
| 25 |
+
const result = await validateAccessKey(state.accessKey);
|
| 26 |
+
if (result === "valid") {
|
| 27 |
+
addLogEntry("Valid access key entered");
|
| 28 |
+
onAccessKeyValid();
|
| 29 |
+
} else if (result === "rateLimited") {
|
| 30 |
+
// The module already raised the refusal notice; no wrong-key error.
|
| 31 |
+
addLogEntry("Access key validation rate-limited");
|
| 32 |
+
} else if (result === "unreachable") {
|
| 33 |
+
setState((prev) => ({
|
| 34 |
+
...prev,
|
| 35 |
+
error: "Could not reach the server. Please try again.",
|
| 36 |
+
}));
|
| 37 |
+
} else {
|
| 38 |
+
setState((prev) => ({ ...prev, error: "Invalid access key" }));
|
| 39 |
+
addLogEntry("Invalid access key attempt");
|
| 40 |
}
|
| 41 |
};
|
| 42 |
|
client/components/Pages/Main/Menu/AISettings/AISettingsForm.tsx
CHANGED
|
@@ -1,8 +1,8 @@
|
|
| 1 |
import { Select, Stack, Switch, Text, TextInput } from "@mantine/core";
|
| 2 |
-
import { useForm } from "@mantine/form";
|
| 3 |
import { notifications } from "@mantine/notifications";
|
| 4 |
import { usePubSub } from "create-pubsub/react";
|
| 5 |
import { useEffect, useState } from "react";
|
|
|
|
| 6 |
import { FALLBACK_CONFIG, getConfig } from "@/modules/config";
|
| 7 |
import { requestNotificationPermission } from "@/modules/notifications";
|
| 8 |
import { settingsPubSub } from "@/modules/pubSub";
|
|
@@ -15,8 +15,26 @@ import { useHordeModels } from "./hooks/useHordeModels";
|
|
| 15 |
import { useHordeUserInfo } from "./hooks/useHordeUserInfo";
|
| 16 |
import { useOpenAiModels } from "./hooks/useOpenAiModels";
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
export default function AISettingsForm() {
|
| 19 |
-
const [settings
|
| 20 |
const { openAiModels, useTextInput } = useOpenAiModels(settings);
|
| 21 |
const hordeModels = useHordeModels(settings);
|
| 22 |
const hordeUserInfo = useHordeUserInfo(settings);
|
|
@@ -29,10 +47,7 @@ export default function AISettingsForm() {
|
|
| 29 |
.then(setServerConfig);
|
| 30 |
}, []);
|
| 31 |
|
| 32 |
-
const form =
|
| 33 |
-
initialValues: settings,
|
| 34 |
-
onValuesChange: setSettings,
|
| 35 |
-
});
|
| 36 |
|
| 37 |
const handleNotificationToggle = async (
|
| 38 |
event: React.ChangeEvent<HTMLInputElement>,
|
|
|
|
| 1 |
import { Select, Stack, Switch, Text, TextInput } from "@mantine/core";
|
|
|
|
| 2 |
import { notifications } from "@mantine/notifications";
|
| 3 |
import { usePubSub } from "create-pubsub/react";
|
| 4 |
import { useEffect, useState } from "react";
|
| 5 |
+
import { useSettingsForm } from "@/hooks/useSettingsForm";
|
| 6 |
import { FALLBACK_CONFIG, getConfig } from "@/modules/config";
|
| 7 |
import { requestNotificationPermission } from "@/modules/notifications";
|
| 8 |
import { settingsPubSub } from "@/modules/pubSub";
|
|
|
|
| 15 |
import { useHordeUserInfo } from "./hooks/useHordeUserInfo";
|
| 16 |
import { useOpenAiModels } from "./hooks/useOpenAiModels";
|
| 17 |
|
| 18 |
+
const SETTINGS_KEYS = [
|
| 19 |
+
"enableAiResponse",
|
| 20 |
+
"enableNotificationOnAiComplete",
|
| 21 |
+
"enablePageContentFetch",
|
| 22 |
+
"inferenceType",
|
| 23 |
+
"openAiApiBaseUrl",
|
| 24 |
+
"openAiApiKey",
|
| 25 |
+
"openAiApiModel",
|
| 26 |
+
"openAiContextLength",
|
| 27 |
+
"hordeApiKey",
|
| 28 |
+
"hordeModel",
|
| 29 |
+
"wllamaModelId",
|
| 30 |
+
"cpuThreads",
|
| 31 |
+
"systemPrompt",
|
| 32 |
+
"reasoningStartMarker",
|
| 33 |
+
"reasoningEndMarker",
|
| 34 |
+
] as const;
|
| 35 |
+
|
| 36 |
export default function AISettingsForm() {
|
| 37 |
+
const [settings] = usePubSub(settingsPubSub);
|
| 38 |
const { openAiModels, useTextInput } = useOpenAiModels(settings);
|
| 39 |
const hordeModels = useHordeModels(settings);
|
| 40 |
const hordeUserInfo = useHordeUserInfo(settings);
|
|
|
|
| 47 |
.then(setServerConfig);
|
| 48 |
}, []);
|
| 49 |
|
| 50 |
+
const form = useSettingsForm(SETTINGS_KEYS);
|
|
|
|
|
|
|
|
|
|
| 51 |
|
| 52 |
const handleNotificationToggle = async (
|
| 53 |
event: React.ChangeEvent<HTMLInputElement>,
|
client/components/Pages/Main/Menu/AISettings/components/BrowserSettings.tsx
CHANGED
|
@@ -8,7 +8,9 @@ const WllamaModelSelect = lazy(
|
|
| 8 |
);
|
| 9 |
|
| 10 |
interface BrowserSettingsProps {
|
| 11 |
-
form: UseFormReturnType<
|
|
|
|
|
|
|
| 12 |
}
|
| 13 |
|
| 14 |
/** Browser inference settings: the model to run (lazy-loaded) and its CPU threads. */
|
|
|
|
| 8 |
);
|
| 9 |
|
| 10 |
interface BrowserSettingsProps {
|
| 11 |
+
form: UseFormReturnType<
|
| 12 |
+
Pick<typeof defaultSettings, "wllamaModelId" | "cpuThreads">
|
| 13 |
+
>;
|
| 14 |
}
|
| 15 |
|
| 16 |
/** Browser inference settings: the model to run (lazy-loaded) and its CPU threads. */
|
client/components/Pages/Main/Menu/AISettings/components/HordeSettings.tsx
CHANGED
|
@@ -5,7 +5,9 @@ import { aiHordeDefaultApiKey } from "@/modules/textGenerationWithHorde";
|
|
| 5 |
import type { HordeUserInfo, ModelOption } from "../types";
|
| 6 |
|
| 7 |
interface HordeSettingsProps {
|
| 8 |
-
form: UseFormReturnType<
|
|
|
|
|
|
|
| 9 |
hordeUserInfo: HordeUserInfo | null;
|
| 10 |
hordeModels: ModelOption[];
|
| 11 |
}
|
|
|
|
| 5 |
import type { HordeUserInfo, ModelOption } from "../types";
|
| 6 |
|
| 7 |
interface HordeSettingsProps {
|
| 8 |
+
form: UseFormReturnType<
|
| 9 |
+
Pick<typeof defaultSettings, "hordeApiKey" | "hordeModel">
|
| 10 |
+
>;
|
| 11 |
hordeUserInfo: HordeUserInfo | null;
|
| 12 |
hordeModels: ModelOption[];
|
| 13 |
}
|
client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.test.tsx
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { useForm } from "@mantine/form";
|
| 3 |
+
import { fireEvent, render, screen } from "@testing-library/react";
|
| 4 |
+
import { describe, expect, it, vi } from "vitest";
|
| 5 |
+
import { defaultSettings } from "@/modules/settings";
|
| 6 |
+
import { OpenAISettings } from "./OpenAISettings";
|
| 7 |
+
|
| 8 |
+
function Harness({
|
| 9 |
+
onValuesChange,
|
| 10 |
+
}: {
|
| 11 |
+
onValuesChange: (values: typeof defaultSettings) => void;
|
| 12 |
+
}) {
|
| 13 |
+
const form = useForm({
|
| 14 |
+
initialValues: defaultSettings,
|
| 15 |
+
onValuesChange,
|
| 16 |
+
});
|
| 17 |
+
|
| 18 |
+
return <OpenAISettings form={form} openAiModels={[]} useTextInput={false} />;
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
describe("OpenAISettings", () => {
|
| 22 |
+
it("keeps a context length below the default after blur", () => {
|
| 23 |
+
const onValuesChange = vi.fn();
|
| 24 |
+
render(
|
| 25 |
+
<MantineProvider>
|
| 26 |
+
<Harness onValuesChange={onValuesChange} />
|
| 27 |
+
</MantineProvider>,
|
| 28 |
+
);
|
| 29 |
+
const input = screen.getByRole("textbox", { name: "Context Length" });
|
| 30 |
+
|
| 31 |
+
fireEvent.change(input, { target: { value: "2048" } });
|
| 32 |
+
fireEvent.blur(input);
|
| 33 |
+
|
| 34 |
+
expect(input).toHaveValue("2048");
|
| 35 |
+
expect(onValuesChange).toHaveBeenLastCalledWith(
|
| 36 |
+
expect.objectContaining({ openAiContextLength: 2048 }),
|
| 37 |
+
expect.anything(),
|
| 38 |
+
);
|
| 39 |
+
});
|
| 40 |
+
});
|
client/components/Pages/Main/Menu/AISettings/components/OpenAISettings.tsx
CHANGED
|
@@ -5,7 +5,15 @@ import { defaultSettings } from "@/modules/settings";
|
|
| 5 |
import type { ModelOption } from "../types";
|
| 6 |
|
| 7 |
interface OpenAISettingsProps {
|
| 8 |
-
form: UseFormReturnType<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
openAiModels: ModelOption[];
|
| 10 |
useTextInput: boolean;
|
| 11 |
}
|
|
@@ -60,8 +68,8 @@ export const OpenAISettings = ({
|
|
| 60 |
description={`Maximum number of tokens the model can consider. Defaults to ${defaultSettings.openAiContextLength}.`}
|
| 61 |
defaultValue={defaultSettings.openAiContextLength}
|
| 62 |
{...form.getInputProps("openAiContextLength")}
|
| 63 |
-
step={
|
| 64 |
-
min={
|
| 65 |
/>
|
| 66 |
</>
|
| 67 |
);
|
|
|
|
| 5 |
import type { ModelOption } from "../types";
|
| 6 |
|
| 7 |
interface OpenAISettingsProps {
|
| 8 |
+
form: UseFormReturnType<
|
| 9 |
+
Pick<
|
| 10 |
+
typeof defaultSettings,
|
| 11 |
+
| "openAiApiBaseUrl"
|
| 12 |
+
| "openAiApiKey"
|
| 13 |
+
| "openAiApiModel"
|
| 14 |
+
| "openAiContextLength"
|
| 15 |
+
>
|
| 16 |
+
>;
|
| 17 |
openAiModels: ModelOption[];
|
| 18 |
useTextInput: boolean;
|
| 19 |
}
|
|
|
|
| 68 |
description={`Maximum number of tokens the model can consider. Defaults to ${defaultSettings.openAiContextLength}.`}
|
| 69 |
defaultValue={defaultSettings.openAiContextLength}
|
| 70 |
{...form.getInputProps("openAiContextLength")}
|
| 71 |
+
step={1024}
|
| 72 |
+
min={512}
|
| 73 |
/>
|
| 74 |
</>
|
| 75 |
);
|
client/components/Pages/Main/Menu/AISettings/components/SystemPromptInput.tsx
CHANGED
|
@@ -3,7 +3,7 @@ import type { UseFormReturnType } from "@mantine/form";
|
|
| 3 |
import { defaultSettings } from "@/modules/settings";
|
| 4 |
|
| 5 |
interface SystemPromptInputProps {
|
| 6 |
-
form: UseFormReturnType<typeof defaultSettings>;
|
| 7 |
}
|
| 8 |
|
| 9 |
/** Custom system prompt editor, with an inline action to restore the default. */
|
|
|
|
| 3 |
import { defaultSettings } from "@/modules/settings";
|
| 4 |
|
| 5 |
interface SystemPromptInputProps {
|
| 6 |
+
form: UseFormReturnType<Pick<typeof defaultSettings, "systemPrompt">>;
|
| 7 |
}
|
| 8 |
|
| 9 |
/** Custom system prompt editor, with an inline action to restore the default. */
|
client/components/Pages/Main/Menu/ClearDataButton.test.tsx
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { cleanup, render, screen, waitFor } from "@testing-library/react";
|
| 3 |
+
import userEvent from "@testing-library/user-event";
|
| 4 |
+
import Dexie from "dexie";
|
| 5 |
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 6 |
+
import { addLogEntry } from "@/modules/logEntries";
|
| 7 |
+
import { clearWllamaCache } from "@/modules/wllama";
|
| 8 |
+
import ClearDataButton from "./ClearDataButton";
|
| 9 |
+
|
| 10 |
+
const mockNavigate = vi.fn();
|
| 11 |
+
|
| 12 |
+
vi.mock("wouter", () => ({
|
| 13 |
+
useLocation: vi.fn(() => ["/", mockNavigate]),
|
| 14 |
+
}));
|
| 15 |
+
|
| 16 |
+
vi.mock("@/modules/logEntries", () => ({
|
| 17 |
+
addLogEntry: vi.fn(),
|
| 18 |
+
}));
|
| 19 |
+
|
| 20 |
+
vi.mock("@/modules/wllama", () => ({
|
| 21 |
+
clearWllamaCache: vi.fn(),
|
| 22 |
+
}));
|
| 23 |
+
|
| 24 |
+
function renderClearDataButton() {
|
| 25 |
+
return render(
|
| 26 |
+
<MantineProvider>
|
| 27 |
+
<ClearDataButton />
|
| 28 |
+
</MantineProvider>,
|
| 29 |
+
);
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
describe("ClearDataButton", () => {
|
| 33 |
+
const originalLocation = self.location;
|
| 34 |
+
const originalCachesDescriptor = Object.getOwnPropertyDescriptor(
|
| 35 |
+
self,
|
| 36 |
+
"caches",
|
| 37 |
+
);
|
| 38 |
+
let reloadMock: ReturnType<typeof vi.fn>;
|
| 39 |
+
|
| 40 |
+
beforeEach(() => {
|
| 41 |
+
vi.clearAllMocks();
|
| 42 |
+
reloadMock = vi.fn();
|
| 43 |
+
Object.defineProperty(self, "location", {
|
| 44 |
+
configurable: true,
|
| 45 |
+
value: { ...originalLocation, reload: reloadMock },
|
| 46 |
+
});
|
| 47 |
+
vi.spyOn(self, "confirm").mockReturnValue(true);
|
| 48 |
+
vi.spyOn(Dexie, "getDatabaseNames").mockResolvedValue(["minisearch-db"]);
|
| 49 |
+
vi.spyOn(Dexie, "delete").mockResolvedValue(undefined);
|
| 50 |
+
vi.mocked(clearWllamaCache).mockResolvedValue(undefined);
|
| 51 |
+
localStorage.setItem("sample-key", "sample-value");
|
| 52 |
+
});
|
| 53 |
+
|
| 54 |
+
afterEach(() => {
|
| 55 |
+
cleanup();
|
| 56 |
+
Object.defineProperty(self, "location", {
|
| 57 |
+
configurable: true,
|
| 58 |
+
value: originalLocation,
|
| 59 |
+
});
|
| 60 |
+
if (originalCachesDescriptor) {
|
| 61 |
+
Object.defineProperty(self, "caches", originalCachesDescriptor);
|
| 62 |
+
} else {
|
| 63 |
+
Reflect.deleteProperty(self, "caches");
|
| 64 |
+
}
|
| 65 |
+
vi.restoreAllMocks();
|
| 66 |
+
});
|
| 67 |
+
|
| 68 |
+
it("completes the teardown and reloads when self.caches is undefined", async () => {
|
| 69 |
+
Object.defineProperty(self, "caches", {
|
| 70 |
+
configurable: true,
|
| 71 |
+
value: undefined,
|
| 72 |
+
});
|
| 73 |
+
|
| 74 |
+
const user = userEvent.setup();
|
| 75 |
+
renderClearDataButton();
|
| 76 |
+
|
| 77 |
+
await user.click(screen.getByRole("button", { name: "Clear all data" }));
|
| 78 |
+
|
| 79 |
+
await waitFor(() => {
|
| 80 |
+
expect(reloadMock).toHaveBeenCalledTimes(1);
|
| 81 |
+
});
|
| 82 |
+
|
| 83 |
+
expect(localStorage.getItem("sample-key")).toBeNull();
|
| 84 |
+
expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");
|
| 85 |
+
expect(clearWllamaCache).toHaveBeenCalledTimes(1);
|
| 86 |
+
expect(addLogEntry).toHaveBeenCalledWith("All data cleared successfully");
|
| 87 |
+
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
|
| 88 |
+
expect(
|
| 89 |
+
screen.getByRole("button", { name: "Data cleared" }),
|
| 90 |
+
).not.toHaveAttribute("data-loading");
|
| 91 |
+
});
|
| 92 |
+
|
| 93 |
+
it("logs the failure, clears the spinner, and still reloads when clearWllamaCache rejects", async () => {
|
| 94 |
+
Object.defineProperty(self, "caches", {
|
| 95 |
+
configurable: true,
|
| 96 |
+
value: undefined,
|
| 97 |
+
});
|
| 98 |
+
vi.mocked(clearWllamaCache).mockRejectedValueOnce(
|
| 99 |
+
new Error("OPFS unavailable"),
|
| 100 |
+
);
|
| 101 |
+
|
| 102 |
+
const user = userEvent.setup();
|
| 103 |
+
renderClearDataButton();
|
| 104 |
+
|
| 105 |
+
await user.click(screen.getByRole("button", { name: "Clear all data" }));
|
| 106 |
+
|
| 107 |
+
await waitFor(() => {
|
| 108 |
+
expect(reloadMock).toHaveBeenCalledTimes(1);
|
| 109 |
+
});
|
| 110 |
+
|
| 111 |
+
expect(addLogEntry).toHaveBeenCalledWith(
|
| 112 |
+
"Error clearing data: OPFS unavailable",
|
| 113 |
+
);
|
| 114 |
+
expect(addLogEntry).not.toHaveBeenCalledWith(
|
| 115 |
+
"All data cleared successfully",
|
| 116 |
+
);
|
| 117 |
+
expect(mockNavigate).toHaveBeenCalledWith("/", { replace: true });
|
| 118 |
+
expect(
|
| 119 |
+
screen.getByRole("button", { name: "Clear all data" }),
|
| 120 |
+
).not.toHaveAttribute("data-loading");
|
| 121 |
+
});
|
| 122 |
+
|
| 123 |
+
it("deletes all caches and continues when one caches.delete call rejects", async () => {
|
| 124 |
+
const deleteMock = vi
|
| 125 |
+
.fn<(cacheName: string) => Promise<boolean>>()
|
| 126 |
+
.mockRejectedValueOnce(new Error("locked cache"))
|
| 127 |
+
.mockResolvedValueOnce(true);
|
| 128 |
+
const keysMock = vi.fn().mockResolvedValue(["cache-a", "cache-b"]);
|
| 129 |
+
|
| 130 |
+
Object.defineProperty(self, "caches", {
|
| 131 |
+
configurable: true,
|
| 132 |
+
value: {
|
| 133 |
+
keys: keysMock,
|
| 134 |
+
delete: deleteMock,
|
| 135 |
+
},
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
const user = userEvent.setup();
|
| 139 |
+
renderClearDataButton();
|
| 140 |
+
|
| 141 |
+
await user.click(screen.getByRole("button", { name: "Clear all data" }));
|
| 142 |
+
|
| 143 |
+
await waitFor(() => {
|
| 144 |
+
expect(reloadMock).toHaveBeenCalledTimes(1);
|
| 145 |
+
});
|
| 146 |
+
|
| 147 |
+
expect(keysMock).toHaveBeenCalledTimes(1);
|
| 148 |
+
expect(deleteMock).toHaveBeenCalledWith("cache-a");
|
| 149 |
+
expect(deleteMock).toHaveBeenCalledWith("cache-b");
|
| 150 |
+
expect(addLogEntry).toHaveBeenCalledWith(
|
| 151 |
+
"Error deleting cache cache-a: locked cache",
|
| 152 |
+
);
|
| 153 |
+
expect(Dexie.delete).toHaveBeenCalledWith("minisearch-db");
|
| 154 |
+
expect(clearWllamaCache).toHaveBeenCalledTimes(1);
|
| 155 |
+
expect(addLogEntry).toHaveBeenCalledWith("All data cleared successfully");
|
| 156 |
+
});
|
| 157 |
+
|
| 158 |
+
it("does nothing when confirmation is cancelled", async () => {
|
| 159 |
+
vi.spyOn(self, "confirm").mockReturnValue(false);
|
| 160 |
+
|
| 161 |
+
const user = userEvent.setup();
|
| 162 |
+
renderClearDataButton();
|
| 163 |
+
|
| 164 |
+
await user.click(screen.getByRole("button", { name: "Clear all data" }));
|
| 165 |
+
|
| 166 |
+
expect(localStorage.getItem("sample-key")).toBe("sample-value");
|
| 167 |
+
expect(clearWllamaCache).not.toHaveBeenCalled();
|
| 168 |
+
expect(reloadMock).not.toHaveBeenCalled();
|
| 169 |
+
});
|
| 170 |
+
});
|
client/components/Pages/Main/Menu/ClearDataButton.tsx
CHANGED
|
@@ -18,7 +18,7 @@ export default function ClearDataButton() {
|
|
| 18 |
|
| 19 |
const handleClearDataButtonClick = async () => {
|
| 20 |
const sureToDelete = self.confirm(
|
| 21 |
-
"Are you sure you want to
|
| 22 |
);
|
| 23 |
|
| 24 |
if (!sureToDelete) return;
|
|
@@ -27,42 +27,71 @@ export default function ClearDataButton() {
|
|
| 27 |
|
| 28 |
setState((prev) => ({ ...prev, isClearingData: true }));
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
for (const cacheName of await self.caches.keys()) {
|
| 33 |
-
await self.caches.delete(cacheName);
|
| 34 |
-
}
|
| 35 |
|
| 36 |
try {
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
-
await Dexie.
|
| 41 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
} catch (error) {
|
| 44 |
addLogEntry(
|
| 45 |
-
`Error
|
| 46 |
error instanceof Error ? error.message : String(error)
|
| 47 |
}`,
|
| 48 |
);
|
| 49 |
-
}
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
| 54 |
|
| 55 |
-
|
| 56 |
-
...prev,
|
| 57 |
-
isClearingData: false,
|
| 58 |
-
hasClearedData: true,
|
| 59 |
-
}));
|
| 60 |
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
navigate("/", { replace: true });
|
| 64 |
-
|
| 65 |
-
self.location.reload();
|
| 66 |
};
|
| 67 |
|
| 68 |
return (
|
|
@@ -77,7 +106,8 @@ export default function ClearDataButton() {
|
|
| 77 |
{state.hasClearedData ? "Data cleared" : "Clear all data"}
|
| 78 |
</Button>
|
| 79 |
<Text size="xs" c="dimmed">
|
| 80 |
-
Reset settings
|
|
|
|
| 81 |
</Text>
|
| 82 |
</Stack>
|
| 83 |
);
|
|
|
|
| 18 |
|
| 19 |
const handleClearDataButtonClick = async () => {
|
| 20 |
const sureToDelete = self.confirm(
|
| 21 |
+
"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.",
|
| 22 |
);
|
| 23 |
|
| 24 |
if (!sureToDelete) return;
|
|
|
|
| 27 |
|
| 28 |
setState((prev) => ({ ...prev, isClearingData: true }));
|
| 29 |
|
| 30 |
+
let clearedSuccessfully = false;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
try {
|
| 33 |
+
self.localStorage.clear();
|
| 34 |
+
|
| 35 |
+
if (self.caches) {
|
| 36 |
+
try {
|
| 37 |
+
for (const cacheName of await self.caches.keys()) {
|
| 38 |
+
try {
|
| 39 |
+
await self.caches.delete(cacheName);
|
| 40 |
+
} catch (error) {
|
| 41 |
+
addLogEntry(
|
| 42 |
+
`Error deleting cache ${cacheName}: ${
|
| 43 |
+
error instanceof Error ? error.message : String(error)
|
| 44 |
+
}`,
|
| 45 |
+
);
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
} catch (error) {
|
| 49 |
+
addLogEntry(
|
| 50 |
+
`Error listing caches: ${
|
| 51 |
+
error instanceof Error ? error.message : String(error)
|
| 52 |
+
}`,
|
| 53 |
+
);
|
| 54 |
+
}
|
| 55 |
+
}
|
| 56 |
|
| 57 |
+
try {
|
| 58 |
+
const dbNames = await Dexie.getDatabaseNames();
|
| 59 |
+
|
| 60 |
+
for (const dbName of dbNames) {
|
| 61 |
+
await Dexie.delete(dbName);
|
| 62 |
+
addLogEntry(`Deleted database: ${dbName}`);
|
| 63 |
+
}
|
| 64 |
+
} catch (error) {
|
| 65 |
+
addLogEntry(
|
| 66 |
+
`Error deleting databases: ${
|
| 67 |
+
error instanceof Error ? error.message : String(error)
|
| 68 |
+
}`,
|
| 69 |
+
);
|
| 70 |
}
|
| 71 |
+
|
| 72 |
+
const { clearWllamaCache } = await import("../../../../modules/wllama");
|
| 73 |
+
|
| 74 |
+
await clearWllamaCache();
|
| 75 |
+
|
| 76 |
+
clearedSuccessfully = true;
|
| 77 |
+
addLogEntry("All data cleared successfully");
|
| 78 |
} catch (error) {
|
| 79 |
addLogEntry(
|
| 80 |
+
`Error clearing data: ${
|
| 81 |
error instanceof Error ? error.message : String(error)
|
| 82 |
}`,
|
| 83 |
);
|
| 84 |
+
} finally {
|
| 85 |
+
setState((prev) => ({
|
| 86 |
+
...prev,
|
| 87 |
+
isClearingData: false,
|
| 88 |
+
hasClearedData: clearedSuccessfully,
|
| 89 |
+
}));
|
| 90 |
|
| 91 |
+
navigate("/", { replace: true });
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
self.location.reload();
|
| 94 |
+
}
|
|
|
|
|
|
|
|
|
|
| 95 |
};
|
| 96 |
|
| 97 |
return (
|
|
|
|
| 106 |
{state.hasClearedData ? "Data cleared" : "Clear all data"}
|
| 107 |
</Button>
|
| 108 |
<Text size="xs" c="dimmed">
|
| 109 |
+
Reset settings, delete cached files and erase your search and chat
|
| 110 |
+
history.
|
| 111 |
</Text>
|
| 112 |
</Stack>
|
| 113 |
);
|
client/components/Pages/Main/Menu/InterfaceSettingsForm.tsx
CHANGED
|
@@ -4,16 +4,12 @@ import {
|
|
| 4 |
useComputedColorScheme,
|
| 5 |
useMantineColorScheme,
|
| 6 |
} from "@mantine/core";
|
| 7 |
-
import {
|
| 8 |
-
|
| 9 |
-
|
| 10 |
|
| 11 |
export default function InterfaceSettingsForm() {
|
| 12 |
-
const
|
| 13 |
-
const form = useForm({
|
| 14 |
-
initialValues: settings,
|
| 15 |
-
onValuesChange: setSettings,
|
| 16 |
-
});
|
| 17 |
const { setColorScheme } = useMantineColorScheme();
|
| 18 |
const computedColorScheme = useComputedColorScheme("light");
|
| 19 |
|
|
|
|
| 4 |
useComputedColorScheme,
|
| 5 |
useMantineColorScheme,
|
| 6 |
} from "@mantine/core";
|
| 7 |
+
import { useSettingsForm } from "@/hooks/useSettingsForm";
|
| 8 |
+
|
| 9 |
+
const SETTINGS_KEYS = ["enterToSubmit"] as const;
|
| 10 |
|
| 11 |
export default function InterfaceSettingsForm() {
|
| 12 |
+
const form = useSettingsForm(SETTINGS_KEYS);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
const { setColorScheme } = useMantineColorScheme();
|
| 14 |
const computedColorScheme = useComputedColorScheme("light");
|
| 15 |
|
client/components/Pages/Main/Menu/SearchSettingsForm.tsx
CHANGED
|
@@ -1,14 +1,14 @@
|
|
| 1 |
import { Slider, Stack, Switch, Text } from "@mantine/core";
|
| 2 |
-
import {
|
| 3 |
-
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
export default function SearchSettingsForm() {
|
| 7 |
-
const
|
| 8 |
-
const form = useForm({
|
| 9 |
-
initialValues: settings,
|
| 10 |
-
onValuesChange: setSettings,
|
| 11 |
-
});
|
| 12 |
|
| 13 |
return (
|
| 14 |
<Stack gap="md">
|
|
|
|
| 1 |
import { Slider, Stack, Switch, Text } from "@mantine/core";
|
| 2 |
+
import { useSettingsForm } from "@/hooks/useSettingsForm";
|
| 3 |
+
|
| 4 |
+
const SETTINGS_KEYS = [
|
| 5 |
+
"searchResultsLimit",
|
| 6 |
+
"enableTextSearch",
|
| 7 |
+
"enableImageSearch",
|
| 8 |
+
] as const;
|
| 9 |
|
| 10 |
export default function SearchSettingsForm() {
|
| 11 |
+
const form = useSettingsForm(SETTINGS_KEYS);
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
return (
|
| 14 |
<Stack gap="md">
|
client/components/Pages/Main/Menu/SettingsForms.test.tsx
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { act, fireEvent, render, screen } from "@testing-library/react";
|
| 3 |
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
| 4 |
+
import { settingsPubSub } from "@/modules/pubSub";
|
| 5 |
+
import { defaultSettings } from "@/modules/settings";
|
| 6 |
+
import AISettingsForm from "./AISettings/AISettingsForm";
|
| 7 |
+
import InterfaceSettingsForm from "./InterfaceSettingsForm";
|
| 8 |
+
import SearchSettingsForm from "./SearchSettingsForm";
|
| 9 |
+
|
| 10 |
+
vi.mock("@/modules/config", async (importOriginal) => {
|
| 11 |
+
const actual = await importOriginal<typeof import("@/modules/config")>();
|
| 12 |
+
return { ...actual, getConfig: async () => actual.FALLBACK_CONFIG };
|
| 13 |
+
});
|
| 14 |
+
|
| 15 |
+
const [updateSettings, , getSettings] = settingsPubSub;
|
| 16 |
+
|
| 17 |
+
function toggle(name: RegExp) {
|
| 18 |
+
fireEvent.click(screen.getByRole("switch", { name }));
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
describe("the menu's settings forms", () => {
|
| 22 |
+
beforeEach(() => {
|
| 23 |
+
updateSettings(defaultSettings);
|
| 24 |
+
});
|
| 25 |
+
|
| 26 |
+
it("keep a change made in one section when another section changes", () => {
|
| 27 |
+
render(
|
| 28 |
+
<MantineProvider>
|
| 29 |
+
<SearchSettingsForm />
|
| 30 |
+
<InterfaceSettingsForm />
|
| 31 |
+
</MantineProvider>,
|
| 32 |
+
);
|
| 33 |
+
|
| 34 |
+
toggle(/Text Search/);
|
| 35 |
+
toggle(/Enter to Submit/);
|
| 36 |
+
|
| 37 |
+
expect(getSettings()).toMatchObject({
|
| 38 |
+
enableTextSearch: false,
|
| 39 |
+
enterToSubmit: false,
|
| 40 |
+
});
|
| 41 |
+
});
|
| 42 |
+
|
| 43 |
+
it("keep a setting another writer changed while the AI form is open", () => {
|
| 44 |
+
render(
|
| 45 |
+
<MantineProvider>
|
| 46 |
+
<AISettingsForm />
|
| 47 |
+
</MantineProvider>,
|
| 48 |
+
);
|
| 49 |
+
|
| 50 |
+
act(() =>
|
| 51 |
+
updateSettings({ ...getSettings(), wllamaModelId: "another-model" }),
|
| 52 |
+
);
|
| 53 |
+
toggle(/AI Response/);
|
| 54 |
+
|
| 55 |
+
expect(getSettings()).toMatchObject({
|
| 56 |
+
enableAiResponse: true,
|
| 57 |
+
wllamaModelId: "another-model",
|
| 58 |
+
});
|
| 59 |
+
});
|
| 60 |
+
});
|
client/components/Pages/Main/Menu/VoiceSettingsForm.test.tsx
CHANGED
|
@@ -168,7 +168,6 @@ describe("VoiceSettingsForm", () => {
|
|
| 168 |
|
| 169 |
expect(setSettings).toHaveBeenCalledWith(
|
| 170 |
expect.objectContaining({ enableLocalDictationModel: false }),
|
| 171 |
-
expect.anything(),
|
| 172 |
);
|
| 173 |
});
|
| 174 |
|
|
@@ -189,7 +188,6 @@ describe("VoiceSettingsForm", () => {
|
|
| 189 |
textToSpeechEngine: "system",
|
| 190 |
selectedVoiceId: "",
|
| 191 |
}),
|
| 192 |
-
expect.anything(),
|
| 193 |
);
|
| 194 |
expect((voiceInput() as HTMLInputElement).value).toBe("");
|
| 195 |
});
|
|
|
|
| 168 |
|
| 169 |
expect(setSettings).toHaveBeenCalledWith(
|
| 170 |
expect.objectContaining({ enableLocalDictationModel: false }),
|
|
|
|
| 171 |
);
|
| 172 |
});
|
| 173 |
|
|
|
|
| 188 |
textToSpeechEngine: "system",
|
| 189 |
selectedVoiceId: "",
|
| 190 |
}),
|
|
|
|
| 191 |
);
|
| 192 |
expect((voiceInput() as HTMLInputElement).value).toBe("");
|
| 193 |
});
|
client/components/Pages/Main/Menu/VoiceSettingsForm.tsx
CHANGED
|
@@ -6,10 +6,10 @@ import {
|
|
| 6 |
Switch,
|
| 7 |
Text,
|
| 8 |
} from "@mantine/core";
|
| 9 |
-
import { useForm } from "@mantine/form";
|
| 10 |
import getUnicodeFlagIcon from "country-flag-icons/unicode";
|
| 11 |
import { usePubSub } from "create-pubsub/react";
|
| 12 |
import { useCallback, useEffect, useState } from "react";
|
|
|
|
| 13 |
import { settingsPubSub } from "@/modules/pubSub";
|
| 14 |
import {
|
| 15 |
listVoices,
|
|
@@ -17,8 +17,15 @@ import {
|
|
| 17 |
type VoiceOption,
|
| 18 |
} from "@/modules/textToSpeech";
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
export default function VoiceSettingsForm() {
|
| 21 |
-
const [settings
|
| 22 |
const [voiceOptions, setVoiceOptions] = useState<VoiceOption[]>([]);
|
| 23 |
|
| 24 |
const getCountryFlag = useCallback((langCode: string) => {
|
|
@@ -33,10 +40,7 @@ export default function VoiceSettingsForm() {
|
|
| 33 |
}
|
| 34 |
}, []);
|
| 35 |
|
| 36 |
-
const form =
|
| 37 |
-
initialValues: settings,
|
| 38 |
-
onValuesChange: setSettings,
|
| 39 |
-
});
|
| 40 |
|
| 41 |
useEffect(() => {
|
| 42 |
let cancelled = false;
|
|
|
|
| 6 |
Switch,
|
| 7 |
Text,
|
| 8 |
} from "@mantine/core";
|
|
|
|
| 9 |
import getUnicodeFlagIcon from "country-flag-icons/unicode";
|
| 10 |
import { usePubSub } from "create-pubsub/react";
|
| 11 |
import { useCallback, useEffect, useState } from "react";
|
| 12 |
+
import { useSettingsForm } from "@/hooks/useSettingsForm";
|
| 13 |
import { settingsPubSub } from "@/modules/pubSub";
|
| 14 |
import {
|
| 15 |
listVoices,
|
|
|
|
| 17 |
type VoiceOption,
|
| 18 |
} from "@/modules/textToSpeech";
|
| 19 |
|
| 20 |
+
const SETTINGS_KEYS = [
|
| 21 |
+
"enableDictation",
|
| 22 |
+
"enableLocalDictationModel",
|
| 23 |
+
"textToSpeechEngine",
|
| 24 |
+
"selectedVoiceId",
|
| 25 |
+
] as const;
|
| 26 |
+
|
| 27 |
export default function VoiceSettingsForm() {
|
| 28 |
+
const [settings] = usePubSub(settingsPubSub);
|
| 29 |
const [voiceOptions, setVoiceOptions] = useState<VoiceOption[]>([]);
|
| 30 |
|
| 31 |
const getCountryFlag = useCallback((langCode: string) => {
|
|
|
|
| 40 |
}
|
| 41 |
}, []);
|
| 42 |
|
| 43 |
+
const form = useSettingsForm(SETTINGS_KEYS);
|
|
|
|
|
|
|
|
|
|
| 44 |
|
| 45 |
useEffect(() => {
|
| 46 |
let cancelled = false;
|
client/components/Search/Form/SearchForm.restore.test.tsx
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { MantineProvider } from "@mantine/core";
|
| 2 |
+
import { act, render, screen, waitFor } from "@testing-library/react";
|
| 3 |
+
import userEvent from "@testing-library/user-event";
|
| 4 |
+
import SearchForm from "@/components/Search/Form/SearchForm";
|
| 5 |
+
import { resetHandledQuery } from "@/modules/autoSearch";
|
| 6 |
+
import type { SearchEntry } from "@/modules/history";
|
| 7 |
+
import {
|
| 8 |
+
isRestoringFromHistoryPubSub,
|
| 9 |
+
updateResponse,
|
| 10 |
+
updateTextSearchResults,
|
| 11 |
+
updateTextSearchState,
|
| 12 |
+
} from "@/modules/pubSub";
|
| 13 |
+
import { sleep } from "@/modules/sleep";
|
| 14 |
+
import { searchAndRespond } from "@/modules/textGeneration";
|
| 15 |
+
|
| 16 |
+
const addToHistory = vi.fn();
|
| 17 |
+
const navigate = vi.fn((path: string) => {
|
| 18 |
+
window.history.replaceState({}, "", path);
|
| 19 |
+
});
|
| 20 |
+
|
| 21 |
+
/** The entry the history button hands to `restoreSearch` when clicked. */
|
| 22 |
+
let entryToRestore: SearchEntry = { query: "", timestamp: 0 };
|
| 23 |
+
|
| 24 |
+
vi.mock("wouter", () => ({
|
| 25 |
+
useLocation: () => ["/", navigate],
|
| 26 |
+
}));
|
| 27 |
+
|
| 28 |
+
vi.mock("@/hooks/useSearchHistory", () => ({
|
| 29 |
+
useSearchHistory: () => ({ addToHistory }),
|
| 30 |
+
}));
|
| 31 |
+
|
| 32 |
+
vi.mock("../History/HistoryButton", () => ({
|
| 33 |
+
default: function HistoryButton({
|
| 34 |
+
onSearchSelect,
|
| 35 |
+
}: {
|
| 36 |
+
onSearchSelect: (entry: SearchEntry) => void;
|
| 37 |
+
}) {
|
| 38 |
+
return (
|
| 39 |
+
<button type="button" onClick={() => onSearchSelect(entryToRestore)}>
|
| 40 |
+
Restore
|
| 41 |
+
</button>
|
| 42 |
+
);
|
| 43 |
+
},
|
| 44 |
+
}));
|
| 45 |
+
|
| 46 |
+
vi.mock("@/modules/textGeneration", () => ({
|
| 47 |
+
searchAndRespond: vi.fn(),
|
| 48 |
+
}));
|
| 49 |
+
|
| 50 |
+
vi.mock("@/modules/querySuggestions", () => ({
|
| 51 |
+
DEFAULT_QUERY_SUGGESTION: "Anything you need!",
|
| 52 |
+
getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"),
|
| 53 |
+
}));
|
| 54 |
+
|
| 55 |
+
vi.mock("@/modules/history", async (importOriginal) => ({
|
| 56 |
+
...(await importOriginal<typeof import("@/modules/history")>()),
|
| 57 |
+
getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),
|
| 58 |
+
getChatMessagesForQuery: vi.fn().mockResolvedValue([]),
|
| 59 |
+
}));
|
| 60 |
+
|
| 61 |
+
vi.mock("@/components/DictationButton", () => ({
|
| 62 |
+
dictationButtonWidth: 34,
|
| 63 |
+
default: () => null,
|
| 64 |
+
}));
|
| 65 |
+
|
| 66 |
+
function renderSearchForm(query = "") {
|
| 67 |
+
const updateQuery = vi.fn();
|
| 68 |
+
render(
|
| 69 |
+
<MantineProvider>
|
| 70 |
+
<SearchForm query={query} updateQuery={updateQuery} />
|
| 71 |
+
</MantineProvider>,
|
| 72 |
+
);
|
| 73 |
+
return updateQuery;
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
/**
|
| 77 |
+
* Clicks the history button, waits for the restore to finish and flushes the
|
| 78 |
+
* `sleepUntilIdle` tick the auto-search effect takes before acting.
|
| 79 |
+
*/
|
| 80 |
+
async function restore(entry: SearchEntry) {
|
| 81 |
+
entryToRestore = entry;
|
| 82 |
+
await userEvent
|
| 83 |
+
.setup()
|
| 84 |
+
.click(screen.getByRole("button", { name: "Restore" }));
|
| 85 |
+
await waitFor(() => expect(isRestoringFromHistoryPubSub[2]()).toBe(false));
|
| 86 |
+
await act(() => sleep(0));
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
describe("SearchForm with the real history restore", () => {
|
| 90 |
+
beforeEach(() => {
|
| 91 |
+
addToHistory.mockClear();
|
| 92 |
+
navigate.mockClear();
|
| 93 |
+
vi.mocked(searchAndRespond).mockClear();
|
| 94 |
+
resetHandledQuery();
|
| 95 |
+
updateTextSearchResults([]);
|
| 96 |
+
updateTextSearchState("idle");
|
| 97 |
+
updateResponse("");
|
| 98 |
+
window.history.replaceState({}, "", "/");
|
| 99 |
+
});
|
| 100 |
+
|
| 101 |
+
it("does not add a history entry or search when an empty entry is restored", async () => {
|
| 102 |
+
renderSearchForm();
|
| 103 |
+
await screen.findByRole("textbox");
|
| 104 |
+
|
| 105 |
+
await restore({ query: "failed search", timestamp: 1 });
|
| 106 |
+
|
| 107 |
+
expect(window.location.search).toBe("?q=failed%20search");
|
| 108 |
+
expect(screen.getByRole("textbox")).toHaveValue("failed search");
|
| 109 |
+
expect(addToHistory).not.toHaveBeenCalled();
|
| 110 |
+
expect(searchAndRespond).not.toHaveBeenCalled();
|
| 111 |
+
});
|
| 112 |
+
|
| 113 |
+
it("does not re-run the auto-search when results and response are cleared after a restore", async () => {
|
| 114 |
+
renderSearchForm();
|
| 115 |
+
await screen.findByRole("textbox");
|
| 116 |
+
await restore({
|
| 117 |
+
query: "saved search",
|
| 118 |
+
timestamp: 1,
|
| 119 |
+
textResults: {
|
| 120 |
+
type: "text",
|
| 121 |
+
items: [{ title: "Saved", snippet: "Saved", url: "https://e.com" }],
|
| 122 |
+
},
|
| 123 |
+
});
|
| 124 |
+
|
| 125 |
+
// Regenerate and "enable AI response" start by clearing the response and
|
| 126 |
+
// the results while the URL still holds the restored query.
|
| 127 |
+
act(() => {
|
| 128 |
+
updateResponse("");
|
| 129 |
+
updateTextSearchResults([]);
|
| 130 |
+
});
|
| 131 |
+
await act(() => sleep(0));
|
| 132 |
+
|
| 133 |
+
expect(addToHistory).not.toHaveBeenCalled();
|
| 134 |
+
expect(searchAndRespond).not.toHaveBeenCalled();
|
| 135 |
+
});
|
| 136 |
+
|
| 137 |
+
it("still adds one entry and runs one search when the restored query is submitted", async () => {
|
| 138 |
+
renderSearchForm();
|
| 139 |
+
await screen.findByRole("textbox");
|
| 140 |
+
await restore({ query: "failed search", timestamp: 1 });
|
| 141 |
+
|
| 142 |
+
await userEvent
|
| 143 |
+
.setup()
|
| 144 |
+
.click(screen.getByRole("button", { name: /search/i }));
|
| 145 |
+
await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1));
|
| 146 |
+
|
| 147 |
+
expect(addToHistory).toHaveBeenCalledTimes(1);
|
| 148 |
+
expect(addToHistory).toHaveBeenCalledWith("failed search", {
|
| 149 |
+
type: "text",
|
| 150 |
+
items: [],
|
| 151 |
+
});
|
| 152 |
+
});
|
| 153 |
+
|
| 154 |
+
it("still auto-searches a fresh URL query once", async () => {
|
| 155 |
+
window.history.replaceState({}, "", "/?q=fresh+load");
|
| 156 |
+
renderSearchForm("fresh load");
|
| 157 |
+
|
| 158 |
+
await waitFor(() => expect(searchAndRespond).toHaveBeenCalledTimes(1));
|
| 159 |
+
expect(addToHistory).toHaveBeenCalledTimes(1);
|
| 160 |
+
});
|
| 161 |
+
});
|
client/components/Search/Form/SearchForm.test.tsx
CHANGED
|
@@ -1,9 +1,10 @@
|
|
| 1 |
import { MantineProvider } from "@mantine/core";
|
| 2 |
import { act, render, screen, waitFor } from "@testing-library/react";
|
| 3 |
import userEvent from "@testing-library/user-event";
|
| 4 |
-
import SearchForm
|
| 5 |
-
|
| 6 |
-
} from "@/
|
|
|
|
| 7 |
import { searchAndRespond } from "@/modules/textGeneration";
|
| 8 |
|
| 9 |
vi.mock("create-pubsub/react", () => ({
|
|
@@ -48,6 +49,7 @@ vi.mock("../../../modules/textGeneration", () => ({
|
|
| 48 |
}));
|
| 49 |
|
| 50 |
vi.mock("../../../modules/querySuggestions", () => ({
|
|
|
|
| 51 |
getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"),
|
| 52 |
}));
|
| 53 |
|
|
@@ -88,7 +90,7 @@ const waitForPlaceholder = async () => {
|
|
| 88 |
describe("SearchForm component", () => {
|
| 89 |
beforeEach(() => {
|
| 90 |
vi.mocked(searchAndRespond).mockClear();
|
| 91 |
-
|
| 92 |
window.history.replaceState({}, "", "/");
|
| 93 |
});
|
| 94 |
|
|
@@ -98,6 +100,37 @@ describe("SearchForm component", () => {
|
|
| 98 |
await waitForPlaceholder();
|
| 99 |
});
|
| 100 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
it("calls updateQuery on submit", async () => {
|
| 102 |
const mockUpdate = vi.fn();
|
| 103 |
const user = userEvent.setup();
|
|
|
|
| 1 |
import { MantineProvider } from "@mantine/core";
|
| 2 |
import { act, render, screen, waitFor } from "@testing-library/react";
|
| 3 |
import userEvent from "@testing-library/user-event";
|
| 4 |
+
import SearchForm from "@/components/Search/Form/SearchForm";
|
| 5 |
+
import { resetHandledQuery } from "@/modules/autoSearch";
|
| 6 |
+
import { settingsPubSub } from "@/modules/pubSub";
|
| 7 |
+
import { defaultSettings } from "@/modules/settings";
|
| 8 |
import { searchAndRespond } from "@/modules/textGeneration";
|
| 9 |
|
| 10 |
vi.mock("create-pubsub/react", () => ({
|
|
|
|
| 49 |
}));
|
| 50 |
|
| 51 |
vi.mock("../../../modules/querySuggestions", () => ({
|
| 52 |
+
DEFAULT_QUERY_SUGGESTION: "Anything you need!",
|
| 53 |
getRandomQuerySuggestion: vi.fn(async () => "Anything you need!"),
|
| 54 |
}));
|
| 55 |
|
|
|
|
| 90 |
describe("SearchForm component", () => {
|
| 91 |
beforeEach(() => {
|
| 92 |
vi.mocked(searchAndRespond).mockClear();
|
| 93 |
+
resetHandledQuery();
|
| 94 |
window.history.replaceState({}, "", "/");
|
| 95 |
});
|
| 96 |
|
|
|
|
| 100 |
await waitForPlaceholder();
|
| 101 |
});
|
| 102 |
|
| 103 |
+
describe("Enter and Shift+Enter", () => {
|
| 104 |
+
afterEach(() => {
|
| 105 |
+
settingsPubSub[0]({ ...defaultSettings });
|
| 106 |
+
});
|
| 107 |
+
|
| 108 |
+
it.each([
|
| 109 |
+
[true, "{Enter}", true],
|
| 110 |
+
[true, "{Shift>}{Enter}{/Shift}", false],
|
| 111 |
+
[false, "{Shift>}{Enter}{/Shift}", true],
|
| 112 |
+
[false, "{Enter}", false],
|
| 113 |
+
])(
|
| 114 |
+
"with enterToSubmit %s, pressing %s submits: %s",
|
| 115 |
+
async (enterToSubmit, keys, submits) => {
|
| 116 |
+
settingsPubSub[0]({ ...defaultSettings, enterToSubmit });
|
| 117 |
+
const mockUpdate = vi.fn();
|
| 118 |
+
const user = userEvent.setup();
|
| 119 |
+
renderSearchForm("", mockUpdate);
|
| 120 |
+
|
| 121 |
+
const textarea = await waitForPlaceholder();
|
| 122 |
+
await user.type(textarea, "test query");
|
| 123 |
+
await user.keyboard(keys);
|
| 124 |
+
|
| 125 |
+
if (submits) {
|
| 126 |
+
expect(mockUpdate).toHaveBeenCalledWith("test query");
|
| 127 |
+
} else {
|
| 128 |
+
expect(mockUpdate).not.toHaveBeenCalled();
|
| 129 |
+
}
|
| 130 |
+
},
|
| 131 |
+
);
|
| 132 |
+
});
|
| 133 |
+
|
| 134 |
it("calls updateQuery on submit", async () => {
|
| 135 |
const mockUpdate = vi.fn();
|
| 136 |
const user = userEvent.setup();
|
client/components/Search/Form/SearchForm.tsx
CHANGED
|
@@ -16,18 +16,16 @@ import DictationButton, {
|
|
| 16 |
} from "@/components/DictationButton";
|
| 17 |
import { useHistoryRestore } from "@/hooks/useHistoryRestore";
|
| 18 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
|
|
|
| 19 |
import { resetSearchRunId } from "@/modules/history";
|
| 20 |
import { handleEnterKeyDown } from "@/modules/keyboard";
|
| 21 |
import { addLogEntry } from "@/modules/logEntries";
|
| 22 |
import { postMessageToParentWindow } from "@/modules/parentWindow";
|
|
|
|
| 23 |
import {
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
settingsPubSub,
|
| 28 |
-
textSearchResultsPubSub,
|
| 29 |
-
} from "@/modules/pubSub";
|
| 30 |
-
import { getRandomQuerySuggestion } from "@/modules/querySuggestions";
|
| 31 |
import { sleepUntilIdle } from "@/modules/sleep";
|
| 32 |
import { searchAndRespond } from "@/modules/textGeneration";
|
| 33 |
import HistoryButton from "../History/HistoryButton";
|
|
@@ -39,20 +37,6 @@ function getUrlQuery() {
|
|
| 39 |
return new URLSearchParams(window.location.search).get("q");
|
| 40 |
}
|
| 41 |
|
| 42 |
-
/**
|
| 43 |
-
* The query whose auto-search already ran. Module-level so it survives
|
| 44 |
-
* the remount when MainPage swaps HomePage for SearchForm as the query
|
| 45 |
-
* goes from empty to non-empty. Kept as a single slot (not a Set) so it
|
| 46 |
-
* suppresses only the most recent auto-search, matching the behavior the
|
| 47 |
-
* user expects when navigating back to a previously searched query.
|
| 48 |
-
*/
|
| 49 |
-
let autoSearchedQuery: string | null = null;
|
| 50 |
-
|
| 51 |
-
/** Exposed for tests to reset module state between runs. */
|
| 52 |
-
export function resetAutoSearchedQuery(): void {
|
| 53 |
-
autoSearchedQuery = null;
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
interface SearchFormState {
|
| 57 |
textAreaValue: string;
|
| 58 |
suggestedQuery: string;
|
|
@@ -81,18 +65,14 @@ export default memo(function SearchForm({
|
|
| 81 |
useEffect(() => {
|
| 82 |
pendingDictationRef.current = null;
|
| 83 |
});
|
| 84 |
-
const defaultSuggestedQuery = "Anything you need!";
|
| 85 |
const [state, setState] = useState<SearchFormState>({
|
| 86 |
textAreaValue: query,
|
| 87 |
-
suggestedQuery:
|
| 88 |
});
|
| 89 |
|
| 90 |
const [, navigate] = useLocation();
|
| 91 |
const [pubSubSettings] = usePubSub(settingsPubSub);
|
| 92 |
const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);
|
| 93 |
-
const [textSearchResults] = usePubSub(textSearchResultsPubSub);
|
| 94 |
-
const [imageSearchResults] = usePubSub(imageSearchResultsPubSub);
|
| 95 |
-
const [responseValue] = usePubSub(responsePubSub);
|
| 96 |
const { addToHistory } = useSearchHistory();
|
| 97 |
const { restoreSearch } = useHistoryRestore((newQuery) => {
|
| 98 |
setState((prev) => ({ ...prev, textAreaValue: newQuery }));
|
|
@@ -102,7 +82,7 @@ export default memo(function SearchForm({
|
|
| 102 |
try {
|
| 103 |
return await getRandomQuerySuggestion();
|
| 104 |
} catch {
|
| 105 |
-
return
|
| 106 |
}
|
| 107 |
}, []);
|
| 108 |
|
|
@@ -112,17 +92,12 @@ export default memo(function SearchForm({
|
|
| 112 |
const normalizedUrlQuery = urlQuery?.trim();
|
| 113 |
|
| 114 |
if (
|
|
|
|
| 115 |
normalizedUrlQuery &&
|
| 116 |
-
normalizedUrlQuery
|
| 117 |
!isRestoringFromHistory
|
| 118 |
) {
|
| 119 |
-
|
| 120 |
-
textSearchResults.length > 0 || imageSearchResults.length > 0;
|
| 121 |
-
const hasRestoredResponse = responseValue.trim().length > 0;
|
| 122 |
-
if (hasRestoredResults || hasRestoredResponse) return;
|
| 123 |
-
|
| 124 |
-
if (!urlQuery) return;
|
| 125 |
-
autoSearchedQuery = normalizedUrlQuery;
|
| 126 |
updateQuery(urlQuery);
|
| 127 |
setState((prevState) => ({
|
| 128 |
...prevState,
|
|
@@ -145,14 +120,7 @@ export default memo(function SearchForm({
|
|
| 145 |
};
|
| 146 |
|
| 147 |
void initializeComponent();
|
| 148 |
-
}, [
|
| 149 |
-
updateQuery,
|
| 150 |
-
isRestoringFromHistory,
|
| 151 |
-
textSearchResults.length,
|
| 152 |
-
imageSearchResults.length,
|
| 153 |
-
responseValue,
|
| 154 |
-
addToHistory,
|
| 155 |
-
]);
|
| 156 |
|
| 157 |
useEffect(() => {
|
| 158 |
if (state.textAreaValue.length === 0) {
|
|
@@ -163,7 +131,7 @@ export default memo(function SearchForm({
|
|
| 163 |
.catch(() => {
|
| 164 |
setState((prev) => ({
|
| 165 |
...prev,
|
| 166 |
-
suggestedQuery:
|
| 167 |
}));
|
| 168 |
});
|
| 169 |
}
|
|
@@ -182,7 +150,7 @@ export default memo(function SearchForm({
|
|
| 182 |
addLogEntry("Failed to get query suggestion");
|
| 183 |
setState((prev) => ({
|
| 184 |
...prev,
|
| 185 |
-
suggestedQuery:
|
| 186 |
}));
|
| 187 |
}
|
| 188 |
}
|
|
@@ -220,7 +188,7 @@ export default memo(function SearchForm({
|
|
| 220 |
const normalizedQuery = queryToEncode.trim();
|
| 221 |
|
| 222 |
if (normalizedQuery.length > 0) {
|
| 223 |
-
|
| 224 |
}
|
| 225 |
|
| 226 |
setState((prev) => ({ ...prev, textAreaValue: queryToEncode }));
|
|
@@ -260,9 +228,7 @@ export default memo(function SearchForm({
|
|
| 260 |
};
|
| 261 |
|
| 262 |
const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
| 263 |
-
|
| 264 |
-
handleEnterKeyDown(event, pubSubSettings, startSearching);
|
| 265 |
-
}
|
| 266 |
};
|
| 267 |
|
| 268 |
return (
|
|
|
|
| 16 |
} from "@/components/DictationButton";
|
| 17 |
import { useHistoryRestore } from "@/hooks/useHistoryRestore";
|
| 18 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
| 19 |
+
import { isQueryHandled, markQueryAsHandled } from "@/modules/autoSearch";
|
| 20 |
import { resetSearchRunId } from "@/modules/history";
|
| 21 |
import { handleEnterKeyDown } from "@/modules/keyboard";
|
| 22 |
import { addLogEntry } from "@/modules/logEntries";
|
| 23 |
import { postMessageToParentWindow } from "@/modules/parentWindow";
|
| 24 |
+
import { isRestoringFromHistoryPubSub, settingsPubSub } from "@/modules/pubSub";
|
| 25 |
import {
|
| 26 |
+
DEFAULT_QUERY_SUGGESTION,
|
| 27 |
+
getRandomQuerySuggestion,
|
| 28 |
+
} from "@/modules/querySuggestions";
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
import { sleepUntilIdle } from "@/modules/sleep";
|
| 30 |
import { searchAndRespond } from "@/modules/textGeneration";
|
| 31 |
import HistoryButton from "../History/HistoryButton";
|
|
|
|
| 37 |
return new URLSearchParams(window.location.search).get("q");
|
| 38 |
}
|
| 39 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
interface SearchFormState {
|
| 41 |
textAreaValue: string;
|
| 42 |
suggestedQuery: string;
|
|
|
|
| 65 |
useEffect(() => {
|
| 66 |
pendingDictationRef.current = null;
|
| 67 |
});
|
|
|
|
| 68 |
const [state, setState] = useState<SearchFormState>({
|
| 69 |
textAreaValue: query,
|
| 70 |
+
suggestedQuery: DEFAULT_QUERY_SUGGESTION,
|
| 71 |
});
|
| 72 |
|
| 73 |
const [, navigate] = useLocation();
|
| 74 |
const [pubSubSettings] = usePubSub(settingsPubSub);
|
| 75 |
const [isRestoringFromHistory] = usePubSub(isRestoringFromHistoryPubSub);
|
|
|
|
|
|
|
|
|
|
| 76 |
const { addToHistory } = useSearchHistory();
|
| 77 |
const { restoreSearch } = useHistoryRestore((newQuery) => {
|
| 78 |
setState((prev) => ({ ...prev, textAreaValue: newQuery }));
|
|
|
|
| 82 |
try {
|
| 83 |
return await getRandomQuerySuggestion();
|
| 84 |
} catch {
|
| 85 |
+
return DEFAULT_QUERY_SUGGESTION;
|
| 86 |
}
|
| 87 |
}, []);
|
| 88 |
|
|
|
|
| 92 |
const normalizedUrlQuery = urlQuery?.trim();
|
| 93 |
|
| 94 |
if (
|
| 95 |
+
urlQuery &&
|
| 96 |
normalizedUrlQuery &&
|
| 97 |
+
!isQueryHandled(normalizedUrlQuery) &&
|
| 98 |
!isRestoringFromHistory
|
| 99 |
) {
|
| 100 |
+
markQueryAsHandled(normalizedUrlQuery);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
updateQuery(urlQuery);
|
| 102 |
setState((prevState) => ({
|
| 103 |
...prevState,
|
|
|
|
| 120 |
};
|
| 121 |
|
| 122 |
void initializeComponent();
|
| 123 |
+
}, [updateQuery, isRestoringFromHistory, addToHistory]);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
useEffect(() => {
|
| 126 |
if (state.textAreaValue.length === 0) {
|
|
|
|
| 131 |
.catch(() => {
|
| 132 |
setState((prev) => ({
|
| 133 |
...prev,
|
| 134 |
+
suggestedQuery: DEFAULT_QUERY_SUGGESTION,
|
| 135 |
}));
|
| 136 |
});
|
| 137 |
}
|
|
|
|
| 150 |
addLogEntry("Failed to get query suggestion");
|
| 151 |
setState((prev) => ({
|
| 152 |
...prev,
|
| 153 |
+
suggestedQuery: DEFAULT_QUERY_SUGGESTION,
|
| 154 |
}));
|
| 155 |
}
|
| 156 |
}
|
|
|
|
| 188 |
const normalizedQuery = queryToEncode.trim();
|
| 189 |
|
| 190 |
if (normalizedQuery.length > 0) {
|
| 191 |
+
markQueryAsHandled(normalizedQuery);
|
| 192 |
}
|
| 193 |
|
| 194 |
setState((prev) => ({ ...prev, textAreaValue: queryToEncode }));
|
|
|
|
| 228 |
};
|
| 229 |
|
| 230 |
const handleKeyDown = (event: KeyboardEvent<HTMLTextAreaElement>) => {
|
| 231 |
+
handleEnterKeyDown(event, pubSubSettings, startSearching);
|
|
|
|
|
|
|
| 232 |
};
|
| 233 |
|
| 234 |
return (
|
client/components/Search/History/HistoryDrawer.test.tsx
CHANGED
|
@@ -141,6 +141,44 @@ describe("HistoryDrawer component", () => {
|
|
| 141 |
expect(onSearchSelect).toHaveBeenCalledWith(entry);
|
| 142 |
});
|
| 143 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 144 |
it("pins an entry without selecting it", async () => {
|
| 145 |
const onSearchSelect = vi.fn();
|
| 146 |
const entry = makeEntry(1, "quantum tunneling");
|
|
|
|
| 141 |
expect(onSearchSelect).toHaveBeenCalledWith(entry);
|
| 142 |
});
|
| 143 |
|
| 144 |
+
it("selects an entry once when its query is clicked", async () => {
|
| 145 |
+
const onSearchSelect = vi.fn();
|
| 146 |
+
const entry = makeEntry(1, "quantum tunneling");
|
| 147 |
+
mockHistory({ filteredSearches: [entry] });
|
| 148 |
+
|
| 149 |
+
const user = userEvent.setup();
|
| 150 |
+
renderDrawer(onSearchSelect);
|
| 151 |
+
await user.click(
|
| 152 |
+
await screen.findByRole("button", { name: /quantum tunneling/ }),
|
| 153 |
+
);
|
| 154 |
+
|
| 155 |
+
expect(onSearchSelect).toHaveBeenCalledTimes(1);
|
| 156 |
+
expect(onSearchSelect).toHaveBeenCalledWith(entry);
|
| 157 |
+
});
|
| 158 |
+
|
| 159 |
+
it("selects an entry from the keyboard", async () => {
|
| 160 |
+
const onSearchSelect = vi.fn();
|
| 161 |
+
const entry = makeEntry(1, "quantum tunneling");
|
| 162 |
+
mockHistory({ filteredSearches: [entry] });
|
| 163 |
+
|
| 164 |
+
const user = userEvent.setup();
|
| 165 |
+
renderDrawer(onSearchSelect);
|
| 166 |
+
const queryButton = await screen.findByRole("button", {
|
| 167 |
+
name: /quantum tunneling/,
|
| 168 |
+
});
|
| 169 |
+
|
| 170 |
+
for (let i = 0; i < 10 && document.activeElement !== queryButton; i++) {
|
| 171 |
+
await user.tab();
|
| 172 |
+
}
|
| 173 |
+
expect(queryButton).toHaveFocus();
|
| 174 |
+
|
| 175 |
+
await user.keyboard("{Enter}");
|
| 176 |
+
await user.keyboard(" ");
|
| 177 |
+
|
| 178 |
+
expect(onSearchSelect).toHaveBeenCalledTimes(2);
|
| 179 |
+
expect(onSearchSelect).toHaveBeenCalledWith(entry);
|
| 180 |
+
});
|
| 181 |
+
|
| 182 |
it("pins an entry without selecting it", async () => {
|
| 183 |
const onSearchSelect = vi.fn();
|
| 184 |
const entry = makeEntry(1, "quantum tunneling");
|
client/components/Search/History/HistoryDrawer.tsx
CHANGED
|
@@ -12,6 +12,7 @@ import {
|
|
| 12 |
Text,
|
| 13 |
TextInput,
|
| 14 |
Tooltip,
|
|
|
|
| 15 |
} from "@mantine/core";
|
| 16 |
import { useReducedMotion } from "@mantine/hooks";
|
| 17 |
import {
|
|
@@ -95,22 +96,30 @@ export default function HistoryDrawer({
|
|
| 95 |
onClick={() => handleSearchSelect(search)}
|
| 96 |
>
|
| 97 |
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
| 98 |
-
<
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
|
|
|
| 114 |
|
| 115 |
<Group gap="xs" style={{ flexShrink: 0 }}>
|
| 116 |
<ActionIcon
|
|
|
|
| 12 |
Text,
|
| 13 |
TextInput,
|
| 14 |
Tooltip,
|
| 15 |
+
UnstyledButton,
|
| 16 |
} from "@mantine/core";
|
| 17 |
import { useReducedMotion } from "@mantine/hooks";
|
| 18 |
import {
|
|
|
|
| 96 |
onClick={() => handleSearchSelect(search)}
|
| 97 |
>
|
| 98 |
<Group justify="space-between" align="flex-start" wrap="nowrap">
|
| 99 |
+
<UnstyledButton
|
| 100 |
+
onClick={(e) => {
|
| 101 |
+
e.stopPropagation();
|
| 102 |
+
handleSearchSelect(search);
|
| 103 |
+
}}
|
| 104 |
+
style={{ flex: 1, minWidth: 0, textAlign: "left" }}
|
| 105 |
+
>
|
| 106 |
+
<Stack gap={2}>
|
| 107 |
+
<Tooltip label={search.query} multiline withArrow>
|
| 108 |
+
<Text size="sm" fw={search.pinned ? 600 : 400} truncate>
|
| 109 |
+
{search.query}
|
| 110 |
+
</Text>
|
| 111 |
+
</Tooltip>
|
| 112 |
|
| 113 |
+
<Text
|
| 114 |
+
size="xs"
|
| 115 |
+
c="dimmed"
|
| 116 |
+
style={{ display: "flex", alignItems: "center", gap: 4 }}
|
| 117 |
+
>
|
| 118 |
+
<IconClock size={12} />
|
| 119 |
+
{formatRelativeTime(search.timestamp)}
|
| 120 |
+
</Text>
|
| 121 |
+
</Stack>
|
| 122 |
+
</UnstyledButton>
|
| 123 |
|
| 124 |
<Group gap="xs" style={{ flexShrink: 0 }}>
|
| 125 |
<ActionIcon
|
client/components/Settings/HistorySettings.tsx
CHANGED
|
@@ -8,21 +8,25 @@ import {
|
|
| 8 |
Switch,
|
| 9 |
Text,
|
| 10 |
} from "@mantine/core";
|
| 11 |
-
import { useForm } from "@mantine/form";
|
| 12 |
import { notifications } from "@mantine/notifications";
|
| 13 |
import { IconInfoCircle } from "@tabler/icons-react";
|
| 14 |
-
import { usePubSub } from "create-pubsub/react";
|
| 15 |
import { useState } from "react";
|
| 16 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
|
|
|
| 17 |
import { addLogEntry } from "@/modules/logEntries";
|
| 18 |
-
import { settingsPubSub } from "@/modules/pubSub";
|
| 19 |
|
| 20 |
interface HistorySettingsProps {
|
| 21 |
onClose?: () => void;
|
| 22 |
}
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
export default function HistorySettings({ onClose }: HistorySettingsProps) {
|
| 25 |
-
const [settings, setSettings] = usePubSub(settingsPubSub);
|
| 26 |
const { recentSearches, llmResponseCount, chatMessageCount, clearAll } =
|
| 27 |
useSearchHistory();
|
| 28 |
const [showClearConfirm, setShowClearConfirm] = useState(false);
|
|
@@ -30,20 +34,7 @@ export default function HistorySettings({ onClose }: HistorySettingsProps) {
|
|
| 30 |
const hasHistory =
|
| 31 |
recentSearches.length > 0 || llmResponseCount > 0 || chatMessageCount > 0;
|
| 32 |
|
| 33 |
-
const form =
|
| 34 |
-
initialValues: {
|
| 35 |
-
enableHistory: settings.enableHistory,
|
| 36 |
-
historyMaxEntries: settings.historyMaxEntries,
|
| 37 |
-
historyAutoCleanup: settings.historyAutoCleanup,
|
| 38 |
-
historyRetentionDays: settings.historyRetentionDays,
|
| 39 |
-
},
|
| 40 |
-
onValuesChange: (values) => {
|
| 41 |
-
setSettings({
|
| 42 |
-
...settings,
|
| 43 |
-
...values,
|
| 44 |
-
});
|
| 45 |
-
},
|
| 46 |
-
});
|
| 47 |
|
| 48 |
const handleClearHistory = async () => {
|
| 49 |
try {
|
|
|
|
| 8 |
Switch,
|
| 9 |
Text,
|
| 10 |
} from "@mantine/core";
|
|
|
|
| 11 |
import { notifications } from "@mantine/notifications";
|
| 12 |
import { IconInfoCircle } from "@tabler/icons-react";
|
|
|
|
| 13 |
import { useState } from "react";
|
| 14 |
import { useSearchHistory } from "@/hooks/useSearchHistory";
|
| 15 |
+
import { useSettingsForm } from "@/hooks/useSettingsForm";
|
| 16 |
import { addLogEntry } from "@/modules/logEntries";
|
|
|
|
| 17 |
|
| 18 |
interface HistorySettingsProps {
|
| 19 |
onClose?: () => void;
|
| 20 |
}
|
| 21 |
|
| 22 |
+
const SETTINGS_KEYS = [
|
| 23 |
+
"enableHistory",
|
| 24 |
+
"historyMaxEntries",
|
| 25 |
+
"historyAutoCleanup",
|
| 26 |
+
"historyRetentionDays",
|
| 27 |
+
] as const;
|
| 28 |
+
|
| 29 |
export default function HistorySettings({ onClose }: HistorySettingsProps) {
|
|
|
|
| 30 |
const { recentSearches, llmResponseCount, chatMessageCount, clearAll } =
|
| 31 |
useSearchHistory();
|
| 32 |
const [showClearConfirm, setShowClearConfirm] = useState(false);
|
|
|
|
| 34 |
const hasHistory =
|
| 35 |
recentSearches.length > 0 || llmResponseCount > 0 || chatMessageCount > 0;
|
| 36 |
|
| 37 |
+
const form = useSettingsForm(SETTINGS_KEYS);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
const handleClearHistory = async () => {
|
| 40 |
try {
|
client/hooks/useHistoryRestore.test.ts
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { act, cleanup, renderHook } from "@testing-library/react";
|
| 2 |
+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
| 3 |
+
import type { ImageResults, SearchEntry, TextResults } from "@/modules/history";
|
| 4 |
+
import { getLatestLlmResponseForEntry } from "@/modules/history";
|
| 5 |
+
import {
|
| 6 |
+
getLlmTextSearchResults,
|
| 7 |
+
getSuppressNextFollowUp,
|
| 8 |
+
imageSearchResultsPubSub,
|
| 9 |
+
imageSearchStatePubSub,
|
| 10 |
+
textSearchResultsPubSub,
|
| 11 |
+
updateImageSearchResults,
|
| 12 |
+
updateSuppressNextFollowUp,
|
| 13 |
+
} from "@/modules/pubSub";
|
| 14 |
+
import { useHistoryRestore } from "./useHistoryRestore";
|
| 15 |
+
|
| 16 |
+
vi.mock("wouter", () => ({
|
| 17 |
+
useLocation: () => ["/", vi.fn()],
|
| 18 |
+
}));
|
| 19 |
+
|
| 20 |
+
vi.mock("@/modules/logEntries", () => ({ addLogEntry: vi.fn() }));
|
| 21 |
+
|
| 22 |
+
vi.mock("@/modules/history", async (importOriginal) => ({
|
| 23 |
+
...(await importOriginal<typeof import("@/modules/history")>()),
|
| 24 |
+
getLatestLlmResponseForEntry: vi.fn().mockResolvedValue(null),
|
| 25 |
+
getChatMessagesForQuery: vi.fn().mockResolvedValue([]),
|
| 26 |
+
}));
|
| 27 |
+
|
| 28 |
+
const textResults: TextResults = {
|
| 29 |
+
type: "text",
|
| 30 |
+
items: [
|
| 31 |
+
{
|
| 32 |
+
title: "Saved text",
|
| 33 |
+
snippet: "Saved snippet",
|
| 34 |
+
url: "https://example.com/text",
|
| 35 |
+
},
|
| 36 |
+
],
|
| 37 |
+
};
|
| 38 |
+
|
| 39 |
+
const imageResults: ImageResults = {
|
| 40 |
+
type: "image",
|
| 41 |
+
items: [
|
| 42 |
+
{
|
| 43 |
+
title: "Saved image",
|
| 44 |
+
url: "https://example.com/image.png",
|
| 45 |
+
thumbnail: "https://example.com/thumbnail.png",
|
| 46 |
+
sourceUrl: "https://example.com/source",
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
title: "Image without a source",
|
| 50 |
+
url: "https://example.com/other.png",
|
| 51 |
+
thumbnail: "https://example.com/other-thumbnail.png",
|
| 52 |
+
},
|
| 53 |
+
],
|
| 54 |
+
};
|
| 55 |
+
|
| 56 |
+
const expectedImages = [
|
| 57 |
+
[
|
| 58 |
+
"Saved image",
|
| 59 |
+
"https://example.com/image.png",
|
| 60 |
+
"https://example.com/thumbnail.png",
|
| 61 |
+
"https://example.com/source",
|
| 62 |
+
],
|
| 63 |
+
[
|
| 64 |
+
"Image without a source",
|
| 65 |
+
"https://example.com/other.png",
|
| 66 |
+
"https://example.com/other-thumbnail.png",
|
| 67 |
+
"",
|
| 68 |
+
],
|
| 69 |
+
];
|
| 70 |
+
|
| 71 |
+
beforeEach(() => {
|
| 72 |
+
vi.useFakeTimers();
|
| 73 |
+
vi.mocked(getLatestLlmResponseForEntry).mockResolvedValue(null);
|
| 74 |
+
updateSuppressNextFollowUp(false);
|
| 75 |
+
updateImageSearchResults([
|
| 76 |
+
["Previous image", "old.png", "old-thumb.png", ""],
|
| 77 |
+
]);
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
afterEach(() => {
|
| 81 |
+
cleanup();
|
| 82 |
+
vi.runOnlyPendingTimers();
|
| 83 |
+
vi.useRealTimers();
|
| 84 |
+
});
|
| 85 |
+
|
| 86 |
+
async function restoreEntry(payload: Partial<SearchEntry>) {
|
| 87 |
+
const { result } = renderHook(() => useHistoryRestore(vi.fn()));
|
| 88 |
+
await act(async () => {
|
| 89 |
+
await result.current.restoreSearch({
|
| 90 |
+
query: "saved search",
|
| 91 |
+
timestamp: 1,
|
| 92 |
+
...payload,
|
| 93 |
+
});
|
| 94 |
+
});
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
describe("useHistoryRestore", () => {
|
| 98 |
+
it("restores both text and images from the same search", async () => {
|
| 99 |
+
await restoreEntry({ results: textResults, textResults, imageResults });
|
| 100 |
+
|
| 101 |
+
expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages);
|
| 102 |
+
const expectedText = [
|
| 103 |
+
["Saved text", "Saved snippet", "https://example.com/text"],
|
| 104 |
+
];
|
| 105 |
+
expect(textSearchResultsPubSub[2]()).toEqual(expectedText);
|
| 106 |
+
expect(getLlmTextSearchResults()).toEqual(expectedText);
|
| 107 |
+
expect(imageSearchStatePubSub[2]()).toBe("completed");
|
| 108 |
+
});
|
| 109 |
+
|
| 110 |
+
it.each([
|
| 111 |
+
{ name: "image-only entry", payload: { imageResults } },
|
| 112 |
+
{ name: "legacy image-only entry", payload: { results: imageResults } },
|
| 113 |
+
{
|
| 114 |
+
name: "legacy images alongside newer text results",
|
| 115 |
+
payload: { textResults, results: imageResults },
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
name: "newer images alongside an empty legacy image payload",
|
| 119 |
+
payload: {
|
| 120 |
+
imageResults,
|
| 121 |
+
results: { type: "image", items: [] } as ImageResults,
|
| 122 |
+
},
|
| 123 |
+
},
|
| 124 |
+
])("restores $name", async ({ payload }) => {
|
| 125 |
+
await restoreEntry(payload);
|
| 126 |
+
|
| 127 |
+
expect(imageSearchResultsPubSub[2]()).toEqual(expectedImages);
|
| 128 |
+
expect(imageSearchStatePubSub[2]()).toBe("completed");
|
| 129 |
+
});
|
| 130 |
+
|
| 131 |
+
it("clears previous images when the saved search has none", async () => {
|
| 132 |
+
await restoreEntry({ textResults });
|
| 133 |
+
|
| 134 |
+
expect(imageSearchResultsPubSub[2]()).toEqual([]);
|
| 135 |
+
expect(imageSearchStatePubSub[2]()).toBe("completed");
|
| 136 |
+
});
|
| 137 |
+
|
| 138 |
+
it("leaves suppressNextFollowUp false when the restored entry has no saved response", async () => {
|
| 139 |
+
await restoreEntry({ textResults });
|
| 140 |
+
|
| 141 |
+
expect(getSuppressNextFollowUp()).toBe(false);
|
| 142 |
+
});
|
| 143 |
+
|
| 144 |
+
it("sets suppressNextFollowUp true when the restored entry has a saved response", async () => {
|
| 145 |
+
vi.mocked(getLatestLlmResponseForEntry).mockResolvedValueOnce(
|
| 146 |
+
"Saved AI answer.",
|
| 147 |
+
);
|
| 148 |
+
|
| 149 |
+
await restoreEntry({ textResults });
|
| 150 |
+
|
| 151 |
+
expect(getSuppressNextFollowUp()).toBe(true);
|
| 152 |
+
});
|
| 153 |
+
});
|
client/hooks/useHistoryRestore.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import { useCallback } from "react";
|
| 2 |
import { useLocation } from "wouter";
|
|
|
|
| 3 |
import type { SearchEntry } from "../modules/history";
|
| 4 |
import {
|
| 5 |
getChatMessagesForQuery,
|
|
@@ -38,13 +39,17 @@ export function useHistoryRestore(
|
|
| 38 |
const restoreSearch = useCallback(
|
| 39 |
async (entry: SearchEntry) => {
|
| 40 |
const selectedQuery = entry.query;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
updateQuery(selectedQuery);
|
| 42 |
|
| 43 |
const searchRunId = entry.searchRunId || entry.query;
|
| 44 |
setCurrentSearchRunId(searchRunId);
|
| 45 |
|
| 46 |
updateIsRestoringFromHistory(true);
|
| 47 |
-
updateSuppressNextFollowUp(true);
|
| 48 |
// Excerpts belong to the search that fetched them; a follow-up on the
|
| 49 |
// restored entry must not be grounded on the live search's pages.
|
| 50 |
updatePageContents({});
|
|
@@ -81,7 +86,9 @@ export function useHistoryRestore(
|
|
| 81 |
}
|
| 82 |
|
| 83 |
if (hasImageResults(entry)) {
|
| 84 |
-
const results =
|
|
|
|
|
|
|
| 85 |
if (results && results.type === "image") {
|
| 86 |
const imageTuples: ImageSearchResults = results.items.map((it) => [
|
| 87 |
it.title,
|
|
@@ -102,9 +109,11 @@ export function useHistoryRestore(
|
|
| 102 |
|
| 103 |
const savedResponse = await getLatestLlmResponseForEntry(entry);
|
| 104 |
if (savedResponse && savedResponse.trim().length > 0) {
|
|
|
|
| 105 |
updateResponse(savedResponse);
|
| 106 |
updateTextGenerationState("completed");
|
| 107 |
} else {
|
|
|
|
| 108 |
updateResponse("");
|
| 109 |
updateTextGenerationState("idle");
|
| 110 |
}
|
|
|
|
| 1 |
import { useCallback } from "react";
|
| 2 |
import { useLocation } from "wouter";
|
| 3 |
+
import { markQueryAsHandled } from "../modules/autoSearch";
|
| 4 |
import type { SearchEntry } from "../modules/history";
|
| 5 |
import {
|
| 6 |
getChatMessagesForQuery,
|
|
|
|
| 39 |
const restoreSearch = useCallback(
|
| 40 |
async (entry: SearchEntry) => {
|
| 41 |
const selectedQuery = entry.query;
|
| 42 |
+
// The URL is about to hold this query; without the mark, an entry that
|
| 43 |
+
// restores empty would fall through to the URL auto-search once
|
| 44 |
+
// isRestoringFromHistory flips back, appending a duplicate history
|
| 45 |
+
// entry and starting a live search.
|
| 46 |
+
markQueryAsHandled(selectedQuery);
|
| 47 |
updateQuery(selectedQuery);
|
| 48 |
|
| 49 |
const searchRunId = entry.searchRunId || entry.query;
|
| 50 |
setCurrentSearchRunId(searchRunId);
|
| 51 |
|
| 52 |
updateIsRestoringFromHistory(true);
|
|
|
|
| 53 |
// Excerpts belong to the search that fetched them; a follow-up on the
|
| 54 |
// restored entry must not be grounded on the live search's pages.
|
| 55 |
updatePageContents({});
|
|
|
|
| 86 |
}
|
| 87 |
|
| 88 |
if (hasImageResults(entry)) {
|
| 89 |
+
const results =
|
| 90 |
+
entry.imageResults ??
|
| 91 |
+
(entry.results?.type === "image" ? entry.results : null);
|
| 92 |
if (results && results.type === "image") {
|
| 93 |
const imageTuples: ImageSearchResults = results.items.map((it) => [
|
| 94 |
it.title,
|
|
|
|
| 109 |
|
| 110 |
const savedResponse = await getLatestLlmResponseForEntry(entry);
|
| 111 |
if (savedResponse && savedResponse.trim().length > 0) {
|
| 112 |
+
updateSuppressNextFollowUp(true);
|
| 113 |
updateResponse(savedResponse);
|
| 114 |
updateTextGenerationState("completed");
|
| 115 |
} else {
|
| 116 |
+
updateSuppressNextFollowUp(false);
|
| 117 |
updateResponse("");
|
| 118 |
updateTextGenerationState("idle");
|
| 119 |
}
|
client/hooks/useSearchHistory.test.ts
CHANGED
|
@@ -7,6 +7,7 @@ import {
|
|
| 7 |
type SearchEntry,
|
| 8 |
type TextResults,
|
| 9 |
} from "@/modules/history";
|
|
|
|
| 10 |
import * as stringFormatters from "@/modules/stringFormatters";
|
| 11 |
import {
|
| 12 |
FILTER_DEBOUNCE_MS,
|
|
@@ -83,6 +84,33 @@ async function settle() {
|
|
| 83 |
}
|
| 84 |
|
| 85 |
describe("useSearchHistory", () => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
it("reads IndexedDB only on load, never while typing", async () => {
|
| 87 |
const readSpy = vi.spyOn(historyModule, "getRecentSearches");
|
| 88 |
|
|
@@ -223,6 +251,58 @@ describe("useSearchHistory", () => {
|
|
| 223 |
expect(result.current.filteredSearches).toHaveLength(SEEDED_QUERIES.length);
|
| 224 |
});
|
| 225 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 226 |
it("paginates from memory: page changes and queries trigger no reads", async () => {
|
| 227 |
await addSearchToHistory("wine tasting porto", textResults);
|
| 228 |
vi.advanceTimersByTime(1000);
|
|
|
|
| 7 |
type SearchEntry,
|
| 8 |
type TextResults,
|
| 9 |
} from "@/modules/history";
|
| 10 |
+
import { getSettings } from "@/modules/pubSub";
|
| 11 |
import * as stringFormatters from "@/modules/stringFormatters";
|
| 12 |
import {
|
| 13 |
FILTER_DEBOUNCE_MS,
|
|
|
|
| 84 |
}
|
| 85 |
|
| 86 |
describe("useSearchHistory", () => {
|
| 87 |
+
it("leaves IndexedDB alone while history is turned off", async () => {
|
| 88 |
+
const settingsMock = vi.mocked(getSettings);
|
| 89 |
+
const historyOn = settingsMock.getMockImplementation();
|
| 90 |
+
settingsMock.mockImplementation(
|
| 91 |
+
() =>
|
| 92 |
+
({
|
| 93 |
+
...historyOn?.(),
|
| 94 |
+
enableHistory: false,
|
| 95 |
+
}) as ReturnType<typeof getSettings>,
|
| 96 |
+
);
|
| 97 |
+
const readSpy = vi.spyOn(historyModule, "getRecentSearches");
|
| 98 |
+
|
| 99 |
+
try {
|
| 100 |
+
const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
|
| 101 |
+
await settle();
|
| 102 |
+
await act(async () => {
|
| 103 |
+
await vi.advanceTimersByTimeAsync(REFRESH_INTERVAL_MS);
|
| 104 |
+
});
|
| 105 |
+
|
| 106 |
+
expect(readSpy).not.toHaveBeenCalled();
|
| 107 |
+
expect(result.current.isLoading).toBe(false);
|
| 108 |
+
expect(result.current.recentSearches).toEqual([]);
|
| 109 |
+
} finally {
|
| 110 |
+
if (historyOn) settingsMock.mockImplementation(historyOn);
|
| 111 |
+
}
|
| 112 |
+
});
|
| 113 |
+
|
| 114 |
it("reads IndexedDB only on load, never while typing", async () => {
|
| 115 |
const readSpy = vi.spyOn(historyModule, "getRecentSearches");
|
| 116 |
|
|
|
|
| 251 |
expect(result.current.filteredSearches).toHaveLength(SEEDED_QUERIES.length);
|
| 252 |
});
|
| 253 |
|
| 254 |
+
it("deletes an entry's answer and chat with it and leaves the other entries' rows", async () => {
|
| 255 |
+
// Seeding shares one search run; give each entry its own, as separate
|
| 256 |
+
// searches have, with an answer and a chat turn stored under it.
|
| 257 |
+
const entries = await historyDatabase.searches.toArray();
|
| 258 |
+
for (const entry of entries) {
|
| 259 |
+
const runId = `run-${entry.id}`;
|
| 260 |
+
await historyDatabase.searches.update(entry.id as number, {
|
| 261 |
+
searchRunId: runId,
|
| 262 |
+
});
|
| 263 |
+
await historyDatabase.llmResponses.add({
|
| 264 |
+
searchRunId: runId,
|
| 265 |
+
searchId: entry.id,
|
| 266 |
+
prompt: entry.query,
|
| 267 |
+
response: "answer",
|
| 268 |
+
model: "m",
|
| 269 |
+
timestamp: Date.now(),
|
| 270 |
+
});
|
| 271 |
+
await historyDatabase.chatHistory.add({
|
| 272 |
+
role: "user",
|
| 273 |
+
content: "chat",
|
| 274 |
+
timestamp: Date.now(),
|
| 275 |
+
conversationId: runId,
|
| 276 |
+
});
|
| 277 |
+
}
|
| 278 |
+
const { result } = renderHook(() => useSearchHistory({ limit: 100 }));
|
| 279 |
+
await settle();
|
| 280 |
+
|
| 281 |
+
const [target] = entries;
|
| 282 |
+
await act(async () => {
|
| 283 |
+
await result.current.deleteEntry(target.id as number);
|
| 284 |
+
});
|
| 285 |
+
|
| 286 |
+
const targetRun = `run-${target.id}`;
|
| 287 |
+
expect(await historyDatabase.searches.get(target.id as number)).toBe(
|
| 288 |
+
undefined,
|
| 289 |
+
);
|
| 290 |
+
expect(
|
| 291 |
+
await historyDatabase.llmResponses
|
| 292 |
+
.where("searchRunId")
|
| 293 |
+
.equals(targetRun)
|
| 294 |
+
.count(),
|
| 295 |
+
).toBe(0);
|
| 296 |
+
expect(
|
| 297 |
+
await historyDatabase.chatHistory
|
| 298 |
+
.where("conversationId")
|
| 299 |
+
.equals(targetRun)
|
| 300 |
+
.count(),
|
| 301 |
+
).toBe(0);
|
| 302 |
+
expect(await historyDatabase.llmResponses.count()).toBe(entries.length - 1);
|
| 303 |
+
expect(await historyDatabase.chatHistory.count()).toBe(entries.length - 1);
|
| 304 |
+
});
|
| 305 |
+
|
| 306 |
it("paginates from memory: page changes and queries trigger no reads", async () => {
|
| 307 |
await addSearchToHistory("wine tasting porto", textResults);
|
| 308 |
vi.advanceTimersByTime(1000);
|
client/hooks/useSearchHistory.ts
CHANGED
|
@@ -5,6 +5,7 @@ import {
|
|
| 5 |
getRecentSearches,
|
| 6 |
historyDatabase,
|
| 7 |
type ImageResults,
|
|
|
|
| 8 |
type SearchEntry,
|
| 9 |
type TextResults,
|
| 10 |
} from "../modules/history";
|
|
@@ -94,6 +95,15 @@ export function useSearchHistory(
|
|
| 94 |
setIsLoading(true);
|
| 95 |
setError(null);
|
| 96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
const searches = await getRecentSearches(
|
| 98 |
enablePagination ? 1000 : limit * 2,
|
| 99 |
);
|
|
@@ -234,7 +244,9 @@ export function useSearchHistory(
|
|
| 234 |
async (searchId: number) => {
|
| 235 |
try {
|
| 236 |
const search = await historyDatabase.searches.get(searchId);
|
| 237 |
-
|
|
|
|
|
|
|
| 238 |
await refreshHistory();
|
| 239 |
|
| 240 |
if (search) {
|
|
|
|
| 5 |
getRecentSearches,
|
| 6 |
historyDatabase,
|
| 7 |
type ImageResults,
|
| 8 |
+
isHistoryEnabled,
|
| 9 |
type SearchEntry,
|
| 10 |
type TextResults,
|
| 11 |
} from "../modules/history";
|
|
|
|
| 95 |
setIsLoading(true);
|
| 96 |
setError(null);
|
| 97 |
|
| 98 |
+
// Reading would open the database too, so a disabled history is shown
|
| 99 |
+
// as empty without touching IndexedDB.
|
| 100 |
+
if (!isHistoryEnabled()) {
|
| 101 |
+
setLlmResponseCount(0);
|
| 102 |
+
setChatMessageCount(0);
|
| 103 |
+
setEntries([]);
|
| 104 |
+
return;
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
const searches = await getRecentSearches(
|
| 108 |
enablePagination ? 1000 : limit * 2,
|
| 109 |
);
|
|
|
|
| 244 |
async (searchId: number) => {
|
| 245 |
try {
|
| 246 |
const search = await historyDatabase.searches.get(searchId);
|
| 247 |
+
if (search) {
|
| 248 |
+
await historyDatabase.deleteSearchesWithChildren([search]);
|
| 249 |
+
}
|
| 250 |
await refreshHistory();
|
| 251 |
|
| 252 |
if (search) {
|
client/hooks/useSettingsForm.test.ts
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { act, renderHook } from "@testing-library/react";
|
| 2 |
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
| 3 |
+
import { settingsPubSub } from "@/modules/pubSub";
|
| 4 |
+
import { defaultSettings } from "@/modules/settings";
|
| 5 |
+
import { useSettingsForm } from "./useSettingsForm";
|
| 6 |
+
|
| 7 |
+
const [updateSettings, onSettingsChange, getSettings] = settingsPubSub;
|
| 8 |
+
|
| 9 |
+
describe("useSettingsForm", () => {
|
| 10 |
+
beforeEach(() => {
|
| 11 |
+
updateSettings(defaultSettings);
|
| 12 |
+
});
|
| 13 |
+
|
| 14 |
+
it("holds only the keys it was given", () => {
|
| 15 |
+
const { result } = renderHook(() =>
|
| 16 |
+
useSettingsForm(["enterToSubmit", "enableTextSearch"]),
|
| 17 |
+
);
|
| 18 |
+
|
| 19 |
+
expect(result.current.values).toEqual({
|
| 20 |
+
enterToSubmit: true,
|
| 21 |
+
enableTextSearch: true,
|
| 22 |
+
});
|
| 23 |
+
});
|
| 24 |
+
|
| 25 |
+
it("writes a changed key into the settings", () => {
|
| 26 |
+
const { result } = renderHook(() => useSettingsForm(["enterToSubmit"]));
|
| 27 |
+
|
| 28 |
+
act(() => result.current.setFieldValue("enterToSubmit", false));
|
| 29 |
+
|
| 30 |
+
expect(getSettings()).toEqual({ ...defaultSettings, enterToSubmit: false });
|
| 31 |
+
});
|
| 32 |
+
|
| 33 |
+
it("keeps a value another writer changed after the form was opened", () => {
|
| 34 |
+
const { result } = renderHook(() => useSettingsForm(["enterToSubmit"]));
|
| 35 |
+
|
| 36 |
+
act(() =>
|
| 37 |
+
updateSettings({
|
| 38 |
+
...getSettings(),
|
| 39 |
+
enableTextSearch: false,
|
| 40 |
+
wllamaModelId: "another-model",
|
| 41 |
+
}),
|
| 42 |
+
);
|
| 43 |
+
act(() => result.current.setFieldValue("enterToSubmit", false));
|
| 44 |
+
|
| 45 |
+
expect(getSettings()).toEqual({
|
| 46 |
+
...defaultSettings,
|
| 47 |
+
enableTextSearch: false,
|
| 48 |
+
wllamaModelId: "another-model",
|
| 49 |
+
enterToSubmit: false,
|
| 50 |
+
});
|
| 51 |
+
});
|
| 52 |
+
|
| 53 |
+
it("writes every key of one change in a single update", () => {
|
| 54 |
+
updateSettings({
|
| 55 |
+
...defaultSettings,
|
| 56 |
+
textToSpeechEngine: "local",
|
| 57 |
+
selectedVoiceId: "piper:voice",
|
| 58 |
+
});
|
| 59 |
+
const { result } = renderHook(() =>
|
| 60 |
+
useSettingsForm(["textToSpeechEngine", "selectedVoiceId"]),
|
| 61 |
+
);
|
| 62 |
+
const onChange = vi.fn();
|
| 63 |
+
const unsubscribe = onSettingsChange(onChange);
|
| 64 |
+
|
| 65 |
+
act(() =>
|
| 66 |
+
result.current.setValues({
|
| 67 |
+
textToSpeechEngine: "system",
|
| 68 |
+
selectedVoiceId: "",
|
| 69 |
+
}),
|
| 70 |
+
);
|
| 71 |
+
unsubscribe();
|
| 72 |
+
|
| 73 |
+
expect(onChange).toHaveBeenCalledTimes(1);
|
| 74 |
+
expect(getSettings()).toMatchObject({
|
| 75 |
+
textToSpeechEngine: "system",
|
| 76 |
+
selectedVoiceId: "",
|
| 77 |
+
});
|
| 78 |
+
});
|
| 79 |
+
|
| 80 |
+
it("does not write when no value changed", () => {
|
| 81 |
+
const { result } = renderHook(() => useSettingsForm(["enterToSubmit"]));
|
| 82 |
+
const onChange = vi.fn();
|
| 83 |
+
const unsubscribe = onSettingsChange(onChange);
|
| 84 |
+
|
| 85 |
+
act(() => result.current.setFieldValue("enterToSubmit", true));
|
| 86 |
+
unsubscribe();
|
| 87 |
+
|
| 88 |
+
expect(onChange).not.toHaveBeenCalled();
|
| 89 |
+
});
|
| 90 |
+
});
|
client/hooks/useSettingsForm.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import { useForm } from "@mantine/form";
|
| 2 |
+
import { usePubSub } from "create-pubsub/react";
|
| 3 |
+
import { settingsPubSub } from "@/modules/pubSub";
|
| 4 |
+
import type { defaultSettings } from "@/modules/settings";
|
| 5 |
+
|
| 6 |
+
type Settings = typeof defaultSettings;
|
| 7 |
+
|
| 8 |
+
function pick<T, K extends keyof T>(source: T, keys: readonly K[]): Pick<T, K> {
|
| 9 |
+
const picked = {} as Pick<T, K>;
|
| 10 |
+
for (const key of keys) picked[key] = source[key];
|
| 11 |
+
return picked;
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
/**
|
| 15 |
+
* A form over the settings in `keys`. Each change writes only the keys that
|
| 16 |
+
* changed, merged into the settings as they are at that moment, so a form that
|
| 17 |
+
* has been open for a while cannot put back a value another writer changed.
|
| 18 |
+
*/
|
| 19 |
+
export function useSettingsForm<K extends keyof Settings>(keys: readonly K[]) {
|
| 20 |
+
const [settings, setSettings] = usePubSub(settingsPubSub);
|
| 21 |
+
const [, , getSettings] = settingsPubSub;
|
| 22 |
+
|
| 23 |
+
return useForm<Pick<Settings, K>>({
|
| 24 |
+
initialValues: pick(settings, keys),
|
| 25 |
+
onValuesChange: (values, previous) => {
|
| 26 |
+
const changed = keys.filter((key) => values[key] !== previous[key]);
|
| 27 |
+
if (changed.length === 0) return;
|
| 28 |
+
|
| 29 |
+
setSettings({ ...getSettings(), ...pick(values, changed) });
|
| 30 |
+
},
|
| 31 |
+
});
|
| 32 |
+
}
|
client/modules/accessKey.test.ts
CHANGED
|
@@ -71,12 +71,24 @@ describe("Access Key Module", () => {
|
|
| 71 |
expect(result).toBe("invalid");
|
| 72 |
});
|
| 73 |
|
| 74 |
-
it("should return
|
| 75 |
const { validateAccessKey } = await import("./accessKey");
|
| 76 |
mockFetch.mockRejectedValue(new Error("Network error"));
|
| 77 |
|
| 78 |
const result = await validateAccessKey("test-key");
|
| 79 |
-
expect(result).toBe("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
});
|
| 81 |
|
| 82 |
it("should send a hash the server can verify against the access key", async () => {
|
|
|
|
| 71 |
expect(result).toBe("invalid");
|
| 72 |
});
|
| 73 |
|
| 74 |
+
it("should return unreachable on network error", async () => {
|
| 75 |
const { validateAccessKey } = await import("./accessKey");
|
| 76 |
mockFetch.mockRejectedValue(new Error("Network error"));
|
| 77 |
|
| 78 |
const result = await validateAccessKey("test-key");
|
| 79 |
+
expect(result).toBe("unreachable");
|
| 80 |
+
});
|
| 81 |
+
|
| 82 |
+
it("should return unreachable when the server reply is not JSON", async () => {
|
| 83 |
+
const { validateAccessKey } = await import("./accessKey");
|
| 84 |
+
mockFetch.mockResolvedValue({
|
| 85 |
+
ok: false,
|
| 86 |
+
status: 502,
|
| 87 |
+
json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token <")),
|
| 88 |
+
});
|
| 89 |
+
|
| 90 |
+
const result = await validateAccessKey("test-key");
|
| 91 |
+
expect(result).toBe("unreachable");
|
| 92 |
});
|
| 93 |
|
| 94 |
it("should send a hash the server can verify against the access key", async () => {
|
client/modules/accessKey.ts
CHANGED
|
@@ -26,7 +26,11 @@ async function hashAccessKey(accessKey: string): Promise<string> {
|
|
| 26 |
* Validates the key against the server; on success the hash is stored locally
|
| 27 |
* so later loads can go through `verifyStoredAccessKey`.
|
| 28 |
*/
|
| 29 |
-
export type AccessKeyResult =
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
export async function validateAccessKey(
|
| 32 |
accessKey: string,
|
|
@@ -66,6 +70,8 @@ export async function validateAccessKey(
|
|
| 66 |
|
| 67 |
return "invalid";
|
| 68 |
} catch (error) {
|
|
|
|
|
|
|
| 69 |
addLogEntry(`Error validating access key: ${error}`);
|
| 70 |
notifications.show({
|
| 71 |
title: "Error validating access key",
|
|
@@ -73,7 +79,7 @@ export async function validateAccessKey(
|
|
| 73 |
color: "red",
|
| 74 |
position: "top-right",
|
| 75 |
});
|
| 76 |
-
return "
|
| 77 |
}
|
| 78 |
}
|
| 79 |
|
|
|
|
| 26 |
* Validates the key against the server; on success the hash is stored locally
|
| 27 |
* so later loads can go through `verifyStoredAccessKey`.
|
| 28 |
*/
|
| 29 |
+
export type AccessKeyResult =
|
| 30 |
+
| "valid"
|
| 31 |
+
| "invalid"
|
| 32 |
+
| "rateLimited"
|
| 33 |
+
| "unreachable";
|
| 34 |
|
| 35 |
export async function validateAccessKey(
|
| 36 |
accessKey: string,
|
|
|
|
| 70 |
|
| 71 |
return "invalid";
|
| 72 |
} catch (error) {
|
| 73 |
+
// The server never judged the key (no connection, or a reply that is not
|
| 74 |
+
// the expected JSON), so access stays closed without calling it wrong.
|
| 75 |
addLogEntry(`Error validating access key: ${error}`);
|
| 76 |
notifications.show({
|
| 77 |
title: "Error validating access key",
|
|
|
|
| 79 |
color: "red",
|
| 80 |
position: "top-right",
|
| 81 |
});
|
| 82 |
+
return "unreachable";
|
| 83 |
}
|
| 84 |
}
|
| 85 |
|
client/modules/autoSearch.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* The query the URL currently belongs to: the one whose auto-search already
|
| 3 |
+
* ran, or that was just submitted or restored from history. Module-level so
|
| 4 |
+
* it survives the remount when MainPage swaps HomePage for SearchForm as the
|
| 5 |
+
* query goes from empty to non-empty. Kept as a single slot (not a Set) so it
|
| 6 |
+
* suppresses only the most recent auto-search, matching the behavior the
|
| 7 |
+
* user expects when navigating back to a previously searched query.
|
| 8 |
+
*/
|
| 9 |
+
let handledQuery: string | null = null;
|
| 10 |
+
|
| 11 |
+
export function markQueryAsHandled(query: string): void {
|
| 12 |
+
handledQuery = query.trim();
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export function isQueryHandled(query: string): boolean {
|
| 16 |
+
return query.trim() === handledQuery;
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
/** Exposed for tests to reset module state between runs. */
|
| 20 |
+
export function resetHandledQuery(): void {
|
| 21 |
+
handledQuery = null;
|
| 22 |
+
}
|