diff --git a/docs/web-ui-memory.md b/docs/web-ui-memory.md
index 1f1968a72..90eba6553 100644
--- a/docs/web-ui-memory.md
+++ b/docs/web-ui-memory.md
@@ -14,6 +14,8 @@ Every view starts with the same four cards, including **Shared**, so one click r
Browse stored results on **Project memories** (`/project-memories`) and **User profile** (`/user-profile`). `/` opens Project memories. Settings retains models, access controls, diagnostics and profile identity controls. See [Settings page](web-ui-settings.md).
+Every save and every job action on this page asks you to confirm first, as on the Settings page. The dialog lists each setting the save changes, or says in one sentence what the job does. **Cancel** sends nothing. See [Each save asks first](web-ui-settings.md#each-save-asks-first).
+
## Welcome panel
A new install has no memories. In that case the **Project memories** page shows a welcome panel in place of the plain "No memories found" line. The panel says that memories appear after your first sessions in OpenCode, Pi or Claude Code, and lists each host with its capture state:
@@ -70,8 +72,8 @@ Each row leads with its plain name and a one-line description, then the default
- The first-message option adds memories once, with the first message of a new session, on every host. Claude Code does this on its first prompt, not at its `SessionStart` hook. OMMS searches with the query and adds only matching memories. The **Opening search text** holds up to 500 characters. An empty text runs no search. The text area shows a counter.
- Subagents get the memories that match their task, and no recall rows. Claude Code adds them once, when the subagent starts. OpenCode V2 and Pi add them with each prompt the subagent gets. On Pi, a subagent gets memories only when its agent maps the OMMS extension in om-pi-subagents. Turn it on in `/omps-settings`, Agent capabilities, Memory.
- The restore switch adds the memories that the session captured when it resumes or compacts. **Memories added back after a summary** takes a positive whole number.
-- **Save** writes only the changed keys to the global file, through the [safe global save](web-ui-settings.md#how-saving-works). A rejected value shows a message that names the key and the rule.
-- **Reset to default** returns the form to the defaults. Select **Save** after it. The save removes the five keys from the file, so each value follows its default again.
+- **Save** lists each change in a dialog first. After you confirm, it writes only the changed keys to the global file, through the [safe global save](web-ui-settings.md#how-saving-works). A rejected value shows a message that names the key and the rule.
+- **Reset to default** returns the form to the defaults and opens no dialog. Select **Save** after it. The dialog lists each key the save removes, with its default. The save removes the five keys from the file, so each value follows its default again.
- A project config can turn the first-message and subagent options off, never on. It can turn the restore on or off. See [Configuration: Memory injection](configuration.md#memory-injection).
## A host view
@@ -283,11 +285,11 @@ Ignored folders leave unresolved counts without importing their sessions. Histor
Automatic import, or backfill, reads older conversations in the background and populates project memories and user profile input. It makes model calls. It starts about 30 seconds after Pi or OpenCode starts. Claude Code starts it after the first session start that reaches the web app.
-**Import past chats automatically** keeps the existing global `autoBackfill` switch. Ticking it opens the same question as **Turn on**, and only the dialog's **Turn on** saves. Turning it off saves at once and stops a running backfill after its current exchange. The first backfill fixes each host's cutoff; later starts resume pending work with that cutoff and ledger. Live capture handles newer turns. A model change applies at the next run.
+**Import past chats automatically** keeps the existing global `autoBackfill` switch. Turning it on opens the same question as **Turn on**, and only the dialog's **Turn on** saves. Turning it off asks you to confirm in a dialog, and **Cancel** leaves the switch on. Confirming stops a running backfill after its current exchange. The first backfill fixes each host's cutoff; later starts resume pending work with that cutoff and ledger. Live capture handles newer turns. A model change applies at the next run.
Each host's view holds its own automatic-import controls: the status header, the run facts below it, and the host's settings. The overview card shows the state in one line. Unsaved model choices stay while counts refresh.
-The Pi and OpenCode **Backfill model** choices remain:
+The Pi and OpenCode **Backfill model** choices remain. **Save model** lists the change in a dialog before it saves:
- **Same as live capture:** saves `inherit` to `piBackfillModel` or `opencodeBackfillModel`.
- **External API:** saves `external` and can run with no host open.
@@ -301,6 +303,7 @@ Counts refresh every three seconds during a run. Operational progress leaves alr
### Pause and Resume
+- **Pause**, **Resume** and **Retry** each ask you to confirm first, with one sentence on what they do. **Resume** and **Retry** make model calls. **Use external API** asks first too, and then sets the host's backfill model to the external API.
- **Pause** stops after the current exchange, including a run in another process. With no run going, it saves the pause so no automatic run starts. The pause survives host restarts.
- **Resume** clears the pause and starts the host's backfill from the ledger, with its existing cutoff, maps and model rule.
@@ -415,7 +418,7 @@ Saving edits only the keys in the table. Comments and unrelated keys retain thei
### Reset to default
-Every row has a **Reset to default** button. Selecting it removes that key from the global file through the same safe save flow, so the value follows the default again. Reset never writes a project file. A row whose key is absent from the file has its Reset button disabled.
+Every row has a **Reset to default** button. Selecting it opens a dialog with the saved value and the default. Confirming removes that key from the global file through the same safe save flow, so the value follows the default again. Reset never writes a project file. A row whose key is absent from the file has its Reset button disabled.
A row whose saved value differs from its default shows a **Differs from default** marker. This is how a file that still holds the old template's `"similarityThreshold": 0.6` becomes visible: with the `qwen3-embedding:0.6b` embedder the row shows the marker, and Reset removes the line so the default 0.5 applies again. A value equal to the default, or no saved value, shows no marker.
@@ -473,11 +476,11 @@ See [Configuration: Reranker](configuration.md#reranker) for the endpoint contra
A directory map links a recorded project folder to its current folder, for example after moving a repository or deleting a worktree. Saved maps apply globally to every host at the next import or backfill run.
- **Saved maps** starts collapsed and shows the `importPathMaps` count. Maps are grouped by target folder, largest group first. Each target group is collapsed.
-- **Remove** marks a saved map for removal; **Keep** undoes it. **Save removals** saves pending removals.
+- **Remove** marks a saved map for removal; **Keep** undoes it. **Save removals** shows how many saved maps remain, and saves after you confirm.
- Keep maps after importing their sessions. Resolution happens before ledger checks. Removing a needed map makes its sessions unresolved again. Previously stored memories remain.
-- **Ignored directories** lists `importIgnoredDirectories`. **Restore** immediately saves removal from that list. The folder returns to each host list that reported it.
+- **Ignored directories** lists `importIgnoredDirectories`. **Restore** names the folder in a dialog, and saves its removal from that list after you confirm. The folder returns to each host list that reported it.
- Each host view lists its **Unresolved directories** open, with a folder field on every row. Its summary counts directories, unresolved sessions and rows with targets. Collapsing keeps unsaved targets. **Shared** keeps **Saved maps** and **Ignored directories**.
-- **Ignore** immediately saves the folder to `importIgnoredDirectories`. Its sessions leave unresolved counts and stay unimported. Maps, ledger and history files remain unchanged.
+- **Ignore** names the folder in a dialog, and saves it to `importIgnoredDirectories` after you confirm. Its sessions leave unresolved counts and stay unimported. Maps, ledger and history files remain unchanged.
- **Ignore all** lists every directory it will ignore, with session counts, and saves them in one global save after you confirm. Cancel saves nothing. It never covers **No directory recorded**.
- Sessions with **No directory recorded** cannot be mapped or ignored.
diff --git a/docs/web-ui-settings.md b/docs/web-ui-settings.md
index e5e4e9ac9..81579d90a 100644
--- a/docs/web-ui-settings.md
+++ b/docs/web-ui-settings.md
@@ -47,11 +47,24 @@ Every card with a server follows the same steps:
1. Edit the values.
2. Select **Test**, where the card has one. The test uses the values in the form, saved or not.
3. Select **Save**. Leaving a field saves nothing.
-4. Read the plain message that follows.
+4. Read the dialog, then select its confirm button.
+5. Read the plain message that follows.
You can clear an optional field, such as the API URL or the model. Saving an empty field removes its key from the file. A URL field accepts only `http://` or `https://` addresses. A number that is not valid shows a message next to the field and keeps **Save** off.
-A save that deletes stored data opens a confirmation first. It says what OMMS deletes and how many items, when OMMS knows the count. Nothing is saved until you confirm. The confirmation has **Cancel** as its first choice.
+### Each save asks first
+
+When you select **Save**, a dialog opens before OMMS sends anything. Its title names the card, for example **Save memory basics?**. Its body lists each setting that the save changes, with the saved value struck through and the new value after it. A reset to a default shows **Default (value)** as the new value.
+
+- **Cancel** sends nothing. The text you typed stays in the form, so you can select **Save** again.
+- A setting that saves when you change it, such as **Summary language**, shows your choice while the dialog is open. **Cancel** puts the saved value back.
+- A button that starts or stops a job, such as **Retry now** or **Record past turns**, asks first with one sentence. The sentence says what the job does.
+- A **Save** that changes nothing still asks first. The dialog says that saving writes the current values again.
+- If the save fails, the dialog shows the reason and its confirm button turns off. Close the dialog and select **Save** again, so the dialog shows the current settings.
+- A value that fails a check on the page shows its message on the page, and no dialog opens.
+- A choice that changes only how the page looks, such as the theme and the date format, saves with no dialog.
+
+A save that deletes stored data keeps its own confirmation. It says what OMMS deletes and how many items, when OMMS knows the count. Nothing is saved until you confirm. The confirmation has **Cancel** as its first choice.
### Key entry
@@ -87,7 +100,7 @@ This card holds the only switch that turns on automatic deletion of memories.
The card warns you that deletion removes memories that are not pinned and have not changed for that many days, in every project, and that OMMS cannot restore a deleted memory. A project file cannot change these two settings. OpenCode, Pi and Claude Code follow the same switch.
-Turning the switch on, or lowering the number of days while it is on, opens a confirmation first. It states how many memories have not changed for that many days, and that OMMS deletes them at its next daily check, not when you save. OMMS counts them with the same selection the deletion uses and deletes nothing while it counts. The number is what goes: the check deletes old prompts and the memories captured from them in the same run. The confirmation also says that pinned memories and memorisations stay. It has **Cancel** as its first choice. Nothing is saved until you confirm, and **Cancel** puts the switch back to its saved state. When OMMS cannot read the count, the confirmation says so and does not let you turn deletion on. Turning the switch off needs no confirmation.
+Turning the switch on, or lowering the number of days while it is on, opens a confirmation first. It states how many memories have not changed for that many days, and that OMMS deletes them at its next daily check, not when you save. OMMS counts them with the same selection the deletion uses and deletes nothing while it counts. The number is what goes: the check deletes old prompts and the memories captured from them in the same run. The confirmation also says that pinned memories and memorisations stay. It has **Cancel** as its first choice. Nothing is saved until you confirm, and **Cancel** puts the switch back to its saved state. When OMMS cannot read the count, the confirmation says so and does not let you turn deletion on. Turning the switch off, or raising the number of days, opens a dialog that lists the change, although it deletes nothing. **Cancel** puts the switch back to its saved state.
The older `autoCleanupEnabled` key was removed in 7.0.0. OMMS ignores it, so a file that still sets `"autoCleanupEnabled": true` deletes nothing. Only the switch on this card turns deletion on. OMMS does not change your file by itself.
@@ -110,7 +123,7 @@ The card sets four values:
| Model | `memoryModel` | The model name at that endpoint, for example `glm-5.3`. Not needed for `orcarouter`. |
| API key | `memoryApiKey` | Where the key comes from. See the three key sources below. |
-Select **Save settings** to save the provider, URL, model and key. **Save settings** first runs the same test as **Test**, once, with the values in the form, and saves only when the test passes. A key the provider refuses (HTTP 401 or 403) is never saved, and the card says nothing was saved. When OMMS cannot reach the address at all (a network error or a timeout), a dialog asks whether to save anyway or cancel. Empty the API URL or the model and save to turn the external API off and remove the key from the file; that save needs no test. The hint under each field says so: an empty field turns the external API off, except for OrcaRouter, which has its own address and picks its own model. The URL must start with `http://` or `https://`.
+Select **Save settings** to save the provider, URL, model and key. **Save settings** first runs the same test as **Test**, once, with the values in the form. A passing test opens a dialog that lists each change. The key shows only as where it is kept, never its value. Nothing is saved until you confirm. A key the provider refuses (HTTP 401 or 403) is never saved, no dialog opens, and the card says nothing was saved. When OMMS cannot reach the address at all (a network error or a timeout), a dialog asks whether to save anyway or cancel. That dialog also lists the changes. Empty the API URL or the model and save to turn the external API off and remove the key from the file; that save needs no test, and its dialog says the external API will be turned off. The hint under each field says so: an empty field turns the external API off, except for OrcaRouter, which has its own address and picks its own model. The URL must start with `http://` or `https://`.
### Preset
@@ -445,7 +458,7 @@ To create a token:
1. Type a **Token name**.
2. Choose **Expires after**: 7, 30, or 90 days, or **Never**.
-3. Select **Generate token**.
+3. Select **Generate token**, then confirm in the dialog.
4. Select **Copy**, and keep the token in a safe place.
The page shows the token value once. OMMS keeps only a hash of it, so nobody can show it again.
@@ -458,9 +471,9 @@ The routes are `GET` and `POST /api/settings/tokens`, and `DELETE /api/settings/
The browser password turns on HTTP Basic Auth. The browser then asks for a user name and password before the page opens.
-- To set it, type the **Password** and, optionally, the **User name**. Then select **Save password**. The default user name is your computer user name.
+- To set it, type the **Password** and, optionally, the **User name**. Then select **Save password** and confirm in the dialog. The default user name is your computer user name.
- OMMS writes the password to `~/.config/omms/secrets/web-password.key` with mode `0600`. It saves `webServerAuthPassword: file://...` and `webServerAuthUsername` in the global config.
-- **Clear password** removes both config keys and deletes the password file.
+- **Clear password** asks you to confirm first. It then removes both config keys and deletes the password file.
- Restart the web app to use a new password. Use the [power button](web-ui.md#power-button).
The route is `POST /api/settings/web-password`. It needs a caller on this machine and the local token file.
@@ -494,7 +507,7 @@ When a live capture fails because the capture model cannot be reached, OMMS keep
- **Retry retention (hours).** How long a waiting turn is kept. The default is 72 hours. The range is 0 to 720.
- Set it to 0 to turn the queue off. When you select **Save retention**, OMMS counts the waiting turns again, and a confirmation says how many it deletes. Nothing is saved until you confirm. The save then deletes the waiting turns at once.
- **Turns waiting for retry** shows the number of waiting turns for Pi, OpenCode, and Claude Code.
-- **Retry now** retries the waiting turns of Pi and Claude Code at once. OpenCode's waiting turns retry at the next OpenCode session start, because only an OpenCode session can call OpenCode's models. The page says so.
+- **Retry now** asks you to confirm first, because it sends the waiting turns to the model again. It then retries the waiting turns of Pi and Claude Code at once. OpenCode's waiting turns retry at the next OpenCode session start, because only an OpenCode session can call OpenCode's models. The page says so.
- The web app always runs the Claude Code retry pass, so **Retry now** works for Claude Code in any web app.
- **Retry now** is disabled when the host has no waiting turns or the queue is off.
- Queued turns can contain conversation content. OMMS removes text inside `` tags and common API key formats first.
@@ -544,7 +557,7 @@ Use this section when Claude Code does not keep its data in `~/.claude`, for exa
Use this card to choose the language that new memory summaries are written in.
-- **Summary language** (`autoCaptureLanguage`) is **Automatic** or one language. Choosing a language saves it at once.
+- **Summary language** (`autoCaptureLanguage`) is **Automatic** or one language. When you choose a language, a dialog asks you to confirm the change. **Cancel** keeps the saved language.
- **Automatic** detects the language of your prompt. Detection is unreliable on short text, so a Latin-script prompt under 100 characters counts as English. Pick a fixed language if your memories come out in a language you do not use.
- A save applies to the next capture. Memories that exist already keep their language.
@@ -625,8 +638,8 @@ See [CLI: Global install](cli.md#global-install-optional) and [Updating and upgr
The card holds the settings of [skill learning](configuration.md#skill-learning). It saves through the same safe flow as the other cards. See [How saving works](#how-saving-works).
-- **Record agent turns** (`skillLearning`) switches recording on or off. While it is on, the card shows a warning. It says that OMMS stores full prompts, replies and tool calls in `skills.db` on this computer, that drafting sends recorded turns to the external API, that the file holds whatever the turns hold, and that the memory chat sends skill counts and short change summaries to the external API, never turn text. A project config can turn recording off for its project. It cannot turn it on.
-- **Record past turns** appears while recording is on. It starts one grouped import of all past history with only **Skill turns** ticked. It makes no model call. A progress bar shows the **Skill turns** phase. When the run ends, the card shows the count of turns recorded.
+- **Record agent turns** (`skillLearning`) switches recording on or off. Each change asks you to confirm it in a dialog. While it is on, the card shows a warning. It says that OMMS stores full prompts, replies and tool calls in `skills.db` on this computer, that drafting sends recorded turns to the external API, that the file holds whatever the turns hold, and that the memory chat sends skill counts and short change summaries to the external API, never turn text. A project config can turn recording off for its project. It cannot turn it on.
+- **Record past turns** appears while recording is on. It asks you to confirm first. It then starts one grouped import of all past history with only **Skill turns** ticked. It makes no model call. A progress bar shows the **Skill turns** phase. When the run ends, the card shows the count of turns recorded.
- **Remove private text and secrets** (`skillLearningRedact`) is on by default. Turning it off needs a confirmation. While it is off, the card shows a danger notice: `` text, API keys and passwords are stored as written and sent to the external API when OMMS drafts.
- **Recorded turns** and **File size** show the contents of `skills.db`.
- **Delete recorded turns** asks first. The confirmation states the number of turns. Confirming deletes all of them, and the card then shows 0 turns. Proposals and skill versions stay.
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/.openspec.yaml b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/.openspec.yaml
new file mode 100644
index 000000000..8c7aa0b95
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-11-27
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/design.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/design.md
new file mode 100644
index 000000000..950e1de46
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/design.md
@@ -0,0 +1,60 @@
+## Context
+
+- The shared pattern exists: `web/src/hooks/useSettingsConfirm.tsx` (`ask(request)` plus one rendered `dialog`) and `web/src/lib/components/settings/SettingsConfirmDialog.tsx`. The dialog runs the request only after confirm, shows progress, keeps a server error inside itself and closes on success. `onCancel` lets a card put a save-on-change control back to its saved value. `MemoryCleanupSection.tsx` shows that use for a switch.
+- The Memorisation page already follows the rule through `web/src/hooks/useMemorisationConfirm.tsx` (PR #311).
+- An audit of `web/src` (2026-11-27) listed every settings action without a dialog. The tasks name each card and trigger.
+- Most cards stage edits in a form and save with one button. A few save on change: the summary language select, the two Skill learning switches, and the automatic import checkbox when turned off. A few are one-click actions: Pause, Resume, Retry, Retry now, Use external API, Generate token, Save password, Clear password, Record past turns, Ignore and Restore.
+- File sizes: `memory/DirectoryMapsSection.tsx` is at the 500-line limit. `settings/ExternalApiSection.tsx` (456), `settings/EmbeddingSection.tsx` (431) and `memory/RerankerSection.tsx` (417) are close to it.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- Every settings save and settings job action on the Settings and Memory pages confirms first, through one shared dialog.
+- The dialog says exactly what will change: each setting with its old and new value, or one sentence for a job.
+- Same request bodies as today. No server change.
+
+**Non-Goals:**
+
+- Actions that are not settings saves: memory delete, cleanup and dedup (`window.confirm` in `useMemoriesExplorer.ts`), "Analyse waiting prompts", Add memory, pin and unpin, profile Refresh, skill proposal Apply, Reject and Undo, skill mode and drafts, and the chat folder move. These go to a later change.
+- Local-only view preferences (theme, palette, date and time format, language, sidebar, paging, filters). They write no server state.
+- Test buttons and the Health check. They change nothing.
+- A new dialog component, or a change to `SettingsConfirmDialog` beyond what the change list needs.
+
+## Decisions
+
+1. **Reuse `useSettingsConfirm` in every card.** Each card calls `ask` from its save handler and renders `dialog` once. A second dialog component was rejected because it would split the progress, error and close behaviour into two copies.
+
+2. **One shared change list.** A pure helper `settingsChanges(saved, edits, fields, words)` returns the changed rows as `{ key, label, from, to }`, and a small `SettingsChangeList` component renders them as a definition list: the saved value struck through, then the new value. `saved` and `edits` use the keys of the request, and `edits` is the body the card is about to send. A `null` edit removes the key, so the row shows the field's default as "Default (value)". A value that was never saved reads "Not set". The helper throws when the request changes a key that no field describes, so the dialog can never leave a change out. `useSettingsChanges()` gives the helper with the words of the page (On, Off, Not set, Default) and each setting's catalogue name, so cards do not repeat them. Each card passes its own labels and value formatters: the translated option name for selects, and a number with its unit. A screen reader hears "changes to" between the two values, and the arrow mirrors for Arabic. A text body per card was rejected: it would drift from the real edits, and nothing would test that it matches what is sent.
+
+3. **One dialog per click.** When a card already opens a special dialog on a path, that dialog is the confirmation for that click, and its text gains the change list where it fits. Examples are memory cleanup's count dialog, the reranker's "Replace the key file?", the capture trace and zero-retention dialogs, and the external API's Save anyway. A second dialog after the first was rejected as noise.
+
+4. **Test, then confirm.** A Save that runs a test call runs the test first, because a test changes nothing. Only the external API Save does this. A passing test opens the confirm dialog. A refused key still saves nothing and opens no dialog. A test that cannot reach the server opens the existing Save anyway dialog, which is the confirmation. The reranker and embedding cards keep **Test** as its own button. The reranker's Save runs no test, so it opens the confirm dialog at once. The embedding card's Re-embed needs a passing Test first and keeps its own Re-embed dialog.
+
+5. **Save-on-change controls hold a pending value.** The control shows the new value while the dialog is open, and `onCancel` puts the saved value back. The pending value is cleared after a successful save, once the snapshot has reloaded, so a later change to the file shows on the control. `MemoryCleanupSection.tsx` and `CaptureLanguageSection.tsx` show this. Leaving the control on its saved value until confirm was rejected, because the user could not see what they had chosen.
+
+6. **Page checks first.** A value the page can check (range, URL scheme, empty required field) shows its message on the page, and no dialog opens. A dialog for a save that cannot succeed was rejected.
+
+7. **Job actions get one sentence.** Pause, Resume, Retry, Retry now and Record past turns each say what the job does and whether it calls a model. Pause is included because it changes saved state; the cost is one extra click.
+
+8. **The redaction warning moves into the dialog.** The inline Callout before turning off "Remove private text and secrets" becomes the shared dialog, with the same warning text in its body.
+
+9. **Size limits.** Cards near 500 lines move their confirm wiring into a small hook beside them, as `useMemorisationConfirm.tsx` does. `DirectoryMapsSection.tsx` is split first: the ignored-folders list moves to its own component, `DirectoryMapIgnoredList.tsx`. `tests/file-size-ceiling.test.ts` gets no new entry.
+
+10. **Docs and rules.** `web/AGENTS.md` says that the rule covers settings saves and settings job actions, and that local-only view preferences are excluded. The two web UI guides say each save asks first.
+
+## Risks / Trade-offs
+
+- [One more click on every save] → This is the rule the project chose. The dialog shows the exact changes, so the click is a check, not a formality.
+- [Many tests expect an immediate request] → Each is updated to confirm first and still asserts the same request body. Each card also gets a test that no request is sent before confirm.
+- [Pending values on save-on-change controls can leave a control showing an unsaved value] → `onCancel` and the dialog's close path always restore the saved value, and a successful save clears the pending value. A test covers Escape and the close button as well as Cancel, and a change to the file after a save.
+- [Special dialogs and the change list can disagree] → Decision 3 keeps one dialog per click, built from the same edits object that is sent.
+- [Large diff across about 25 files] → The work is split by page, so the groups do not touch the same files.
+
+## Migration Plan
+
+Web only. No data or config migration. Rollback: revert the commit.
+
+## Open Questions
+
+None.
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/proposal.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/proposal.md
new file mode 100644
index 000000000..08a75ae05
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/proposal.md
@@ -0,0 +1,43 @@
+## Why
+
+`web/AGENTS.md` says every action that changes state opens a confirm dialog first. Many settings cards do not follow it. PR #311 made the Memorisation page confirm every save, and a read-only audit of `web/src` then found the rest of the app split three ways:
+
+- About 25 settings actions on the Settings and Memory pages write at once, with no dialog.
+- 7 cards confirm on one path only, for example the reranker's "Replace the key file?". Their ordinary Save still writes at once.
+- 9 cards already use the shared dialog (`useSettingsConfirm` and `SettingsConfirmDialog`).
+
+So the same kind of click asks first on one card and writes at once on the next. This change gives every settings save in the app the same confirm step.
+
+## What Changes
+
+- Every settings action on the Settings page and the Memory pages opens the shared settings confirm dialog before it sends a request. This covers Save buttons, settings that save on change (selects, switches, checkboxes), per-row Reset to default, and buttons that start or stop a settings job (Pause, Resume, Retry, Retry now, Record past turns, Use external API, Generate token, Save password and Clear password).
+- The dialog names the card, and lists each setting that changes with its old and new value in plain words. It has Cancel and a confirm button. Nothing is sent until the user confirms. It shows progress while the request runs. It shows a server error inside itself and stays open, and it closes on success.
+- **Cancel** sends nothing. A setting that saves on change goes back to its saved value. Text the user typed in a form stays as a draft.
+- A value that breaks a rule on the page still shows its message on the page, and no dialog opens.
+- The 7 partly covered cards keep their special dialogs. Their ordinary Save also confirms: capture retention, reasoning level, the external API Save (including the empty URL or model that turns it off), OpenRouter routing, memory cleanup (turning it off or raising the days), reranker and profile learning.
+- The inline Callout that asks before turning off "Remove private text and secrets" in Skill learning is replaced by the same shared dialog.
+- Every new string is in English, Chinese and Arabic. `docs/web-ui-settings.md`, `docs/web-ui-memory.md` and `web/AGENTS.md` describe the rule and its exceptions.
+
+No server, API or config change. The same requests are sent with the same bodies, only after the user confirms.
+
+Out of scope, for a later change: actions that are not settings saves, which the audit also found without the shared dialog. These are memory delete, cleanup and dedup through `window.confirm`, "Analyse waiting prompts", Add memory, pin and unpin, the profile Refresh, skill proposal Apply, Reject and Undo, skill mode and drafts, and the chat folder move. Local-only view preferences (theme, palette, date format, language, sidebar and paging state) stay without a dialog, because they change no server state.
+
+## Capabilities
+
+### New Capabilities
+
+None.
+
+### Modified Capabilities
+
+- `web-settings`: the shared confirm dialog for settings saves, its content and Cancel behaviour, and the Settings page cards that use it.
+- `web-memory`: the shared Memory page cards (memory limits, keyword mode, reranker, profile learning, profile auto cleanup and catch-up, directory maps) confirm before saving.
+- `web-memory-hosts`: the host cards and the overview (host model, automatic import off, Use external API, Pause, Resume and Retry, opening context and compaction, ignored folders) confirm before saving.
+
+## Impact
+
+- Web only, in `web/src/lib/components/settings/`, `web/src/lib/components/memory/` and `web/src/lib/components/skills/use-skill-settings.ts`. These use the existing `web/src/hooks/useSettingsConfirm.tsx` and `web/src/lib/components/settings/SettingsConfirmDialog.tsx`, plus three small shared pieces: the helper `web/src/lib/settings-changes.ts`, its hook `web/src/hooks/useSettingsChanges.ts`, and `web/src/lib/components/settings/SettingsChangeList.tsx`.
+- Translation tables in `web/src/lib/i18n/` (English, Chinese, Arabic).
+- Tests in `web/tests/` for each card: no request before confirm, Cancel sends nothing, confirm sends the same body as today, and a server error stays in the dialog. Existing tests that expect an immediate request are updated to confirm first, without weakening what they check.
+- Docs: `docs/web-ui-settings.md`, `docs/web-ui-memory.md`, `web/AGENTS.md`.
+- Users: one more click per settings save.
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory-hosts/spec.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory-hosts/spec.md
new file mode 100644
index 000000000..1b2a277ff
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory-hosts/spec.md
@@ -0,0 +1,25 @@
+## ADDED Requirements
+
+### Requirement: Host and overview saves confirm first
+
+On the host pages and the Memory overview these actions SHALL use the shared settings confirm dialog before they send a request: the host Save model, turning automatic import off, Use external API, Pause, Resume and Retry, Ignore on a folder row, and the opening context and compaction Save. The dialog content, Cancel and page checks SHALL follow the Settings rules. Turning automatic import on SHALL keep its existing dialog.
+
+#### Scenario: Turn automatic import off
+
+- **WHEN** the user clears "Import past chats automatically" for Pi
+- **THEN** a confirm dialog opens, and Cancel leaves the box ticked
+
+#### Scenario: Retry an import
+
+- **WHEN** the user selects **Retry** on a host whose import failed
+- **THEN** a confirm dialog says the retry calls the model again, and no run starts before the user confirms
+
+#### Scenario: Use external API
+
+- **WHEN** the user selects **Use external API** for OpenCode
+- **THEN** a confirm dialog says OpenCode will use the external API model, and nothing is saved before the user confirms
+
+#### Scenario: Opening context
+
+- **WHEN** the user changes the opening context and selects **Save**
+- **THEN** a confirm dialog lists the change and nothing is sent before the user confirms
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory/spec.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory/spec.md
new file mode 100644
index 000000000..694c30147
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-memory/spec.md
@@ -0,0 +1,25 @@
+## ADDED Requirements
+
+### Requirement: Shared Memory page saves confirm first
+
+On the shared Memory page these actions SHALL use the shared settings confirm dialog before they send a request: Save memory limits and each row's Reset to default, keyword mode, the reranker card's Save, profile learning Save, profile auto cleanup Save, catch-up Pause, and the directory maps Save removals and Restore. The dialog content, Cancel and page checks SHALL follow the Settings rules.
+
+#### Scenario: Memory limits
+
+- **WHEN** the user changes the maximum memories and selects **Save memory limits**
+- **THEN** a confirm dialog lists the change and nothing is sent before the user confirms
+
+#### Scenario: Reset one row
+
+- **WHEN** the user selects **Reset to default** on the similarity threshold row
+- **THEN** a confirm dialog shows the saved value and the default, and nothing is sent before the user confirms
+
+#### Scenario: Reranker switch
+
+- **WHEN** the user turns the reranker off and selects **Save**
+- **THEN** a confirm dialog opens, and Cancel leaves the saved reranker settings unchanged
+
+#### Scenario: Restore an ignored folder
+
+- **WHEN** the user selects **Restore** on an ignored folder
+- **THEN** a confirm dialog names the folder, and the folder stays ignored until the user confirms
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-settings/spec.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-settings/spec.md
new file mode 100644
index 000000000..c01f9757a
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/specs/web-settings/spec.md
@@ -0,0 +1,158 @@
+## ADDED Requirements
+
+### Requirement: Settings saves confirm before sending
+
+Every action on the Settings and Memory pages that writes a setting or starts or stops a settings job SHALL open the shared settings confirm dialog first. The page SHALL send no request until the user confirms. The dialog SHALL show progress while the request runs, show a server error inside itself and stay open, and close on success. The confirmed request SHALL have the same body as it had before this rule.
+
+#### Scenario: Save button
+
+- **WHEN** the user changes the web app autostart box and selects **Save**
+- **THEN** a confirm dialog opens and no request is sent
+
+#### Scenario: Confirm
+
+- **WHEN** the user selects the confirm button in that dialog
+- **THEN** the page sends `webServerAutoStart` as before, shows progress, and closes the dialog when the save succeeds
+
+#### Scenario: Server refusal
+
+- **WHEN** the server refuses a confirmed save
+- **THEN** the dialog shows the server's reason and stays open
+
+### Requirement: Cancel and page checks
+
+**Cancel** SHALL send nothing. A control that saves on change, such as a select, switch or checkbox, SHALL show its saved value again after Cancel. Text the user typed in a form SHALL stay as a draft after Cancel. A value that breaks a rule the page checks SHALL show its message on the page, and no dialog SHALL open.
+
+#### Scenario: Cancel a select
+
+- **WHEN** the user picks a new summary language and then selects **Cancel**
+- **THEN** nothing is saved and the select shows the saved language
+
+#### Scenario: Cancel a form
+
+- **WHEN** the user types a Claude Code folder, selects **Save folder** and then **Cancel**
+- **THEN** nothing is saved and the typed folder stays in the box
+
+#### Scenario: Invalid value
+
+- **WHEN** the user enters an interval outside its range and selects **Save**
+- **THEN** the page shows the range message and no dialog opens
+
+### Requirement: The dialog lists the changes
+
+The dialog SHALL name the card and list each setting the save changes, with its saved value and its new value in plain words. A reset to default SHALL show the default as the new value. A job action SHALL say in one sentence what the job does, for example that a retry calls the model again.
+
+#### Scenario: Two settings change
+
+- **WHEN** the user turns off automatic capture, picks a new default scope and selects **Save**
+- **THEN** the dialog lists both settings, each with its old and new value
+
+#### Scenario: Job action
+
+- **WHEN** the user selects **Retry now** for a host
+- **THEN** the dialog says the waiting captures will be sent to the model again
+
+### Requirement: Settings page cards confirm every save
+
+On the Settings page these actions SHALL confirm first: the host model Save, the summary language, the Claude Code folder, web app autostart, Memory basics, the two Skill learning switches, Record past turns, Save password, Clear password, Generate token, the embedding Retry, capture Retry now, capture retention, the reasoning level, the external API Save, OpenRouter routing and memory cleanup. Each card's own special dialogs SHALL stay.
+
+#### Scenario: External API turned off
+
+- **WHEN** the user empties the external API URL and selects **Save settings**
+- **THEN** a confirm dialog says the external API will be turned off, and nothing is sent before the user confirms
+
+#### Scenario: Turn off redaction
+
+- **WHEN** the user turns off "Remove private text and secrets"
+- **THEN** the shared confirm dialog opens in place of the inline warning, and Cancel leaves redaction on
+
+#### Scenario: Memory cleanup turned off
+
+- **WHEN** the user turns off memory cleanup and selects **Save**
+- **THEN** a confirm dialog opens, although turning it off deletes nothing
+
+## MODIFIED Requirements
+
+### Requirement: Every settings card saves the same way
+
+Each settings card with a server SHALL test the values in the form, not the saved values. Each card SHALL save with a Save button, not on leaving a field, SHALL confirm with the shared settings confirm dialog before it saves, and SHALL show a plain message after each test and save. A Save that tests first SHALL test, then confirm; when the test cannot reach the server, the existing Save anyway dialog SHALL be the confirmation.
+
+#### Scenario: Testing an unsaved model
+
+- **WHEN** the user types a new model on the External API card and selects Test without saving
+- **THEN** the test call SHALL use the typed model
+
+#### Scenario: Clearing the API URL
+
+- **WHEN** the user empties the API URL, saves and confirms
+- **THEN** `memoryApiUrl` SHALL be removed from the global config
+
+#### Scenario: A URL without a scheme
+
+- **WHEN** the user saves `api.example.com/v1` as the API URL
+- **THEN** the save SHALL be refused with a message that the URL must start with `http://` or `https://`
+
+#### Scenario: An invalid number
+
+- **WHEN** the user enters a value that is not a valid number in a number field and selects Save
+- **THEN** a message SHALL show next to the field, and no confirm dialog SHALL open
+
+### Requirement: The page controls automatic import
+
+Each host view on the Memory page SHALL have a settings card with the **Import past chats automatically** switch for `autoBackfill`, which applies to every host, and, for Pi and OpenCode, a backfill model choice for `piBackfillModel` or `opencodeBackfillModel`: **Same as live capture** (saves `inherit`), **External API** (saves `external`), or a manual `provider/model`. Claude Code's backfill always uses the external API. The host view's status header SHALL show the backfill state, including paused and off, the counts of imported, skipped, failed, and pending exchanges, the number of sessions whose project cannot be resolved with a link to that host's list of sessions that need a folder, the model used, the cutoff, the last error, and the progress bar, percentage, and time left defined by the import progress capability. It SHALL offer Pause, Resume and Retry as the import progress capability defines. The counts SHALL refresh while a run is active. The settings card SHALL say that a model change takes effect at the next run, except that turning the switch off also stops a running automatic backfill after its current exchange. It SHALL say that automatic import makes model calls. Turning the switch on SHALL open the same confirm dialog as **Turn on** in the status header, and only its **Turn on** SHALL save; turning the switch off SHALL ask in the shared settings confirm dialog first, and only its confirm SHALL save.
+
+#### Scenario: Turning automatic import off
+
+- **WHEN** the user turns off the switch while an automatic Pi backfill runs, and confirms
+- **THEN** the global config SHALL have `autoBackfill` set to `false`
+- **AND** the Pi backfill SHALL stop after its current exchange
+- **AND** the Pi status header SHALL read **Off** once the run has stopped
+
+#### Scenario: Choosing a backfill model for Pi
+
+- **WHEN** the user picks provider `zai` and model `glm-5-turbo` for Pi's backfill and saves
+- **THEN** the global config SHALL have `piBackfillModel` set to `zai/glm-5-turbo`
+- **AND** `piProvider` and `piModel` SHALL be unchanged
+
+#### Scenario: Choosing the external API for OpenCode's backfill
+
+- **WHEN** the user chooses External API for OpenCode's backfill and saves
+- **THEN** the global config SHALL have `opencodeBackfillModel` set to `external`
+
+#### Scenario: Watching progress
+
+- **WHEN** a backfill runs while the host view is open
+- **THEN** the counts, progress bar, percentage, and time left SHALL update without a page reload
+
+#### Scenario: Opening the section with no active run
+
+The scenario title is kept so the archive step can match it. The Automatic import section and its host cards no longer exist; each host view holds one host.
+
+- **WHEN** no host has a running or paused run and the user opens `/memory/pi`
+- **THEN** the status header SHALL show Pi's state, pending exchanges, and unresolved sessions
+
+#### Scenario: A run is active
+
+- **WHEN** a Pi backfill is running and the user opens `/memory/pi`
+- **THEN** the status header SHALL show the progress bar, percentage and time left
+
+#### Scenario: Keeping a card's state during refresh
+
+The scenario title is kept so the archive step can match it.
+
+- **WHEN** the counts refresh while the user edits Pi's backfill model choice
+- **THEN** the unsaved model choice SHALL stay
+
+#### Scenario: Reading automatic import without duplicate pills
+
+The scenario title is kept so the archive step can match it.
+
+- **WHEN** the user opens `/memory/opencode`
+- **THEN** the status header SHALL show the host name without an overall import-status pill
+- **AND** it SHALL keep its operational state and its one main action
+
+#### Scenario: Following the automatic import directory link
+
+- **WHEN** the user activates OpenCode's unresolved-directory link in the status header
+- **THEN** OpenCode's list of sessions that need a folder SHALL open and its summary SHALL receive focus
+- **AND** other hosts' drafts and disclosure states SHALL remain unchanged
diff --git a/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/tasks.md b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/tasks.md
new file mode 100644
index 000000000..f3b7d9afc
--- /dev/null
+++ b/openspec/changes/archive/2026-11-27-settings-confirm-dialogs/tasks.md
@@ -0,0 +1,71 @@
+## 1. Shared change list
+
+- [x] 1.1 Write tests for a pure `settingsChanges(saved, draft, fields)` helper in `web/src/lib/settings-changes.ts`. Cover these cases:
+ - no change
+ - one change
+ - two changes in field order
+ - a boolean as On and Off
+ - a reset to default shown as "Default (value)"
+ - a nested key such as `compaction.enabled`
+
+ Run them and confirm that they fail.
+
+- [x] 1.2 Add the helper and a `SettingsChangeList` component that renders the rows. Make 1.1 pass. Add its strings in English, Chinese and Arabic.
+- [x] 1.3 Split `web/src/lib/components/memory/DirectoryMapsSection.tsx` (500 lines): move the ignored-folders list into its own component, with no behaviour change. Run its tests and `tests/file-size-ceiling.test.ts`.
+
+## 2. Settings page cards
+
+For each task: write the tests first and prove that they fail. Each card's tests cover:
+
+- no request before confirm
+- Cancel sends nothing, and a save-on-change control shows its saved value again
+- confirm sends the same body as today
+- a server error stays in the dialog
+
+Update existing tests that expect an immediate request, without weakening what they check.
+
+- [x] 2.1 `settings/ModelsSection.tsx` (Save model), `settings/ClaudeFolderSection.tsx` (Save folder), `settings/WebAppSection.tsx` (Save), `settings/MemoryBasicsSection.tsx` (Save).
+- [x] 2.2 `settings/CaptureLanguageSection.tsx` (the select saves on change; it holds a pending value and `onCancel` restores it).
+- [x] 2.3 `settings/SkillLearningSection.tsx` and `skills/use-skill-settings.ts`:
+ - the Record agent turns switch
+ - the redaction switch, where the inline Callout is replaced by the dialog and both directions confirm
+ - `skills/RecordPast.tsx` (Record past turns)
+- [x] 2.4 `settings/KeysAccessSection.tsx` (Save password, Clear password) and `settings/ApiTokensTable.tsx` (Generate token).
+- [x] 2.5 `settings/EmbeddingSection.tsx` (Retry after a failed re-embed) and `settings/CaptureControls.tsx`:
+ - Retry now, also through `DiagnosticsSection.tsx`
+ - the plain retention Save; the trace and zero-retention dialogs stay as the confirmation for their paths
+- [x] 2.6 `settings/ReasoningLevel.tsx` (normal Save), `settings/OpenRouterRouting.tsx` (Save routing), `settings/MemoryCleanupSection.tsx` (turning off and raising the days; the count dialog stays for turning on and lowering the days).
+- [x] 2.7 `settings/ExternalApiSection.tsx`:
+ - a passing test opens the confirm dialog
+ - an emptied URL or model confirms that the external API turns off
+ - Save anyway stays as the confirmation when the test cannot reach the server
+
+ Keep the file at 500 lines or fewer.
+
+## 3. Memory page cards
+
+Test-first rule as in group 2.
+
+- [x] 3.1 `memory/MemorySection.tsx`: Save memory limits and each row's Reset to default.
+- [x] 3.2 `memory/KeywordModeSection.tsx`, `memory/AutoCleanupSettings.tsx`, `memory/ProfileLearningSettingsSection.tsx` (Save; the Reset to default dialog stays) and `memory/ProfileCatchUpSection.tsx` (Pause).
+- [x] 3.3 `memory/RerankerSection.tsx`: Save confirms (it runs no test call; Test is its own button); "Replace the key file?" stays as the confirmation for its path. Keep the file at 500 lines or fewer.
+- [x] 3.4 `memory/DirectoryMapsSection.tsx`: Save removals and Restore. `settings/DirectoryMapHost.tsx`: Ignore.
+- [x] 3.5 `memory/HostSettings.tsx`: Save model, and turning automatic import off (turning it on keeps `TurnOnDialog`).
+- [x] 3.6 `memory/HostStatusHeader.tsx` and `memory/use-backfill.ts`: Use external API, Pause, Resume and Retry.
+- [x] 3.7 `memory/MemoryInjectionSection.tsx`: Save. The draft-only Reset to default opens no dialog; the Save after it lists the removed keys.
+
+## 4. Docs and rules
+
+- [x] 4.1 Update `web/AGENTS.md` (Actions): the rule covers settings saves and settings job actions, and local-only view preferences are excluded. Update `docs/web-ui-settings.md` and `docs/web-ui-memory.md`: each save asks first, with the dialog shown once in each guide. Run Prettier on the changed files.
+
+## 5. Verification
+
+- [x] 5.1 Run `bun run check` and the web test files changed in groups 1 to 3, then `tests/file-size-ceiling.test.ts`.
+- [x] 5.2 Browser check with Orca on a scratch web app (scratch HOME, free port). Check one form Save, one save-on-change select, one job action and one Reset to default:
+ - Cancel writes nothing (check the scratch config file)
+ - confirm writes the same value as before
+
+ Check desktop and 390 px widths and the Arabic layout. Save the screenshots in the scratchpad.
+
+- [x] 5.3 Run `bun run ci:local` and confirm that the exit line shows exit 0.
+- [x] 5.4 Run `graphify update .`.
diff --git a/openspec/specs/web-memory-hosts/spec.md b/openspec/specs/web-memory-hosts/spec.md
index 7210e7142..e245719b6 100644
--- a/openspec/specs/web-memory-hosts/spec.md
+++ b/openspec/specs/web-memory-hosts/spec.md
@@ -686,3 +686,27 @@ Every name, description, option and message in the learning table SHALL have Chi
- **WHEN** the language is Arabic and the user opens the Profile learning row
- **THEN** every label and option SHALL show in Arabic
- **AND** the config keys SHALL read left-to-right
+
+### Requirement: Host and overview saves confirm first
+
+On the host pages and the Memory overview these actions SHALL use the shared settings confirm dialog before they send a request: the host Save model, turning automatic import off, Use external API, Pause, Resume and Retry, Ignore on a folder row, and the opening context and compaction Save. The dialog content, Cancel and page checks SHALL follow the Settings rules. Turning automatic import on SHALL keep its existing dialog.
+
+#### Scenario: Turn automatic import off
+
+- **WHEN** the user clears "Import past chats automatically" for Pi
+- **THEN** a confirm dialog opens, and Cancel leaves the box ticked
+
+#### Scenario: Retry an import
+
+- **WHEN** the user selects **Retry** on a host whose import failed
+- **THEN** a confirm dialog says the retry calls the model again, and no run starts before the user confirms
+
+#### Scenario: Use external API
+
+- **WHEN** the user selects **Use external API** for OpenCode
+- **THEN** a confirm dialog says OpenCode will use the external API model, and nothing is saved before the user confirms
+
+#### Scenario: Opening context
+
+- **WHEN** the user changes the opening context and selects **Save**
+- **THEN** a confirm dialog lists the change and nothing is sent before the user confirms
diff --git a/openspec/specs/web-memory/spec.md b/openspec/specs/web-memory/spec.md
index 3232f0eff..153288157 100644
--- a/openspec/specs/web-memory/spec.md
+++ b/openspec/specs/web-memory/spec.md
@@ -279,3 +279,27 @@ Every string in the welcome panel SHALL exist in English, Chinese and Arabic. Th
- **WHEN** the language is Arabic and the screen is 390 px wide
- **THEN** the panel SHALL show Arabic text, right-to-left, with no sideways scrolling
+
+### Requirement: Shared Memory page saves confirm first
+
+On the shared Memory page these actions SHALL use the shared settings confirm dialog before they send a request: Save memory limits and each row's Reset to default, keyword mode, the reranker card's Save, profile learning Save, profile auto cleanup Save, catch-up Pause, and the directory maps Save removals and Restore. The dialog content, Cancel and page checks SHALL follow the Settings rules.
+
+#### Scenario: Memory limits
+
+- **WHEN** the user changes the maximum memories and selects **Save memory limits**
+- **THEN** a confirm dialog lists the change and nothing is sent before the user confirms
+
+#### Scenario: Reset one row
+
+- **WHEN** the user selects **Reset to default** on the similarity threshold row
+- **THEN** a confirm dialog shows the saved value and the default, and nothing is sent before the user confirms
+
+#### Scenario: Reranker switch
+
+- **WHEN** the user turns the reranker off and selects **Save**
+- **THEN** a confirm dialog opens, and Cancel leaves the saved reranker settings unchanged
+
+#### Scenario: Restore an ignored folder
+
+- **WHEN** the user selects **Restore** on an ignored folder
+- **THEN** a confirm dialog names the folder, and the folder stays ignored until the user confirms
diff --git a/openspec/specs/web-settings/spec.md b/openspec/specs/web-settings/spec.md
index 749edc966..fda20a85c 100644
--- a/openspec/specs/web-settings/spec.md
+++ b/openspec/specs/web-settings/spec.md
@@ -461,11 +461,11 @@ Every Settings endpoint that changes config, saves a key file, deletes trace fil
### Requirement: The page controls automatic import
-Each host view on the Memory page SHALL have a settings card with the **Import past chats automatically** switch for `autoBackfill`, which applies to every host, and, for Pi and OpenCode, a backfill model choice for `piBackfillModel` or `opencodeBackfillModel`: **Same as live capture** (saves `inherit`), **External API** (saves `external`), or a manual `provider/model`. Claude Code's backfill always uses the external API. The host view's status header SHALL show the backfill state, including paused and off, the counts of imported, skipped, failed, and pending exchanges, the number of sessions whose project cannot be resolved with a link to that host's list of sessions that need a folder, the model used, the cutoff, the last error, and the progress bar, percentage, and time left defined by the import progress capability. It SHALL offer Pause, Resume and Retry as the import progress capability defines. The counts SHALL refresh while a run is active. The settings card SHALL say that a model change takes effect at the next run, except that turning the switch off also stops a running automatic backfill after its current exchange. It SHALL say that automatic import makes model calls. Turning the switch on SHALL open the same confirm dialog as **Turn on** in the status header, and only its **Turn on** SHALL save; turning the switch off SHALL save at once with no dialog.
+Each host view on the Memory page SHALL have a settings card with the **Import past chats automatically** switch for `autoBackfill`, which applies to every host, and, for Pi and OpenCode, a backfill model choice for `piBackfillModel` or `opencodeBackfillModel`: **Same as live capture** (saves `inherit`), **External API** (saves `external`), or a manual `provider/model`. Claude Code's backfill always uses the external API. The host view's status header SHALL show the backfill state, including paused and off, the counts of imported, skipped, failed, and pending exchanges, the number of sessions whose project cannot be resolved with a link to that host's list of sessions that need a folder, the model used, the cutoff, the last error, and the progress bar, percentage, and time left defined by the import progress capability. It SHALL offer Pause, Resume and Retry as the import progress capability defines. The counts SHALL refresh while a run is active. The settings card SHALL say that a model change takes effect at the next run, except that turning the switch off also stops a running automatic backfill after its current exchange. It SHALL say that automatic import makes model calls. Turning the switch on SHALL open the same confirm dialog as **Turn on** in the status header, and only its **Turn on** SHALL save; turning the switch off SHALL ask in the shared settings confirm dialog first, and only its confirm SHALL save.
#### Scenario: Turning automatic import off
-- **WHEN** the user turns off the switch while an automatic Pi backfill runs
+- **WHEN** the user turns off the switch while an automatic Pi backfill runs, and confirms
- **THEN** the global config SHALL have `autoBackfill` set to `false`
- **AND** the Pi backfill SHALL stop after its current exchange
- **AND** the Pi status header SHALL read **Off** once the run has stopped
@@ -1212,7 +1212,7 @@ The External API, Embedding and Reranker cards SHALL use one key-entry control w
### Requirement: Every settings card saves the same way
-Each settings card with a server SHALL test the values in the form, not the saved values. Each card SHALL save with a Save button, not on leaving a field, and SHALL show a plain message after each test and save. An optional URL or model field SHALL be clearable, which removes the key. Every URL field SHALL accept only `http://` or `https://` URLs. An invalid number SHALL show a message next to the field.
+Each settings card with a server SHALL test the values in the form, not the saved values. Each card SHALL save with a Save button, not on leaving a field, SHALL confirm with the shared settings confirm dialog before it saves, and SHALL show a plain message after each test and save. A Save that tests first SHALL test, then confirm; when the test cannot reach the server, the existing Save anyway dialog SHALL be the confirmation.
#### Scenario: Testing an unsaved model
@@ -1221,7 +1221,7 @@ Each settings card with a server SHALL test the values in the form, not the save
#### Scenario: Clearing the API URL
-- **WHEN** the user empties the API URL and saves
+- **WHEN** the user empties the API URL, saves and confirms
- **THEN** `memoryApiUrl` SHALL be removed from the global config
#### Scenario: A URL without a scheme
@@ -1229,6 +1229,11 @@ Each settings card with a server SHALL test the values in the form, not the save
- **WHEN** the user saves `api.example.com/v1` as the API URL
- **THEN** the save SHALL be refused with a message that the URL must start with `http://` or `https://`
+#### Scenario: An invalid number
+
+- **WHEN** the user enters a value that is not a valid number in a number field and selects Save
+- **THEN** a message SHALL show next to the field, and no confirm dialog SHALL open
+
### Requirement: A save that deletes data asks first
A save that deletes stored data at once SHALL open a confirm dialog that states what will be deleted, with a count when one is known. Saving retry retention 0 SHALL read the waiting count again when Save is pressed and state how many waiting turns will be deleted. Nothing SHALL be saved until the user confirms.
@@ -1328,3 +1333,74 @@ Every link that names a Settings section SHALL select its chip and bring the sec
- **WHEN** the user searches for `retention` and chooses a result on the Memory cleanup card
- **THEN** the page SHALL show the Memory cleanup section with its chip pressed
- **AND** keyboard focus SHALL move to the card heading
+
+### Requirement: Settings saves confirm before sending
+
+Every action on the Settings and Memory pages that writes a setting or starts or stops a settings job SHALL open the shared settings confirm dialog first. The page SHALL send no request until the user confirms. The dialog SHALL show progress while the request runs, show a server error inside itself and stay open, and close on success. The confirmed request SHALL have the same body as it had before this rule.
+
+#### Scenario: Save button
+
+- **WHEN** the user changes the web app autostart box and selects **Save**
+- **THEN** a confirm dialog opens and no request is sent
+
+#### Scenario: Confirm
+
+- **WHEN** the user selects the confirm button in that dialog
+- **THEN** the page sends `webServerAutoStart` as before, shows progress, and closes the dialog when the save succeeds
+
+#### Scenario: Server refusal
+
+- **WHEN** the server refuses a confirmed save
+- **THEN** the dialog shows the server's reason and stays open
+
+### Requirement: Cancel and page checks
+
+**Cancel** SHALL send nothing. A control that saves on change, such as a select, switch or checkbox, SHALL show its saved value again after Cancel. Text the user typed in a form SHALL stay as a draft after Cancel. A value that breaks a rule the page checks SHALL show its message on the page, and no dialog SHALL open.
+
+#### Scenario: Cancel a select
+
+- **WHEN** the user picks a new summary language and then selects **Cancel**
+- **THEN** nothing is saved and the select shows the saved language
+
+#### Scenario: Cancel a form
+
+- **WHEN** the user types a Claude Code folder, selects **Save folder** and then **Cancel**
+- **THEN** nothing is saved and the typed folder stays in the box
+
+#### Scenario: Invalid value
+
+- **WHEN** the user enters an interval outside its range and selects **Save**
+- **THEN** the page shows the range message and no dialog opens
+
+### Requirement: The dialog lists the changes
+
+The dialog SHALL name the card and list each setting the save changes, with its saved value and its new value in plain words. A reset to default SHALL show the default as the new value. A job action SHALL say in one sentence what the job does, for example that a retry calls the model again.
+
+#### Scenario: Two settings change
+
+- **WHEN** the user turns off automatic capture, picks a new default scope and selects **Save**
+- **THEN** the dialog lists both settings, each with its old and new value
+
+#### Scenario: Job action
+
+- **WHEN** the user selects **Retry now** for a host
+- **THEN** the dialog says the waiting captures will be sent to the model again
+
+### Requirement: Settings page cards confirm every save
+
+On the Settings page these actions SHALL confirm first: the host model Save, the summary language, the Claude Code folder, web app autostart, Memory basics, the two Skill learning switches, Record past turns, Save password, Clear password, Generate token, the embedding Retry, capture Retry now, capture retention, the reasoning level, the external API Save, OpenRouter routing and memory cleanup. Each card's own special dialogs SHALL stay.
+
+#### Scenario: External API turned off
+
+- **WHEN** the user empties the external API URL and selects **Save settings**
+- **THEN** a confirm dialog says the external API will be turned off, and nothing is sent before the user confirms
+
+#### Scenario: Turn off redaction
+
+- **WHEN** the user turns off "Remove private text and secrets"
+- **THEN** the shared confirm dialog opens in place of the inline warning, and Cancel leaves redaction on
+
+#### Scenario: Memory cleanup turned off
+
+- **WHEN** the user turns off memory cleanup and selects **Save**
+- **THEN** a confirm dialog opens, although turning it off deletes nothing
diff --git a/web/AGENTS.md b/web/AGENTS.md
index d324a7628..4bf7d83ab 100644
--- a/web/AGENTS.md
+++ b/web/AGENTS.md
@@ -64,6 +64,9 @@ One dialog per space operation, in `src/lib/components/spaces/`. The owners are
- Every action that sends a request shows a visible answer at once and again when it ends (see the "Feedback after a click" section of the design reference).
- Every action that changes state opens a confirm dialog first (`SpaceConfirmDialog` is the example): a title that names the thing, a plain sentence on the effect, Cancel and a confirm button. Nothing is sent until the user confirms. The dialog shows progress while the request runs, shows a server error inside itself and stays open, and closes on success.
+- A settings save or a settings job action on the Settings page or the Memory page uses the shared settings confirm dialog (`useSettingsConfirm`). This covers Save buttons, controls that save on change, Reset to default, and buttons that start or stop a job, such as Pause, Resume and Retry.
+- The settings dialog has a title that names the card, and a body from `useSettingsChanges` and `SettingsChangeList`. Build the list from the same edits object that the request sends. A job action gets one sentence. Open one dialog for each click: when a card has its own special dialog for a path, that dialog is the confirmation. A page check comes first, and no dialog opens when the page refuses a value. **Cancel** sends nothing. A control that saves on change shows its saved value again. Typed text stays as a draft. Copy `MemoryBasicsSection.tsx` for a form, or `CaptureLanguageSection.tsx` for a control that saves on change.
+- A choice that changes only how the page looks needs no dialog, because it writes no server state. These are the theme, the palette, the date and time format, the language, the sidebar, paging and filters.
- A delete or another action that cannot be undone asks for the exact name in a dialog. The confirm button stays disabled until the text matches.
- Every clickable control shows a pointer cursor, and a disabled one does not. The shared `Button` carries `cursor-pointer` and `disabled:pointer-events-none`. A raw `` needs `cursor-pointer` in its class. A link already shows a pointer.
- Show the server's reason when a request fails. Keep the previous state on screen.
diff --git a/web/src/hooks/useDirectoryMapConfirm.tsx b/web/src/hooks/useDirectoryMapConfirm.tsx
new file mode 100644
index 000000000..d1cb881d7
--- /dev/null
+++ b/web/src/hooks/useDirectoryMapConfirm.tsx
@@ -0,0 +1,80 @@
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { PathMap } from "$lib/external-api-settings";
+import { useSettingsText } from "$lib/i18n/settings";
+import { fill } from "$lib/skills-model";
+
+/** What a directory-map save answers: undefined once saved, else the failure message. */
+type Save = () => Promise;
+
+/**
+ * Puts the Directory maps saves behind the shared confirm dialog. Save removals lists how many
+ * saved maps remain; Ignore and Restore each name the folder in one sentence. `run` is the card's
+ * existing save, unchanged, and its failure message reaches the dialog. Render `dialog` once.
+ */
+export function useDirectoryMapConfirm() {
+ const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
+ const mapCount = (value: unknown) => {
+ const count = Array.isArray(value) ? value.length : 0;
+ return count === 1 ? s("1 map") : fill(s("{count} maps"), { count });
+ };
+ const fields = [{ key: "importPathMaps", label: name("importPathMaps"), print: mapCount }];
+ const answer = async (run: Save) => {
+ const failure = await run();
+ return failure === undefined ? { success: true } : { success: false, error: s(failure) };
+ };
+ const askFolder = (
+ title: string,
+ sentence: string,
+ confirmLabel: string,
+ folder: string,
+ run: Save
+ ) =>
+ ask({
+ title,
+ body: (
+
+ {folder} . {sentence}
+
+ ),
+ confirmLabel,
+ busyLabel: s("Saving…"),
+ run: () => answer(run),
+ });
+
+ return {
+ dialog,
+ /** Save removals: the count of saved maps before and after. */
+ askRemovals: (saved: readonly PathMap[], edits: readonly PathMap[], run: Save) =>
+ ask({
+ title: s("Save removals?"),
+ body: (
+
+ ),
+ confirmLabel: s("Save removals"),
+ busyLabel: s("Saving…"),
+ run: () => answer(run),
+ }),
+ askIgnore: (folder: string, run: Save) =>
+ askFolder(
+ s("Ignore this folder?"),
+ s("The folder stays unimported and leaves the unresolved counts."),
+ s("Ignore"),
+ folder,
+ run
+ ),
+ askRestore: (folder: string, run: Save) =>
+ askFolder(
+ s("Restore this folder?"),
+ s("The folder shows again in each host list that reported it."),
+ s("Restore"),
+ folder,
+ run
+ ),
+ };
+}
diff --git a/web/src/hooks/useExternalApiConfirm.tsx b/web/src/hooks/useExternalApiConfirm.tsx
new file mode 100644
index 000000000..8a95c5a3f
--- /dev/null
+++ b/web/src/hooks/useExternalApiConfirm.tsx
@@ -0,0 +1,92 @@
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
+import type { SavedKey } from "$lib/components/settings/KeySourceField";
+import type { KeySource } from "$lib/external-api-settings";
+import { useCardText } from "$lib/i18n/settings-cards";
+import { providerName } from "$lib/provider-names";
+
+/** The values in force and the edits, keyed as the request spells them. */
+export type ExternalApiConfirmState = {
+ saved: Record;
+ edits: Record;
+ /** The key the user entered, when the save writes one. Never the key value itself. */
+ key: { source: KeySource; name: string; path: string } | undefined;
+ savedKey: SavedKey;
+};
+
+export type ExternalApiSaveAsk = {
+ title: string;
+ /** A sentence before the list, such as the turn-off note. */
+ lead?: string;
+ confirmLabel: string;
+ busyLabel?: string;
+ run: () => Promise;
+};
+
+const KEY_WORDS = {
+ env: "environment variable",
+ file: "key file",
+ paste: "key file",
+ literal: "set in the config file",
+} as const;
+
+/** The saved key in words: its source and where it lives, never the key itself. */
+function savedKeyWords(t: (message: string) => string, saved: SavedKey): string {
+ if (!saved?.source) return t("Not set");
+ const words = t(KEY_WORDS[saved.source]);
+ return saved.reference ? `${words} ${saved.reference}` : words;
+}
+
+/** The entered key in words: where it will live, never the key itself. */
+function enteredKeyWords(
+ t: (message: string) => string,
+ key: { source: KeySource; name: string; path: string }
+): string {
+ if (key.source === "env") return `${t(KEY_WORDS.env)} ${key.name.trim()}`;
+ if (key.source === "file") return `${t(KEY_WORDS.file)} ${key.path.trim()}`;
+ return `${t(KEY_WORDS.paste)} ${key.name.trim() || "memory-api"}`;
+}
+
+/**
+ * Puts each External API save behind the shared confirm dialog, with the change list built from
+ * the same edits the save sends. Nothing is sent until the user confirms. `ask` stays free for
+ * the card's own special dialogs, which share the one rendered `dialog`.
+ */
+export function useExternalApiConfirm(state: ExternalApiConfirmState) {
+ const t = useCardText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
+ const fields = [
+ {
+ key: "memoryProvider",
+ label: name("memoryProvider"),
+ print: (value: unknown) => (value ? providerName(String(value)) : t("Not set")),
+ },
+ { key: "memoryApiUrl", label: name("memoryApiUrl") },
+ { key: "memoryModel", label: name("memoryModel") },
+ { key: "memoryApiKey", label: name("memoryApiKey") },
+ ];
+ const inForce = { ...state.saved, memoryApiKey: savedKeyWords(t, state.savedKey) };
+ const edits = state.key
+ ? { ...state.edits, memoryApiKey: enteredKeyWords(t, state.key) }
+ : state.edits;
+
+ /** Opens the shared dialog with the change list, after the card's own lead sentence. */
+ function askSave(request: ExternalApiSaveAsk) {
+ ask({
+ title: request.title,
+ body: (
+ <>
+ {request.lead ? {request.lead}
: null}
+
+ >
+ ),
+ confirmLabel: request.confirmLabel,
+ busyLabel: request.busyLabel,
+ run: request.run,
+ });
+ }
+ return { ask, dialog, askSave };
+}
diff --git a/web/src/hooks/useSettingsChanges.ts b/web/src/hooks/useSettingsChanges.ts
new file mode 100644
index 000000000..a943e5ab0
--- /dev/null
+++ b/web/src/hooks/useSettingsChanges.ts
@@ -0,0 +1,34 @@
+import { useCatalogueText } from "$lib/i18n/settings-catalogue";
+import { findCatalogueEntry } from "$lib/settings-catalogue";
+import {
+ settingsChanges,
+ type SettingsChange,
+ type SettingsChangeField,
+} from "$lib/settings-changes";
+
+/**
+ * What a card needs to fill the shared settings confirm dialog. Call `changes` where the card
+ * builds its request, so the list and the request body come from the same edits.
+ */
+export function useSettingsChanges() {
+ const t = useCatalogueText();
+ const words = {
+ on: t("On"),
+ off: t("Off"),
+ notSet: t("Not set"),
+ default: (value: string) => t("Default ({value})", { value }),
+ };
+ return {
+ /** The rows of the change list, in the order of `fields`. */
+ changes: (
+ saved: Record,
+ edits: Record,
+ fields: readonly SettingsChangeField[]
+ ): SettingsChange[] => settingsChanges(saved, edits, fields, words),
+ /** A setting's name in the language of the page, or its key when the catalogue has no entry. */
+ name: (key: string): string => {
+ const entry = findCatalogueEntry(key);
+ return entry ? t(entry.name) : key;
+ },
+ };
+}
diff --git a/web/src/hooks/useSettingsConfirm.tsx b/web/src/hooks/useSettingsConfirm.tsx
index 74b82aee3..9a6f647fa 100644
--- a/web/src/hooks/useSettingsConfirm.tsx
+++ b/web/src/hooks/useSettingsConfirm.tsx
@@ -1,4 +1,5 @@
import { useRef, useState, type ReactNode } from "react";
+import { useCatalogueText } from "$lib/i18n/settings-catalogue";
import {
SettingsConfirmDialog,
type ConfirmResult,
@@ -24,10 +25,17 @@ export type ConfirmRequest = {
* `dialog` once in the card. The dialog mounts only while a request is pending.
*/
export function useSettingsConfirm() {
+ const t = useCatalogueText();
const [pending, setPending] = useState(null);
+ // A failed run keeps values and a revision from the click, which the card may have reloaded.
+ // Confirming again could resend a rejected revision, so the user closes and saves again.
+ const [failed, setFailed] = useState(false);
const confirmed = useRef(false);
+ const current = useRef(null);
const ask = (request: ConfirmRequest) => {
confirmed.current = false;
+ current.current = request;
+ setFailed(false);
setPending(request);
};
const dialog = pending ? (
@@ -36,15 +44,24 @@ export function useSettingsConfirm() {
body={pending.body}
confirmLabel={pending.confirmLabel}
busyLabel={pending.busyLabel}
- blocked={pending.blocked}
+ blocked={
+ failed
+ ? t("Close this dialog and save again, so it shows the current settings.")
+ : pending.blocked
+ }
destructive={pending.destructive}
onConfirm={async () => {
- const result = await pending.run();
+ const request = pending;
+ const result = await request.run();
confirmed.current = result.success;
+ // A run that asked a follow-up question (a new request) has not failed.
+ if (!result.success && current.current === request) setFailed(true);
return result;
}}
onClose={() => {
if (!confirmed.current) pending.onCancel?.();
+ setFailed(false);
+ current.current = null;
setPending(null);
}}
/>
diff --git a/web/src/lib/components/memory/AutoCleanupSettings.tsx b/web/src/lib/components/memory/AutoCleanupSettings.tsx
index 582cfc769..a53d516fe 100644
--- a/web/src/lib/components/memory/AutoCleanupSettings.tsx
+++ b/web/src/lib/components/memory/AutoCleanupSettings.tsx
@@ -1,9 +1,13 @@
import { useEffect, useState } from "react";
import { onSettingsSnapshot, reloadSettingsSnapshot, settingsRequest } from "$lib/settings-api";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { SettingRow } from "$lib/components/settings/SettingRow";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Switch } from "$lib/components/ui/switch";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { useCatalogueText } from "$lib/i18n/settings-catalogue";
import { useSettingsText } from "$lib/i18n/settings";
import { enabledEdit, intervalEdit } from "./auto-cleanup-settings-state";
@@ -30,6 +34,8 @@ export function AutoCleanupSettings() {
const [fieldError, setFieldError] = useState("");
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const savedEnabled = snapshot?.settings.userProfileAutoCleanupEnabled?.globalValue !== false;
const savedInterval = Number(
@@ -62,9 +68,10 @@ export function AutoCleanupSettings() {
if (snapshot) setDraft(String(savedInterval));
}, [snapshot, savedInterval]);
- async function save(edits: Record) {
- if (!snapshot) return;
+ async function save(edits: Record): Promise {
+ if (!snapshot) return { success: false };
setBusy(true);
+ let failure: string | undefined;
try {
await settingsRequest("/api/settings", {
method: "PATCH",
@@ -73,10 +80,12 @@ export function AutoCleanupSettings() {
setEnabled(undefined);
setMessage(s("Saved. Changes apply at the next learning pass."));
} catch (error) {
- setMessage((error as Error).message);
+ failure = (error as Error).message;
+ setMessage(failure);
}
await reloadSettingsSnapshot();
setBusy(false);
+ return failure === undefined ? { success: true } : { success: false, error: s(failure) };
}
function saveAll() {
@@ -90,7 +99,27 @@ export function AutoCleanupSettings() {
...enabledEdit(savedEnabled, nextEnabled),
...(result.kind === "edit" ? result.edits : {}),
};
- if (Object.keys(edits).length > 0) void save(edits);
+ if (Object.keys(edits).length === 0) return;
+ const inForce = {
+ userProfileAutoCleanupEnabled: savedEnabled,
+ userProfileAutoCleanupInterval: savedInterval,
+ };
+ const fields = [
+ { key: "userProfileAutoCleanupEnabled", label: name("userProfileAutoCleanupEnabled") },
+ {
+ key: "userProfileAutoCleanupInterval",
+ label: name("userProfileAutoCleanupInterval"),
+ default: DEFAULT_INTERVAL,
+ print: (value: unknown) => `${String(value)} ${s("prompts")}`,
+ },
+ ];
+ ask({
+ title: s("Save automatic profile cleanup?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ run: () => save(edits),
+ });
}
return (
@@ -153,6 +182,7 @@ export function AutoCleanupSettings() {
{message}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/DirectoryMapIgnoredList.tsx b/web/src/lib/components/memory/DirectoryMapIgnoredList.tsx
new file mode 100644
index 000000000..ecb0793df
--- /dev/null
+++ b/web/src/lib/components/memory/DirectoryMapIgnoredList.tsx
@@ -0,0 +1,45 @@
+import { Button } from "$lib/components/ui/button";
+import { useSettingsText } from "$lib/i18n/settings";
+
+type Props = {
+ ignored?: string[];
+ restoreDisabled: boolean;
+ onRestore: (directory: string) => void;
+};
+
+/** The Ignored directories disclosure; each Restore asks before it saves. */
+export function DirectoryMapIgnoredList({ ignored, restoreDisabled, onRestore }: Props) {
+ const s = useSettingsText();
+ return (
+
+
+ {s("Ignored directories")} ·{" "}
+ {ignored?.length ?? 0}
+
+ {s("Ignored directories stay unimported and leave the unresolved counts.")}
+
+
+
+ {!ignored?.length && {s("none")} }
+ {ignored?.map((directory) => (
+
+
+ {directory}
+
+ onRestore(directory)}
+ >
+ {s("Restore")}
+
+
+ ))}
+
+
+ );
+}
diff --git a/web/src/lib/components/memory/DirectoryMapsSection.tsx b/web/src/lib/components/memory/DirectoryMapsSection.tsx
index eca07ab56..8e53e73a8 100644
--- a/web/src/lib/components/memory/DirectoryMapsSection.tsx
+++ b/web/src/lib/components/memory/DirectoryMapsSection.tsx
@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react";
+import { useDirectoryMapConfirm } from "@/hooks/useDirectoryMapConfirm";
import {
onSettingsSnapshot,
publishSettingsSnapshot,
@@ -18,6 +19,7 @@ import {
type DirectoryMapReview,
type SuggestedDirectory,
} from "$lib/directory-maps";
+import { DirectoryMapIgnoredList } from "./DirectoryMapIgnoredList";
import { DirectoryMapHost } from "../settings/DirectoryMapHost";
import { DirectoryMapReviewDialog } from "../settings/DirectoryMapReviewDialog";
import { IgnoreAllDialog } from "../settings/IgnoreAllDialog";
@@ -39,6 +41,7 @@ type View = {
};
const ALL_HOSTS = ["pi", "opencode", "claude-code"] as const;
+const LOADING = "The list is still loading. Try again in a moment.";
/**
* The Directory maps card. The Shared view shows the saved maps and ignored
@@ -57,6 +60,7 @@ export function DirectoryMapsSection({
anchorId?: string;
} = {}) {
const s = useSettingsText();
+ const confirms = useDirectoryMapConfirm();
const [ignoringAll, setIgnoringAll] = useState<{ host: WebHost; rows: Suggested[] }>();
const [snapshot, setSnapshot] = useState();
const [view, setView] = useState();
@@ -124,20 +128,21 @@ export function DirectoryMapsSection({
// The server supplies resolved paths, also used by rows and Restore.
const ignoredList = () => view?.ignored ?? [];
- /** Save removals, Ignore, and Restore: one immediate save, then a fresh list. */
+ /** The page check before a dialog opens. A refused save must say so; a pending refresh and a
+ * running save already show their own message. */
+ function ready(): boolean {
+ if (snapshot && view && !saving.current && !refreshNeeded) return true;
+ if (!saving.current && !refreshNeeded) setMessage(LOADING);
+ return false;
+ }
+ /** Save removals, Ignore, and Restore: one save, then a fresh list. The answer is the
+ * failure message, or undefined once saved, so the confirm dialog can show the reason. */
async function saveNow(
edits: Record,
done: string,
failed: string
- ): Promise {
- if (!snapshot || !view || saving.current || refreshNeeded) {
- // A refused save must say so; a silent no-op looks like a broken button.
- // A pending refresh and a running save already show their own message.
- if (!saving.current && !refreshNeeded) {
- setMessage("The list is still loading. Try again in a moment.");
- }
- return false;
- }
+ ): Promise {
+ if (!snapshot || !ready()) return LOADING;
saving.current = true;
setBusy(true);
try {
@@ -149,20 +154,24 @@ export function DirectoryMapsSection({
const conflict = error instanceof SettingsRequestError && error.status === 409;
try {
if (!conflict) {
- setMessage(failed);
+ // The server's reason follows the card's own words, when it gave one.
+ const reason = error instanceof Error ? error.message : "";
+ const text = reason ? `${failed} ${reason}` : failed;
+ setMessage(text);
await reloadSettingsSnapshot();
- return false;
+ return text;
}
- setMessage("Settings changed elsewhere. Check the list and try again.");
+ let failure = "Settings changed elsewhere. Check the list and try again.";
+ setMessage(failure);
try {
await refreshReview();
} catch {
setRefreshNeeded("conflict");
- setMessage(
- "Settings changed elsewhere and could not be refreshed. Refresh the list, then try again."
- );
+ failure =
+ "Settings changed elsewhere and could not be refreshed. Refresh the list, then try again.";
+ setMessage(failure);
}
- return false;
+ return failure;
} finally {
saving.current = false;
setBusy(false);
@@ -180,22 +189,30 @@ export function DirectoryMapsSection({
saving.current = false;
setBusy(false);
}
- return true;
+ return undefined;
}
function saveRemovals() {
- void saveNow(
- { importPathMaps: mapsToSave(view?.saved ?? [], removed) },
- "Saved. Removed maps stop applying at the next import or backfill run.",
- "Removals could not be saved. Try again."
- ).then((saved) => {
- if (saved) setRemoved(new Set());
+ if (!ready()) return;
+ const maps = view?.saved ?? [];
+ const edits = mapsToSave(maps, removed);
+ confirms.askRemovals(maps, edits, async () => {
+ const failure = await saveNow(
+ { importPathMaps: edits },
+ "Saved. Removed maps stop applying at the next import or backfill run.",
+ "Removals could not be saved. Try again."
+ );
+ if (failure === undefined) setRemoved(new Set());
+ return failure;
});
}
function ignore(row: Suggested) {
- void saveNow(
- { importIgnoredDirectories: [...new Set([...ignoredList(), row.directory])] },
- "Ignored. The directory stays unimported.",
- "The directory could not be ignored. Try again."
+ if (!ready()) return;
+ confirms.askIgnore(row.directory, () =>
+ saveNow(
+ { importIgnoredDirectories: [...new Set([...ignoredList(), row.directory])] },
+ "Ignored. The directory stays unimported.",
+ "The directory could not be ignored. Try again."
+ )
);
}
function ignoreAll() {
@@ -205,16 +222,19 @@ export function DirectoryMapsSection({
{ importIgnoredDirectories: ignoreAllList(ignoredList(), rows) },
"Ignored. The directories stay unimported.",
"The directories could not be ignored. Try again."
- ).then((saved) => {
+ ).then((failure) => {
// A failed or refused save keeps the dialog open, with the reason on the page.
- if (saved) setIgnoringAll(undefined);
+ if (failure === undefined) setIgnoringAll(undefined);
});
}
function restore(directory: string) {
- void saveNow(
- { importIgnoredDirectories: ignoredList().filter((item) => item !== directory) },
- "Restored. The directory shows again in each host list that reported it.",
- "The directory could not be restored. Try again."
+ if (!ready()) return;
+ confirms.askRestore(directory, () =>
+ saveNow(
+ { importIgnoredDirectories: ignoredList().filter((item) => item !== directory) },
+ "Restored. The directory shows again in each host list that reported it.",
+ "The directory could not be restored. Try again."
+ )
);
}
async function refreshReview() {
@@ -408,36 +428,11 @@ export function DirectoryMapsSection({
))}
-
-
-
- {s("Ignored directories")}
- {" "}
- · {view?.ignored?.length ?? 0}
-
- {s("Ignored directories stay unimported and leave the unresolved counts.")}
-
-
-
- {!view?.ignored?.length && {s("none")} }
- {view?.ignored?.map((directory) => (
-
-
- {directory}
-
- restore(directory)}
- >
- {s("Restore")}
-
-
- ))}
-
-
+
>
)}
{hosts.map((host) => {
@@ -495,6 +490,7 @@ export function DirectoryMapsSection({
{s(message)}
)}
+ {confirms.dialog}
);
}
diff --git a/web/src/lib/components/memory/HostSettings.tsx b/web/src/lib/components/memory/HostSettings.tsx
index d6516ba35..9a34d63c3 100644
--- a/web/src/lib/components/memory/HostSettings.tsx
+++ b/web/src/lib/components/memory/HostSettings.tsx
@@ -1,7 +1,16 @@
import { useState } from "react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
+import { Input } from "$lib/components/ui/input";
import { Select } from "$lib/components/ui/select";
-import { manualModelFieldVisible, type ModelBackfillHost } from "$lib/auto-import-settings";
+import { Switch } from "$lib/components/ui/switch";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import {
+ backfillModelEdit,
+ manualModelFieldVisible,
+ type ModelBackfillHost,
+} from "$lib/auto-import-settings";
import { externalMissing } from "$lib/external-api-settings";
import { hostLabel, type WebHost } from "$lib/host-label";
import { useSettingsText } from "$lib/i18n/settings";
@@ -14,11 +23,16 @@ export function HostSettings({ host, backfill }: { host: WebHost; backfill: Back
const s = useSettingsText();
const readOnly = useSettingsReadOnly();
const { snapshot, lists, busy } = backfill;
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes } = useSettingsChanges();
const [choice, setChoice] = useState();
const [typedMode, setTypedMode] = useState();
- // Turning automatic import on costs money on every host, so it asks first; off needs no question.
+ // Turning automatic import on costs money on every host, so it keeps its own Turn on dialog.
const [asking, setAsking] = useState(false);
+ /** The switch while the turn-off dialog asks. Cancel puts the saved value back. */
+ const [pendingAuto, setPendingAuto] = useState();
const settings = snapshot?.settings ?? {};
+ const savedAuto = Boolean(settings.autoBackfill?.globalValue);
const saved = String(settings[`${host}BackfillModel`]?.globalValue ?? "inherit");
const current = choice ?? saved;
const options = lists[host]?.models ?? [];
@@ -33,6 +47,59 @@ export function HostSettings({ host, backfill }: { host: WebHost; backfill: Back
memoryApiUrl: settings.memoryApiUrl?.globalValue as string | undefined,
keySet: Boolean(snapshot?.secrets?.memoryApiKey?.set),
});
+ const modelName = (value: unknown) =>
+ value === "inherit"
+ ? s("Same as live capture")
+ : value === "external"
+ ? s("External API")
+ : String(value);
+
+ /** A bad manual model shows its message on the page and opens no dialog. */
+ function askModel() {
+ let edits: Record;
+ try {
+ edits = backfillModelEdit(host as ModelBackfillHost, current.trim());
+ } catch (error) {
+ backfill.setMessage(s((error as Error).message));
+ return;
+ }
+ const key = `${host}BackfillModel`;
+ const rows = changes({ [key]: saved }, edits, [
+ { key, label: s("Backfill model"), print: modelName },
+ ]);
+ ask({
+ title: s("Save the backfill model?"),
+ body: ,
+ confirmLabel: s("Save model"),
+ busyLabel: s("Saving…"),
+ run: () => backfill.save(edits),
+ });
+ }
+
+ /** Asks before automatic import turns off. The box shows the cleared state meanwhile. */
+ function askTurnOff() {
+ const edits = { autoBackfill: false };
+ setPendingAuto(false);
+ ask({
+ title: s("Turn automatic import off?"),
+ body: (
+
+ ),
+ confirmLabel: s("Turn off"),
+ busyLabel: s("Saving…"),
+ onCancel: () => setPendingAuto(undefined),
+ run: async () => {
+ const result = await backfill.save(edits);
+ // The reloaded snapshot shows the saved value, so the picked one can go.
+ if (result.success) setPendingAuto(undefined);
+ return result;
+ },
+ });
+ }
return (
);
}
diff --git a/web/src/lib/components/memory/HostStatusHeader.tsx b/web/src/lib/components/memory/HostStatusHeader.tsx
index 1bfbea09b..33ed39eeb 100644
--- a/web/src/lib/components/memory/HostStatusHeader.tsx
+++ b/web/src/lib/components/memory/HostStatusHeader.tsx
@@ -1,4 +1,5 @@
import { Pause, Play, Power, RotateCw, ExternalLink } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
import { Button } from "$lib/components/ui/button";
import type { ModelBackfillHost } from "$lib/auto-import-settings";
import { hostLabel, type WebHost } from "$lib/host-label";
@@ -26,21 +27,60 @@ const STATE_LABEL: Record = {
stopped: "Stopped",
};
+/** What each job action asks before it runs. */
+const JOB_TEXT = {
+ pause: {
+ title: "Pause automatic import?",
+ sentence:
+ "Automatic import stops after the current exchange, and no automatic run starts until you resume it.",
+ },
+ resume: {
+ title: "Resume automatic import?",
+ sentence: "Automatic import starts again and makes model calls, which can cost money.",
+ },
+ retry: {
+ title: "Retry the import?",
+ sentence: "The import runs again, so it calls the model again and can cost money.",
+ },
+} as const;
+/** The request each job action sends once the user confirms. */
+const JOB_REQUEST = { pause: "pause", resume: "resume", retry: "run" } as const;
+
/** The host's state, its one main action, and the sentence that explains both. */
export function HostStatusHeader({ host, statuses }: { host: WebHost; statuses: HostStatuses }) {
const s = useSettingsText();
const { looks } = useHostLooks();
+ const { ask, dialog } = useSettingsConfirm();
const { backfill } = statuses;
const status = statuses.status(host);
const facts = statuses.input(host);
const row = backfill.rows[host];
const run = backfill.runs?.[host]?.run ?? null;
+ /** Each job action asks first, with one sentence on what it does. */
const act = () => {
const kind = status.action.kind;
- if (kind === "pause") void backfill.control(host, "pause");
- else if (kind === "resume") void backfill.control(host, "resume");
- else if (kind === "retry") void backfill.control(host, "run");
+ if (!(kind in JOB_TEXT)) return;
+ const job = kind as keyof typeof JOB_TEXT;
+ ask({
+ title: s(JOB_TEXT[job].title),
+ body: {s(JOB_TEXT[job].sentence)}
,
+ confirmLabel: label[job],
+ run: () => backfill.control(host, JOB_REQUEST[job]),
+ });
};
+ const useExternal = () =>
+ ask({
+ title: s("Use the external API?"),
+ body: (
+
+ {s(
+ "{host} will use the external API model to import past chats. It can then run with no host open."
+ ).replace("{host}", hostLabel(host))}
+
+ ),
+ confirmLabel: s("Use external API"),
+ run: () => backfill.saveModel(host as ModelBackfillHost, "external"),
+ });
const label: Record = {
setup: s("How to set up"),
pause: s("Pause"),
@@ -103,7 +143,9 @@ export function HostStatusHeader({ host, statuses }: { host: WebHost; statuses:
) : status.action.kind === "turn-on" ? (
backfill.save({ autoBackfill: true })}
+ onConfirm={async () => {
+ await backfill.save({ autoBackfill: true });
+ }}
/>
) : (
@@ -117,12 +159,7 @@ export function HostStatusHeader({ host, statuses }: { host: WebHost; statuses:
)}
{status.offerExternal && (
- backfill.saveModel(host as ModelBackfillHost, "external")}
- >
+
{s("Use external API")}
)}
@@ -147,6 +184,7 @@ export function HostStatusHeader({ host, statuses }: { host: WebHost; statuses:
{s("Importing makes model calls and can cost money.")}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/KeywordModeSection.tsx b/web/src/lib/components/memory/KeywordModeSection.tsx
index 2690cdf78..50f1203f3 100644
--- a/web/src/lib/components/memory/KeywordModeSection.tsx
+++ b/web/src/lib/components/memory/KeywordModeSection.tsx
@@ -6,9 +6,13 @@ import {
settingsRequest,
withNote,
} from "$lib/settings-api";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
import { SettingRow } from "$lib/components/settings/SettingRow";
import { Select } from "$lib/components/ui/select";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { useSettingsText } from "$lib/i18n/settings";
import { useCatalogueText } from "$lib/i18n/settings-catalogue";
import { PLAIN_TEXT } from "$lib/settings-catalogue";
@@ -35,6 +39,8 @@ export function KeywordModeSection() {
const [mode, setMode] = useState("boost");
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const saving = useRef(false);
const latest = useRef(undefined);
useEffect(() => {
@@ -75,25 +81,46 @@ export function KeywordModeSection() {
const reranker = snapshot ? rerankerOverridesMode(snapshot.settings) : false;
const readOnly = snapshot?.readOnly === true;
- async function save() {
+ // The same words the dropdown shows, in the language of the page.
+ const modeName = (value: unknown) => {
+ const label = KEYWORD_MODE_OPTIONS.find((option) => option.value === value)?.label;
+ return label ? t(label) : String(value);
+ };
+ const fields = [{ key: "keywordMode", label: name("keywordMode"), print: modeName }];
+ /** Asks first; the choice stays in the dropdown until the dialog closes. */
+ function save() {
if (!snapshot || saving.current) return;
+ const edits = keywordModeSaveEdits(mode);
+ ask({
+ title: s("Save keyword matching?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ run: () => commit(edits),
+ });
+ }
+ async function commit(edits: { keywordMode: KeywordMode }): Promise {
+ if (!snapshot || saving.current) return { success: false };
saving.current = true;
setBusy(true);
let ok = false;
let stale = false;
+ let failure: string | undefined;
try {
await settingsRequest("/api/settings", {
method: "PATCH",
- body: JSON.stringify({ edits: keywordModeSaveEdits(mode), revision: snapshot.revision }),
+ body: JSON.stringify({ edits, revision: snapshot.revision }),
});
ok = true;
} catch (error) {
- stale = (error as Error)?.message?.includes("Config changed") === true;
+ failure = (error as Error)?.message ?? "";
+ stale = failure.includes("Config changed") === true;
}
const reloaded = (await reloadSettingsSnapshot()) !== null;
setBusy(false);
saving.current = false;
setStatus(stale ? { kind: "save", ok, reloaded, stale } : { kind: "save", ok, reloaded });
+ return ok ? { success: true } : { success: false, error: s(failure ?? "") };
}
function statusText(current: Status): string {
@@ -174,6 +201,7 @@ export function KeywordModeSection() {
{statusText(status)}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/MemoryInjectionSection.tsx b/web/src/lib/components/memory/MemoryInjectionSection.tsx
index bb808fbba..d064620b7 100644
--- a/web/src/lib/components/memory/MemoryInjectionSection.tsx
+++ b/web/src/lib/components/memory/MemoryInjectionSection.tsx
@@ -1,4 +1,8 @@
import { useEffect, useRef, useState } from "react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Switch } from "$lib/components/ui/switch";
@@ -40,6 +44,9 @@ export function MemoryInjectionSection() {
const [draft, setDraft] = useState(DEFAULT_INJECTION_DRAFT);
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState();
+ // After the card's own state, whose order the section spec relies on.
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const saving = useRef(false);
// The draft the file held at the last load, so a refresh keeps typed values.
const loaded = useRef(DEFAULT_INJECTION_DRAFT);
@@ -77,18 +84,42 @@ export function MemoryInjectionSection() {
setDraft((previous) => ({ ...previous, ...patch }));
const readOnly = snapshot?.readOnly === true;
- async function save() {
+ /** Asks first, with each setting the save changes. A value back at its default reads Default. */
+ function save() {
if (!snapshot || !canSave || saving.current) return;
+ const edits = injectionSaveEdits(draft, loaded.current);
+ const saved = loaded.current;
+ const inForce = {
+ openingContext: saved.opening,
+ openingContextQuery: saved.query.trim(),
+ subagentMemory: saved.subagent,
+ "compaction.enabled": saved.restore,
+ "compaction.memoryLimit": saved.limit,
+ };
+ const fields = [
+ { key: "openingContext", default: DEFAULT_INJECTION_DRAFT.opening },
+ { key: "openingContextQuery", default: DEFAULT_INJECTION_DRAFT.query },
+ { key: "subagentMemory", default: DEFAULT_INJECTION_DRAFT.subagent },
+ { key: "compaction.enabled", default: DEFAULT_INJECTION_DRAFT.restore },
+ { key: "compaction.memoryLimit", default: DEFAULT_INJECTION_DRAFT.limit },
+ ].map((field) => ({ ...field, label: name(field.key) }));
+ ask({
+ title: s("Save memory injection?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ run: () => send(edits),
+ });
+ }
+ async function send(edits: Record): Promise {
+ if (!snapshot || saving.current) return { success: false };
saving.current = true;
setBusy(true);
let failure: Error | undefined;
try {
await settingsRequest("/api/settings", {
method: "PATCH",
- body: JSON.stringify({
- edits: injectionSaveEdits(draft, loaded.current),
- revision: snapshot.revision,
- }),
+ body: JSON.stringify({ edits, revision: snapshot.revision }),
});
} catch (error) {
failure = error as Error;
@@ -101,6 +132,7 @@ export function MemoryInjectionSection() {
? { kind: "save-failed", message: failure.message, reloaded }
: { kind: "saved", reloaded }
);
+ return failure ? { success: false, error: failure.message } : { success: true };
}
function statusText(current: Status): string {
@@ -290,6 +322,7 @@ export function MemoryInjectionSection() {
{statusText(status)}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/MemorySection.tsx b/web/src/lib/components/memory/MemorySection.tsx
index 1d7479d32..7f7a8af4a 100644
--- a/web/src/lib/components/memory/MemorySection.tsx
+++ b/web/src/lib/components/memory/MemorySection.tsx
@@ -6,9 +6,13 @@ import {
settingsRequest,
withNote,
} from "$lib/settings-api";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { useSettingsText } from "$lib/i18n/settings";
import { useCatalogueText } from "$lib/i18n/settings-catalogue";
import { findCatalogueEntry, PLAIN_TEXT } from "$lib/settings-catalogue";
@@ -50,6 +54,8 @@ export function MemorySection() {
const [draft, setDraft] = useState>({});
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const saving = useRef(false);
useEffect(() => {
let active = true;
@@ -83,20 +89,44 @@ export function MemorySection() {
"Edit ~/.config/omms/omms.jsonc directly to set these limits without the web UI."
).split(configPath);
const readOnly = snapshot?.readOnly === true;
- async function save() {
+ // The values in force, keyed as the request spells them, so the dialog lists the same
+ // numbers the card compares a draft against.
+ const inForce = Object.fromEntries(
+ MEMORY_CONTROLS.map((control) => [control.key, loaded[control.key] ?? defaults[control.key]])
+ );
+ const fields = MEMORY_CONTROLS.map((control) => ({
+ key: control.key,
+ label: name(control.key),
+ default: defaults[control.key],
+ print: (value: unknown) =>
+ typeof value === "number" ? formatMemoryDefault(value) : String(value ?? ""),
+ }));
+ function save() {
if (!snapshot || !canSave || saving.current) return;
const edits = memorySaveEdits(draft, loaded);
if (!Object.keys(edits).length) return;
- await saveEdits(edits);
+ ask({
+ title: s("Save memory limits?"),
+ body: ,
+ confirmLabel: s("Save memory limits"),
+ busyLabel: s("Saving…"),
+ run: () => saveEdits(edits),
+ });
}
/** Reset one row: null on the wire removes the key so the default applies again. */
- async function reset(key: MemoryControlKey) {
+ function reset(key: MemoryControlKey) {
if (!snapshot || busy || saving.current) return;
if (!snapshot.settings[key]?.hasGlobal) return;
- await saveEdits({ [key]: null });
+ ask({
+ title: s("Reset to default?"),
+ body: ,
+ confirmLabel: s("Reset to default"),
+ busyLabel: s("Saving…"),
+ run: () => saveEdits({ [key]: null }),
+ });
}
- async function saveEdits(edits: Record) {
- if (!snapshot || saving.current) return;
+ async function saveEdits(edits: Record): Promise {
+ if (!snapshot || saving.current) return { success: false };
saving.current = true;
setBusy(true);
let saved = false;
@@ -120,12 +150,14 @@ export function MemorySection() {
return next;
});
setStatus({ kind: "saved", reloaded });
- } else
- setStatus({
- kind: "save-failed",
- failure: classifyMemorySaveFailure(failure?.message ?? ""),
- reloaded,
- });
+ return { success: true };
+ }
+ setStatus({
+ kind: "save-failed",
+ failure: classifyMemorySaveFailure(failure?.message ?? ""),
+ reloaded,
+ });
+ return { success: false, error: s(failure?.message ?? "") };
}
function statusText(current: MemoryStatus): string {
if (current.kind === "load-failed")
@@ -305,6 +337,7 @@ export function MemorySection() {
{statusText(status)}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/ProfileCatchUpSection.tsx b/web/src/lib/components/memory/ProfileCatchUpSection.tsx
index e2a05a04d..39eccc43b 100644
--- a/web/src/lib/components/memory/ProfileCatchUpSection.tsx
+++ b/web/src/lib/components/memory/ProfileCatchUpSection.tsx
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { settingsRequest } from "$lib/settings-api";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
import { useSettingsText } from "$lib/i18n/settings";
import { AutoCleanupSettings } from "./AutoCleanupSettings";
@@ -75,6 +76,7 @@ export function ProfileCatchUpSection({ onReanalyse }: { onReanalyse?: () => voi
const [local, setLocal] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
+ const { ask, dialog } = useSettingsConfirm();
async function load() {
const value = await settingsRequest<{ preview: CatchUpPreview; job: CatchUpJob }>(
@@ -118,17 +120,29 @@ export function ProfileCatchUpSection({ onReanalyse }: { onReanalyse?: () => voi
}
setBusy(false);
}
- async function pause() {
- try {
- setJob(
- await settingsRequest("/api/settings/profile/catch-up/pause", {
- method: "POST",
- body: "{}",
- })
- );
- } catch (cause) {
- setError((cause as Error).message);
- }
+ /** A job action: asks first, with one sentence that says what pausing does. */
+ function pause() {
+ ask({
+ title: s("Pause the catch-up run?"),
+ body: {s("This pauses the catch-up run, so no model calls run until you resume it.")}
,
+ confirmLabel: s("Pause"),
+ busyLabel: s("Pausing…"),
+ run: async () => {
+ try {
+ setJob(
+ await settingsRequest("/api/settings/profile/catch-up/pause", {
+ method: "POST",
+ body: "{}",
+ })
+ );
+ setError("");
+ return { success: true };
+ } catch (cause) {
+ setError((cause as Error).message);
+ return { success: false, error: (cause as Error).message };
+ }
+ },
+ });
}
return (
@@ -177,6 +191,7 @@ export function ProfileCatchUpSection({ onReanalyse }: { onReanalyse?: () => voi
))}
{error && {error}
}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/ProfileLearningSettingsSection.tsx b/web/src/lib/components/memory/ProfileLearningSettingsSection.tsx
index 7c78151e6..7d0815d8a 100644
--- a/web/src/lib/components/memory/ProfileLearningSettingsSection.tsx
+++ b/web/src/lib/components/memory/ProfileLearningSettingsSection.tsx
@@ -15,6 +15,9 @@ import {
} from "$lib/components/settings/SettingsConfirmDialog";
import { Select } from "$lib/components/ui/select";
import { Tooltip } from "$lib/components/ui/tooltip";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { useSettingsText } from "$lib/i18n/settings";
import {
PROFILE_LEARNING_CONTROLS,
@@ -124,6 +127,8 @@ export function ProfileLearningSettingsSection() {
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState();
const [resetting, setResetting] = useState(false);
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const saving = useRef(false);
useEffect(() => {
let active = true;
@@ -197,8 +202,28 @@ export function ProfileLearningSettingsSection() {
return { ok, stale, reloaded, reason };
}
- async function save() {
+ /** Asks first; the choices stay in the dropdowns until the dialog closes. */
+ function save() {
if (!snapshot || saving.current || !changed) return;
+ const fields = PROFILE_LEARNING_CONTROLS.map((control) => ({
+ key: control.key,
+ label: name(control.key),
+ print: (value: unknown) => {
+ const option = control.options.find((entry) => entry.value === value);
+ return option ? s(option.label) : String(value);
+ },
+ }));
+ ask({
+ title: s("Save learning settings?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ run: commit,
+ });
+ }
+
+ async function commit(): Promise {
+ if (!snapshot || saving.current || !changed) return { success: false };
saving.current = true;
setBusy(true);
const start = snapshot;
@@ -212,6 +237,9 @@ export function ProfileLearningSettingsSection() {
setStatus(
stale ? { kind: "save", ok, reloaded, stale } : { kind: "save", ok, reloaded, reason }
);
+ return ok
+ ? { success: true }
+ : { success: false, error: failureText({ ok, stale, reloaded, reason }, "save") };
}
async function reset(): Promise {
@@ -366,6 +394,7 @@ export function ProfileLearningSettingsSection() {
onClose={() => setResetting(false)}
/>
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/RerankerSection.tsx b/web/src/lib/components/memory/RerankerSection.tsx
index 0d448433a..60fbf392b 100644
--- a/web/src/lib/components/memory/RerankerSection.tsx
+++ b/web/src/lib/components/memory/RerankerSection.tsx
@@ -16,6 +16,9 @@ import {
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Switch } from "$lib/components/ui/switch";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { useSettingsText } from "$lib/i18n/settings";
import { useCatalogueText } from "$lib/i18n/settings-catalogue";
import {
@@ -25,6 +28,8 @@ import {
keyDraftFromSecret,
keyReference,
parseRerankerTimeout,
+ RERANKER_KEY_FILE,
+ RERANKER_TIMEOUT_DEFAULT,
rerankerFieldProblem,
rerankerKeyBody,
rerankerSaveEdits,
@@ -71,6 +76,8 @@ export function RerankerSection() {
const [busy, setBusy] = useState(false);
const [status, setStatus] = useState();
const [replacing, setReplacing] = useState(false);
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const saving = useRef(false);
// The latest shared snapshot, so a refresh can tell untouched fields from typed ones.
const latestSnapshot = useRef(undefined);
@@ -162,8 +169,74 @@ export function RerankerSection() {
setStatus(result);
}
+ /** The saved key in words the dialog can show: its source and where it lives, never the key. */
+ function savedKeyWord(): string {
+ const saved = keyDraftFromSecret(secret);
+ if (saved.keyChoice === "env") return `${t("Environment variable")} ${saved.keyInput.name}`;
+ if (saved.keyChoice === "file") return `${t("Key file")} ${saved.keyInput.path}`;
+ return t("No key");
+ }
+
+ /**
+ * The typed key in words: where it will live, never the key itself. A pasted key goes to a
+ * private file, so it reads as a key file with the name that file will have.
+ */
+ function typedKeyWord(): string {
+ if (draft.keyChoice === "env")
+ return `${t("Environment variable")} ${draft.keyInput.name.trim()}`;
+ if (draft.keyChoice === "file") return `${t("Key file")} ${draft.keyInput.path.trim()}`;
+ if (draft.keyChoice === "paste")
+ return `${t("Key file")} ${draft.keyInput.name.trim() || RERANKER_KEY_FILE}`;
+ return t("No key");
+ }
+
+ /** Asks first; the typed values stay in the form until the dialog closes. */
+ function save() {
+ if (!snapshot || !canSave || saving.current) return;
+ const edits = rerankerSaveEdits(draft, secret);
+ // The key goes through its own route; the list still names the change, in words.
+ const listEdits: Record = { ...edits };
+ if (draft.keyChoice !== "none" && keyChanged(draft, secret))
+ listEdits.rerankerApiKey = typedKeyWord();
+ const savedDraft = draftFromSnapshot(snapshot);
+ const inForce: Record = {
+ rerankerEnabled: savedDraft.enabled,
+ rerankerApiUrl: savedDraft.url.trim() || null,
+ rerankerModel: savedDraft.model.trim() || null,
+ rerankerTimeoutMs: parseRerankerTimeout(savedDraft.timeout) ?? RERANKER_TIMEOUT_DEFAULT,
+ rerankerApiKey: savedKeyWord(),
+ };
+ const textOrNull = (value: unknown) => (value == null ? t("Not set") : String(value));
+ const fields = [
+ { key: "rerankerEnabled", label: name("rerankerEnabled") },
+ { key: "rerankerApiUrl", label: name("rerankerApiUrl"), print: textOrNull },
+ { key: "rerankerModel", label: name("rerankerModel"), print: textOrNull },
+ // The key's values are already words, so the row prints them as they are.
+ { key: "rerankerApiKey", label: name("rerankerApiKey"), default: t("No key") },
+ {
+ key: "rerankerTimeoutMs",
+ label: name("rerankerTimeoutMs"),
+ default: RERANKER_TIMEOUT_DEFAULT,
+ print: (value: unknown) => `${String(value)} ${s("milliseconds")}`,
+ },
+ ];
+ const rows = changes(inForce, listEdits, fields);
+ ask({
+ title: s("Save the reranker settings?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ run: async () => {
+ const result = await persist();
+ // The server asked whether to replace the key file: that dialog takes over
+ // from this one, and nothing else is sent until the user decides.
+ return result.error === undefined ? { success: true } : result;
+ },
+ });
+ }
+
/** Save the key first (it can need a confirm), then the other settings with the new revision. */
- async function save(replace = false): Promise {
+ async function persist(replace = false): Promise {
if (!snapshot || !canSave || saving.current) return { success: false };
saving.current = true;
setBusy(true);
@@ -408,10 +481,11 @@ export function RerankerSection() {
title={t("Replace the key file?")}
body={{s("A key file with this name exists. Replace it?")}
}
confirmLabel={t("Replace")}
- onConfirm={() => save(true)}
+ onConfirm={() => persist(true)}
onClose={() => setReplacing(false)}
/>
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/memory/use-backfill.ts b/web/src/lib/components/memory/use-backfill.ts
index 88061512a..ba3b5bb57 100644
--- a/web/src/lib/components/memory/use-backfill.ts
+++ b/web/src/lib/components/memory/use-backfill.ts
@@ -35,6 +35,9 @@ export type BackfillRow = {
} | null;
export type Rows = Record;
+/** What a save or a control action answers, so a confirm dialog can hold a refusal open. */
+type ActionResult = { success: boolean; error?: string };
+
const POLL_MS = 3000;
/**
@@ -89,9 +92,10 @@ export function useBackfill() {
};
}, []);
- async function save(edits: Record) {
- if (!snapshot) return;
+ async function save(edits: Record): Promise {
+ if (!snapshot) return { success: false };
setBusy(true);
+ let failure: string | undefined;
try {
await settingsRequest("/api/settings", {
method: "PATCH",
@@ -99,16 +103,22 @@ export function useBackfill() {
});
setMessage(s("Saved. Changes apply at the next run."));
} catch (error) {
- setMessage((error as Error).message);
+ failure = (error as Error).message;
+ setMessage(failure);
}
await reloadSettingsSnapshot();
setBusy(false);
+ return failure === undefined ? { success: true } : { success: false, error: failure };
}
- async function control(host: BackfillHost, action: "run" | "pause" | "resume") {
+ async function control(
+ host: BackfillHost,
+ action: "run" | "pause" | "resume"
+ ): Promise {
setBusy(true);
// Pausing with no run going only saves the flag; nothing stops "after the current exchange".
const live = runs?.[host]?.run?.state === "running";
+ let failure: string | undefined;
try {
await settingsRequest(`/api/settings/backfill/${host}/${action}`, {
method: "POST",
@@ -124,17 +134,20 @@ export function useBackfill() {
)
);
} catch (error) {
- setMessage((error as Error).message);
+ failure = (error as Error).message;
+ setMessage(failure);
}
await Promise.all([loadRuns(), loadRows()]);
setBusy(false);
+ return failure === undefined ? { success: true } : { success: false, error: failure };
}
- function saveModel(host: ModelBackfillHost, choice: string) {
+ async function saveModel(host: ModelBackfillHost, choice: string): Promise {
try {
- void save(backfillModelEdit(host, choice.trim()));
+ return await save(backfillModelEdit(host, choice.trim()));
} catch (error) {
setMessage(s((error as Error).message));
+ return { success: false, error: (error as Error).message };
}
}
diff --git a/web/src/lib/components/settings/CaptureControls.tsx b/web/src/lib/components/settings/CaptureControls.tsx
index 4408e6f00..3804516a9 100644
--- a/web/src/lib/components/settings/CaptureControls.tsx
+++ b/web/src/lib/components/settings/CaptureControls.tsx
@@ -1,9 +1,11 @@
import { useState } from "react";
import { Loader } from "lucide-react";
import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
import { Checkbox } from "$lib/components/ui/checkbox";
import { Input } from "$lib/components/ui/input";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { hostLabel, type WebHost } from "$lib/host-label";
import { useCardText } from "$lib/i18n/settings-cards";
import { settingsRequest } from "$lib/settings-api";
@@ -39,8 +41,9 @@ function whole(text: string, min: number, max = Number.MAX_SAFE_INTEGER): number
/**
* The capture trace switch, the retention fields, the retry queue and the trace files of the
* Capture diagnostics card. The switch and the three retention fields save together with one
- * Save button. A change that deletes data asks first: turning the retry queue off (0 hours) names
- * how many turns wait, and turning traces on warns that traces can hold conversation text.
+ * Save button, and every save asks first: a plain change lists what changes, while a change that
+ * deletes data keeps its own dialog: turning the retry queue off (0 hours) names how many turns
+ * wait, and turning traces on warns that traces can hold conversation text.
*/
export function CaptureControls({
snapshot,
@@ -59,12 +62,14 @@ export function CaptureControls({
traces: Trace[];
/** What the last Retry now did. */
note: string;
- onRetry: (host: WebHost) => void;
+ /** Runs Retry now for one host, and reports whether the run started. */
+ onRetry: (host: WebHost) => Promise<{ success: boolean; error?: string }>;
/** Reload what the card shows after a save or a deleted file. */
onChanged: () => Promise;
}) {
const t = useCardText();
const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const [trace, setTrace] = useState();
const [drafts, setDrafts] = useState>({});
const [message, setMessage] = useState("");
@@ -92,6 +97,24 @@ export function CaptureControls({
if (next !== null && next !== saved(key, key === HOURS_KEY ? 72 : 30)) edits[key] = next;
}
const changed = Object.keys(edits).length > 0;
+ const retentionInWords = (hours: boolean, value: unknown) =>
+ value == null
+ ? t("Not set")
+ : hours
+ ? t("{count} hours", { count: String(value) })
+ : t("{count} days", { count: String(value) });
+ const fields = [
+ { key: "captureTrace", label: name("captureTrace") },
+ ...ALL_KEYS.map((key) => ({
+ key,
+ label: name(key),
+ print: (value: unknown) => retentionInWords(key === HOURS_KEY, value),
+ })),
+ ];
+ const inForce: Record = {
+ captureTrace: settings?.captureTrace?.globalValue === true,
+ ...Object.fromEntries(ALL_KEYS.map((key) => [key, saved(key, key === HOURS_KEY ? 72 : 30)])),
+ };
async function commit() {
const result = await saveSettingEdits(snapshot!.revision, edits);
@@ -111,10 +134,19 @@ export function CaptureControls({
const queueOff = edits[HOURS_KEY] === 0;
const traceOnNow = edits.captureTrace === true;
if (!queueOff && !traceOnNow) {
- setBusy(true);
- const result = await commit();
- setBusy(false);
- if (!result.success) setMessage(result.error ?? "");
+ ask({
+ title: t("Save retention?"),
+ body: ,
+ confirmLabel: t("Save retention"),
+ busyLabel: t("Saving…"),
+ run: async () => {
+ setBusy(true);
+ const result = await commit();
+ setBusy(false);
+ if (!result.success) setMessage(result.error ?? "");
+ return result;
+ },
+ });
return;
}
let fresh: Record | undefined;
@@ -168,6 +200,17 @@ export function CaptureControls({
});
}
+ /** Asks first: Retry now sends the waiting turns of one host to the model again. */
+ function retryNow(host: WebHost) {
+ ask({
+ title: t("Retry waiting turns?"),
+ body: {t("The waiting turns will be sent to the model again.")}
,
+ confirmLabel: t("Retry now"),
+ busyLabel: t("Retrying…"),
+ run: () => onRetry(host),
+ });
+ }
+
async function openTrace(name: string) {
try {
const result = await settingsRequest<{ content: string }>(
@@ -293,7 +336,7 @@ export function CaptureControls({
variant="outline"
size="sm"
disabled={count === 0 || retryHours === 0}
- onClick={() => onRetry(host)}
+ onClick={() => retryNow(host)}
>
{t("Retry now")}
diff --git a/web/src/lib/components/settings/CaptureLanguageSection.tsx b/web/src/lib/components/settings/CaptureLanguageSection.tsx
index cc6fe8ce3..39f6b946e 100644
--- a/web/src/lib/components/settings/CaptureLanguageSection.tsx
+++ b/web/src/lib/components/settings/CaptureLanguageSection.tsx
@@ -6,6 +6,9 @@ import {
reloadSettingsSnapshot,
settingsRequest,
} from "$lib/settings-api";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { useSettingsText } from "$lib/i18n/settings";
import { captureLanguageOptions, currentCaptureLanguage } from "$lib/capture-language";
import { ReadOnlyNote } from "./ReadOnlyNote";
@@ -48,9 +51,13 @@ export function CaptureLanguageField({
export function CaptureLanguageSection() {
const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes } = useSettingsChanges();
const [snapshot, setSnapshot] = useState();
const [message, setMessage] = useState("");
const [busy, setBusy] = useState(false);
+ /** The language picked while the dialog asks. Cancel puts the saved one back. */
+ const [pending, setPending] = useState();
useEffect(() => {
let active = true;
const read = beginSettingsRead();
@@ -70,20 +77,49 @@ export function CaptureLanguageSection() {
};
}, []);
const readOnly = snapshot?.readOnly === true;
- async function save(code: string) {
+ const saved = currentCaptureLanguage(snapshot?.settings.autoCaptureLanguage?.value);
+ const language = (code: unknown) =>
+ code === "auto"
+ ? s("Automatic")
+ : (captureLanguageOptions(String(code)).find((entry) => entry.code === code)?.name ??
+ String(code));
+ const fields = [{ key: "autoCaptureLanguage", label: s("Summary language"), print: language }];
+
+ /** Asks first. The picker shows the picked language until the dialog closes. */
+ function choose(code: string) {
if (!snapshot) return;
- setBusy(true);
- try {
- await settingsRequest("/api/settings", {
- method: "PATCH",
- body: JSON.stringify({ edits: { autoCaptureLanguage: code }, revision: snapshot.revision }),
- });
- setMessage(s("Saved. New memories use this language."));
- } catch (error) {
- setMessage((error as Error).message);
- }
- await reloadSettingsSnapshot();
- setBusy(false);
+ const edits = { autoCaptureLanguage: code };
+ setPending(code);
+ ask({
+ title: s("Change the summary language?"),
+ body: ,
+ confirmLabel: s("Save"),
+ busyLabel: s("Saving…"),
+ onCancel: () => setPending(undefined),
+ run: async () => {
+ setBusy(true);
+ let failure: string | undefined;
+ try {
+ await settingsRequest("/api/settings", {
+ method: "PATCH",
+ body: JSON.stringify({ edits, revision: snapshot.revision }),
+ });
+ } catch (error) {
+ failure = (error as Error).message;
+ }
+ await reloadSettingsSnapshot();
+ setBusy(false);
+ // The card's own feedback stays; the dialog keeps the reason too until the user decides.
+ if (failure !== undefined) {
+ setMessage(failure);
+ return { success: false, error: failure };
+ }
+ // The reloaded snapshot shows the saved language, so the picked one can go.
+ setPending(undefined);
+ setMessage(s("Saved. New memories use this language."));
+ return { success: true };
+ },
+ });
}
return (
void save(code)}
+ onChange={(code) => choose(code)}
/>
+ {dialog}
{message && (
{message}
diff --git a/web/src/lib/components/settings/ClaudeFolderSection.tsx b/web/src/lib/components/settings/ClaudeFolderSection.tsx
index 37c93b1d6..e198eeaba 100644
--- a/web/src/lib/components/settings/ClaudeFolderSection.tsx
+++ b/web/src/lib/components/settings/ClaudeFolderSection.tsx
@@ -1,6 +1,10 @@
import { useEffect, useRef, useState } from "react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { SettingRow } from "./SettingRow";
import {
beginSettingsRead,
@@ -22,6 +26,8 @@ type Snapshot = {
export function ClaudeFolderSection() {
const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const [snapshot, setSnapshot] = useState();
const [draft, setDraft] = useState("");
const [message, setMessage] = useState("");
@@ -52,28 +58,51 @@ export function ClaudeFolderSection() {
};
}, []);
const readOnly = snapshot?.readOnly === true;
- async function save() {
+ /** Asks first, with the folder that will be saved. The card's own feedback stays. */
+ function save() {
if (!snapshot) return;
if (!isValidClaudeConfigDir(draft)) {
setMessage(s("Enter a full path, or a path that starts with ~/."));
return;
}
+ const edits = { claudeConfigDir: draft.trim() };
+ const fields = [
+ {
+ key: "claudeConfigDir",
+ label: name("claudeConfigDir"),
+ // An unset folder means the usual one, both before the save and after it is emptied.
+ print: (value: unknown) => (value ? String(value) : s("The usual Claude folder")),
+ },
+ ];
+ const inForce = { claudeConfigDir: snapshot.settings.claudeConfigDir?.globalValue };
+ const rows = changes(inForce, edits, fields);
+ ask({
+ title: s("Save the Claude Code folder?"),
+ body: ,
+ confirmLabel: s("Save folder"),
+ busyLabel: s("Saving…"),
+ run: () => saveFolder(edits),
+ });
+ }
+ /** Saves the folder. A refusal keeps the dialog open with its reason. */
+ async function saveFolder(edits: { claudeConfigDir: string }): Promise {
+ if (!snapshot) return { success: false };
setBusy(true);
+ let failure: string | undefined;
try {
await settingsRequest("/api/settings", {
method: "PATCH",
- body: JSON.stringify({
- edits: { claudeConfigDir: draft.trim() },
- revision: snapshot.revision,
- }),
+ body: JSON.stringify({ edits, revision: snapshot.revision }),
});
edited.current = false;
setMessage(s("Saved. Capture and import use this folder now."));
} catch (error) {
- setMessage((error as Error).message);
+ failure = (error as Error).message;
+ setMessage(failure);
}
await reloadSettingsSnapshot();
setBusy(false);
+ return failure === undefined ? { success: true } : { success: false, error: failure };
}
return (
- void save()}>
+ save()}>
{s("Save folder")}
@@ -110,6 +139,7 @@ export function ClaudeFolderSection() {
{message}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/settings/DiagnosticsSection.tsx b/web/src/lib/components/settings/DiagnosticsSection.tsx
index 1c2379971..e678e7532 100644
--- a/web/src/lib/components/settings/DiagnosticsSection.tsx
+++ b/web/src/lib/components/settings/DiagnosticsSection.tsx
@@ -115,6 +115,7 @@ export function DiagnosticsSection() {
void refresh(days, host);
}, [days, host, refresh]);
useEffect(() => onSettingsSnapshot((value) => setSnapshot(value as Snapshot)), []);
+ /** Runs Retry now for one host. The confirm dialog in the capture controls calls this. */
async function retryNow(retryHost: RetryHost) {
try {
const { result } = await settingsRequest<{ result: "started" | "scheduled" | "running" }>(
@@ -133,8 +134,10 @@ export function DiagnosticsSection() {
: s("Retrying now.")
);
await refresh(days, host);
+ return { success: true };
} catch (cause) {
setError((cause as Error).message);
+ return { success: false, error: (cause as Error).message };
}
}
return (
@@ -341,7 +344,7 @@ export function DiagnosticsSection() {
}
traces={traces}
note={retryNote}
- onRetry={(retryHost) => void retryNow(retryHost)}
+ onRetry={retryNow}
onChanged={async () => {
// A saved retention change can empty the queue, so an earlier Retry now note is stale.
setRetryNote("");
diff --git a/web/src/lib/components/settings/EmbeddingSection.tsx b/web/src/lib/components/settings/EmbeddingSection.tsx
index 23f3f1f00..9c4dc36ab 100644
--- a/web/src/lib/components/settings/EmbeddingSection.tsx
+++ b/web/src/lib/components/settings/EmbeddingSection.tsx
@@ -254,17 +254,32 @@ export function EmbeddingSection() {
});
}
- async function retry() {
- try {
- setRun(
- await settingsRequest("/api/settings/embedding/run", {
- method: "POST",
- body: "{}",
- })
- );
- } catch (error) {
- report(false, (error as Error).message);
- }
+ /** Asks first: a retry re-embeds every stored memory, which calls the embedding model again. */
+ function retry() {
+ ask({
+ title: s("Retry the re-embed?"),
+ body: (
+
+ {s("The re-embed will run again and send every stored memory to the embedding model.")}
+
+ ),
+ confirmLabel: s("Retry"),
+ busyLabel: s("Re-embedding…"),
+ run: async () => {
+ try {
+ setRun(
+ await settingsRequest("/api/settings/embedding/run", {
+ method: "POST",
+ body: "{}",
+ })
+ );
+ return { success: true };
+ } catch (error) {
+ report(false, (error as Error).message);
+ return { success: false, error: (error as Error).message };
+ }
+ },
+ });
}
const saved = snapshot?.secrets.embeddingApiKey;
@@ -419,7 +434,7 @@ export function EmbeddingSection() {
) : null}
)}
- void retry()} />
+
{message && (
{message}
diff --git a/web/src/lib/components/settings/ExternalApiSection.tsx b/web/src/lib/components/settings/ExternalApiSection.tsx
index 652a99a9a..a0149cecb 100644
--- a/web/src/lib/components/settings/ExternalApiSection.tsx
+++ b/web/src/lib/components/settings/ExternalApiSection.tsx
@@ -1,6 +1,6 @@
import { useState } from "react";
import { Loader } from "lucide-react";
-import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useExternalApiConfirm } from "@/hooks/useExternalApiConfirm";
import { useSettingsSnapshot } from "@/hooks/useSettingsSnapshot";
import { useOpenRouterModels } from "@/hooks/useOpenRouterModels";
import { Callout } from "$lib/components/skills/Callout";
@@ -21,6 +21,7 @@ import { applyOpenRouterPreset, isOpenRouterUrl } from "$lib/openrouter-routing"
import { providerName } from "$lib/provider-names";
import { reloadSettingsSnapshot, settingsRequest } from "$lib/settings-api";
import { saveSettingEdits } from "$lib/settings-save";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { KeySourceField, type KeyChoice, type SavedKey } from "./KeySourceField";
import { OpenRouterRouting } from "./OpenRouterRouting";
import { ReasoningLevel } from "./ReasoningLevel";
@@ -44,11 +45,12 @@ const PROVIDERS = [
"google-gemini",
];
const URL_PATTERN = /^https?:\/\/\S+$/;
+/** `persist` hands the click to the Replace-the-key-file dialog, which is then the open one. */
+const KEY_DIALOG = "key-file-dialog";
export function ExternalApiSection() {
const t = useCardText();
const { snapshot, error: loadError } = useSettingsSnapshot();
- const { ask, dialog } = useSettingsConfirm();
const [fields, setFields] = useState>({});
const [source, setSource] = useState("file");
const [keyInput, setKeyInput] = useState({ name: "", path: "", value: "" });
@@ -77,6 +79,16 @@ export function ExternalApiSection() {
}
const hasKey = keyEntered(source, keyInput);
const changed = Object.keys(edits).length > 0 || hasKey;
+ const { ask, dialog, askSave } = useExternalApiConfirm({
+ saved: {
+ memoryProvider: saved("memoryProvider"),
+ memoryApiUrl: saved("memoryApiUrl"),
+ memoryModel: saved("memoryModel"),
+ },
+ edits,
+ key: hasKey ? { source, name: keyInput.name, path: keyInput.path } : undefined,
+ savedKey: snapshot?.externalKey ?? null,
+ });
function report(ok: boolean, text: string, status?: number) {
setFailed(!ok);
@@ -126,11 +138,21 @@ export function ExternalApiSection() {
return;
}
}
- // An emptied address or model turns the external API off: there is nothing to call.
+ // An emptied address or model turns the external API off: there is nothing to call, so the
+ // confirm dialog says so and no test runs.
const turnsOff =
provider !== "orcarouter" && (url === "" || value("memoryModel").trim() === "");
- if (turnsOff) return persist(snapshot.revision);
- // The same test as the Test button, once: only a key the provider accepts is saved.
+ if (turnsOff) {
+ return askSave({
+ title: t("Save external API settings?"),
+ lead: t("The external API will be turned off."),
+ confirmLabel: t("Save settings"),
+ busyLabel: t("Saving…"),
+ run: () => runSave(snapshot.revision),
+ });
+ }
+ // The same test as the Test button, once: only a key the provider accepts is saved. A passing
+ // test opens the confirm dialog, and nothing is saved before the user confirms.
setWorking("save");
let reply: ExternalTestReply;
try {
@@ -140,33 +162,45 @@ export function ExternalApiSection() {
report(false, t((cause as Error).message));
return;
}
- if (reply.ok) return persist(snapshot.revision);
setWorking("");
+ if (reply.ok) {
+ return askSave({
+ title: t("Save external API settings?"),
+ confirmLabel: t("Save settings"),
+ busyLabel: t("Saving…"),
+ run: () => runSave(snapshot.revision),
+ });
+ }
if (reply.reason !== "unreachable") {
report(false, `${t(testFailureText(reply.reason))} ${t("Nothing was saved.")}`, reply.status);
return;
}
- const revision = snapshot.revision;
- ask({
+ // The test cannot reach the server: the existing Save-anyway dialog is this click's
+ // confirmation, so it also lists the changes and no second dialog follows it.
+ askSave({
title: t("Save without a working test?"),
- body: (
-
- {t(testFailureText(reply.reason))}{" "}
- {t("Save these settings anyway? Capture fails until OMMS can reach the address.")}
-
- ),
+ lead: `${t(testFailureText(reply.reason))} ${t("Save these settings anyway? Capture fails until OMMS can reach the address.")}`,
confirmLabel: t("Save anyway"),
busyLabel: t("Saving…"),
- // The dialog closes; the card shows the save's progress and result.
- run: async () => {
- void persist(revision);
- return { success: true };
- },
+ // A refusal stays in this dialog; the key-file dialog can still take over.
+ run: () => runSave(snapshot.revision),
});
}
- /** Saves the key, then the endpoint and model edits. A key file with this name asks first. */
- async function persist(start: string) {
+ /** Runs the confirmed save; the answer keeps the dialog open when the server refuses. */
+ async function runSave(revision: string): Promise {
+ const problem = await persist(revision);
+ // The key-file dialog took over this click; the dialog now open is that one.
+ if (problem === KEY_DIALOG) return { success: false, error: "" };
+ return problem === "" ? { success: true } : { success: false, error: t(problem) };
+ }
+
+ /**
+ * Saves the key, then the endpoint and model edits. Returns the problem, "" on success, or
+ * KEY_DIALOG when the Replace-the-key-file dialog took over. A key file with this name asks
+ * first.
+ */
+ async function persist(start: string): Promise {
let revision = start;
setWorking("save");
if (hasKey) {
@@ -194,13 +228,15 @@ export function ExternalApiSection() {
}
},
});
- return;
+ return KEY_DIALOG;
}
report(false, t(reason));
- return;
+ return reason;
}
}
- await finish(await saveEdits(revision));
+ const problem = await saveEdits(revision);
+ await finish(problem);
+ return problem;
}
/** One test call with the form's values, saved or not. A pasted key is used for it only. */
diff --git a/web/src/lib/components/settings/KeysAccessSection.tsx b/web/src/lib/components/settings/KeysAccessSection.tsx
index 2e846e28c..7cb34bbbc 100644
--- a/web/src/lib/components/settings/KeysAccessSection.tsx
+++ b/web/src/lib/components/settings/KeysAccessSection.tsx
@@ -232,16 +232,37 @@ export function KeysAccessSection() {
}).catch(() => {});
}
- const generate = (name: string, expiresInDays: number | null) =>
- act(async () => {
- const created = await settingsRequest<{ value: string }>("/api/settings/tokens", {
- method: "POST",
- body: JSON.stringify({ name, expiresInDays }),
- });
- setNewValue(created.value);
- setMessage("");
- await loadTokens();
+ const generate = (name: string, expiresInDays: number | null) => {
+ ask({
+ title: t("Generate a token?"),
+ body: (
+
+ {t("OMMS creates a token that lets scripts and other computers call this web app's API.")}
+
+ ),
+ confirmLabel: s("Generate token"),
+ busyLabel: t("Saving…"),
+ run: async () => {
+ let failure: string | undefined;
+ // `act` keeps the card's busy flag, message and reload as they were.
+ await act(async () => {
+ try {
+ const created = await settingsRequest<{ value: string }>("/api/settings/tokens", {
+ method: "POST",
+ body: JSON.stringify({ name, expiresInDays }),
+ });
+ setNewValue(created.value);
+ setMessage("");
+ await loadTokens();
+ } catch (error) {
+ failure = (error as Error).message;
+ throw error;
+ }
+ });
+ return failure === undefined ? { success: true } : { success: false, error: failure };
+ },
});
+ };
function revoke(token: ApiToken) {
setNewValue(undefined);
@@ -267,25 +288,51 @@ export function KeysAccessSection() {
});
}
- const savePassword = (clear: boolean) =>
- act(async () => {
- if (!snapshot) return;
- await settingsRequest("/api/settings/web-password", {
- method: "POST",
- body: JSON.stringify(
- clear
- ? { clear: true, revision: snapshot.revision }
- : {
- password: password.value,
- username: password.username,
- revision: snapshot.revision,
- }
- ),
- });
- // The password leaves the page as soon as it is saved.
- setPassword({ username: "", value: "" });
- setMessage(s(passwordStatusMessage(clear)));
+ /** Asks first, with one sentence and no secret. The card's own feedback stays. */
+ const savePassword = (clear: boolean) => {
+ ask({
+ title: t(clear ? "Clear the browser password?" : "Save the browser password?"),
+ body: (
+
+ {t(
+ clear
+ ? "The browser password is removed. The web app stops asking for it after it restarts."
+ : "The password is stored in a private file on this computer. The web app asks for it after it restarts."
+ )}
+
+ ),
+ confirmLabel: s(clear ? "Clear password" : "Save password"),
+ busyLabel: t("Saving…"),
+ destructive: clear,
+ run: async () => {
+ let failure: string | undefined;
+ await act(async () => {
+ if (!snapshot) return;
+ try {
+ await settingsRequest("/api/settings/web-password", {
+ method: "POST",
+ body: JSON.stringify(
+ clear
+ ? { clear: true, revision: snapshot.revision }
+ : {
+ password: password.value,
+ username: password.username,
+ revision: snapshot.revision,
+ }
+ ),
+ });
+ // The password leaves the page as soon as it is saved.
+ setPassword({ username: "", value: "" });
+ setMessage(s(passwordStatusMessage(clear)));
+ } catch (error) {
+ failure = (error as Error).message;
+ throw error;
+ }
+ });
+ return failure === undefined ? { success: true } : { success: false, error: failure };
+ },
});
+ };
const access = snapshot?.access;
return (
@@ -314,7 +361,7 @@ export function KeysAccessSection() {
tokens={tokens}
newValue={newValue}
busy={busy}
- onGenerate={(name, days) => void generate(name, days)}
+ onGenerate={(name, days) => generate(name, days)}
onRevoke={revoke}
/>
@@ -333,7 +380,7 @@ export function KeysAccessSection() {
type="button"
variant="outline"
disabled={busy || !snapshot || readOnly || !password.value}
- onClick={() => void savePassword(false)}
+ onClick={() => savePassword(false)}
>
{s("Save password")}
@@ -341,7 +388,7 @@ export function KeysAccessSection() {
type="button"
variant="outline"
disabled={busy || !snapshot || readOnly || !access?.authEnabled}
- onClick={() => void savePassword(true)}
+ onClick={() => savePassword(true)}
>
{s("Clear password")}
diff --git a/web/src/lib/components/settings/MemoryBasicsSection.tsx b/web/src/lib/components/settings/MemoryBasicsSection.tsx
index 80506be1a..2cd1b460f 100644
--- a/web/src/lib/components/settings/MemoryBasicsSection.tsx
+++ b/web/src/lib/components/settings/MemoryBasicsSection.tsx
@@ -1,9 +1,12 @@
import { useState } from "react";
import { Loader } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { useSettingsSnapshot } from "@/hooks/useSettingsSnapshot";
import { Button } from "$lib/components/ui/button";
import { Checkbox } from "$lib/components/ui/checkbox";
import { Select } from "$lib/components/ui/select";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { useCardText } from "$lib/i18n/settings-cards";
import { saveSettingEdits } from "$lib/settings-save";
import { SettingRow } from "./SettingRow";
@@ -23,6 +26,8 @@ const SCOPE = "memory.defaultScope";
export function MemoryBasicsSection() {
const t = useCardText();
const { snapshot, error: loadError } = useSettingsSnapshot();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const [edits, setEdits] = useState>({});
const [message, setMessage] = useState("");
const [failed, setFailed] = useState(false);
@@ -34,28 +39,45 @@ export function MemoryBasicsSection() {
const changed = Object.keys(edits).filter((key) => edits[key] !== saved(key));
const readOnly = snapshot?.readOnly === true;
const projectDecides = (key: string) => snapshot?.settings[key]?.source === "project";
+ const scopeName = (code: unknown) =>
+ t(
+ code === "all-projects" ? "All projects" : code === "project" ? "This project" : String(code)
+ );
+ const fields = [
+ ...SWITCHES.map((key) => ({ key, label: name(key) })),
+ { key: SCOPE, label: name(SCOPE), print: scopeName },
+ ];
function edit(key: string, next: boolean | string) {
setEdits((previous) => ({ ...previous, [key]: next }));
setMessage("");
}
- async function save() {
+ /** Asks first, with each changed setting and its new value. The card's own feedback stays. */
+ function save() {
if (!snapshot || changed.length === 0) return;
- setBusy(true);
- setMessage("");
- const result = await saveSettingEdits(
- snapshot.revision,
- Object.fromEntries(changed.map((key) => [key, edits[key]]))
- );
- setBusy(false);
- setFailed(!result.success);
- if (result.success) {
- setEdits({});
- setMessage(t("Saved."));
- } else {
- setMessage(result.error ?? "");
- }
+ const body = Object.fromEntries(changed.map((key) => [key, edits[key]]));
+ const inForce = Object.fromEntries([...SWITCHES, SCOPE].map((key) => [key, saved(key)]));
+ ask({
+ title: t("Save memory basics?"),
+ body: ,
+ confirmLabel: t("Save"),
+ busyLabel: t("Saving…"),
+ run: async () => {
+ setBusy(true);
+ setMessage("");
+ const result = await saveSettingEdits(snapshot.revision, body);
+ setBusy(false);
+ setFailed(!result.success);
+ if (result.success) {
+ setEdits({});
+ setMessage(t("Saved."));
+ } else {
+ setMessage(result.error ?? "");
+ }
+ return result;
+ },
+ });
}
return (
@@ -128,6 +150,7 @@ export function MemoryBasicsSection() {
) : null}
+ {dialog}
);
}
diff --git a/web/src/lib/components/settings/MemoryCleanupSection.tsx b/web/src/lib/components/settings/MemoryCleanupSection.tsx
index 6f75a9449..d865ca5c8 100644
--- a/web/src/lib/components/settings/MemoryCleanupSection.tsx
+++ b/web/src/lib/components/settings/MemoryCleanupSection.tsx
@@ -1,11 +1,13 @@
import { useState } from "react";
import { Loader } from "lucide-react";
import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { useSettingsSnapshot } from "@/hooks/useSettingsSnapshot";
import { Callout } from "$lib/components/skills/Callout";
import { Button } from "$lib/components/ui/button";
import { Checkbox } from "$lib/components/ui/checkbox";
import { Input } from "$lib/components/ui/input";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { useCardText } from "$lib/i18n/settings-cards";
import { settingsRequest } from "$lib/settings-api";
import { saveSettingEdits } from "$lib/settings-save";
@@ -32,14 +34,15 @@ function parseDays(text: string): number | null {
/**
* The only place a user turns automatic deletion on. The switch writes `autoDeleteOldMemories`.
- * Turning it on, or lowering the days while it is on,
- * first shows how many memories the deletion would remove now. When that count cannot be read,
- * the dialog refuses the save.
+ * Every save asks first. Turning it on, or lowering the days while it is on, first shows how many
+ * memories the deletion would remove now; when that count cannot be read, the dialog refuses the
+ * save. Turning it off or raising the days lists the change instead, because it deletes nothing.
*/
export function MemoryCleanupSection() {
const t = useCardText();
const { snapshot, error: loadError } = useSettingsSnapshot();
const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const [on, setOn] = useState();
const [daysText, setDaysText] = useState();
const [message, setMessage] = useState("");
@@ -65,6 +68,13 @@ export function MemoryCleanupSection() {
if (changed && daysRejected && days !== null) edits[DAYS] = days;
// Deletion that reaches more memories than the saved setting does needs a count first.
const needsCount = nextOn && days !== null && (!savedOn || days < savedDays);
+ const daysInWords = (value: unknown) =>
+ value == null ? t("Not set") : t("{count} days", { count: String(value) });
+ const fields = [
+ { key: SWITCH, label: name(SWITCH) },
+ { key: DAYS, label: name(DAYS), print: daysInWords },
+ ];
+ const inForce = { [SWITCH]: savedOn, [DAYS]: savedDays };
async function commit(): Promise<{ success: boolean; error?: string }> {
const result = await saveSettingEdits(snapshot!.revision, edits);
@@ -81,10 +91,23 @@ export function MemoryCleanupSection() {
if (!snapshot || !changed || days === null) return;
setMessage("");
if (!needsCount) {
- setBusy(true);
- const result = await commit();
- setBusy(false);
- if (!result.success) setMessage(result.error ?? "");
+ ask({
+ // Only a switch that goes from on to off turns cleanup off. A days change while it is
+ // off, or a raise while it is on, is an ordinary save.
+ title: t(savedOn && !nextOn ? "Turn off memory cleanup?" : "Save memory cleanup?"),
+ body: ,
+ confirmLabel: t("Save"),
+ busyLabel: t("Saving…"),
+ // Cancel puts the switch back to its saved state, so nobody thinks a change is in force.
+ onCancel: () => setOn(undefined),
+ run: async () => {
+ setBusy(true);
+ const result = await commit();
+ setBusy(false);
+ if (!result.success) setMessage(result.error ?? "");
+ return result;
+ },
+ });
return;
}
setBusy(true);
diff --git a/web/src/lib/components/settings/ModelsSection.tsx b/web/src/lib/components/settings/ModelsSection.tsx
index fb6da49bb..3ea0d8a1d 100644
--- a/web/src/lib/components/settings/ModelsSection.tsx
+++ b/web/src/lib/components/settings/ModelsSection.tsx
@@ -1,7 +1,11 @@
import { useEffect, useState } from "react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
import { Input } from "$lib/components/ui/input";
import { Select } from "$lib/components/ui/select";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { SettingRow } from "./SettingRow";
import {
beginSettingsRead,
@@ -14,6 +18,7 @@ import { useSettingsText } from "$lib/i18n/settings";
import { useCardText } from "$lib/i18n/settings-cards";
import { externalMissing, hostModelEdit } from "$lib/external-api-settings";
import { hostLabel } from "$lib/host-label";
+import { fill } from "$lib/skills-model";
import { ClaudeCaptureStatus, type ClaudeCaptureState } from "./ClaudeCaptureStatus";
import { ReadOnlyNote } from "./ReadOnlyNote";
@@ -36,6 +41,8 @@ type ModelList = { available: boolean; models?: Model[]; reason?: string };
export function ModelsSection() {
const s = useSettingsText();
const t = useCardText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const [snapshot, setSnapshot] = useState();
const [lists, setLists] = useState>({});
const [message, setMessage] = useState("");
@@ -69,7 +76,17 @@ export function ModelsSection() {
}, []);
const readOnly = snapshot?.readOnly === true;
- async function save(host: string, choice: string) {
+ /** A model value in plain words: the two special choices have names, the rest is provider/model. */
+ const modelText = (value: unknown) =>
+ value === "inherit"
+ ? s("Session model")
+ : value === "external"
+ ? s("External API")
+ : value == null
+ ? s("Not set")
+ : String(value);
+ /** Asks first, with each setting the model choice changes. The card's own feedback stays. */
+ function save(host: string, choice: string) {
if (!snapshot) return;
let edits: Record;
try {
@@ -78,6 +95,28 @@ export function ModelsSection() {
setMessage(s((error as Error).message));
return;
}
+ const providerKey = `${host}Provider`;
+ const modelKey = `${host}Model`;
+ const fields = [
+ { key: providerKey, label: name(providerKey) },
+ { key: modelKey, label: name(modelKey), print: modelText },
+ ];
+ const inForce = {
+ [providerKey]: snapshot.settings[providerKey]?.globalValue,
+ [modelKey]: snapshot.settings[modelKey]?.globalValue,
+ };
+ const rows = changes(inForce, edits, fields);
+ ask({
+ title: fill(s("Save the {host} model?"), { host: hostLabel(host as "opencode" | "pi") }),
+ body: ,
+ confirmLabel: s("Save model"),
+ busyLabel: s("Saving…"),
+ run: () => saveChoice(edits),
+ });
+ }
+ /** Saves the choice. A refusal keeps the dialog open with its reason. */
+ async function saveChoice(edits: Record): Promise {
+ if (!snapshot) return { success: false };
setBusy(true);
let result: { migratedLegacy: boolean } | undefined;
let failure: Error | undefined;
@@ -109,6 +148,7 @@ export function ModelsSection() {
)
);
}
+ return result ? { success: true } : { success: false, error: failure?.message ?? "" };
}
const missing = externalMissing({
@@ -159,11 +199,12 @@ export function ModelsSection() {
{message}
)}
+ {dialog}
);
}
-function ModelCard({
+export function ModelCard({
host,
model,
provider,
diff --git a/web/src/lib/components/settings/OpenRouterRouting.tsx b/web/src/lib/components/settings/OpenRouterRouting.tsx
index 99f7e3da9..21ce50913 100644
--- a/web/src/lib/components/settings/OpenRouterRouting.tsx
+++ b/web/src/lib/components/settings/OpenRouterRouting.tsx
@@ -1,5 +1,9 @@
import { useEffect, useRef, useState } from "react";
import { Loader } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { Button } from "$lib/components/ui/button";
import { Checkbox } from "$lib/components/ui/checkbox";
import { Input } from "$lib/components/ui/input";
@@ -62,6 +66,8 @@ export function OpenRouterRouting({
readOnly?: boolean;
}) {
const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes } = useSettingsChanges();
const [state, setState] = useState(() => routingFromProvider(saved));
const [debounced, setDebounced] = useState(model.trim());
const [list, setList] = useState({ kind: model.trim() ? "loading" : "idle" });
@@ -153,9 +159,55 @@ export function OpenRouterRouting({
toggle(slug, true);
}
- async function saveRouting() {
+ /**
+ * Asks first, with each routing choice the save changes. The left side is what the file holds.
+ * The right side is what the request sends: while OpenRouter chooses, the list is not sent, so
+ * the order and Only rows read as off rather than as the ticks still on the page.
+ */
+ function saveRouting() {
+ const initial = routingFromProvider(saved);
+ const asSaved = {
+ data_collection: initial.dataCollection,
+ zdr: initial.zdr,
+ chooses: initial.openRouterChooses,
+ order: initial.openRouterChooses ? [] : initial.ticked,
+ only: initial.openRouterChooses ? false : initial.only,
+ };
+ const sentOrder = state.openRouterChooses ? [] : usableTicked(state, loaded);
+ // The request sends Only just when a usable provider is ticked, as providerFromRouting does.
+ const asSent = {
+ data_collection: state.dataCollection,
+ zdr: state.zdr,
+ chooses: state.openRouterChooses,
+ order: sentOrder,
+ only: sentOrder.length > 0 && state.only,
+ };
+ const fields = [
+ { key: "data_collection", label: s("Block providers that may train on or store data") },
+ { key: "zdr", label: s("Zero data retention only") },
+ { key: "chooses", label: s("Let OpenRouter choose the provider") },
+ {
+ key: "order",
+ label: s("Providers for this model in try order"),
+ print: (value: unknown) =>
+ Array.isArray(value) && value.length > 0 ? value.join(", ") : s("None"),
+ },
+ { key: "only", label: s("Use only these providers") },
+ ];
+ const rows = changes(asSaved, asSent, fields);
+ ask({
+ title: s("Save OpenRouter routing?"),
+ body: ,
+ confirmLabel: s("Save routing"),
+ busyLabel: s("Saving routing…"),
+ run: sendRouting,
+ });
+ }
+ /** Saves the routing. A refusal keeps the dialog open with its reason. */
+ async function sendRouting(): Promise {
setSave({ kind: "saving" });
const sent = edits.current;
+ let failure: string | undefined;
try {
await settingsRequest(SAVE_PATH, {
method: "POST",
@@ -166,13 +218,18 @@ export function OpenRouterRouting({
...(state.openRouterChooses ? { chooses: true } : {}),
}),
});
+ } catch (error) {
+ failure = (error as Error).message;
+ }
+ if (failure === undefined) {
setSave({ kind: edits.current === sent ? "saved" : "idle" });
setOrderTicks(usableTicked(state, loaded));
setScrollKey((key) => key + 1);
- } catch (error) {
- setSave({ kind: "error", message: (error as Error).message });
+ } else {
+ setSave({ kind: "error", message: failure });
}
await reloadSettingsSnapshot();
+ return failure === undefined ? { success: true } : { success: false, error: failure };
}
const canOnly = usableTicked(state, loaded).length > 0;
@@ -212,7 +269,7 @@ export function OpenRouterRouting({
void saveRouting()}
+ onClick={() => saveRouting()}
>
{s("Save routing")}
@@ -372,6 +429,7 @@ export function OpenRouterRouting({
{save.message}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/settings/ReasoningLevel.tsx b/web/src/lib/components/settings/ReasoningLevel.tsx
index 6c2061da4..5bbdf8332 100644
--- a/web/src/lib/components/settings/ReasoningLevel.tsx
+++ b/web/src/lib/components/settings/ReasoningLevel.tsx
@@ -1,6 +1,9 @@
import { useState } from "react";
import { Loader } from "lucide-react";
import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
+import type { ConfirmResult } from "$lib/components/settings/SettingsConfirmDialog";
import { Callout } from "$lib/components/skills/Callout";
import { Button } from "$lib/components/ui/button";
import { Label } from "$lib/components/ui/label";
@@ -54,6 +57,7 @@ export function ReasoningLevel({
const [picked, setPicked] = useState<{ at: string; level: string }>();
const [save, setSave] = useState({ kind: "idle" });
const { ask, dialog } = useSettingsConfirm();
+ const { changes } = useSettingsChanges();
const family = reasoningFamily(savedUrl, savedProvider);
if (family === "none") {
@@ -115,10 +119,35 @@ export function ReasoningLevel({
}
}
- async function saveLevel() {
+ /** Saves the level and reports on the card. A refusal keeps the dialog open with its reason. */
+ async function saveLevelNow(): Promise {
setSave({ kind: "saving" });
const failure = await submit();
- setSave(failure === undefined ? { kind: "saved" } : { kind: "error", message: failure });
+ if (failure !== undefined) {
+ setSave({ kind: "error", message: failure });
+ return { success: false, error: failure };
+ }
+ setSave({ kind: "saved" });
+ return { success: true };
+ }
+
+ /** Asks first. The picked level stays on screen as a draft when the user cancels. */
+ function saveLevel() {
+ const fields = [
+ {
+ key: "level",
+ label: s("Reasoning level"),
+ print: (value: unknown) => label(value as Level),
+ },
+ ];
+ const rows = changes({ level: initial }, { level: shown }, fields);
+ ask({
+ title: s("Save reasoning level?"),
+ body: ,
+ confirmLabel: s("Save reasoning level"),
+ busyLabel: s("Saving reasoning level…"),
+ run: saveLevelNow,
+ });
}
// A hand-written value is replaced by the save, so the user confirms first. The dialog shows
@@ -151,7 +180,7 @@ export function ReasoningLevel({
save.kind === "saving" || readOnly || shown === "custom" || blockReason !== undefined
}
aria-describedby={blockReason === undefined ? undefined : "reasoning-save-reason"}
- onClick={() => (initial === "custom" ? askToReplace() : void saveLevel())}
+ onClick={() => (initial === "custom" ? askToReplace() : saveLevel())}
>
{s("Save reasoning level")}
diff --git a/web/src/lib/components/settings/SettingsChangeList.tsx b/web/src/lib/components/settings/SettingsChangeList.tsx
new file mode 100644
index 000000000..b85fb0096
--- /dev/null
+++ b/web/src/lib/components/settings/SettingsChangeList.tsx
@@ -0,0 +1,35 @@
+import { ArrowRight } from "lucide-react";
+import { useCatalogueText } from "$lib/i18n/settings-catalogue";
+import type { SettingsChange } from "$lib/settings-changes";
+
+/**
+ * The list in a settings confirm dialog: each setting the save changes, with its saved value struck
+ * through and its new value after it. The rows are already translated. A screen reader hears
+ * "changes to" between the two values. With no rows, a save that keeps every value still asks
+ * first, and the list says so in one sentence.
+ */
+export function SettingsChangeList({ changes }: { changes: readonly SettingsChange[] }) {
+ const t = useCatalogueText();
+ if (changes.length === 0)
+ return {t("Nothing changes. Saving writes the current values again.")}
;
+ return (
+
+ {changes.map((change) => (
+
+
{change.label}
+
+
+ {change.from}
+
+
+ {t("changes to")}
+ {change.to}
+
+
+ ))}
+
+ );
+}
diff --git a/web/src/lib/components/settings/SkillLearningSection.tsx b/web/src/lib/components/settings/SkillLearningSection.tsx
index 517e9518c..8aabb69c4 100644
--- a/web/src/lib/components/settings/SkillLearningSection.tsx
+++ b/web/src/lib/components/settings/SkillLearningSection.tsx
@@ -1,6 +1,10 @@
import { useCallback, useEffect, useState } from "react";
import { Trash2 } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { Button } from "$lib/components/ui/button";
+import { Switch as SwitchControl } from "$lib/components/ui/switch";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { useSettingsText } from "$lib/i18n/settings";
import { skillsApi, type SkillStats } from "$lib/skills-api";
import { countText, fileSizeText, fill } from "$lib/skills-model";
@@ -9,7 +13,7 @@ import { RecordPast } from "../skills/RecordPast";
import { useSkillSettings } from "../skills/use-skill-settings";
import { ReadOnlyNote, useSettingsReadOnly } from "./ReadOnlyNote";
-function Switch({
+export function Switch({
label,
checked,
disabled,
@@ -22,13 +26,11 @@ function Switch({
}) {
return (
- onChange(event.target.checked)}
+ onCheckedChange={onChange}
/>
{label}
@@ -44,12 +46,12 @@ export type SkillLearningCardProps = {
busy: boolean;
/** The config file cannot be read, so the two switches cannot save. */
readOnly?: boolean;
- confirm: "redact" | "delete" | null;
+ confirm: "delete" | null;
message: string;
failure: string;
onRecording: (on: boolean) => void;
onRedact: (on: boolean) => void;
- onConfirm: (what: "redact" | "delete" | null) => void;
+ onConfirm: (what: "delete" | null) => void;
onDeleteTurns: () => void;
onRecordPastEnd: () => void;
};
@@ -107,31 +109,6 @@ export function SkillLearningCard(props: SkillLearningCardProps) {
disabled={busy || props.readOnly === true}
onChange={props.onRedact}
/>
- {confirm === "redact" ? (
-
- {s("Stop removing private text and secrets?")}
- {s("New turns will be stored as written.")}
-
- props.onRedact(false)}
- >
- {s("Turn off")}
-
- props.onConfirm(null)}
- >
- {s("Cancel")}
-
-
-
- ) : null}
{!redact ? (
@@ -206,12 +183,17 @@ export function SkillLearningCard(props: SkillLearningCardProps) {
/** Skill learning settings: recording, redaction, the store size and a delete. */
export function SkillLearningSection() {
const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const { snapshot, loadError, busy, save } = useSkillSettings();
const readOnly = useSettingsReadOnly();
const [stats, setStats] = useState(null);
const [message, setMessage] = useState("");
const [failure, setFailure] = useState("");
- const [confirm, setConfirm] = useState<"redact" | "delete" | null>(null);
+ const [confirm, setConfirm] = useState<"delete" | null>(null);
+ /** The values picked while a dialog asks. Cancel puts the saved ones back. */
+ const [pendingRecording, setPendingRecording] = useState();
+ const [pendingRedact, setPendingRedact] = useState();
const loadStats = useCallback(async () => {
const reply = await skillsApi.stats();
@@ -222,8 +204,10 @@ export function SkillLearningSection() {
}, [loadStats]);
const recordEntry = snapshot?.settings.skillLearning;
+ const savedRecording = recordEntry?.globalValue === true;
+ const savedRedact = snapshot?.settings.skillLearningRedact?.globalValue !== false;
- async function change(edits: Record) {
+ async function change(edits: Record): Promise {
setMessage("");
setFailure("");
setConfirm(null);
@@ -231,6 +215,63 @@ export function SkillLearningSection() {
if (error) setFailure(error);
else setMessage(s("Saved."));
await loadStats();
+ return error;
+ }
+
+ /** The run every switch dialog shares: save, then drop the pending value once the file agrees. */
+ async function runSwitch(
+ dropPending: (value: boolean | undefined) => void,
+ edits: Record
+ ) {
+ const error = await change(edits);
+ if (error) return { success: false, error };
+ // The reloaded snapshot shows the saved value, so the picked one can go.
+ dropPending(undefined);
+ return { success: true };
+ }
+
+ /** Asks before the recording switch saves. The switch shows the picked value meanwhile. */
+ function turnRecording(on: boolean) {
+ const edits = { skillLearning: on };
+ setPendingRecording(on);
+ ask({
+ title: s(on ? "Turn on skill learning?" : "Turn off skill learning?"),
+ body: (
+
+ ),
+ confirmLabel: s(on ? "Turn on" : "Turn off"),
+ busyLabel: s("Saving…"),
+ onCancel: () => setPendingRecording(undefined),
+ run: () => runSwitch(setPendingRecording, edits),
+ });
+ }
+
+ /** Asks before the redaction switch saves; the dialog carries the old warning when it turns off. */
+ function turnRedact(on: boolean) {
+ const edits = { skillLearningRedact: on };
+ setPendingRedact(on);
+ ask({
+ title: s(on ? "Remove private text and secrets?" : "Stop removing private text and secrets?"),
+ body: (
+ <>
+
+ {!on ? {s("New turns will be stored as written.")}
: null}
+ >
+ ),
+ confirmLabel: s(on ? "Turn on" : "Turn off"),
+ busyLabel: s("Saving…"),
+ destructive: !on,
+ onCancel: () => setPendingRedact(undefined),
+ run: () => runSwitch(setPendingRedact, edits),
+ });
}
async function deleteTurns() {
@@ -246,25 +287,24 @@ export function SkillLearningSection() {
}
return (
- void change({ skillLearning: on })}
- onRedact={(on) => {
- // Turning redaction off asks first; turning it back on needs no question.
- if (on || confirm === "redact") void change({ skillLearningRedact: on });
- else setConfirm("redact");
- }}
- onConfirm={setConfirm}
- onDeleteTurns={() => void deleteTurns()}
- onRecordPastEnd={() => void loadStats()}
- />
+ <>
+ turnRecording(on)}
+ onRedact={(on) => turnRedact(on)}
+ onConfirm={setConfirm}
+ onDeleteTurns={() => void deleteTurns()}
+ onRecordPastEnd={() => void loadStats()}
+ />
+ {dialog}
+ >
);
}
diff --git a/web/src/lib/components/settings/WebAppSection.tsx b/web/src/lib/components/settings/WebAppSection.tsx
index 6c9baa8e5..e1b67da58 100644
--- a/web/src/lib/components/settings/WebAppSection.tsx
+++ b/web/src/lib/components/settings/WebAppSection.tsx
@@ -1,8 +1,11 @@
import { useEffect, useState } from "react";
import { Loader } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
+import { useSettingsChanges } from "@/hooks/useSettingsChanges";
import { useSettingsSnapshot } from "@/hooks/useSettingsSnapshot";
import { Button } from "$lib/components/ui/button";
import { Checkbox } from "$lib/components/ui/checkbox";
+import { SettingsChangeList } from "$lib/components/settings/SettingsChangeList";
import { settingsRequest } from "$lib/settings-api";
import { saveSettingEdits } from "$lib/settings-save";
import { useSettingsText } from "$lib/i18n/settings";
@@ -21,6 +24,8 @@ type LoginItem = { state: string; command?: string };
export function WebAppSection() {
const s = useSettingsText();
const t = useCardText();
+ const { ask, dialog } = useSettingsConfirm();
+ const { changes, name } = useSettingsChanges();
const { snapshot, error: loadError } = useSettingsSnapshot();
const [item, setItem] = useState();
const [version, setVersion] = useState();
@@ -49,20 +54,32 @@ export function WebAppSection() {
const saved = Boolean(snapshot?.settings.webServerAutoStart?.globalValue);
const enabled = edit ?? saved;
- async function save() {
+ /** Asks first, with the changed setting and its new value. The card's own feedback stays. */
+ function save() {
if (!snapshot || edit === undefined || edit === saved) return;
- setBusy(true);
- const result = await saveSettingEdits(snapshot.revision, { webServerAutoStart: edit });
- setBusy(false);
- setFailed(!result.success);
- if (result.success) setEdit(undefined);
- setMessage(
- result.success
- ? s(
- "Saved. The login item changes at the next OpenCode or Pi start, or right away with the commands below. With Claude Code alone, run the command yourself."
- )
- : (result.error ?? "")
- );
+ const body = { webServerAutoStart: edit };
+ const fields = [{ key: "webServerAutoStart", label: name("webServerAutoStart") }];
+ ask({
+ title: t("Save web app settings?"),
+ body: ,
+ confirmLabel: t("Save"),
+ busyLabel: t("Saving…"),
+ run: async () => {
+ setBusy(true);
+ const result = await saveSettingEdits(snapshot.revision, body);
+ setBusy(false);
+ setFailed(!result.success);
+ if (result.success) setEdit(undefined);
+ setMessage(
+ result.success
+ ? s(
+ "Saved. The login item changes at the next OpenCode or Pi start, or right away with the commands below. With Claude Code alone, run the command yourself."
+ )
+ : (result.error ?? "")
+ );
+ return result;
+ },
+ });
}
return (
void save()}
+ onClick={() => save()}
>
{t("Save")}
@@ -129,6 +146,7 @@ export function WebAppSection() {
{message}
)}
+ {dialog}
);
}
diff --git a/web/src/lib/components/skills/RecordPast.tsx b/web/src/lib/components/skills/RecordPast.tsx
index 926eed255..634964a30 100644
--- a/web/src/lib/components/skills/RecordPast.tsx
+++ b/web/src/lib/components/skills/RecordPast.tsx
@@ -1,4 +1,5 @@
import { History, Loader } from "lucide-react";
+import { useSettingsConfirm } from "@/hooks/useSettingsConfirm";
import { Button } from "$lib/components/ui/button";
import { useSettingsText } from "$lib/i18n/settings";
import { fill, jobEnded, jobPercent, recordedTurns, countText } from "$lib/skills-model";
@@ -7,15 +8,39 @@ import { useRecordPast } from "./use-record-past";
/** Record past turns: the button, progress while it runs, and the count when it ends. */
export function RecordPast({ onEnd }: { onEnd: () => void }) {
+ const s = useSettingsText();
+ const { ask, dialog } = useSettingsConfirm();
const { job, running, starting, error, start } = useRecordPast(onEnd);
+ /** Asks first: the job reads every set-up host's history, so it needs a clear go-ahead. */
+ function askFirst() {
+ ask({
+ title: s("Record past turns?"),
+ body: (
+
+ {s(
+ "OMMS records skill turns from the past sessions of every set-up host, with no model call."
+ )}
+
+ ),
+ confirmLabel: s("Record past turns"),
+ busyLabel: s("Finding past sessions…"),
+ run: async () => {
+ // A refused start keeps its reason in the dialog. The card follows the job after a start.
+ return start();
+ },
+ });
+ }
return (
- void start()}
- />
+ <>
+ void askFirst()}
+ />
+ {dialog}
+ >
);
}
diff --git a/web/src/lib/components/skills/use-record-past.ts b/web/src/lib/components/skills/use-record-past.ts
index 2ce26b7eb..8a1eb12c1 100644
--- a/web/src/lib/components/skills/use-record-past.ts
+++ b/web/src/lib/components/skills/use-record-past.ts
@@ -49,18 +49,20 @@ export function useRecordPast(onEnd: () => void) {
}
}, [job]);
- async function start() {
- if (starting || running) return;
+ /** Starts the job. A refused start shows its reason on the card and comes back for the dialog. */
+ async function start(): Promise<{ success: boolean; error?: string }> {
+ if (starting || running) return { success: true };
setStarting(true);
setError("");
const reply = await skillsApi.recordPast();
- if (!mounted.current) return;
+ if (!mounted.current) return { success: true };
setStarting(false);
if (!reply.ok) {
setError(reply.error);
- return;
+ return { success: false, error: reply.error };
}
setJob((reply.data as unknown as { job: ImportJob }).job);
+ return { success: true };
}
return { job, running, starting, error, start };
}
diff --git a/web/src/lib/i18n/arabic-count.ts b/web/src/lib/i18n/arabic-count.ts
new file mode 100644
index 000000000..e59748c80
--- /dev/null
+++ b/web/src/lib/i18n/arabic-count.ts
@@ -0,0 +1,33 @@
+/**
+ * Arabic counted nouns change form with the number: 1 and 2 have their own words, 3 to 10 take
+ * the plural, 11 to 99 take the singular with tanween, and 100 takes the plain singular. The
+ * one-text-per-key tables cannot hold that, so these messages pick their form here.
+ */
+type Forms = Partial> & { other: string };
+
+const FORMS: Readonly> = {
+ "{count} days": {
+ one: "يوم واحد",
+ two: "يومان",
+ few: "{count} أيام",
+ many: "{count} يوماً",
+ other: "{count} يوم",
+ },
+ "{count} hours": {
+ one: "ساعة واحدة",
+ two: "ساعتان",
+ few: "{count} ساعات",
+ many: "{count} ساعة",
+ other: "{count} ساعة",
+ },
+};
+
+const rules = new Intl.PluralRules("ar");
+
+/** The Arabic text for a counted message, or undefined when the table text applies. */
+export function arabicCount(message: string, count: string | number): string | undefined {
+ const forms = FORMS[message];
+ const value = Number(count);
+ if (!forms || !Number.isInteger(value)) return undefined;
+ return (forms[rules.select(value)] ?? forms.other).replace("{count}", String(value));
+}
diff --git a/web/src/lib/i18n/openrouter.ts b/web/src/lib/i18n/openrouter.ts
index eb594f1a4..af88d0e2a 100644
--- a/web/src/lib/i18n/openrouter.ts
+++ b/web/src/lib/i18n/openrouter.ts
@@ -51,7 +51,12 @@ export const openrouterSettingText = {
"هذا المزوّد موجود في القائمة.",
],
"Save routing": ["保存路由", "حفظ التوجيه"],
+ "Save OpenRouter routing?": ["保存 OpenRouter 路由?", "حفظ توجيه OpenRouter؟"],
"Saving routing…": ["正在保存路由…", "جارٍ حفظ التوجيه…"],
+ "Providers for this model in try order": [
+ "此模型的提供商尝试顺序",
+ "ترتيب تجربة المزوّدين لهذا النموذج",
+ ],
"Routing saved.": ["路由已保存。", "تم حفظ التوجيه."],
"Other routing fields are set in the config file and are kept.": [
"其他路由字段在配置文件中设置,并会保留。",
diff --git a/web/src/lib/i18n/reasoning-level.ts b/web/src/lib/i18n/reasoning-level.ts
index 222beca9b..70fcd2440 100644
--- a/web/src/lib/i18n/reasoning-level.ts
+++ b/web/src/lib/i18n/reasoning-level.ts
@@ -51,6 +51,7 @@ export const reasoningLevelText = {
"احفظ العنوان أولاً. يُطبَّق المستوى على العنوان والمزوّد والنموذج المحفوظة.",
],
"Save reasoning level": ["保存推理级别", "حفظ مستوى الاستدلال"],
+ "Save reasoning level?": ["保存推理级别?", "حفظ مستوى الاستدلال؟"],
"Saving reasoning level…": ["正在保存推理级别…", "جارٍ حفظ مستوى الاستدلال…"],
"Reasoning level saved.": ["推理级别已保存。", "تم حفظ مستوى الاستدلال."],
} as const;
diff --git a/web/src/lib/i18n/settings-cards-text.ts b/web/src/lib/i18n/settings-cards-text.ts
index 246e3ba5d..d610161cf 100644
--- a/web/src/lib/i18n/settings-cards-text.ts
+++ b/web/src/lib/i18n/settings-cards-text.ts
@@ -17,6 +17,8 @@ export const settingsCardsText: Readonly
+): string {
+ const counted =
+ language === "ar" && params?.count !== undefined
+ ? arabicCount(message, params.count)
+ : undefined;
+ if (counted !== undefined) return counted;
+ return message in settingsCatalogueText
+ ? translateCatalogue(message, language, params)
+ : translateCatalogue(translateSettings(message, language), "en", params);
+}
+
+/** The translator for the Settings page cards, bound to the page language. */
export function useCardText() {
const { language } = useI18n();
return (message: string, params?: Record): string =>
- message in settingsCatalogueText
- ? translateCatalogue(message, language, params)
- : translateCatalogue(translateSettings(message, language), "en", params);
+ cardText(message, language, params);
}
diff --git a/web/src/lib/i18n/settings-catalogue-rows.ts b/web/src/lib/i18n/settings-catalogue-rows.ts
index 6364aa63e..69504bef7 100644
--- a/web/src/lib/i18n/settings-catalogue-rows.ts
+++ b/web/src/lib/i18n/settings-catalogue-rows.ts
@@ -25,7 +25,18 @@ export const settingsCatalogueRowText = {
On: ["开", "قيد التشغيل"],
Off: ["关", "متوقف"],
"Not set": ["未设置", "غير محدد"],
+ "Default ({value})": ["默认({value})", "افتراضي ({value})"],
None: ["无", "لا شيء"],
+ // The list of changes in a settings confirm dialog.
+ "changes to": ["改为", "يتغير إلى"],
+ "Nothing changes. Saving writes the current values again.": [
+ "没有更改。保存会再次写入当前值。",
+ "لا يتغير شيء. الحفظ يكتب القيم الحالية مرة أخرى.",
+ ],
+ "Close this dialog and save again, so it shows the current settings.": [
+ "请关闭此对话框并重新保存,以显示当前设置。",
+ "أغلق هذه النافذة واحفظ مرة أخرى، لتعرض الإعدادات الحالية.",
+ ],
"This project": ["本项目", "هذا المشروع"],
"OpenAI Chat Completions": ["OpenAI Chat Completions", "OpenAI Chat Completions"],
"Session model": ["会话模型", "نموذج الجلسة"],
diff --git a/web/src/lib/i18n/settings.ts b/web/src/lib/i18n/settings.ts
index c5efa1369..79dd2e0ac 100644
--- a/web/src/lib/i18n/settings.ts
+++ b/web/src/lib/i18n/settings.ts
@@ -153,7 +153,18 @@ const text = {
"已保存。更改将在下一次学习时生效。",
"تم الحفظ. تنطبق التغييرات في جولة التعلّم التالية.",
],
+ "Save automatic profile cleanup?": [
+ "保存自动画像清理设置?",
+ "حفظ التنظيف التلقائي للملف الشخصي؟",
+ ],
+ prompts: ["个提示", "مطالبة"],
"Analyse waiting prompts": ["分析等待处理的提示", "تحليل المطالبات المنتظرة"],
+ "Pause the catch-up run?": ["暂停补齐任务?", "إيقاف مهمة اللحاق مؤقتاً؟"],
+ "This pauses the catch-up run, so no model calls run until you resume it.": [
+ "这会暂停补齐任务,在你恢复之前不会进行任何模型调用。",
+ "يوقف هذا مهمة اللحاق مؤقتاً، فلن تُنفَّذ أي استدعاءات نموذج حتى تستأنفها.",
+ ],
+ "Pausing…": ["正在暂停…", "جارٍ الإيقاف المؤقت…"],
"Re-analyse chat history": ["重新分析聊天记录", "إعادة تحليل سجل المحادثات"],
"Analyse waiting prompts reads prompts already inside OMMS with the saved external API, 50 eligible prompts per analysis call. Completed history is not re-analysed. Preferences, patterns, and workflows are the outputs.":
[
@@ -240,6 +251,7 @@ const text = {
"لا توجد في Pi نماذج مسجَّل الدخول إليها. سجّل الدخول إلى مزوّد في Pi ثم أعد تحميل هذه الصفحة.",
],
"Save model": ["保存模型", "حفظ النموذج"],
+ "Save the {host} model?": ["保存 {host} 模型?", "حفظ نموذج {host}؟"],
"Enter a model as provider/model.": [
"按 提供商/模型 格式输入。",
"أدخل النموذج بصيغة المزوّد/النموذج.",
@@ -381,6 +393,8 @@ const text = {
],
"Import past chats automatically": ["自动导入过去的对话", "استيراد المحادثات السابقة تلقائياً"],
"Backfill model": ["历史导入模型", "نموذج استيراد السجل"],
+ "Save the backfill model?": ["保存历史导入模型?", "حفظ نموذج استيراد السجل؟"],
+ "Turn automatic import off?": ["关闭自动导入?", "إيقاف الاستيراد التلقائي؟"],
"Same as live capture": ["与实时捕获相同", "مثل الالتقاط المباشر"],
"Saved. Changes apply at the next host start.": [
"已保存。更改在下次启动主机时生效。",
@@ -709,6 +723,7 @@ const text = {
"已保存。新记忆将使用此语言。",
"تم الحفظ. ستستخدم الذكريات الجديدة هذه اللغة.",
],
+ "Change the summary language?": ["更改摘要语言?", "تغيير لغة الملخص؟"],
"Claude Code folder": ["Claude Code 文件夹", "مجلد Claude Code"],
"Set this when Claude Code does not use ~/.claude, for example when you start it with CLAUDE_CONFIG_DIR. Leave it empty to use the default.":
[
@@ -716,6 +731,7 @@ const text = {
"اضبط هذا عندما لا يستخدم Claude Code المجلد ~/.claude، مثلاً عند تشغيله مع CLAUDE_CONFIG_DIR. اتركه فارغاً لاستخدام المجلد الافتراضي.",
],
"Save folder": ["保存文件夹", "حفظ المجلد"],
+ "Save the Claude Code folder?": ["保存 Claude Code 文件夹?", "حفظ مجلد Claude Code؟"],
"Transcripts folder in use": ["正在使用的会话记录文件夹", "مجلد سجلات الجلسات المستخدم"],
From: ["来源", "المصدر"],
"this setting": ["此设置", "هذا الإعداد"],
@@ -1001,6 +1017,10 @@ const text = {
"احتفظ بالخريطة بعد استيراد جلساتها. يفحص كل استيراد الخريطة قبل أن يتجاوز جلسة، لذا فإن حذف الخريطة يجعل جلساتها غير محلولة مجدداً في التشغيل التالي.",
],
"Save removals": ["保存删除", "حفظ عمليات الحذف"],
+ "Save removals?": ["保存删除?", "حفظ عمليات الحذف؟"],
+ maps: ["个映射", "خرائط"],
+ "1 map": ["1 个映射", "خريطة واحدة"],
+ "{count} maps": ["{count} 个映射", "{count} خرائط"],
"Settings changed elsewhere. Check the list and try again.": [
"设置已在其他位置更改。请检查列表后再试。",
"تغيّرت الإعدادات في مكان آخر. راجع القائمة، ثم حاول مجدداً.",
@@ -1033,6 +1053,16 @@ const text = {
"无法恢复该目录。请重试。",
"تعذّرت استعادة المجلد. حاول مجدداً.",
],
+ "Ignore this folder?": ["忽略此文件夹?", "أتجاهل هذا المجلد؟"],
+ "The folder stays unimported and leaves the unresolved counts.": [
+ "该文件夹保持未导入,并且不计入未解析数量。",
+ "يظل المجلد دون استيراد ولا يُحسب ضمن الأعداد غير المحلولة.",
+ ],
+ "Restore this folder?": ["恢复此文件夹?", "أستعيد هذا المجلد؟"],
+ "The folder shows again in each host list that reported it.": [
+ "该文件夹会重新出现在报告它的每个主机列表中。",
+ "يظهر المجلد مجدداً في قائمة كل مضيف أبلغ عنه.",
+ ],
"Saved, but the list could not be refreshed. Refresh the list without saving again.": [
"已保存,但无法刷新列表。请刷新列表,无需再次保存。",
"تم الحفظ، لكن تعذّر تحديث القائمة. حدّث القائمة دون الحفظ مجدداً.",
@@ -1143,6 +1173,8 @@ const text = {
"عدّل الملف ~/.config/omms/omms.jsonc مباشرة لضبط هذه الحدود دون واجهة الويب.",
],
"Save memory limits": ["保存记忆限制", "حفظ حدود الذاكرة"],
+ "Save memory limits?": ["保存记忆限制?", "حفظ حدود الذاكرة؟"],
+ "Reset to default?": ["恢复默认值?", "الإعادة إلى الافتراضي؟"],
"Saved. New memory operations use these limits.": [
"已保存。新的记忆操作将使用这些限制。",
"تم الحفظ. ستستخدم عمليات الذاكرة الجديدة هذه الحدود.",
@@ -1173,6 +1205,7 @@ const text = {
"Reset to default": ["恢复默认", "إعادة إلى الافتراضي"],
"Differs from default": ["与默认值不同", "يختلف عن الافتراضي"],
"Keyword matching": ["关键词匹配", "مطابقة الكلمات"],
+ "Save keyword matching?": ["保存关键词匹配设置?", "حفظ إعدادات مطابقة الكلمات؟"],
"Search finds memories by meaning and by exact words from your prompt.": [
"搜索按含义和提示中的确切词语查找记忆。",
"يجد البحث الذكريات بالمعنى وبالكلمات الدقيقة من مطالبتك.",
@@ -1210,6 +1243,7 @@ const text = {
"تعذّر تحميل إعداد مطابقة الكلمات. أعد تحميل الصفحة للمحاولة مرة أخرى.",
],
Reranker: ["重排序器", "إعادة الترتيب"],
+ "Save the reranker settings?": ["保存重排序器设置?", "حفظ إعدادات معيد الترتيب؟"],
"Use a reranker": ["使用重排序器", "استخدم معيد الترتيب"],
Key: ["密钥", "المفتاح"],
Timeout: ["超时", "مهلة الانتهاء"],
@@ -1370,6 +1404,7 @@ const text = {
"已保存。下一个会话将使用这些选项。",
"تم الحفظ. ستستخدم الجلسة التالية هذه الخيارات.",
],
+ "Save memory injection?": ["保存记忆注入设置?", "حفظ إعدادات حقن الذاكرة؟"],
"The memory injection settings could not be loaded. Reload the page to try again.": [
"无法加载记忆注入设置。请重新加载页面后重试。",
"تعذّر تحميل إعدادات حقن الذاكرة. أعد تحميل الصفحة للمحاولة مرة أخرى.",
@@ -1488,6 +1523,28 @@ const text = {
],
"Upload image": ["上传图片", "رفع صورة"],
"Use external API": ["使用外部 API", "استخدام واجهة API الخارجية"],
+ "Use the external API?": ["使用外部 API?", "استخدام واجهة API الخارجية؟"],
+ "{host} will use the external API model to import past chats. It can then run with no host open.":
+ [
+ "{host} 将使用外部 API 模型导入过去的对话。之后无需打开主机即可运行。",
+ "سيستخدم {host} نموذج واجهة API الخارجية لاستيراد المحادثات السابقة. ويمكنه بعد ذلك العمل دون فتح المضيف.",
+ ],
+ "Pause automatic import?": ["暂停自动导入?", "إيقاف الاستيراد التلقائي مؤقتاً؟"],
+ "Automatic import stops after the current exchange, and no automatic run starts until you resume it.":
+ [
+ "自动导入会在当前这轮交流后停止,在你恢复之前不会开始新的自动运行。",
+ "يتوقف الاستيراد التلقائي بعد التبادل الحالي، ولا يبدأ أي تشغيل تلقائي حتى تستأنفه.",
+ ],
+ "Resume automatic import?": ["恢复自动导入?", "استئناف الاستيراد التلقائي؟"],
+ "Automatic import starts again and makes model calls, which can cost money.": [
+ "自动导入会再次开始并调用模型,可能会产生费用。",
+ "يبدأ الاستيراد التلقائي من جديد ويستدعي النموذج، وقد يكلّف ذلك مالاً.",
+ ],
+ "Retry the import?": ["重试导入?", "إعادة محاولة الاستيراد؟"],
+ "The import runs again, so it calls the model again and can cost money.": [
+ "导入会再次运行,因此会再次调用模型,可能会产生费用。",
+ "يعمل الاستيراد مرة أخرى، لذا يستدعي النموذج مرة أخرى وقد يكلّف ذلك مالاً.",
+ ],
settings: ["设置", "الإعدادات"],
"{saved} saved · {ignored} ignored": [
"已保存 {saved} · 已忽略 {ignored}",
@@ -1516,6 +1573,7 @@ const text = {
"تعذّر تحميل أحدث الإعدادات. أعد تحميل الصفحة قبل الحفظ مرة أخرى.",
],
"Learning settings": ["学习设置", "إعدادات التعلّم"],
+ "Save learning settings?": ["保存学习设置?", "حفظ إعدادات التعلّم؟"],
"Wait until the current save finishes.": ["请等当前保存完成。", "انتظر حتى ينتهي الحفظ الحالي."],
"The settings have not loaded yet.": ["设置尚未加载。", "لم يتم تحميل الإعدادات بعد."],
"Change a setting to turn on Save.": [
diff --git a/web/src/lib/i18n/skills.ts b/web/src/lib/i18n/skills.ts
index 5a6d5aefe..d5355737d 100644
--- a/web/src/lib/i18n/skills.ts
+++ b/web/src/lib/i18n/skills.ts
@@ -127,6 +127,11 @@ export const skillText = {
"سجّل أدوار الوكيل ليتمكن OMMS من ترتيب مهاراتك وصياغة التحسينات.",
],
"Record past turns": ["记录过去的回合", "تسجيل الأدوار السابقة"],
+ "Record past turns?": ["记录过去的回合?", "تسجيل الأدوار السابقة؟"],
+ "OMMS records skill turns from the past sessions of every set-up host, with no model call.": [
+ "OMMS 会从每个已设置宿主的过往会话中记录技能回合,不调用模型。",
+ "يسجّل OMMS أدوار المهارات من الجلسات السابقة لكل مضيف مهيّأ، دون أي استدعاء لنموذج.",
+ ],
"Record past turns did not finish.": [
"记录过去的回合未完成。",
"لم يكتمل تسجيل الأدوار السابقة.",
@@ -140,6 +145,7 @@ export const skillText = {
"Remove folder": ["移除文件夹", "إزالة المجلد"],
"Remove folder {path}": ["移除文件夹 {path}", "إزالة المجلد {path}"],
"Remove private text and secrets": ["移除私密文本和机密", "إزالة النص الخاص والأسرار"],
+ "Remove private text and secrets?": ["移除私密文本和机密?", "إزالة النص الخاص والأسرار؟"],
"Reset default": ["恢复默认", "استعادة الافتراضي"],
"Saved.": ["已保存。", "تم الحفظ."],
"Show changes": ["显示更改", "عرض التغييرات"],
@@ -164,6 +170,8 @@ export const skillText = {
],
Suggested: ["建议", "مقترحة"],
"Turn off": ["关闭", "إيقاف"],
+ "Turn on skill learning?": ["开启技能学习?", "تشغيل تعلّم المهارات؟"],
+ "Turn off skill learning?": ["关闭技能学习?", "إيقاف تعلّم المهارات؟"],
"Turn on Automatic": ["开启自动", "تشغيل التلقائي"],
"Turn on Automatic mode for this skill?": [
"为此技能开启自动模式?",
diff --git a/web/src/lib/settings-changes.ts b/web/src/lib/settings-changes.ts
new file mode 100644
index 000000000..9da46bf7a
--- /dev/null
+++ b/web/src/lib/settings-changes.ts
@@ -0,0 +1,61 @@
+/**
+ * The rows a settings confirm dialog lists before a save: each setting the request changes, with
+ * its saved value and its new value. Pure, with no React or translation imports: the card passes
+ * the words of the page.
+ */
+
+/** One setting the save changes. `from` and `to` are already in plain words. */
+export type SettingsChange = { key: string; label: string; from: string; to: string };
+
+export type SettingsChangeField = {
+ /** The request identifier, as the config file spells it: `maxMemories`, `compaction.enabled`. */
+ key: string;
+ /** The setting's name, already translated. */
+ label: string;
+ /** Prints a value in plain words. Without it a switch reads On or Off and anything else as text. */
+ print?: (value: unknown) => string;
+ /** What applies once the key is removed. A removal reads `Default (value)`. */
+ default?: unknown;
+};
+
+/** The page's words for the values a card does not spell itself. */
+export type SettingsChangeWords = {
+ on: string;
+ off: string;
+ notSet: string;
+ /** Says that the default applies, as `Default (10)`. */
+ default: (value: string) => string;
+};
+
+/**
+ * Lists what a request changes, in the order of `fields`. `saved` holds the values in force and
+ * `edits` is the body the card is about to send; both use the keys of the request. A key that the
+ * request leaves out, or that reads the same as its saved value, is no change. A `null` edit removes
+ * the key, so the row shows the default. Throws when the request changes a key that no field
+ * describes: the dialog must never leave a change out.
+ */
+export function settingsChanges(
+ saved: Record,
+ edits: Record,
+ fields: readonly SettingsChangeField[],
+ words: SettingsChangeWords
+): SettingsChange[] {
+ for (const key of Object.keys(edits)) {
+ if (edits[key] !== undefined && !fields.some((field) => field.key === key))
+ throw new Error(`settingsChanges: no field describes "${key}"`);
+ }
+ const plain = (value: unknown): string => {
+ if (value === true) return words.on;
+ if (value === false) return words.off;
+ return value == null ? words.notSet : String(value);
+ };
+ const rows: SettingsChange[] = [];
+ for (const { key, label, print = plain, default: fallback } of fields) {
+ const after = edits[key];
+ if (after === undefined) continue;
+ const from = print(saved[key]);
+ const to = after === null ? words.default(print(fallback)) : print(after);
+ if (from !== to) rows.push({ key, label, from, to });
+ }
+ return rows;
+}
diff --git a/web/tests/arabic-count.spec.ts b/web/tests/arabic-count.spec.ts
new file mode 100644
index 000000000..eeaf44a40
--- /dev/null
+++ b/web/tests/arabic-count.spec.ts
@@ -0,0 +1,32 @@
+import { expect, it } from "bun:test";
+import { arabicCount } from "../src/lib/i18n/arabic-count.ts";
+
+it("picks the Arabic plural form for a count of days", () => {
+ expect(arabicCount("{count} days", 1)).toBe("يوم واحد");
+ expect(arabicCount("{count} days", 2)).toBe("يومان");
+ expect(arabicCount("{count} days", 3)).toBe("3 أيام");
+ expect(arabicCount("{count} days", 10)).toBe("10 أيام");
+ expect(arabicCount("{count} days", 11)).toBe("11 يوماً");
+ expect(arabicCount("{count} days", 30)).toBe("30 يوماً");
+ expect(arabicCount("{count} days", 100)).toBe("100 يوم");
+});
+
+it("picks the Arabic plural form for a count of hours", () => {
+ expect(arabicCount("{count} hours", 1)).toBe("ساعة واحدة");
+ expect(arabicCount("{count} hours", 2)).toBe("ساعتان");
+ expect(arabicCount("{count} hours", 5)).toBe("5 ساعات");
+ expect(arabicCount("{count} hours", 72)).toBe("72 ساعة");
+});
+
+it("leaves other messages and counts that are not whole numbers to the table", () => {
+ expect(arabicCount("{count} maps", 3)).toBeUndefined();
+ expect(arabicCount("{count} days", "abc")).toBeUndefined();
+});
+
+it("the Settings card translator uses the Arabic form, and leaves other languages alone", async () => {
+ const { cardText } = await import("../src/lib/i18n/settings-cards.ts");
+ expect(cardText("{count} days", "ar", { count: "30" })).toBe("30 يوماً");
+ expect(cardText("{count} hours", "ar", { count: "1" })).toBe("ساعة واحدة");
+ expect(cardText("{count} days", "en", { count: "30" })).toBe("30 days");
+ expect(cardText("{count} days", "zh", { count: "30" })).toBe("30 天");
+});
diff --git a/web/tests/automatic-import-navigation.spec.tsx b/web/tests/automatic-import-navigation.spec.tsx
index 83bc8ab79..315ec7388 100644
--- a/web/tests/automatic-import-navigation.spec.tsx
+++ b/web/tests/automatic-import-navigation.spec.tsx
@@ -98,7 +98,7 @@ it("keeps the backfill model and the automatic-import switch in each host's own
expect(opencode).toContain('aria-label="OpenCode Backfill model"');
expect(opencode).toContain("Save model");
expect(opencode).toContain("Import past chats automatically");
- expect(opencode).toMatch(/type="checkbox"[^>]*checked/);
+ expect(opencode).toMatch(/role="switch"[^>]*aria-checked="true"/);
expect(opencode).toContain("applies to every host");
});
diff --git a/web/tests/capture-language-confirm.spec.tsx b/web/tests/capture-language-confirm.spec.tsx
new file mode 100644
index 000000000..261d15001
--- /dev/null
+++ b/web/tests/capture-language-confirm.spec.tsx
@@ -0,0 +1,169 @@
+import { beforeEach, expect, it, mock } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+// A failed settings reload shows a toast; the real one needs a page.
+mock.module("sonner", () => ({ toast: { warning: () => {}, success: () => {}, error: () => {} } }));
+
+const { CaptureLanguageField, CaptureLanguageSection } =
+ await import("../src/lib/components/settings/CaptureLanguageSection.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Dialog } = await import("../src/lib/components/ui/dialog.tsx");
+const { Select } = await import("../src/lib/components/ui/select.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { SettingsChangeList } =
+ await import("../src/lib/components/settings/SettingsChangeList.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+const { publishSettingsSnapshot } = await import("../src/lib/settings-api.ts");
+
+/** The card on its own: the dialog stays an element to drive through its props. */
+const card = [CaptureLanguageSection, CaptureLanguageField];
+/** The card with its dialog opened up, so its real buttons can be clicked. */
+const shown = [...card, SettingsConfirmDialog, SettingsChangeList];
+const REFUSED = "Config changed. Reload settings and save again.";
+let saved: string;
+let refusal: string | undefined;
+let requests: Request[];
+
+// The file answers every read with what the last save left, as the real one does.
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ saved = request.body.edits.autoCaptureLanguage;
+ }
+ return { body: { revision: "rev-1", settings: { autoCaptureLanguage: { value: saved } } } };
+};
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ saved = "auto";
+ refusal = undefined;
+ requests = installFetch(reply);
+});
+
+const picker = (tree: Node[]) => byType(tree, Select)[0]!;
+const choose = (tree: Node[], code: string) =>
+ (picker(tree).props.onChange as (event: unknown) => void)({ target: { value: code } });
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const saves = () => requests.filter((request) => request.method === "PATCH");
+const shownCard = (own: readonly unknown[]) => settle( , own);
+
+it("asks before it saves a new language, and sends nothing until the user confirms", async () => {
+ let tree = await shownCard(card);
+ expect(picker(tree).props.value).toBe("auto");
+ choose(tree, "fr");
+ tree = await shownCard(card);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Change the summary language?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "autoCaptureLanguage", label: "Summary language", from: "Automatic", to: "Français" },
+ ]);
+ expect(saves()).toHaveLength(0);
+ // The picker shows the picked language while the dialog asks.
+ expect(picker(tree).props.value).toBe("fr");
+});
+
+it("sends nothing on Cancel, and the picker shows the saved language again", async () => {
+ let tree = await shownCard(card);
+ choose(tree, "fr");
+ tree = await shownCard(card);
+ dialogOf(tree)!.props.onClose();
+ tree = await shownCard(card);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(saves()).toHaveLength(0);
+ expect(picker(tree).props.value).toBe("auto");
+ expect(allText(tree)).not.toContain("Saved.");
+});
+
+it("puts the saved language back from the Cancel button, from Escape and from the close button", async () => {
+ let tree = await shownCard(shown);
+ choose(tree, "de");
+ tree = await shownCard(shown);
+ expect(allText(tree)).toContain("Change the summary language?");
+ expect(allText(tree)).toContain("changes to");
+ byText(tree, Button, "Cancel")[0]!.props.onClick();
+ tree = await shownCard(shown);
+ expect(byType(tree, Dialog)).toHaveLength(0);
+ expect(picker(tree).props.value).toBe("auto");
+
+ // Escape and the close button both reach the dialog as a request to close it.
+ choose(tree, "de");
+ tree = await shownCard(shown);
+ byType(tree, Dialog)[0]!.props.onOpenChange(false);
+ tree = await shownCard(shown);
+ expect(byType(tree, Dialog)).toHaveLength(0);
+ expect(picker(tree).props.value).toBe("auto");
+ expect(saves()).toHaveLength(0);
+});
+
+it("sends the same request as before the rule once the user confirms", async () => {
+ let tree = await shownCard(card);
+ choose(tree, "fr");
+ tree = await shownCard(card);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(saves()).toHaveLength(1);
+ expect(saves()[0]!.body).toEqual({
+ edits: { autoCaptureLanguage: "fr" },
+ revision: "rev-1",
+ });
+ // The dialog itself closes once the request succeeds.
+ dialogOf(tree)!.props.onClose();
+ tree = await shownCard(card);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(picker(tree).props.value).toBe("fr");
+ expect(allText(tree)).toContain("Saved. New memories use this language.");
+});
+
+it("shows the saved language again when the file changes after a save", async () => {
+ let tree = await shownCard(card);
+ choose(tree, "fr");
+ tree = await shownCard(card);
+ await dialogOf(tree)!.props.onConfirm();
+ dialogOf(tree)!.props.onClose();
+ await shownCard(card);
+
+ // Another window, or a hand edit, changes the file.
+ publishSettingsSnapshot({
+ revision: "rev-2",
+ settings: { autoCaptureLanguage: { value: "de" } },
+ });
+ tree = await shownCard(card);
+ expect(picker(tree).props.value).toBe("de");
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await shownCard(card);
+ choose(tree, "fr");
+ tree = await shownCard(card);
+ const dialog = dialogOf(tree)!;
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await shownCard(card);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(saves()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await shownCard(card);
+ expect(picker(tree).props.value).toBe("auto");
+});
diff --git a/web/tests/claude-folder-confirm.spec.tsx b/web/tests/claude-folder-confirm.spec.tsx
new file mode 100644
index 000000000..2aa7ac253
--- /dev/null
+++ b/web/tests/claude-folder-confirm.spec.tsx
@@ -0,0 +1,186 @@
+import { beforeEach, expect, it } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { ClaudeFolderSection } =
+ await import("../src/lib/components/settings/ClaudeFolderSection.tsx");
+const { SettingRow } = await import("../src/lib/components/settings/SettingRow.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Input } = await import("../src/lib/components/ui/input.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [ClaudeFolderSection, SettingRow];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+/** The folder saved in the file; every read answers with what the last save left. */
+let folder: string | undefined;
+let refusal: string | undefined;
+let requests: Request[];
+
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ folder = request.body.edits.claudeConfigDir;
+ }
+ return {
+ body: {
+ revision: "r1",
+ settings: { claudeConfigDir: { globalValue: folder } },
+ claudeFolder: { root: folder ?? "/home/me/.claude", source: "default", exists: true },
+ },
+ };
+};
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ folder = undefined;
+ refusal = undefined;
+ requests = installFetch(reply);
+});
+
+const field = (tree: Node[]) => byType(tree, Input)[0]!;
+const buttonOf = (tree: Node[], label: string) =>
+ byText(tree, Button, label).find((node) => !node.props.disabled)!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
+
+it("lists the typed folder and sends nothing until the user confirms", async () => {
+ let tree = await settle( , own);
+ field(tree).props.onChange({ target: { value: "/data/claude" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save the Claude Code folder?");
+ expect(dialog.props.confirmLabel).toBe("Save folder");
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "claudeConfigDir",
+ label: "Claude Code folder",
+ from: "The usual Claude folder",
+ to: "/data/claude",
+ },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("opens the dialog with an empty change list when the folder did not change, and saves only on confirm", async () => {
+ folder = "/data/claude";
+ let tree = await settle( , own);
+ expect(field(tree).props.value).toBe("/data/claude");
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+
+ // Save stays on for an unchanged folder. The dialog opens with nothing to list.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(rowsOf(dialogOf(tree)!)).toEqual([]);
+ expect(patches()).toHaveLength(0);
+
+ await confirm(tree);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ edits: { claudeConfigDir: "/data/claude" },
+ revision: "r1",
+ });
+});
+
+it("sends nothing on Cancel and the typed folder stays in the box", async () => {
+ let tree = await settle( , own);
+ field(tree).props.onChange({ target: { value: "/data/claude" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(allText(tree)).not.toContain("Saved.");
+ // The typed folder stays as a draft, so Save folder can be used again.
+ expect(field(tree).props.value).toBe("/data/claude");
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ revision: "r1",
+ edits: { claudeConfigDir: "/data/claude" },
+ });
+ expect(allText(tree)).toContain("Saved. Capture and import use this folder now.");
+});
+
+it("shows the path rule on the page and opens no dialog", async () => {
+ let tree = await settle( , own);
+ field(tree).props.onChange({ target: { value: "claude" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(allText(tree)).toContain("Enter a full path, or a path that starts with ~/");
+});
+
+it("lists the usual folder when the box is emptied", async () => {
+ folder = "/data/claude";
+ let tree = await settle( , own);
+ field(tree).props.onChange({ target: { value: "" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+
+ expect(rowsOf(dialogOf(tree)!)).toEqual([
+ {
+ key: "claudeConfigDir",
+ label: "Claude Code folder",
+ from: "/data/claude",
+ to: "The usual Claude folder",
+ },
+ ]);
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle( , own);
+ field(tree).props.onChange({ target: { value: "/data/claude" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save folder").props.onClick();
+ tree = await settle( , own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved. Capture and import use this folder now.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+});
diff --git a/web/tests/diagnostics-retention.spec.tsx b/web/tests/diagnostics-retention.spec.tsx
index 47649787e..c2bad7650 100644
--- a/web/tests/diagnostics-retention.spec.tsx
+++ b/web/tests/diagnostics-retention.spec.tsx
@@ -15,6 +15,8 @@ import {
installReact();
const { CaptureControls } = await import("../src/lib/components/settings/CaptureControls.tsx");
+const { DiagnosticsSection } =
+ await import("../src/lib/components/settings/DiagnosticsSection.tsx");
const { SettingsConfirmDialog } =
await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { Button } = await import("../src/lib/components/ui/button.tsx");
@@ -23,6 +25,9 @@ const { Input } = await import("../src/lib/components/ui/input.tsx");
const { setLanguage } = await import("../src/lib/i18n/index.ts");
const own = [CaptureControls];
+/** The diagnostics card with its capture controls expanded. */
+const section = [DiagnosticsSection, CaptureControls];
+const REFUSED = "Config changed. Reload settings and save again.";
const entry = (value: unknown) => ({ value, source: "global", globalValue: value });
const snapshot = (readOnly = false) => ({
@@ -45,7 +50,7 @@ const props = (over: Record = {}) => ({
readQueue: async () => ({ pi: 2, opencode: 1, "claude-code": 0 }),
traces: [{ file: "2026-01-01.jsonl", size: 120 }],
note: "",
- onRetry: () => {},
+ onRetry: async () => ({ success: true }),
onChanged: async () => {
reloaded += 1;
},
@@ -57,6 +62,8 @@ const buttonOf = (tree: Node[], label: string) =>
const field = (tree: Node[], label: string) =>
byType(tree, Input).find((node) => node.props["aria-label"] === label)!;
const dialog = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (node: Node) => node.props.body.props.changes as unknown[];
const patches = () => requests.filter((request) => request.method === "PATCH");
beforeEach(() => {
@@ -73,7 +80,7 @@ beforeEach(() => {
});
});
-it("saves a changed retention with the Save button, not on leaving the field", async () => {
+it("saves a changed retention with the Save button, and only after the user confirms", async () => {
let tree = await settle(view(), own);
field(tree, "Trace retention (days)").props.onChange({ target: { value: "14" } });
field(tree, "Trace retention (days)").props.onBlur?.();
@@ -81,11 +88,62 @@ it("saves a changed retention with the Save button, not on leaving the field", a
expect(patches()).toHaveLength(0);
buttonOf(tree, "Save retention").props.onClick();
tree = await settle(view(), own);
+ const ask = dialog(tree)!;
+ expect(ask.props.title).toBe("Save retention?");
+ expect(ask.props.confirmLabel).toBe("Save retention");
+ expect(rowsOf(ask)).toEqual([
+ {
+ key: "captureTraceRetentionDays",
+ label: "Days to keep traces",
+ from: "30 days",
+ to: "14 days",
+ },
+ ]);
+ expect(patches()).toHaveLength(0);
+ await ask.props.onConfirm();
expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { captureTraceRetentionDays: 14 } });
+ tree = await settle(view(), own);
expect(allText(tree)).toContain("Saved.");
expect(reloaded).toBe(1);
});
+it("sends nothing on Cancel, and the typed numbers stay as a draft", async () => {
+ let tree = await settle(view(), own);
+ field(tree, "Trace retention (days)").props.onChange({ target: { value: "14" } });
+ tree = await settle(view(), own);
+ buttonOf(tree, "Save retention").props.onClick();
+ tree = await settle(view(), own);
+ dialog(tree)!.props.onClose();
+ tree = await settle(view(), own);
+
+ expect(dialog(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(field(tree, "Trace retention (days)").props.value).toBe("14");
+ expect(allText(tree)).not.toContain("Saved.");
+ // Save can be used again, and the confirm sends the same body as before the rule.
+ buttonOf(tree, "Save retention").props.onClick();
+ tree = await settle(view(), own);
+ await dialog(tree)!.props.onConfirm();
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { captureTraceRetentionDays: 14 } });
+});
+
+it("keeps a server refusal inside the retention dialog, which stays open", async () => {
+ requests = installFetch((request) =>
+ request.method === "GET" ? { body: snapshot() } : { status: 409, body: { error: REFUSED } }
+ );
+ let tree = await settle(view(), own);
+ field(tree, "Trace retention (days)").props.onChange({ target: { value: "14" } });
+ tree = await settle(view(), own);
+ buttonOf(tree, "Save retention").props.onClick();
+ tree = await settle(view(), own);
+
+ expect(await dialog(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle(view(), own);
+ expect(dialog(tree)).toBeDefined();
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+});
+
it("shows a message next to an invalid field and keeps Save off", async () => {
let tree = await settle(view(), own);
field(tree, "Trace retention (days)").props.onChange({ target: { value: "0" } });
@@ -156,6 +214,103 @@ it("asks before it turns trace saving on, and saves it only after confirm", asyn
expect(patches()[0]!.body.edits).toEqual({ captureTrace: true });
});
+it("asks before Retry now, and runs it only after the user confirms", async () => {
+ const calls: string[] = [];
+ const over = {
+ onRetry: async (host: string) => {
+ calls.push(host);
+ return { success: true };
+ },
+ };
+ let tree = await settle(view(over), own);
+ buttonOf(tree, "Retry now").props.onClick();
+ tree = await settle(view(over), own);
+
+ const ask = dialog(tree)!;
+ expect(ask.props.title).toBe("Retry waiting turns?");
+ expect(ask.props.confirmLabel).toBe("Retry now");
+ expect(text(ask.props.body)).toBe("The waiting turns will be sent to the model again.");
+ expect(calls).toEqual([]);
+ // Cancel runs nothing.
+ ask.props.onClose();
+ tree = await settle(view(over), own);
+ expect(dialog(tree)).toBeUndefined();
+ expect(calls).toEqual([]);
+ // Confirm runs the retry for the host of the row that was clicked.
+ buttonOf(tree, "Retry now").props.onClick();
+ tree = await settle(view(over), own);
+ expect(await dialog(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(calls).toEqual(["pi"]);
+});
+
+it("keeps a Retry now refusal inside the dialog, which stays open", async () => {
+ const over = { onRetry: async () => ({ success: false, error: REFUSED }) };
+ let tree = await settle(view(over), own);
+ buttonOf(tree, "Retry now").props.onClick();
+ tree = await settle(view(over), own);
+
+ expect(await dialog(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle(view(over), own);
+ expect(dialog(tree)).toBeDefined();
+});
+
+it("sends the retry run request only after confirm, through the diagnostics card", async () => {
+ requests = installFetch((request) => {
+ if (request.path.startsWith("/api/settings/capture-retry/")) {
+ return { body: { result: "started" } };
+ }
+ if (request.path.startsWith("/api/settings/diagnostics")) {
+ return {
+ body: {
+ byModel: [],
+ byReason: [],
+ recent: [],
+ retryQueue: { pi: 2, opencode: 0, "claude-code": 0 },
+ },
+ };
+ }
+ if (request.path.startsWith("/api/settings/traces")) return { body: { traces: [] } };
+ return { body: snapshot() };
+ });
+ let tree = await settle( , section);
+ buttonOf(tree, "Retry now").props.onClick();
+ tree = await settle( , section);
+
+ expect(text(dialog(tree)!.props.body)).toContain("sent to the model again");
+ expect(requests.filter((request) => request.method === "POST")).toHaveLength(0);
+ await dialog(tree)!.props.onConfirm();
+ const post = requests.find((request) => request.method === "POST")!;
+ expect(post.path).toBe("/api/settings/capture-retry/pi/run");
+ expect(post.body).toEqual({});
+});
+
+it("keeps a retry refusal inside the dialog, through the diagnostics card", async () => {
+ requests = installFetch((request) => {
+ if (request.path.startsWith("/api/settings/capture-retry/")) {
+ return { status: 409, body: { error: REFUSED } };
+ }
+ if (request.path.startsWith("/api/settings/diagnostics")) {
+ return {
+ body: {
+ byModel: [],
+ byReason: [],
+ recent: [],
+ retryQueue: { pi: 2, opencode: 0, "claude-code": 0 },
+ },
+ };
+ }
+ if (request.path.startsWith("/api/settings/traces")) return { body: { traces: [] } };
+ return { body: snapshot() };
+ });
+ let tree = await settle( , section);
+ buttonOf(tree, "Retry now").props.onClick();
+ tree = await settle( , section);
+
+ expect(await dialog(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , section);
+ expect(dialog(tree)).toBeDefined();
+});
+
it("keeps Save off while the snapshot is read-only", async () => {
let tree = await settle(view({ snapshot: snapshot(true) }), own);
field(tree, "Trace retention (days)").props.onChange({ target: { value: "14" } });
diff --git a/web/tests/directory-map-review.spec.tsx b/web/tests/directory-map-review.spec.tsx
index 06115bee6..c487d1709 100644
--- a/web/tests/directory-map-review.spec.tsx
+++ b/web/tests/directory-map-review.spec.tsx
@@ -27,6 +27,8 @@ mock.module("react", () => ({
}));
const { DirectoryMapsSection } =
await import("../src/lib/components/settings/DirectoryMapsSection.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { publishSettingsSnapshot } = await import("../src/lib/settings-api.ts");
type Node = ReactElement<{ children?: ReactNode; [key: string]: unknown }>;
type PathMap = { from: string; to: string };
@@ -93,7 +95,7 @@ function walk(value: ReactNode): Node[] {
if (!react.isValidElement(value)) return [];
const node = value as Node;
const name = typeof node.type === "function" ? node.type.name : "";
- if (["DirectoryMapHost", "DirectoryMapReviewDialog"].includes(name)) {
+ if (["DirectoryMapIgnoredList", "DirectoryMapHost", "DirectoryMapReviewDialog"].includes(name)) {
return [node, ...walk((node.type as (props: Node["props"]) => ReactNode)(node.props))];
}
return [node, ...walk(node.props.children)];
@@ -129,6 +131,16 @@ function review() {
return node!;
}
const click = (node: Node) => (node.props.onClick as () => void)();
+/** The shared confirm dialog an Ignore, Restore or Save removals opens. */
+const confirmDialog = () => tree().find((node) => node.type === SettingsConfirmDialog)!;
+/** Confirm it, then close it as the real one does when the request succeeds. */
+async function agree() {
+ const dialog = confirmDialog();
+ const result = await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
+ if (result.success) (dialog.props.onClose as () => void)();
+ await flush();
+ return result;
+}
const flush = async () => {
for (let i = 0; i < 6; i++) await new Promise((resolve) => setTimeout(resolve, 0));
};
@@ -464,43 +476,51 @@ it("starts guesses unticked and saves only the items left ticked", async () => {
expect(host("claude-code").props.rows).toContainEqual(hostRows["claude-code"][0]);
});
-it("ignores a row at once and restores it from Ignored directories", async () => {
+it("ignores a row only once the user confirms, and restores it the same way", async () => {
await mount();
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ expect(patches()).toHaveLength(0);
+ await agree();
expect(patches()[0].body).toEqual({
revision: "rev-1",
edits: { importIgnoredDirectories: ["/missing"] },
});
expect(host("pi").props.rows).not.toContainEqual(hostRows.pi[2]);
click(button("Restore"));
- await flush();
+ expect(patches()).toHaveLength(1);
+ await agree();
expect(patches()[1].body).toEqual({ revision: "rev-2", edits: { importIgnoredDirectories: [] } });
expect(host("pi").props.rows).toContainEqual(hostRows.pi[2]);
expect(patches().every((call) => !call.body!.edits.importPathMaps)).toBe(true);
});
-it("keeps the row after a failed Ignore and does not retry", async () => {
+it("keeps the row and the dialog open after a failed Ignore, and does not retry", async () => {
await mount();
reply = (call) =>
call.method === "PATCH"
? Response.json({ error: "Changed elsewhere" }, { status: 409 })
: defaultReply(call);
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ const result = await agree();
+ expect(result).toEqual({
+ success: false,
+ error: "Settings changed elsewhere. Check the list and try again.",
+ });
+ expect(tree().some((node) => node.type === SettingsConfirmDialog)).toBe(true);
expect(patches()).toHaveLength(1);
expect(host("pi").props.rows).toContainEqual(hostRows.pi[2]);
const status = tree().find((node) => node.props.role === "status");
expect(text(status?.props.children)).toContain("Settings changed elsewhere");
});
-it("saves removals only through Save removals", async () => {
+it("saves removals only through Save removals, after the user confirms", async () => {
await mount();
expect(button("Save removals").props.disabled).toBe(true);
click(button("Remove"));
edit("pi", "/unsaved");
click(button("Save removals"));
- await flush();
+ expect(patches()).toHaveLength(0);
+ await agree();
expect(patches()[0].body!.edits).toEqual({ importPathMaps: [] });
expect(decisions()["/pi-old"]).toEqual({ directory: "/pi-old", target: "/unsaved" });
expect(tree().some((node) => text(node.props.children) === "Save maps")).toBe(false);
@@ -515,7 +535,8 @@ it("restores an ignored directory written in another form in the config file", a
settings: { importIgnoredDirectories: { globalValue: ["/scratch/"] } },
});
click(button("Restore"));
- await flush();
+ expect(patches()).toHaveLength(0);
+ await agree();
expect(patches()[0].body!.edits).toEqual({ importIgnoredDirectories: [] });
});
@@ -532,9 +553,9 @@ it("refreshes the list after a conflicting Ignore, so a retry keeps ignores save
return defaultReply(call);
};
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ await agree();
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ await agree();
expect(patches()).toHaveLength(2);
expect(patches()[1].body).toEqual({
revision: "rev-newer",
@@ -555,10 +576,15 @@ it("blocks Ignore after a conflict until the list is refreshed", async () => {
return defaultReply(call);
};
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ expect(await agree()).toMatchObject({ success: false });
expect(host("pi").props.busy).toBe(true);
+ // The refused save keeps its dialog open with the reason; the user closes it.
+ (confirmDialog().props.onClose as () => void)();
+ await flush();
+ // A list that must be refreshed is a page check: the second Ignore opens no dialog at all.
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
await flush();
+ expect(tree().some((node) => node.type === SettingsConfirmDialog)).toBe(false);
expect(patches()).toHaveLength(1);
offline = false;
reply = defaultReply;
@@ -576,7 +602,8 @@ it("removes a saved map written as ~/x in the config file", async () => {
});
click(button("Remove"));
click(button("Save removals"));
- await flush();
+ expect(patches()).toHaveLength(0);
+ await agree();
expect(patches()[0].body!.edits).toEqual({ importPathMaps: [] });
});
@@ -588,7 +615,7 @@ it("reloads the list when another section saves, so Ignore keeps newer ignores",
publishSettingsSnapshot({ revision: "rev-newer" });
await flush();
(host("pi").props.onIgnore as (row: unknown) => void)(hostRows.pi[2]);
- await flush();
+ await agree();
expect(patches()[0].body).toEqual({
revision: "rev-newer",
edits: { importIgnoredDirectories: ["/elsewhere", "/missing"] },
diff --git a/web/tests/directory-maps-confirm.spec.tsx b/web/tests/directory-maps-confirm.spec.tsx
new file mode 100644
index 000000000..1deebe315
--- /dev/null
+++ b/web/tests/directory-maps-confirm.spec.tsx
@@ -0,0 +1,260 @@
+import { beforeEach, expect, it } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { DirectoryMapsSection } =
+ await import("../src/lib/components/memory/DirectoryMapsSection.tsx");
+const { DirectoryMapIgnoredList } =
+ await import("../src/lib/components/memory/DirectoryMapIgnoredList.tsx");
+const { DirectoryMapHost } = await import("../src/lib/components/settings/DirectoryMapHost.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [DirectoryMapsSection, DirectoryMapIgnoredList, DirectoryMapHost];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+type PathMap = { from: string; to: string };
+const savedMaps: PathMap[] = [
+ { from: "/saved-a", to: "/keep" },
+ { from: "/saved-b", to: "/keep" },
+];
+
+// What the server holds; a real save replaces it, as the refreshed list then shows.
+let serverSaved: PathMap[];
+let serverIgnored: string[];
+let refusal: { status: number; error: string } | undefined;
+let requests: Request[];
+
+const serve = () =>
+ (requests = installFetch((request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: refusal.status, body: { error: refusal.error } };
+ serverSaved = request.body.edits.importPathMaps ?? serverSaved;
+ serverIgnored = request.body.edits.importIgnoredDirectories ?? serverIgnored;
+ return { body: { ok: true } };
+ }
+ if (request.path === "/api/settings") return { body: { revision: "r1", settings: {} } };
+ return {
+ body: {
+ saved: serverSaved,
+ ignored: serverIgnored,
+ pi: [{ directory: "/pi-missing", sessions: 2, suggestion: null }],
+ opencode: [],
+ "claude-code": [],
+ },
+ };
+ }));
+
+const shown = () => settle( , own);
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+const button = (tree: Node[], label: string) => byText(tree, Button, label)[0]!;
+/** The raw page buttons, such as Remove and Keep, are plain elements in the tree. */
+const rawButton = (tree: Node[], label: string) =>
+ byType(tree, "button").find((node) => text(node.props.children).trim() === label)!;
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ serverSaved = [...savedMaps];
+ serverIgnored = ["/old/ignored"];
+ refusal = undefined;
+ serve();
+});
+
+it("asks before Save removals, with how many maps remain, and sends nothing first", async () => {
+ let tree = await shown();
+ rawButton(tree, "Remove").props.onClick();
+ tree = await shown();
+ button(tree, "Save removals").props.onClick();
+ tree = await shown();
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save removals?");
+ expect(dialog.props.confirmLabel).toBe("Save removals");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "importPathMaps", label: "Folder maps", from: "2 maps", to: "1 map" },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("sends nothing on a cancelled Save removals, and keeps the removal as a draft", async () => {
+ let tree = await shown();
+ rawButton(tree, "Remove").props.onClick();
+ tree = await shown();
+ button(tree, "Save removals").props.onClick();
+ tree = await shown();
+ dialogOf(tree)!.props.onClose();
+ tree = await shown();
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ // The struck-through removal stays, so Save removals can be used again.
+ expect(rawButton(tree, "Keep")).toBeDefined();
+
+ button(tree, "Save removals").props.onClick();
+ tree = await shown();
+ const result = await confirm(tree);
+ expect(result).toEqual({ success: true });
+ tree = await shown();
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ revision: "r1",
+ edits: { importPathMaps: [{ from: "/saved-b", to: "/keep" }] },
+ });
+ expect(allText(tree)).toContain(
+ "Saved. Removed maps stop applying at the next import or backfill run."
+ );
+});
+
+it("keeps a conflicting Save removals in the dialog, with the reason on the card", async () => {
+ refusal = { status: 409, error: REFUSED };
+ let tree = await shown();
+ rawButton(tree, "Remove").props.onClick();
+ tree = await shown();
+ button(tree, "Save removals").props.onClick();
+ tree = await shown();
+
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toEqual({
+ success: false,
+ error: "Settings changed elsewhere. Check the list and try again.",
+ });
+ tree = await shown();
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ expect(allText(tree)).not.toContain("Saved. Removed maps");
+});
+
+it("asks before Ignore, naming the folder, and sends the same save on confirm", async () => {
+ let tree = await shown();
+ button(tree, "Ignore").props.onClick();
+ tree = await shown();
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Ignore this folder?");
+ expect(dialog.props.confirmLabel).toBe("Ignore");
+ expect(text(dialog.props.body)).toContain("/pi-missing");
+ expect(text(dialog.props.body)).toContain(
+ "The folder stays unimported and leaves the unresolved counts."
+ );
+ expect(patches()).toHaveLength(0);
+
+ const result = await confirm(tree);
+ expect(result).toEqual({ success: true });
+ tree = await shown();
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ revision: "r1",
+ edits: { importIgnoredDirectories: ["/old/ignored", "/pi-missing"] },
+ });
+ expect(allText(tree)).toContain("Ignored. The directory stays unimported.");
+});
+
+it("sends nothing when the user cancels an Ignore, and the row stays", async () => {
+ let tree = await shown();
+ button(tree, "Ignore").props.onClick();
+ tree = await shown();
+ dialogOf(tree)!.props.onClose();
+ tree = await shown();
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(button(tree, "Ignore")).toBeDefined();
+});
+
+it("keeps a failed Ignore in the dialog, with the card's reason and the server's message", async () => {
+ refusal = { status: 400, error: "Target unavailable" };
+ let tree = await shown();
+ button(tree, "Ignore").props.onClick();
+ tree = await shown();
+
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toEqual({
+ success: false,
+ error: "The directory could not be ignored. Try again. Target unavailable",
+ });
+ tree = await shown();
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ // The row stays unignored, so the user can confirm again.
+ expect(button(tree, "Ignore")).toBeDefined();
+});
+
+it("asks before Restore, naming the folder, which stays ignored until confirmed", async () => {
+ let tree = await shown();
+ button(tree, "Restore").props.onClick();
+ tree = await shown();
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Restore this folder?");
+ expect(dialog.props.confirmLabel).toBe("Restore");
+ expect(text(dialog.props.body)).toContain("/old/ignored");
+ expect(text(dialog.props.body)).toContain(
+ "The folder shows again in each host list that reported it."
+ );
+ expect(patches()).toHaveLength(0);
+ // Still ignored: the list keeps the folder while the dialog asks.
+ expect(button(tree, "Restore")).toBeDefined();
+
+ const result = await confirm(tree);
+ expect(result).toEqual({ success: true });
+ tree = await shown();
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { importIgnoredDirectories: [] } });
+ expect(allText(tree)).toContain(
+ "Restored. The directory shows again in each host list that reported it."
+ );
+});
+
+it("sends nothing when the user cancels a Restore, and the folder stays ignored", async () => {
+ let tree = await shown();
+ button(tree, "Restore").props.onClick();
+ tree = await shown();
+ dialogOf(tree)!.props.onClose();
+ tree = await shown();
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(button(tree, "Restore")).toBeDefined();
+});
+
+it("keeps a conflicting Restore in the dialog, with the reason on the card", async () => {
+ refusal = { status: 409, error: REFUSED };
+ let tree = await shown();
+ button(tree, "Restore").props.onClick();
+ tree = await shown();
+
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toEqual({
+ success: false,
+ error: "Settings changed elsewhere. Check the list and try again.",
+ });
+ tree = await shown();
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ expect(allText(tree)).not.toContain("Restored. The directory shows again");
+});
diff --git a/web/tests/embedding-retry-confirm.spec.tsx b/web/tests/embedding-retry-confirm.spec.tsx
new file mode 100644
index 000000000..4343a4dcc
--- /dev/null
+++ b/web/tests/embedding-retry-confirm.spec.tsx
@@ -0,0 +1,119 @@
+import { beforeEach, expect, it } from "bun:test";
+import {
+ allText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { EmbeddingSection, EmbeddingRunStatus, EmbeddingSummary } =
+ await import("../src/lib/components/settings/EmbeddingSection.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+/** The card on its own: the dialog stays an element to drive through its props. */
+const own = [EmbeddingSection, EmbeddingRunStatus, EmbeddingSummary];
+const REFUSED = "A re-embed is already running";
+
+const current = {
+ kind: "builtin" as const,
+ url: null,
+ model: "Xenova/nomic-embed-text-v1",
+ dimensions: 768,
+ memoryCount: 12,
+ run: { state: "failed" as const, progress: { processed: 3, total: 12 }, error: "503" },
+};
+
+let refusal: string | undefined;
+let requests: Request[];
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ refusal = undefined;
+ requests = installFetch((request) => {
+ if (request.method === "POST" && request.path === "/api/settings/embedding/run") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ // "done" keeps the card from polling a running re-embed inside this spec.
+ return { body: { state: "done", progress: { processed: 12, total: 12 } } };
+ }
+ if (request.path === "/api/settings/embedding") return { body: current };
+ if (request.path === "/api/web/status") return { body: { isLocal: true } };
+ return { body: { revision: "r1", secrets: {} } };
+ });
+});
+
+const card = () => settle( , own);
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+const buttonOf = (tree: Node[], label: string) =>
+ byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
+const runs = () => requests.filter((request) => request.path === "/api/settings/embedding/run");
+
+it("asks before it retries a failed re-embed, and sends nothing until the user confirms", async () => {
+ let tree = await card();
+ expect(allText(tree)).toContain("Re-embed failed");
+ buttonOf(tree, "Retry").props.onClick();
+ tree = await card();
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Retry the re-embed?");
+ expect(dialog.props.confirmLabel).toBe("Retry");
+ expect(dialog.props.busyLabel).toBe("Re-embedding…");
+ expect(text(dialog.props.body)).toBe(
+ "The re-embed will run again and send every stored memory to the embedding model."
+ );
+ expect(runs()).toHaveLength(0);
+});
+
+it("sends nothing on Cancel, and the failure stays on the card", async () => {
+ let tree = await card();
+ buttonOf(tree, "Retry").props.onClick();
+ tree = await card();
+ dialogOf(tree)!.props.onClose();
+ tree = await card();
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(runs()).toHaveLength(0);
+ expect(allText(tree)).not.toContain("Re-embed finished.");
+});
+
+it("sends the same request as before the rule once the user confirms", async () => {
+ let tree = await card();
+ buttonOf(tree, "Retry").props.onClick();
+ tree = await card();
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(runs()).toHaveLength(1);
+ expect(runs()[0]!.method).toBe("POST");
+ expect(runs()[0]!.body).toEqual({});
+ // The dialog itself closes once the request succeeds.
+ dialogOf(tree)!.props.onClose();
+ tree = await card();
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(allText(tree)).toContain("Re-embed finished.");
+});
+
+it("keeps a server refusal inside the dialog, which stays open", async () => {
+ refusal = REFUSED;
+ let tree = await card();
+ buttonOf(tree, "Retry").props.onClick();
+ tree = await card();
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({
+ success: false,
+ error: REFUSED,
+ });
+ tree = await card();
+ expect(dialogOf(tree)).toBeDefined();
+ expect(runs()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+});
diff --git a/web/tests/external-api-section.spec.tsx b/web/tests/external-api-section.spec.tsx
index 3e70b7076..3b6ab5bb3 100644
--- a/web/tests/external-api-section.spec.tsx
+++ b/web/tests/external-api-section.spec.tsx
@@ -23,6 +23,8 @@ const { ReasoningLevel } = await import("../src/lib/components/settings/Reasonin
const { KeySourceField } = await import("../src/lib/components/settings/KeySourceField.tsx");
const { SettingsConfirmDialog } =
await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { SettingsChangeList } =
+ await import("../src/lib/components/settings/SettingsChangeList.tsx");
const { Button } = await import("../src/lib/components/ui/button.tsx");
const { Select } = await import("../src/lib/components/ui/select.tsx");
const { setLanguage } = await import("../src/lib/i18n/index.ts");
@@ -60,6 +62,24 @@ const inputByHolder = (tree: Node[], holder: string) =>
const type = (node: Node, value: string) => node.props.onChange({ target: { value } });
const keyField = (tree: Node[]) => byType(tree, KeySourceField)[0]!;
const post = (path: string) => requests.find((request) => request.path === path);
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+const bodyChildren = (dialog: Node) =>
+ ([dialog.props.body.props.children].flat() as Node[]).filter(Boolean);
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) =>
+ (
+ bodyChildren(dialog).find((node) => node.type === SettingsChangeList)!.props as {
+ changes: unknown[];
+ }
+ ).changes;
+const leadOf = (dialog: Node) => text(bodyChildren(dialog).find((node) => node.type === "p"));
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
beforeEach(() => {
resetRender();
@@ -153,16 +173,51 @@ const tests = () =>
requests.filter((request) => request.path === "/api/settings/external-api/test");
const patched = () => requests.some((request) => request.method === "PATCH");
-it("Save tests the form values first and saves after the test passes, with one test call", async () => {
+it("Save tests the form values first, then confirms, and saves only after the user confirms", async () => {
let tree = await settle( , own);
type(inputByHolder(tree, "glm-5-turbo"), "glm-6");
tree = await settle( , own);
buttonOf(tree, "Save settings").props.onClick();
- await settle( , own);
+ tree = await settle( , own);
expect(tests()).toHaveLength(1);
expect(tests()[0]!.body.model).toBe("glm-6");
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save external API settings?");
+ expect(dialog.props.confirmLabel).toBe("Save settings");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "memoryModel", label: "Model name", from: "glm-5-turbo", to: "glm-6" },
+ ]);
+ expect(patched()).toBe(false);
+
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(patched()).toBe(true);
const patch = requests.find((request) => request.method === "PATCH")!;
expect(requests.indexOf(tests()[0]!)).toBeLessThan(requests.indexOf(patch));
+ expect(patch.body).toEqual({ revision: "rev-1", edits: { memoryModel: "glm-6" } });
+ expect(allText(tree)).toContain("Saved. New capture and profile work uses these settings.");
+});
+
+it("sends nothing on Cancel, and the typed model stays as a draft", async () => {
+ let tree = await settle( , own);
+ type(inputByHolder(tree, "glm-5-turbo"), "glm-6");
+ tree = await settle( , own);
+ buttonOf(tree, "Save settings").props.onClick();
+ tree = await settle( , own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patched()).toBe(false);
+ expect(allText(tree)).not.toContain("Saved. New capture and profile work uses these settings.");
+ // The typed model stays, so Save can be used again.
+ expect(inputByHolder(tree, "glm-5-turbo").props.value).toBe("glm-6");
+ buttonOf(tree, "Save settings").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ await settle( , own);
+ expect(patched()).toBe(true);
});
it("Save never saves a key the provider refuses (401 or 403)", async () => {
@@ -197,6 +252,10 @@ it("Save asks before it saves when the provider cannot be reached, and Cancel sa
tree = await settle( , own);
const dialog = byType(tree, SettingsConfirmDialog)[0]!;
expect(dialog.props.confirmLabel).toBe("Save anyway");
+ // The Save-anyway dialog is the confirmation for this click, so it also lists the changes.
+ expect(rowsOf(dialog)).toEqual([
+ { key: "memoryModel", label: "Model name", from: "glm-5-turbo", to: "glm-6" },
+ ]);
expect(patched()).toBe(false);
dialog.props.onClose();
tree = await settle( , own);
@@ -218,16 +277,54 @@ it("Save anyway saves without a second test call", async () => {
expect(tests()).toHaveLength(1);
});
-it("clears the URL: an emptied field saves null so the key is removed", async () => {
+it("clears the URL: a confirm dialog says the external API turns off, then saves null", async () => {
let tree = await settle( , own);
type(inputByHolder(tree, "https://api.example.com/v1"), "");
tree = await settle( , own);
buttonOf(tree, "Save settings").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save external API settings?");
+ expect(leadOf(dialog)).toBe("The external API will be turned off.");
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "memoryApiUrl",
+ label: "Model service address",
+ from: "https://api.example.com/v1",
+ to: "Default (Not set)",
+ },
+ ]);
+ // An emptied address turns the external API off: there is nothing to test, and nothing is sent.
+ expect(post("/api/settings/external-api/test")).toBeUndefined();
+ expect(patched()).toBe(false);
+
+ await confirm(tree);
await settle( , own);
const patch = requests.find((request) => request.method === "PATCH")!;
expect(patch.body).toEqual({ revision: "rev-1", edits: { memoryApiUrl: null } });
- // An emptied address turns the external API off: there is nothing to test.
+});
+
+it("clears the model: the same turn-off confirm, and nothing is sent before the user confirms", async () => {
+ let tree = await settle( , own);
+ type(inputByHolder(tree, "glm-5-turbo"), "");
+ tree = await settle( , own);
+ buttonOf(tree, "Save settings").props.onClick();
+ tree = await settle( , own);
+ const dialog = dialogOf(tree)!;
+ expect(leadOf(dialog)).toBe("The external API will be turned off.");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "memoryModel", label: "Model name", from: "glm-5-turbo", to: "Default (Not set)" },
+ ]);
expect(post("/api/settings/external-api/test")).toBeUndefined();
+ expect(patched()).toBe(false);
+
+ await confirm(tree);
+ await settle( , own);
+ expect(requests.find((request) => request.method === "PATCH")!.body).toEqual({
+ revision: "rev-1",
+ edits: { memoryModel: null },
+ });
});
it("refuses a URL without http:// or https:// and says why next to the field", async () => {
@@ -256,6 +353,16 @@ it("saves a pasted key as a private file with the setting name and the fresh rev
tree = await settle( , own);
buttonOf(tree, "Save settings").props.onClick();
tree = await settle( , own);
+ // The dialog names the key source, never the key itself.
+ const dialog = dialogOf(tree)!;
+ expect(rowsOf(dialog)).toEqual([
+ { key: "memoryModel", label: "Model name", from: "glm-5-turbo", to: "glm-6" },
+ { key: "memoryApiKey", label: "Model service key", from: "Not set", to: "key file zai" },
+ ]);
+ expect(JSON.stringify(rowsOf(dialog))).not.toContain("sk-secret-123");
+ expect(patched()).toBe(false);
+ await confirm(tree);
+ tree = await settle( , own);
expect(post("/api/settings/external-api/key")!.body).toMatchObject({
setting: "memoryApiKey",
source: "paste",
@@ -289,7 +396,7 @@ it("checks the key before any request: a bad variable name saves nothing", async
expect(allText(tree)).toContain("Enter a variable name such as ZAI_API_KEY");
});
-it("saves nothing when the server refuses the key, and translates the reason", async () => {
+it("saves nothing when the server refuses the key, and the dialog stays open with the reason", async () => {
keyReply = { status: 400, body: { error: "Enter the path of a key file" } };
setLanguage("zh");
let tree = await settle( , own);
@@ -300,7 +407,12 @@ it("saves nothing when the server refuses the key, and translates the reason", a
tree = await settle( , own);
buttonOf(tree, "保存设置").props.onClick();
tree = await settle( , own);
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result.success).toBe(false);
expect(requests.some((request) => request.method === "PATCH")).toBe(false);
+ // The reason stays inside the dialog; the card shows it in the page's language.
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
expect(allText(tree)).not.toContain("Enter the path of a key file");
});
@@ -312,6 +424,8 @@ it("clears every key field after a save, so Save turns off", async () => {
tree = await settle( , own);
buttonOf(tree, "Save settings").props.onClick();
tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
expect(keyField(tree).props.input).toEqual({ name: "", path: "", value: "" });
expect(buttonOf(tree, "Save settings").props.disabled).toBe(true);
});
@@ -325,18 +439,49 @@ it("asks in a dialog before it replaces a key file, and replaces only after conf
tree = await settle( , own);
buttonOf(tree, "Save settings").props.onClick();
tree = await settle( , own);
- const dialog = byType(tree, SettingsConfirmDialog)[0]!;
- expect(dialog).toBeDefined();
- const first = requests.filter((request) => request.path === "/api/settings/external-api/key");
- expect(first).toHaveLength(1);
+ // The save confirms first; the key file question replaces the open dialog, with no second one.
+ const saveDialog = dialogOf(tree)!;
+ expect(saveDialog.props.confirmLabel).toBe("Save settings");
+ expect(
+ requests.filter((request) => request.path === "/api/settings/external-api/key")
+ ).toHaveLength(0);
+ await saveDialog.props.onConfirm();
+ tree = await settle( , own);
+ expect(
+ requests.filter((request) => request.path === "/api/settings/external-api/key")
+ ).toHaveLength(1);
+ const replaceDialog = dialogOf(tree)!;
+ expect(replaceDialog.props.confirmLabel).toBe("Replace");
+ expect(replaceDialog.props.title).toBe("Replace the key file?");
+ expect(byType(tree, SettingsConfirmDialog)).toHaveLength(1);
keyReply = { body: { revision: "rev-3" } };
- const result = await dialog.props.onConfirm();
+ const result = await replaceDialog.props.onConfirm();
expect(result.success).toBe(true);
const all = requests.filter((request) => request.path === "/api/settings/external-api/key");
expect(all).toHaveLength(2);
expect(all[1]!.body.replace).toBe(true);
});
+it("keeps a refused save inside the dialog, which stays open until the user decides", async () => {
+ const REFUSED = "Config changed. Reload settings and save again.";
+ requests = installFetch((request) => {
+ if (request.path === "/api/settings/external-api/test") return testReply;
+ if (request.method === "PATCH") return { status: 409, body: { error: REFUSED } };
+ return { body: snapshot() };
+ });
+ let tree = await settle( , own);
+ type(inputByHolder(tree, "glm-5-turbo"), "glm-6");
+ tree = await settle( , own);
+ buttonOf(tree, "Save settings").props.onClick();
+ tree = await settle( , own);
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved. New capture and profile work uses these settings.");
+});
+
it("uses no raw button and no window.confirm", () => {
const source = readFileSync(
new URL("../src/lib/components/settings/ExternalApiSection.tsx", import.meta.url),
diff --git a/web/tests/host-settings-confirm.spec.tsx b/web/tests/host-settings-confirm.spec.tsx
new file mode 100644
index 000000000..cbddbdfe6
--- /dev/null
+++ b/web/tests/host-settings-confirm.spec.tsx
@@ -0,0 +1,219 @@
+import { beforeEach, expect, it, mock } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installReact,
+ resetRender,
+ settle,
+ type Node,
+} from "./space-kit.tsx";
+
+installReact();
+// A failed settings reload shows a toast; the real one needs a page.
+mock.module("sonner", () => ({ toast: { warning: () => {}, success: () => {}, error: () => {} } }));
+
+const { HostSettings } = await import("../src/lib/components/memory/HostSettings.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Switch } = await import("../src/lib/components/ui/switch.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+/** The card on its own: the dialog stays an element to drive through its props. */
+const own = [HostSettings];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+// The file the fake hook saves to, as the real one does through the snapshot.
+let file: Record;
+let saves: Record[];
+let messages: string[];
+let refusal: string | undefined;
+
+const backfill = () =>
+ ({
+ snapshot: { revision: "rev-1", settings: file, secrets: { memoryApiKey: { set: true } } },
+ lists: {
+ pi: { available: true, models: [{ provider: "zai", model: "glm-5-turbo", name: "GLM" }] },
+ },
+ message: "",
+ busy: false,
+ save: async (edits: Record) => {
+ saves.push(edits);
+ if (refusal) return { success: false, error: refusal };
+ for (const [key, value] of Object.entries(edits)) {
+ if (value === null) delete file[key];
+ else file[key] = { globalValue: value };
+ }
+ return { success: true };
+ },
+ saveModel: () => {},
+ setMessage: (message: string) => void messages.push(message),
+ }) as never;
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ // A complete external API, so the External API model choice is available.
+ file = {
+ autoBackfill: { globalValue: true },
+ memoryProvider: { globalValue: "openai" },
+ memoryModel: { globalValue: "deepseek/deepseek-chat" },
+ memoryApiUrl: { globalValue: "https://api.example.com/v1" },
+ };
+ saves = [];
+ messages = [];
+ refusal = undefined;
+});
+
+const el = () => ;
+const checkbox = (tree: Node[]) => byType(tree, Switch)[0]!;
+const modelSelect = (tree: Node[]) =>
+ tree.find((node) => node.props["aria-label"] === "Pi Backfill model")!;
+const saveModel = (tree: Node[]) => byText(tree, Button, "Save model")[0]!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+
+it("asks before it saves a backfill model, and sends nothing until the user confirms", async () => {
+ let tree = await settle(el(), own);
+ modelSelect(tree).props.onChange({ target: { value: "zai/glm-5-turbo" } });
+ tree = await settle(el(), own);
+ saveModel(tree).props.onClick();
+ tree = await settle(el(), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save the backfill model?");
+ expect(dialog.props.confirmLabel).toBe("Save model");
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "piBackfillModel",
+ label: "Backfill model",
+ from: "Same as live capture",
+ to: "zai/glm-5-turbo",
+ },
+ ]);
+ expect(saves).toHaveLength(0);
+});
+
+it("keeps the picked model as a draft when the model save is cancelled", async () => {
+ let tree = await settle(el(), own);
+ modelSelect(tree).props.onChange({ target: { value: "zai/glm-5-turbo" } });
+ tree = await settle(el(), own);
+ saveModel(tree).props.onClick();
+ tree = await settle(el(), own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(saves).toHaveLength(0);
+ expect(modelSelect(tree).props.value).toBe("zai/glm-5-turbo");
+});
+
+it("sends the same model save as before the rule once the user confirms", async () => {
+ let tree = await settle(el(), own);
+ modelSelect(tree).props.onChange({ target: { value: "external" } });
+ tree = await settle(el(), own);
+ saveModel(tree).props.onClick();
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(saves).toEqual([{ piBackfillModel: "external" }]);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(modelSelect(tree).props.value).toBe("external");
+});
+
+it("keeps a refused model save inside the dialog, which stays open", async () => {
+ refusal = REFUSED;
+ let tree = await settle(el(), own);
+ modelSelect(tree).props.onChange({ target: { value: "zai/glm-5-turbo" } });
+ tree = await settle(el(), own);
+ saveModel(tree).props.onClick();
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(saves).toHaveLength(1);
+});
+
+it("refuses an empty manual model on the page, and opens no dialog", async () => {
+ let tree = await settle(el(), own);
+ modelSelect(tree).props.onChange({ target: { value: "typed" } });
+ tree = await settle(el(), own);
+ saveModel(tree).props.onClick();
+ tree = await settle(el(), own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(saves).toHaveLength(0);
+ expect(messages).toContain("Enter a model as provider/model.");
+});
+
+it("asks before it turns automatic import off, and Cancel leaves the box ticked", async () => {
+ let tree = await settle(el(), own);
+ expect(checkbox(tree).props.checked).toBe(true);
+ checkbox(tree).props.onCheckedChange(false);
+ tree = await settle(el(), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Turn automatic import off?");
+ expect(dialog.props.confirmLabel).toBe("Turn off");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "autoBackfill", label: "Import past chats automatically", from: "On", to: "Off" },
+ ]);
+ // The box shows the cleared state while the dialog asks, and nothing is saved yet.
+ expect(checkbox(tree).props.checked).toBe(false);
+ expect(saves).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(saves).toHaveLength(0);
+ expect(checkbox(tree).props.checked).toBe(true);
+});
+
+it("sends the same autoBackfill false as before the rule once the user confirms", async () => {
+ let tree = await settle(el(), own);
+ checkbox(tree).props.onCheckedChange(false);
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(saves).toEqual([{ autoBackfill: false }]);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(checkbox(tree).props.checked).toBe(false);
+});
+
+it("shows the file's value again after a save when the file changes", async () => {
+ let tree = await settle(el(), own);
+ checkbox(tree).props.onCheckedChange(false);
+ tree = await settle(el(), own);
+ await dialogOf(tree)!.props.onConfirm();
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(checkbox(tree).props.checked).toBe(false);
+
+ // Another window, or a hand edit, turns automatic import back on.
+ file.autoBackfill = { globalValue: true };
+ tree = await settle(el(), own);
+ expect(checkbox(tree).props.checked).toBe(true);
+});
+
+it("keeps a refused turn-off inside the dialog, and Cancel then re-ticks the box", async () => {
+ refusal = REFUSED;
+ let tree = await settle(el(), own);
+ checkbox(tree).props.onCheckedChange(false);
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(saves).toHaveLength(1);
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(checkbox(tree).props.checked).toBe(true);
+ expect(allText(tree)).not.toContain("Saved.");
+});
diff --git a/web/tests/host-status-confirm.spec.tsx b/web/tests/host-status-confirm.spec.tsx
new file mode 100644
index 000000000..4471aa966
--- /dev/null
+++ b/web/tests/host-status-confirm.spec.tsx
@@ -0,0 +1,173 @@
+import { beforeEach, expect, it } from "bun:test";
+import type { ImportRunView } from "../src/lib/auto-import-settings";
+import { hostStatus, type HostStatusInput } from "../src/lib/components/memory/host-status";
+import {
+ allText,
+ byText,
+ byType,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+} from "./space-kit.tsx";
+
+installReact();
+const { HostStatusHeader } = await import("../src/lib/components/memory/HostStatusHeader.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [HostStatusHeader];
+const REFUSED = "Another import is already running.";
+
+/** The runs that give the header its Pause, Resume and Retry actions. A running run that is
+ * paused is still pausing; a paused run that has stopped offers Resume. */
+const pausedRun = { state: "stopped", paused: true, total: 0, done: 0 } as ImportRunView;
+const failedRun = { state: "failed", error: "model refused", total: 0, done: 0 } as ImportRunView;
+
+type Call = { host: string; action: string };
+let controls: Call[];
+let models: Call[];
+let refusal: string | undefined;
+
+function statuses(run: ImportRunView, blocked: string | null = null) {
+ const input = (host: "pi"): HostStatusInput => ({
+ host,
+ run,
+ pending: 5,
+ cutoff: null,
+ runNowUnavailable: blocked,
+ setUp: true,
+ autoImport: true,
+ formatDate: String,
+ lastSaved: null,
+ formatSaved: String,
+ });
+ return {
+ backfill: {
+ snapshot: undefined,
+ rows: { pi: null, opencode: null, "claude-code": null },
+ runs: undefined,
+ lists: {},
+ message: "",
+ busy: false,
+ save: async () => ({ success: true }),
+ control: async (host: string, action: string) => {
+ controls.push({ host, action });
+ return refusal ? { success: false, error: refusal } : { success: true };
+ },
+ saveModel: async (host: string, choice: string) => {
+ models.push({ host, action: choice });
+ return refusal ? { success: false, error: refusal } : { success: true };
+ },
+ setMessage: () => {},
+ },
+ readiness: null,
+ input,
+ status: () => hostStatus(input("pi")),
+ line: () => ({ text: "" }),
+ } as never;
+}
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ controls = [];
+ models = [];
+ refusal = undefined;
+});
+
+const el = (run: ImportRunView, blocked: string | null = null) => (
+
+);
+const action = (tree: Node[], label: string) => byText(tree, Button, label).at(-1)!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+
+it("asks before it pauses, and Pause controls nothing until the user confirms", async () => {
+ let tree = await settle(el(null), own);
+ action(tree, "Pause").props.onClick();
+ tree = await settle(el(null), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Pause automatic import?");
+ expect(dialog.props.confirmLabel).toBe("Pause");
+ expect(text(dialog.props.body)).toContain("stops after the current exchange");
+ expect(controls).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle(el(null), own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(controls).toHaveLength(0);
+});
+
+it("pauses through the confirmed request once the user confirms", async () => {
+ let tree = await settle(el(null), own);
+ action(tree, "Pause").props.onClick();
+ tree = await settle(el(null), own);
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(controls).toEqual([{ host: "pi", action: "pause" }]);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(null), own);
+ expect(dialogOf(tree)).toBeUndefined();
+});
+
+it("asks before it resumes a paused import, and says it makes model calls", async () => {
+ let tree = await settle(el(pausedRun), own);
+ action(tree, "Resume").props.onClick();
+ tree = await settle(el(pausedRun), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Resume automatic import?");
+ expect(dialog.props.confirmLabel).toBe("Resume");
+ expect(text(dialog.props.body)).toContain("makes model calls");
+ expect(controls).toHaveLength(0);
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: true });
+ expect(controls).toEqual([{ host: "pi", action: "resume" }]);
+});
+
+it("asks before it retries a failed import, and says the retry calls the model again", async () => {
+ let tree = await settle(el(failedRun), own);
+ action(tree, "Retry").props.onClick();
+ tree = await settle(el(failedRun), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Retry the import?");
+ expect(dialog.props.confirmLabel).toBe("Retry");
+ expect(text(dialog.props.body)).toContain("calls the model again");
+ expect(controls).toHaveLength(0);
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: true });
+ expect(controls).toEqual([{ host: "pi", action: "run" }]);
+});
+
+it("asks before it switches a blocked host to the external API model", async () => {
+ const blocked = "Pi needs an open host or an external backfill model.";
+ let tree = await settle(el(pausedRun, blocked), own);
+ action(tree, "Use external API").props.onClick();
+ tree = await settle(el(pausedRun, blocked), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Use the external API?");
+ expect(dialog.props.confirmLabel).toBe("Use external API");
+ expect(text(dialog.props.body)).toContain("Pi will use the external API model");
+ expect(models).toHaveLength(0);
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: true });
+ expect(models).toEqual([{ host: "pi", action: "external" }]);
+});
+
+it("keeps a refused action inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle(el(failedRun), own);
+ action(tree, "Retry").props.onClick();
+ tree = await settle(el(failedRun), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await settle(el(failedRun), own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(controls).toEqual([{ host: "pi", action: "run" }]);
+ expect(allText(tree)).not.toContain("Backfill started.");
+});
diff --git a/web/tests/host-status-header.spec.tsx b/web/tests/host-status-header.spec.tsx
index 92d3b7884..5ab6809af 100644
--- a/web/tests/host-status-header.spec.tsx
+++ b/web/tests/host-status-header.spec.tsx
@@ -12,6 +12,12 @@ mock.module("react", () => ({
useMemo: (factory: () => unknown) => factory(),
useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(),
useEffect: () => undefined,
+ // The confirm dialog hook keeps its pending request in state; no dialog is open here.
+ useState: (initial: unknown) => [
+ typeof initial === "function" ? (initial as () => unknown)() : initial,
+ () => {},
+ ],
+ useRef: (initial: unknown) => ({ current: initial }),
}));
const { HostStatusHeader } = await import("../src/lib/components/memory/HostStatusHeader");
const { TurnOnAction } = await import("../src/lib/components/memory/TurnOnAction");
diff --git a/web/tests/ignore-all.spec.tsx b/web/tests/ignore-all.spec.tsx
index 56c6afd97..8d42ca6e2 100644
--- a/web/tests/ignore-all.spec.tsx
+++ b/web/tests/ignore-all.spec.tsx
@@ -74,6 +74,8 @@ const { DirectoryMapsSection } =
await import("../src/lib/components/memory/DirectoryMapsSection.tsx");
const { DirectoryMapHost } = await import("../src/lib/components/settings/DirectoryMapHost.tsx");
const { IgnoreAllDialog } = await import("../src/lib/components/settings/IgnoreAllDialog.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
type Node = ReactElement<{ children?: ReactNode; [key: string]: any }>;
function nodes(node: ReactNode): Node[] {
@@ -92,6 +94,14 @@ async function settle() {
}
const host = (tree: Node[]) => tree.find((node) => node.type === DirectoryMapHost)!;
const dialog = (tree: Node[]) => tree.find((node) => node.type === IgnoreAllDialog);
+/** The shared confirm dialog a single Ignore opens; confirm it as the user would. */
+async function agree() {
+ const confirm = render().find((node) => node.type === SettingsConfirmDialog)!;
+ const result = await (confirm.props.onConfirm as () => Promise<{ success: boolean }>)();
+ if (result.success) (confirm.props.onClose as () => void)();
+ await settle();
+ return result;
+}
async function open() {
render();
@@ -180,7 +190,7 @@ it("drops a single ignored directory from the list once saved", async () => {
const tree = render();
const row = host(tree).props.rows[0];
host(tree).props.onIgnore(row);
- await settle();
+ expect(await agree()).toEqual({ success: true });
await settle();
expect(rowPaths(render())).not.toContain(row.directory);
});
@@ -193,7 +203,7 @@ it("keeps the dialog open and says why when the save fails", async () => {
await settle();
const after = render();
expect(dialog(after)).toBeDefined();
- expect(texts(after)).toContain("The directories could not be ignored. Try again.");
+ expect(texts(after)).toContain("The directories could not be ignored. Try again. stale");
});
it("says so, and keeps the dialog open, when the list is not ready to save", async () => {
diff --git a/web/tests/keys-access-revoke.spec.tsx b/web/tests/keys-access-revoke.spec.tsx
index 07c0f510b..213b92a38 100644
--- a/web/tests/keys-access-revoke.spec.tsx
+++ b/web/tests/keys-access-revoke.spec.tsx
@@ -1,5 +1,6 @@
import { beforeEach, expect, it } from "bun:test";
import {
+ allText,
byType,
installFetch,
installReact,
@@ -12,27 +13,49 @@ import {
installReact();
-const { KeysAccessSection } = await import("../src/lib/components/settings/KeysAccessSection.tsx");
+const { KeysAccessSection, PasswordFields } =
+ await import("../src/lib/components/settings/KeysAccessSection.tsx");
const { ApiTokensTable } = await import("../src/lib/components/settings/ApiTokensTable.tsx");
const { SettingsConfirmDialog } =
await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Input } = await import("../src/lib/components/ui/input.tsx");
const { setLanguage } = await import("../src/lib/i18n/index.ts");
-const own = [KeysAccessSection, ApiTokensTable];
+const own = [KeysAccessSection, ApiTokensTable, PasswordFields];
const token = { id: "t1", name: "ci", createdAt: 0, expiresAt: null, lastUsedAt: null };
+const REFUSED = "The web app could not write the password file.";
+let refusal: string | undefined;
let requests: Request[] = [];
beforeEach(() => {
resetRender();
setLanguage("en");
+ refusal = undefined;
requests = installFetch((request) => {
+ if (refusal && request.method === "POST" && request.path === "/api/settings/web-password")
+ return { status: 409, body: { error: refusal } };
if (request.path === "/api/web/status") return { body: { isLocal: true } };
- if (request.path === "/api/settings/tokens" && request.method === "GET") {
+ if (request.path === "/api/settings/tokens") {
+ if (request.method === "POST") return { body: { value: "omms_new" } };
return { body: { tokens: [token] } };
}
if (request.path === "/api/settings") {
- return { body: { revision: "r1", secrets: {}, effective: {}, access: undefined } };
+ return {
+ body: {
+ revision: "r1",
+ secrets: {},
+ effective: {},
+ access: {
+ host: "127.0.0.1",
+ authEnabled: true,
+ tokenAvailable: true,
+ embeddingApiUrl: null,
+ authUsername: "me",
+ configTokenIgnored: false,
+ },
+ },
+ };
}
return { body: { ok: true } };
});
@@ -40,7 +63,23 @@ beforeEach(() => {
const button = (tree: Node[], label: string) =>
byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
+const inputOf = (tree: Node[], id: string) =>
+ byType(tree, Input).find((node) => node.props.id === id)!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
const deletes = () => requests.filter((request) => request.method === "DELETE");
+const passwordPosts = () =>
+ requests.filter((request) => request.path === "/api/settings/web-password");
+const tokenPosts = () =>
+ requests.filter(
+ (request) => request.path === "/api/settings/tokens" && request.method === "POST"
+ );
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
it("revokes a token only after the dialog is confirmed", async () => {
let tree = await settle( , own);
@@ -60,3 +99,121 @@ it("revokes a token only after the dialog is confirmed", async () => {
expect(result.success).toBe(true);
expect(deletes().map((request) => request.path)).toEqual(["/api/settings/tokens/t1"]);
});
+
+it("asks before the password is saved, shows no secret, and keeps it on Cancel", async () => {
+ let tree = await settle( , own);
+ inputOf(tree, "web-password-user").props.onChange({ target: { value: "me" } });
+ tree = await settle( , own);
+ inputOf(tree, "web-password-value").props.onChange({ target: { value: "hunter2" } });
+ tree = await settle( , own);
+ button(tree, "Save password").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save the browser password?");
+ expect(dialog.props.confirmLabel).toBe("Save password");
+ expect(dialog.props.destructive).toBeFalsy();
+ // One sentence, and never the password itself.
+ expect(text(dialog.props.body)).toBe(
+ "The password is stored in a private file on this computer. The web app asks for it after it restarts."
+ );
+ expect(allText(tree)).not.toContain("hunter2");
+ expect(passwordPosts()).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(passwordPosts()).toHaveLength(0);
+ // The typed password stays as a draft, so Save password can be used again.
+ expect(inputOf(tree, "web-password-value").props.value).toBe("hunter2");
+ button(tree, "Save password").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(passwordPosts()).toHaveLength(1);
+ expect(passwordPosts()[0]!.body).toEqual({
+ password: "hunter2",
+ username: "me",
+ revision: "r1",
+ });
+ // The password leaves the page as soon as it is saved.
+ expect(inputOf(tree, "web-password-value").props.value).toBe("");
+ expect(allText(tree)).toContain("Saved. Restart the web app to use the new browser password.");
+});
+
+it("asks before the password is cleared, and confirm sends the same body", async () => {
+ let tree = await settle( , own);
+ button(tree, "Clear password").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Clear the browser password?");
+ expect(dialog.props.confirmLabel).toBe("Clear password");
+ expect(dialog.props.destructive).toBe(true);
+ expect(text(dialog.props.body)).toBe(
+ "The browser password is removed. The web app stops asking for it after it restarts."
+ );
+ expect(passwordPosts()).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(passwordPosts()).toHaveLength(0);
+
+ button(tree, "Clear password").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(passwordPosts()).toHaveLength(1);
+ expect(passwordPosts()[0]!.body).toEqual({ clear: true, revision: "r1" });
+ expect(allText(tree)).toContain("Browser password cleared. Restart the web app to turn it off.");
+});
+
+it("asks before a token is generated, and confirm sends the same body", async () => {
+ let tree = await settle( , own);
+ inputOf(tree, "api-token-name").props.onChange({ target: { value: "ci" } });
+ tree = await settle( , own);
+ button(tree, "Generate token").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Generate a token?");
+ expect(dialog.props.confirmLabel).toBe("Generate token");
+ expect(text(dialog.props.body)).toBe(
+ "OMMS creates a token that lets scripts and other computers call this web app's API."
+ );
+ expect(tokenPosts()).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(tokenPosts()).toHaveLength(0);
+
+ button(tree, "Generate token").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(tokenPosts()).toHaveLength(1);
+ expect(tokenPosts()[0]!.body).toEqual({ name: "ci", expiresInDays: 30 });
+ // The new value is shown once, with its copy warning.
+ expect(allText(tree)).toContain("omms_new");
+ expect(allText(tree)).toContain("Copy this token now. It will not be shown again.");
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle( , own);
+ inputOf(tree, "web-password-value").props.onChange({ target: { value: "hunter2" } });
+ tree = await settle( , own);
+ button(tree, "Save password").props.onClick();
+ tree = await settle( , own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(passwordPosts()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+});
diff --git a/web/tests/keyword-mode-section.spec.tsx b/web/tests/keyword-mode-section.spec.tsx
index 09e57768f..370a31d3f 100644
--- a/web/tests/keyword-mode-section.spec.tsx
+++ b/web/tests/keyword-mode-section.spec.tsx
@@ -1,4 +1,4 @@
-import { beforeEach, expect, it, mock } from "bun:test";
+import { afterEach, beforeEach, expect, it, mock } from "bun:test";
import { renderToStaticMarkup } from "react-dom/server";
import type { ReactElement, ReactNode } from "react";
import * as react from "react";
@@ -30,6 +30,8 @@ mock.module("react", () => ({
const { KeywordModeSection } = await import("../src/lib/components/memory/KeywordModeSection.tsx");
const { Select } = await import("../src/lib/components/ui/select.tsx");
const { SettingRow } = await import("../src/lib/components/settings/SettingRow.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { PLAIN_TEXT } = await import("../src/lib/settings-catalogue.ts");
const { Button } = await import("../src/lib/components/ui/button.tsx");
@@ -48,7 +50,42 @@ function snapshotFixture(overrides: Record = {}) {
};
}
-beforeEach(() => setLanguage("en"));
+beforeEach(() => {
+ setLanguage("en");
+ Object.assign(globalThis, { window: { __OMMS_TOKEN__: "page-token" } });
+});
+
+type Call = { url: string; init?: RequestInit };
+const realFetch = globalThis.fetch;
+let calls: Call[] = [];
+function stubFetch(reply: (call: Call) => unknown) {
+ calls = [];
+ globalThis.fetch = (async (url: string, init?: RequestInit) => {
+ const call = { url: String(url), init };
+ calls.push(call);
+ return reply(call);
+ }) as unknown as typeof fetch;
+}
+afterEach(() => {
+ globalThis.fetch = realFetch;
+});
+/** The Save button submits the form, so the form's onSubmit is the click. */
+const submitForm = (nodes: Node[]) =>
+ (
+ nodes.find((node) => node.type === "form")!.props.onSubmit as (event: {
+ preventDefault: () => void;
+ }) => void
+ )({ preventDefault: () => {} });
+/** A fresh render of the card, with the shared hook cursor reset as `tree` does. */
+const shown = (): Node[] => {
+ cursor = 0;
+ return find(KeywordModeSection(), () => true);
+};
+const dialogOf = (nodes: Node[]) => nodes.find((node) => node.type === SettingsConfirmDialog)!;
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const flush = async () => {
+ for (let i = 0; i < 4; i++) await new Promise((resolve) => setTimeout(resolve, 0));
+};
const html = (mode = "boost", overrides: Record = {}, busy = false) => {
states = [snapshotFixture(overrides), mode, busy, undefined];
@@ -136,3 +173,91 @@ it("has a Chinese and an Arabic text for every message the card shows", () => {
expect(translateSettings(message, "ar")).not.toBe(message);
}
});
+
+it("asks before it saves the mode, and sends nothing until the user confirms", () => {
+ stubFetch((call) =>
+ call.init?.method === "PATCH"
+ ? { ok: true, json: async () => ({}) }
+ : { ok: true, json: async () => snapshotFixture() }
+ );
+ submitForm(tree("rrf"));
+ const dialog = dialogOf(shown());
+ expect(dialog.props.title).toBe("Save keyword matching?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "keywordMode",
+ label: "How word matches join the results",
+ from: PLAIN_TEXT.keywordBoost,
+ to: PLAIN_TEXT.keywordMerge,
+ },
+ ]);
+ expect(calls.filter((call) => call.init?.method === "PATCH")).toHaveLength(0);
+});
+
+it("lists the mode names in the language of the page", () => {
+ stubFetch(() => {
+ throw new Error("no request expected");
+ });
+ setLanguage("ar");
+ submitForm(tree("rrf"));
+ const [row] = rowsOf(dialogOf(shown())) as { from: string; to: string }[];
+ // The dropdown shows these names translated, so the dialog must too.
+ expect(row!.from).not.toBe(PLAIN_TEXT.keywordBoost);
+ expect(row!.to).not.toBe(PLAIN_TEXT.keywordMerge);
+ expect(row!.from).toMatch(/[-ۿ]/);
+ expect(row!.to).toMatch(/[-ۿ]/);
+});
+
+it("sends nothing on Cancel, and the chosen mode stays", () => {
+ stubFetch(() => {
+ throw new Error("no request expected");
+ });
+ submitForm(tree("rrf"));
+ (dialogOf(shown()).props.onClose as () => void)();
+ expect(calls).toHaveLength(0);
+ expect(states[1]).toBe("rrf");
+ expect(shown().filter((node) => node.type === Select)[0]!.props.value).toBe("rrf");
+});
+
+it("sends the same request as before the rule once the user confirms", async () => {
+ stubFetch((call) =>
+ call.init?.method === "PATCH"
+ ? { ok: true, json: async () => ({}) }
+ : { ok: true, json: async () => snapshotFixture() }
+ );
+ submitForm(tree("rrf"));
+ const dialog = dialogOf(shown());
+ const result = await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
+ expect(result).toEqual({ success: true });
+ const patch = calls.find((call) => call.init?.method === "PATCH")!;
+ expect(patch.url).toBe("/api/settings");
+ expect(JSON.parse(String(patch.init!.body))).toEqual({
+ edits: { keywordMode: "rrf" },
+ revision: "rev-1",
+ });
+});
+
+it("keeps a server refusal inside the dialog, which stays open", async () => {
+ stubFetch((call) =>
+ call.init?.method === "PATCH"
+ ? {
+ ok: false,
+ status: 409,
+ json: async () => ({ error: "Config changed. Reload settings and save again." }),
+ }
+ : { ok: true, json: async () => snapshotFixture() }
+ );
+ submitForm(tree("rrf"));
+ const dialog = dialogOf(shown());
+ const result = await (
+ dialog.props.onConfirm as () => Promise<{ success: boolean; error?: string }>
+ )();
+ expect(result).toMatchObject({
+ success: false,
+ error: "Config changed. Reload settings and save again.",
+ });
+ expect(dialogOf(shown())).toBeDefined();
+ await flush();
+ expect(states[1]).toBe("rrf");
+});
diff --git a/web/tests/memory-basics-section.spec.tsx b/web/tests/memory-basics-section.spec.tsx
index 7bc9909e7..416906897 100644
--- a/web/tests/memory-basics-section.spec.tsx
+++ b/web/tests/memory-basics-section.spec.tsx
@@ -19,9 +19,12 @@ const { SettingRow } = await import("../src/lib/components/settings/SettingRow.t
const { Button } = await import("../src/lib/components/ui/button.tsx");
const { Checkbox } = await import("../src/lib/components/ui/checkbox.tsx");
const { Select } = await import("../src/lib/components/ui/select.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { setLanguage } = await import("../src/lib/i18n/index.ts");
const own = [MemoryBasicsSection, SettingRow];
+const REFUSED = "Config changed. Reload settings and save again.";
const entry = (value: unknown, source = "global") => ({
value,
@@ -56,6 +59,17 @@ const buttonOf = (tree: Node[], label: string) =>
byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
const checkbox = (tree: Node[], key: string) =>
byType(tree, Checkbox).find((node) => node.props.id === `basics-${key}`)!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
beforeEach(() => {
resetRender();
@@ -70,6 +84,8 @@ it("saves chatMessage.enabled false and nothing else", async () => {
tree = await settle( , own);
buttonOf(tree, "Save").props.onClick();
tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
const patch = requests.find((request) => request.method === "PATCH")!;
expect(patch.body).toEqual({ revision: "r1", edits: { "chatMessage.enabled": false } });
expect(allText(tree)).toContain("Saved.");
@@ -80,11 +96,58 @@ it("saves the default memory scope as all-projects", async () => {
byType(tree, Select)[0]!.props.onChange({ target: { value: "all-projects" } });
tree = await settle( , own);
buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
await settle( , own);
const patch = requests.find((request) => request.method === "PATCH")!;
expect(patch.body.edits).toEqual({ "memory.defaultScope": "all-projects" });
});
+it("lists each changed setting and sends nothing until the user confirms", async () => {
+ let tree = await settle( , own);
+ checkbox(tree, "autoCaptureEnabled").props.onCheckedChange(false);
+ byType(tree, Select)[0]!.props.onChange({ target: { value: "all-projects" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save memory basics?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "autoCaptureEnabled", label: "Save memories automatically", from: "On", to: "Off" },
+ {
+ key: "memory.defaultScope",
+ label: "Where a search looks",
+ from: "This project",
+ to: "All projects",
+ },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("sends nothing on Cancel and keeps the choices as a draft", async () => {
+ let tree = await settle( , own);
+ checkbox(tree, "autoCaptureEnabled").props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(allText(tree)).not.toContain("Saved.");
+ // The typed choices stay, so Save can be used again.
+ expect(checkbox(tree, "autoCaptureEnabled").props.checked).toBe(false);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ await settle( , own);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { autoCaptureEnabled: false } });
+});
+
it("says when this project's file decides a switch", async () => {
current = snapshot({ autoCaptureEnabled: { ...entry(false, "project"), globalValue: true } });
const tree = await settle( , own);
@@ -106,14 +169,22 @@ it("keeps Save off with no change and while the snapshot is read-only", async ()
it("shows the server's reason when a save fails", async () => {
requests = installFetch((request) =>
- request.method === "GET"
- ? { body: current }
- : { status: 409, body: { error: "Config changed. Reload settings and save again." } }
+ request.method === "GET" ? { body: current } : { status: 409, body: { error: REFUSED } }
);
let tree = await settle( , own);
checkbox(tree, "injectProfile").props.onCheckedChange(false);
tree = await settle( , own);
buttonOf(tree, "Save").props.onClick();
tree = await settle( , own);
- expect(allText(tree)).toContain("Config changed. Reload settings and save again.");
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
});
diff --git a/web/tests/memory-cleanup-section.spec.tsx b/web/tests/memory-cleanup-section.spec.tsx
index 719a230e8..72f81564e 100644
--- a/web/tests/memory-cleanup-section.spec.tsx
+++ b/web/tests/memory-cleanup-section.spec.tsx
@@ -55,6 +55,8 @@ const buttonOf = (tree: Node[], label: string) =>
byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
const patches = () => requests.filter((request) => request.method === "PATCH");
const dialog = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (node: Node) => node.props.body.props.changes as unknown[];
async function turnOn(days?: string) {
let tree = await settle( , own);
@@ -164,18 +166,63 @@ it("refuses to save on when the count is not a number", async () => {
expect(dialog(tree)!.props.blocked).toBeTruthy();
});
-it("turning it off needs no dialog", async () => {
+it("asks before it turns deletion off, although turning it off deletes nothing", async () => {
current = snapshot(true);
let tree = await settle( , own);
byType(tree, Checkbox)[0]!.props.onCheckedChange(false);
tree = await settle( , own);
buttonOf(tree, "Save").props.onClick();
tree = await settle( , own);
- expect(dialog(tree)).toBeUndefined();
+ const ask = dialog(tree)!;
+ expect(ask.props.title).toBe("Turn off memory cleanup?");
+ expect(ask.props.confirmLabel).toBe("Save");
+ expect(rowsOf(ask)).toEqual([
+ {
+ key: "autoDeleteOldMemories",
+ label: "Delete old memories automatically",
+ from: "On",
+ to: "Off",
+ },
+ ]);
+ // No count is needed, and nothing is sent before the user confirms.
expect(requests.some((item) => item.path.includes("preview"))).toBe(false);
+ expect(patches()).toHaveLength(0);
+ // Cancel saves nothing and puts the switch back on.
+ ask.props.onClose();
+ tree = await settle( , own);
+ expect(dialog(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(byType(tree, Checkbox)[0]!.props.checked).toBe(true);
+ // The same body as before the rule once the user confirms.
+ byType(tree, Checkbox)[0]!.props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ await dialog(tree)!.props.onConfirm();
expect(patches()[0]!.body.edits).toEqual({ autoDeleteOldMemories: false });
});
+it("keeps a server refusal inside the turn-off dialog, which stays open", async () => {
+ const REFUSED = "Config changed. Reload settings and save again.";
+ current = snapshot(true);
+ requests = installFetch((request) => {
+ if (request.method === "GET") return { body: current };
+ return { status: 409, body: { error: REFUSED } };
+ });
+ let tree = await settle( , own);
+ byType(tree, Checkbox)[0]!.props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+
+ const result = await dialog(tree)!.props.onConfirm();
+ expect(result).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialog(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ expect(allText(tree)).not.toContain("Saved.");
+});
+
it("asks again when the days go down while deletion is on", async () => {
current = snapshot(true, 30);
let tree = await settle( , own);
@@ -185,7 +232,7 @@ it("asks again when the days go down while deletion is on", async () => {
tree = await settle( , own);
expect(dialog(tree)).toBeDefined();
expect(requests.find((item) => item.path.includes("preview"))!.path).toContain("days=7");
- // More days is safe: it saves with no dialog.
+ // More days reaches fewer memories: it asks with the change list, not the count.
resetRender();
requests.length = 0;
tree = await settle( , own);
@@ -193,10 +240,44 @@ it("asks again when the days go down while deletion is on", async () => {
tree = await settle( , own);
buttonOf(tree, "Save").props.onClick();
tree = await settle( , own);
- expect(dialog(tree)).toBeUndefined();
+ const raise = dialog(tree)!;
+ expect(raise.props.title).toBe("Save memory cleanup?");
+ expect(rowsOf(raise)).toEqual([
+ {
+ key: "autoCleanupRetentionDays",
+ label: "Days before a memory is old",
+ from: "30 days",
+ to: "60 days",
+ },
+ ]);
+ expect(requests.some((item) => item.path.includes("preview"))).toBe(false);
+ expect(patches()).toHaveLength(0);
+ await raise.props.onConfirm();
expect(patches()[0]!.body.edits).toEqual({ autoCleanupRetentionDays: 60 });
});
+it("asks with the save title when only the days change while deletion is off", async () => {
+ let tree = await settle( , own);
+ byType(tree, Input)[0]!.props.onChange({ target: { value: "60" } });
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+
+ // Nothing turns off here, so the title must not say so.
+ const ask = dialog(tree)!;
+ expect(ask.props.title).toBe("Save memory cleanup?");
+ expect(rowsOf(ask)).toEqual([
+ {
+ key: "autoCleanupRetentionDays",
+ label: "Days before a memory is old",
+ from: "30 days",
+ to: "60 days",
+ },
+ ]);
+ expect(requests.some((item) => item.path.includes("preview"))).toBe(false);
+ expect(patches()).toHaveLength(0);
+});
+
it("shows a message next to the days field for an invalid number", async () => {
let tree = await settle( , own);
byType(tree, Input)[0]!.props.onChange({ target: { value: "0" } });
diff --git a/web/tests/memory-injection-confirm.spec.tsx b/web/tests/memory-injection-confirm.spec.tsx
new file mode 100644
index 000000000..564e1b786
--- /dev/null
+++ b/web/tests/memory-injection-confirm.spec.tsx
@@ -0,0 +1,231 @@
+import { beforeEach, expect, it, mock } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+// A failed settings reload shows a toast; the real one needs a page.
+mock.module("sonner", () => ({ toast: { warning: () => {}, success: () => {}, error: () => {} } }));
+
+const { MemoryInjectionSection } =
+ await import("../src/lib/components/memory/MemoryInjectionSection.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+/** The card on its own: the dialog stays an element to drive through its props. */
+const own = [MemoryInjectionSection];
+const DEFAULT_QUERY = "project architecture, setup, conventions and key decisions";
+const REFUSED = "Config changed. Reload settings and save again.";
+
+// The file answers every read with what the last save left, as the real one does.
+let saved: Record;
+let refusal: string | undefined;
+let requests: Request[];
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ for (const [key, value] of Object.entries(request.body.edits as Record)) {
+ if (value === null) delete saved[key];
+ else saved[key] = value;
+ }
+ }
+ return {
+ body: {
+ revision: "rev-1",
+ settings: Object.fromEntries(
+ Object.entries(saved).map(([key, value]) => [key, { globalValue: value }])
+ ),
+ },
+ };
+};
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ // A custom file, so both a save and a reset to default have keys to change.
+ saved = {
+ openingContext: true,
+ openingContextQuery: "release notes",
+ subagentMemory: false,
+ "compaction.enabled": false,
+ "compaction.memoryLimit": 25,
+ };
+ refusal = undefined;
+ requests = installFetch(reply);
+});
+
+const el = () => ;
+const opening = (tree: Node[]) => tree.find((node) => node.props.id === "injection-opening")!;
+const query = (tree: Node[]) => tree.find((node) => node.props.id === "injection-query")!;
+const limit = (tree: Node[]) => tree.find((node) => node.props.id === "injection-limit")!;
+const save = (tree: Node[]) => byText(tree, Button, "Save")[0]!;
+/** Save is the form's submit button: submit the form, as the browser does on a click. */
+const submit = (tree: Node[]) =>
+ tree.find((node) => node.type === "form")!.props.onSubmit({ preventDefault: () => {} });
+const reset = (tree: Node[]) => byText(tree, Button, "Reset to default")[0]!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+
+it("asks before it saves, listing each setting with its old and new value", async () => {
+ let tree = await settle(el(), own);
+ opening(tree).props.onCheckedChange(false);
+ query(tree).props.onChange({ target: { value: "setup guide" } });
+ limit(tree).props.onChange({ target: { value: "20" } });
+ tree = await settle(el(), own);
+ submit(tree);
+ tree = await settle(el(), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save memory injection?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(rowsOf(dialog)).toEqual([
+ // Off is the default, so the save removes the key and the row says so.
+ {
+ key: "openingContext",
+ label: "Add memories to the first message",
+ from: "On",
+ to: "Default (Off)",
+ },
+ {
+ key: "openingContextQuery",
+ label: "Opening search text",
+ from: "release notes",
+ to: "setup guide",
+ },
+ {
+ key: "compaction.memoryLimit",
+ label: "Memories added back after a summary",
+ from: "25",
+ to: "20",
+ },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("keeps what the user typed as a draft when the save is cancelled", async () => {
+ let tree = await settle(el(), own);
+ opening(tree).props.onCheckedChange(false);
+ query(tree).props.onChange({ target: { value: "setup guide" } });
+ tree = await settle(el(), own);
+ submit(tree);
+ tree = await settle(el(), own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(opening(tree).props.checked).toBe(false);
+ expect(query(tree).props.value).toBe("setup guide");
+});
+
+it("sends the same request as before the rule once the user confirms", async () => {
+ let tree = await settle(el(), own);
+ opening(tree).props.onCheckedChange(false);
+ query(tree).props.onChange({ target: { value: "setup guide" } });
+ limit(tree).props.onChange({ target: { value: "20" } });
+ tree = await settle(el(), own);
+ submit(tree);
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: true });
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ // Returning to a default removes the key, exactly as before the rule.
+ edits: {
+ openingContext: null,
+ openingContextQuery: "setup guide",
+ "compaction.memoryLimit": 20,
+ },
+ revision: "rev-1",
+ });
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(allText(tree)).toContain("Saved. The next session uses these options.");
+});
+
+it("opens no dialog for Reset to default, and the Save after it lists the removed keys", async () => {
+ let tree = await settle(el(), own);
+ reset(tree).props.onClick();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+
+ submit(tree);
+ tree = await settle(el(), own);
+ const dialog = dialogOf(tree)!;
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "openingContext",
+ label: "Add memories to the first message",
+ from: "On",
+ to: "Default (Off)",
+ },
+ {
+ key: "openingContextQuery",
+ label: "Opening search text",
+ from: "release notes",
+ to: `Default (${DEFAULT_QUERY})`,
+ },
+ { key: "subagentMemory", label: "Give subagents memories", from: "Off", to: "Default (On)" },
+ {
+ key: "compaction.enabled",
+ label: "Add memories back after a summary",
+ from: "Off",
+ to: "Default (On)",
+ },
+ {
+ key: "compaction.memoryLimit",
+ label: "Memories added back after a summary",
+ from: "25",
+ to: "Default (10)",
+ },
+ ]);
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: true });
+ expect(patches()[0]!.body.edits).toEqual({
+ openingContext: null,
+ openingContextQuery: null,
+ subagentMemory: null,
+ "compaction.enabled": null,
+ "compaction.memoryLimit": null,
+ });
+});
+
+it("keeps a server refusal inside the dialog, which stays open", async () => {
+ refusal = REFUSED;
+ let tree = await settle(el(), own);
+ query(tree).props.onChange({ target: { value: "setup guide" } });
+ tree = await settle(el(), own);
+ submit(tree);
+ tree = await settle(el(), own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ // The draft stays, so the user can save again.
+ expect(query(tree).props.value).toBe("setup guide");
+});
+
+it("shows the page's own message for an invalid limit, and opens no dialog", async () => {
+ let tree = await settle(el(), own);
+ limit(tree).props.onChange({ target: { value: "0" } });
+ tree = await settle(el(), own);
+
+ expect(save(tree).props.disabled).toBe(true);
+ expect(allText(tree)).toContain("Enter a positive whole number.");
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+});
diff --git a/web/tests/memory-limits-plain.spec.tsx b/web/tests/memory-limits-plain.spec.tsx
index 79020b1db..260f013f8 100644
--- a/web/tests/memory-limits-plain.spec.tsx
+++ b/web/tests/memory-limits-plain.spec.tsx
@@ -19,6 +19,8 @@ const { MemoryInjectionSection } =
await import("../src/lib/components/memory/MemoryInjectionSection.tsx");
const { AutoCleanupSettings } =
await import("../src/lib/components/memory/AutoCleanupSettings.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { SettingRow } = await import("../src/lib/components/settings/SettingRow.tsx");
const { Select } = await import("../src/lib/components/ui/select.tsx");
const { setLanguage } = await import("../src/lib/i18n/index.ts");
@@ -199,12 +201,128 @@ it("keeps the profile tidy switch in the form until one Save", async () => {
expect(toggle(tree).props.checked).toBe(false);
const save = byType(tree, Button).find((node) => text(node.props.children).trim() === "Save")!;
save.props.onClick();
+ tree = await settle( , own);
+ const dialog = byType(tree, SettingsConfirmDialog)[0]!;
+ await dialog.props.onConfirm();
+ dialog.props.onClose();
await settle( , own);
const patches = requests.filter((request) => request.method === "PATCH");
expect(patches).toHaveLength(1);
expect(patches[0]!.body.edits).toEqual({ userProfileAutoCleanupEnabled: false });
});
+it("asks before it saves the profile tidy settings, and sends nothing until the user confirms", async () => {
+ const requests = installFetch((request) =>
+ request.method === "GET"
+ ? {
+ body: snapshot({
+ userProfileAutoCleanupEnabled: { value: true, globalValue: true },
+ userProfileAutoCleanupInterval: { value: 500, globalValue: 500 },
+ }),
+ }
+ : { body: { ok: true } }
+ );
+ let tree = await settle( , own);
+ const { Button } = await import("../src/lib/components/ui/button.tsx");
+ const toggle = (nodes: Node[]) => nodes.find((node) => node.props.id === "auto-cleanup-enabled")!;
+ const field = (nodes: Node[]) => nodes.find((node) => node.props.id === "auto-cleanup-interval")!;
+ toggle(tree).props.onCheckedChange(false);
+ field(tree).props.onChange({ target: { value: "300" } });
+ tree = await settle( , own);
+ byType(tree, Button)
+ .find((node) => text(node.props.children).trim() === "Save")!
+ .props.onClick();
+ tree = await settle( , own);
+
+ const dialog = byType(tree, SettingsConfirmDialog)[0]!;
+ expect(dialog.props.title).toBe("Save automatic profile cleanup?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(dialog.props.body.props.changes).toEqual([
+ {
+ key: "userProfileAutoCleanupEnabled",
+ label: "Tidy the profile automatically",
+ from: "On",
+ to: "Off",
+ },
+ {
+ key: "userProfileAutoCleanupInterval",
+ label: "Profile tidy interval",
+ from: "500 prompts",
+ to: "300 prompts",
+ },
+ ]);
+ expect(requests.filter((request) => request.method === "PATCH")).toHaveLength(0);
+ // Cancel keeps what the user chose as a draft, and sends nothing.
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(byType(tree, SettingsConfirmDialog)).toHaveLength(0);
+ expect(requests.filter((request) => request.method === "PATCH")).toHaveLength(0);
+ expect(toggle(tree).props.checked).toBe(false);
+ expect(field(tree).props.value).toBe("300");
+});
+
+it("sends the same tidy request as before the rule once the user confirms", async () => {
+ const requests = installFetch((request) =>
+ request.method === "GET"
+ ? {
+ body: snapshot({
+ userProfileAutoCleanupEnabled: { value: true, globalValue: true },
+ userProfileAutoCleanupInterval: { value: 500, globalValue: 500 },
+ }),
+ }
+ : { body: { ok: true } }
+ );
+ let tree = await settle( , own);
+ const { Button } = await import("../src/lib/components/ui/button.tsx");
+ const field = (nodes: Node[]) => nodes.find((node) => node.props.id === "auto-cleanup-interval")!;
+ field(tree).props.onChange({ target: { value: "300" } });
+ tree = await settle( , own);
+ byType(tree, Button)
+ .find((node) => text(node.props.children).trim() === "Save")!
+ .props.onClick();
+ tree = await settle( , own);
+ const dialog = byType(tree, SettingsConfirmDialog)[0]!;
+ expect(await dialog.props.onConfirm()).toEqual({ success: true });
+ dialog.props.onClose();
+ await settle( , own);
+ const patches = requests.filter((request) => request.method === "PATCH");
+ expect(patches).toHaveLength(1);
+ expect(patches[0]!.body).toEqual({
+ edits: { userProfileAutoCleanupInterval: 300 },
+ revision: "rev-1",
+ });
+});
+
+it("keeps a tidy-save refusal inside the dialog, which stays open", async () => {
+ const REFUSED = "Config changed. Reload settings and save again.";
+ installFetch((request) =>
+ request.method === "GET"
+ ? {
+ body: snapshot({
+ userProfileAutoCleanupEnabled: { value: true, globalValue: true },
+ userProfileAutoCleanupInterval: { value: 500, globalValue: 500 },
+ }),
+ }
+ : { status: 409, body: { error: REFUSED } }
+ );
+ let tree = await settle( , own);
+ const { Button } = await import("../src/lib/components/ui/button.tsx");
+ const toggle = (nodes: Node[]) => nodes.find((node) => node.props.id === "auto-cleanup-enabled")!;
+ toggle(tree).props.onCheckedChange(false);
+ tree = await settle( , own);
+ byType(tree, Button)
+ .find((node) => text(node.props.children).trim() === "Save")!
+ .props.onClick();
+ tree = await settle( , own);
+ const dialog = byType(tree, SettingsConfirmDialog)[0]!;
+ expect(await dialog.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(byType(tree, SettingsConfirmDialog)).toHaveLength(1);
+ expect(allText(tree)).toContain(REFUSED);
+ // The draft stays, so the user can save again.
+ expect(toggle(tree).props.checked).toBe(false);
+});
+
it("lets search open every Memory and Memorisation page anchor", () => {
const asked: string[] = [];
Object.assign(globalThis, {
diff --git a/web/tests/memory-profile-actions.spec.tsx b/web/tests/memory-profile-actions.spec.tsx
index e9b3dacad..153d98fc8 100644
--- a/web/tests/memory-profile-actions.spec.tsx
+++ b/web/tests/memory-profile-actions.spec.tsx
@@ -11,6 +11,8 @@ mock.module("react", () => ({
useContext: () => null,
useMemo: (factory: () => unknown) => factory(),
useSyncExternalStore: (_s: unknown, snapshot: () => unknown) => snapshot(),
+ // The confirm hook keeps its outcome in a ref; the specs drive it outside a renderer.
+ useRef: (initialValue: unknown) => ({ current: initialValue }),
useEffect: (effect: () => unknown) => effects.push(effect),
useState: (initial: unknown) => {
const index = cursor++;
@@ -50,6 +52,8 @@ Object.assign(globalThis, {
});
const { ProfileCatchUpSection, CatchUpStatus } =
await import("../src/lib/components/memory/ProfileCatchUpSection.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
type Node = ReactElement<{ children?: ReactNode; [key: string]: any }>;
function nodes(node: ReactNode): Node[] {
if (!react.isValidElement(node)) return Array.isArray(node) ? node.flatMap(nodes) : [];
@@ -78,6 +82,16 @@ async function mount() {
}
const button = (name: string) =>
render().find((node) => node.type === "button" && text(node) === name)!;
+/** The shared confirm dialog a settings action opens, as an element to drive through its props. */
+const dialogOf = () => render().find((node) => node.type === SettingsConfirmDialog);
+/** Starts a run through the start action's own window.confirm, so Pause shows. */
+async function running() {
+ await mount();
+ confirmed = true;
+ button("Analyse waiting prompts").props.onClick();
+ await settle();
+}
+const pauses = () => requests.filter((request) => request.path.endsWith("/pause"));
beforeEach(() => {
states = [];
effects = [];
@@ -120,3 +134,57 @@ it("translates both actions and keeps the waiting prompt state on language chang
expect(render().map(text).join(" ")).toContain("2600");
}
});
+it("asks before it pauses the catch-up run, and sends nothing until the user confirms", async () => {
+ await running();
+ button("Pause").props.onClick();
+ await settle();
+ const dialog = dialogOf()!;
+ expect(dialog.props.title).toBe("Pause the catch-up run?");
+ expect(dialog.props.confirmLabel).toBe("Pause");
+ expect(text(dialog.props.body)).toContain("no model calls run until you resume it");
+ expect(pauses()).toHaveLength(0);
+ dialog.props.onClose();
+ await settle();
+ expect(pauses()).toHaveLength(0);
+ expect(dialogOf()).toBeUndefined();
+});
+it("pauses the run after the user confirms", async () => {
+ await running();
+ button("Pause").props.onClick();
+ await settle();
+ const result = await dialogOf()!.props.onConfirm();
+ expect(result).toEqual({ success: true });
+ await settle();
+ expect(pauses()).toHaveLength(1);
+});
+it("keeps a pause refusal inside the dialog, which stays open", async () => {
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = (async (path: string, options: RequestInit = {}) => {
+ requests.push({ path, method: options.method ?? "GET" });
+ if (String(path).endsWith("/pause"))
+ return new Response(JSON.stringify({ error: "No catch-up run is active" }), { status: 409 });
+ const value =
+ path === "/api/web/status"
+ ? { isLocal: true }
+ : path === "/api/settings/profile/catch-up"
+ ? {
+ preview: { waiting: 2600, calls: 52 },
+ job: { state: "idle", batchesBuilt: 0, remaining: 2600 },
+ }
+ : { state: "running", batchesBuilt: 0, remaining: 2600 };
+ return new Response(JSON.stringify(value));
+ }) as unknown as typeof fetch;
+ try {
+ await running();
+ button("Pause").props.onClick();
+ await settle();
+ const dialog = dialogOf()!;
+ const result = await dialog.props.onConfirm();
+ expect(result).toEqual({ success: false, error: "No catch-up run is active" });
+ await settle();
+ expect(dialogOf()).toBeDefined();
+ expect(render().map(text).join(" ")).toContain("No catch-up run is active");
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+});
diff --git a/web/tests/memory-section.spec.tsx b/web/tests/memory-section.spec.tsx
index 5b9dec237..15a51001c 100644
--- a/web/tests/memory-section.spec.tsx
+++ b/web/tests/memory-section.spec.tsx
@@ -35,6 +35,8 @@ mock.module("react", () => ({
},
}));
const { MemorySection } = await import("../src/lib/components/memory/MemorySection.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
const { Button } = await import("../src/lib/components/ui/button.tsx");
const { Input } = await import("../src/lib/components/ui/input.tsx");
const { findCatalogueEntry, PLAIN_TEXT } = await import("../src/lib/settings-catalogue.ts");
@@ -111,6 +113,15 @@ const button = (label: string, nodes: Node[]) =>
)!;
const input = (nodes: Node[], id: string) =>
nodes.find((node) => node.type === Input && node.props.id === id)!;
+/** A fresh render of the card, with the shared hook cursor reset as `tree` does. */
+const shown = (): Node[] => {
+ cursor = 0;
+ return find(MemorySection(), () => true);
+};
+/** The card's confirm dialog, once a save or reset has asked for one. */
+const dialogOf = (nodes: Node[]) => nodes.find((node) => node.type === SettingsConfirmDialog)!;
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => calls.filter((call) => call.init?.method === "PATCH");
type Call = { url: string; init?: RequestInit };
const realFetch = globalThis.fetch;
@@ -412,6 +423,91 @@ it("shows the Differs from default marker only on rows whose saved value differs
expect(renderToStaticMarkup( )).not.toContain("Differs from default");
});
+it("asks before it saves the limits, and sends nothing until the user confirms", async () => {
+ stubFetch((call) =>
+ call.url === "/api/settings" && call.init?.method === "PATCH"
+ ? Response.json({}, { status: 200 })
+ : Response.json(snapshotFixture())
+ );
+ const nodes = tree({ maxMemories: "2", retrievalMaxTokens: "3000" });
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ expect(dialog.props.title).toBe("Save memory limits?");
+ expect(dialog.props.confirmLabel).toBe("Save memory limits");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "maxMemories", label: "Memories per search", from: "10", to: "2" },
+ { key: "retrievalMaxTokens", label: "Memory text per prompt", from: "2,000", to: "3,000" },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("sends nothing on Cancel, and the drafts stay in the inputs", () => {
+ stubFetch(() => {
+ throw new Error("no request expected");
+ });
+ const nodes = tree({ maxMemories: "2" });
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ (dialog.props.onClose as () => void)();
+ expect(calls).toEqual([]);
+ expect(states[1]).toEqual({ maxMemories: "2" });
+ const after = shown();
+ expect(input(after, "memory-maxMemories-input").props.value).toBe("2");
+ expect(dialogOf(after)).toBeUndefined();
+});
+
+it("asks before it resets one row, and shows the saved value and the default", async () => {
+ stubFetch((call) =>
+ call.url === "/api/settings" && call.init?.method === "PATCH"
+ ? Response.json({}, { status: 200 })
+ : Response.json(snapshotFixture())
+ );
+ states = [
+ snapshotFixture({
+ maxMemories: { value: 6, source: "global", globalValue: 6, hasGlobal: true },
+ }),
+ {},
+ false,
+ "",
+ ];
+ cursor = 0;
+ const nodes = find(MemorySection(), () => true);
+ const reset = nodes.find(
+ (node) => node.type === Button && node.props["data-reset"] === "maxMemories"
+ )!;
+ (reset.props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ expect(dialog.props.title).toBe("Reset to default?");
+ expect(dialog.props.confirmLabel).toBe("Reset to default");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "maxMemories", label: "Memories per search", from: "6", to: "Default (10)" },
+ ]);
+ expect(patches()).toHaveLength(0);
+ (dialog.props.onClose as () => void)();
+ expect(patches()).toHaveLength(0);
+});
+
+it("keeps a server refusal inside the dialog, which stays open", async () => {
+ stubFetch((call) =>
+ call.init?.method === "PATCH"
+ ? Response.json({ error: "Config changed. Reload settings and save again." }, { status: 409 })
+ : Response.json(snapshotFixture())
+ );
+ const nodes = tree({ retrievalMaxTokens: "3000" });
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ const result = await (
+ dialog.props.onConfirm as () => Promise<{ success: boolean; error?: string }>
+ )();
+ expect(result).toEqual({
+ success: false,
+ error: "Config changed. Reload settings and save again.",
+ });
+ expect(dialogOf(shown())).toBeDefined();
+ // The draft stays for review.
+ expect(states[1]).toEqual({ retrievalMaxTokens: "3000" });
+});
+
it("sends null for the reset row and reloads the shared snapshot", async () => {
stubFetch((call) =>
call.url === "/api/settings" && call.init?.method === "PATCH"
@@ -431,7 +527,9 @@ it("sends null for the reset row and reloads the shared snapshot", async () => {
const reset = nodes.find(
(node) => node.type === Button && node.props["data-reset"] === "maxMemories"
)!;
- await (reset.props.onClick as () => Promise)();
+ (reset.props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
await flush();
const patch = calls.find((call) => call.init?.method === "PATCH");
expect(JSON.parse(String(patch?.init?.body))).toEqual({
@@ -475,7 +573,11 @@ it("saves through the shared settings flow and refreshes the revision", async ()
)
);
const nodes = tree({ maxMemories: "2", retrievalMaxTokens: "3000" });
- await (button("Save memory limits", nodes).props.onClick as () => void)();
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
+ // The real dialog closes itself once the request succeeds.
+ (dialog.props.onClose as () => void)();
await flush();
const patch = calls.find((call) => call.init?.method === "PATCH");
expect(patch?.url).toBe("/api/settings");
@@ -506,7 +608,9 @@ it("translates stale-revision save failures and retranslates on language switch"
: Response.json(snapshotFixture())
);
const nodes = tree({ retrievalMaxTokens: "3000" });
- await (button("Save memory limits", nodes).props.onClick as () => void)();
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
await flush();
// The identity is captured, never the raw or translated string.
expect(states[3]).toEqual({
@@ -516,6 +620,8 @@ it("translates stale-revision save failures and retranslates on language switch"
});
// The draft stays for review.
expect(states[1]).toEqual({ retrievalMaxTokens: "3000" });
+ // The refusal keeps the dialog open; the user then closes it.
+ (dialog.props.onClose as () => void)();
setLanguage("en");
cursor = 0;
expect(renderToStaticMarkup( )).toContain(
@@ -556,8 +662,12 @@ it("prevents duplicate submissions while a save runs", async () => {
return Response.json(snapshotFixture());
});
const nodes = tree({ retrievalMaxTokens: "3000" });
- const save = button("Save memory limits", nodes).props.onClick as () => Promise;
- const inFlight = save();
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const inFlight = (
+ dialogOf(shown()).props.onConfirm as () => Promise<{
+ success: boolean;
+ }>
+ )();
const busyNodes = tree({ retrievalMaxTokens: "3000" }, true);
expect(button("Save memory limits", busyNodes).props.disabled).toBe(true);
expect(button("Cancel", busyNodes).props.disabled).toBe(true);
@@ -602,13 +712,16 @@ it("maps invalid five-setting rejections to translated accepted values", async (
: Response.json(snapshotFixture())
);
const nodes = tree({ maxMemories: "2" });
- await (button("Save memory limits", nodes).props.onClick as () => void)();
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
await flush();
expect(states[3]).toEqual({
kind: "save-failed",
failure: { kind: "invalid", key: "retrievalMaxTokens" },
reloaded: true,
});
+ (dialog.props.onClose as () => void)();
setLanguage("zh");
cursor = 0;
const html = renderToStaticMarkup( );
@@ -627,13 +740,16 @@ it("shows a translated generic message for unknown server and network failures",
: Response.json(snapshotFixture())
);
const nodes = tree({ retrievalMaxTokens: "3000" });
- await (button("Save memory limits", nodes).props.onClick as () => void)();
+ (button("Save memory limits", nodes).props.onClick as () => void)();
+ const dialog = dialogOf(shown());
+ await (dialog.props.onConfirm as () => Promise<{ success: boolean }>)();
await flush();
expect(states[3]).toEqual({
kind: "save-failed",
failure: { kind: "unknown" },
reloaded: true,
});
+ (dialog.props.onClose as () => void)();
setLanguage("ar");
cursor = 0;
const html = renderToStaticMarkup( );
@@ -648,13 +764,19 @@ it("shows a translated generic message for unknown server and network failures",
setLanguage("zh");
const retry = tree({ retrievalMaxTokens: "3000" });
const submit = retry.find((node) => node.type === Button && node.props.type === "submit")!;
- await (submit.props.onClick as () => void)();
+ (submit.props.onClick as () => void)();
+ await (
+ dialogOf(shown()).props.onConfirm as () => Promise<{
+ success: boolean;
+ }>
+ )();
await flush();
expect(states[3]).toEqual({
kind: "save-failed",
failure: { kind: "unknown" },
reloaded: true,
});
+ (dialogOf(shown()).props.onClose as () => void)();
cursor = 0;
const html2 = renderToStaticMarkup( );
expect(html2).toContain("无法保存记忆设置。");
@@ -671,9 +793,11 @@ it("guards a second submission from the same render to one PATCH", async () => {
const nodes = tree({ retrievalMaxTokens: "3000" });
const save = button("Save memory limits", nodes).props.onClick as () => void;
// Both invocations run from the same render, before any re-render.
- const first = save();
- const second = save();
- await Promise.all([first, second]);
+ save();
+ save();
+ const dialog = dialogOf(shown());
+ const confirm = dialog.props.onConfirm as () => Promise<{ success: boolean }>;
+ await Promise.all([confirm(), confirm()]);
await flush();
expect(calls.filter((call) => call.init?.method === "PATCH")).toHaveLength(1);
expect(states[3]).toEqual({ kind: "saved", reloaded: true });
diff --git a/web/tests/models-section-confirm.spec.tsx b/web/tests/models-section-confirm.spec.tsx
new file mode 100644
index 000000000..ebb12193a
--- /dev/null
+++ b/web/tests/models-section-confirm.spec.tsx
@@ -0,0 +1,175 @@
+import { beforeEach, expect, it } from "bun:test";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { ModelsSection, ModelCard } =
+ await import("../src/lib/components/settings/ModelsSection.tsx");
+const { SettingRow } = await import("../src/lib/components/settings/SettingRow.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Input } = await import("../src/lib/components/ui/input.tsx");
+const { Select } = await import("../src/lib/components/ui/select.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [ModelsSection, ModelCard, SettingRow];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+/** What the file holds for OpenCode's model choice; reads answer with what the last save left. */
+let opencodeModel: string | undefined;
+let refusal: string | undefined;
+let requests: Request[];
+
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ const edits = request.body.edits as Record;
+ if ("opencodeModel" in edits) opencodeModel = edits.opencodeModel;
+ }
+ if (request.path.startsWith("/api/settings/models")) return { body: { available: false } };
+ return {
+ body: {
+ revision: "r1",
+ settings: {
+ opencodeModel: { value: opencodeModel, globalValue: opencodeModel, source: "global" },
+ piModel: { value: "inherit", globalValue: "inherit", source: "global" },
+ },
+ fallback: { model: null, configured: false },
+ effective: { opencode: { mode: "session", ready: true }, pi: { kind: "session" } },
+ secrets: {},
+ },
+ };
+};
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ opencodeModel = "inherit";
+ refusal = undefined;
+ requests = installFetch(reply);
+});
+
+/** OpenCode's choice select: the first Select in the card. */
+const choice = (tree: Node[]) => byType(tree, Select)[0]!;
+const manualInput = (tree: Node[]) => byType(tree, Input)[0]!;
+const saveModel = (tree: Node[]) => byText(tree, Button, "Save model")[0]!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
+
+it("names the host, lists the model change and sends nothing until the user confirms", async () => {
+ let tree = await settle( , own);
+ choice(tree).props.onChange({ target: { value: "external" } });
+ tree = await settle( , own);
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save the OpenCode model?");
+ expect(dialog.props.confirmLabel).toBe("Save model");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "opencodeModel", label: "OpenCode model", from: "Session model", to: "External API" },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("opens the dialog with an empty change list when the choice did not change, and saves only on confirm", async () => {
+ let tree = await settle( , own);
+ expect(choice(tree).props.value).toBe("inherit");
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+
+ // Save stays on for an unchanged choice. The dialog opens with nothing to list.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(rowsOf(dialogOf(tree)!)).toEqual([]);
+ expect(patches()).toHaveLength(0);
+
+ await confirm(tree);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ edits: { opencodeModel: "inherit" }, revision: "r1" });
+});
+
+it("lists both settings of a manual model and sends the same body after Cancel kept the draft", async () => {
+ let tree = await settle( , own);
+ choice(tree).props.onChange({ target: { value: "manual" } });
+ tree = await settle( , own);
+ manualInput(tree).props.onChange({ target: { value: "zai/glm-4.7" } });
+ tree = await settle( , own);
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+
+ expect(rowsOf(dialogOf(tree)!)).toEqual([
+ { key: "opencodeProvider", label: "OpenCode model service", from: "Not set", to: "zai" },
+ { key: "opencodeModel", label: "OpenCode model", from: "Session model", to: "glm-4.7" },
+ ]);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+
+ // Cancel sends nothing; the typed model stays, so Save model can be used again.
+ expect(patches()).toHaveLength(0);
+ expect(manualInput(tree).props.value).toBe("zai/glm-4.7");
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({
+ revision: "r1",
+ edits: { opencodeProvider: "zai", opencodeModel: "glm-4.7" },
+ });
+ expect(allText(tree)).toContain("Saved. New capture and profile work uses these settings.");
+});
+
+it("shows the provider/model rule on the page and opens no dialog", async () => {
+ let tree = await settle( , own);
+ choice(tree).props.onChange({ target: { value: "manual" } });
+ tree = await settle( , own);
+ manualInput(tree).props.onChange({ target: { value: "glm-4.7" } });
+ tree = await settle( , own);
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(allText(tree)).toContain("Enter a model as provider/model.");
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle( , own);
+ choice(tree).props.onChange({ target: { value: "external" } });
+ tree = await settle( , own);
+ saveModel(tree).props.onClick();
+ tree = await settle( , own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+});
diff --git a/web/tests/openrouter-routing.spec.tsx b/web/tests/openrouter-routing.spec.tsx
index 86bb9ed0f..24376fac0 100644
--- a/web/tests/openrouter-routing.spec.tsx
+++ b/web/tests/openrouter-routing.spec.tsx
@@ -226,6 +226,17 @@ const buttonNamed = (tree: Node[], label: string) =>
byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
const tick = (tree: Node[], slug: string, checked = true) =>
(box(tree, `openrouter-provider-${slug}`).props.onCheckedChange as (v: boolean) => void)(checked);
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const posts = () => requests.filter((request) => request.path === SAVE);
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
function deferred() {
let resolve!: (value: T) => void;
@@ -408,7 +419,7 @@ it("shows the try order, adds a provider by hand and rejects a bad or repeated s
expect(box(tree, "openrouter-provider-my-host").props.checked).toBe(true);
});
-it("saves the choice with the snapshot revision, answers at once, and reloads the settings", async () => {
+it("asks before it saves the routing, and sends the same request once the user confirms", async () => {
const pending = deferred<{ status?: number; body: unknown }>();
requests = installFetch((request) => {
if (request.path.startsWith(LIST)) return { body: { ok: true, providers: rows } };
@@ -425,6 +436,28 @@ it("saves the choice with the snapshot revision, answers at once, and reloads th
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block(), own);
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save OpenRouter routing?");
+ expect(dialog.props.confirmLabel).toBe("Save routing");
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "data_collection",
+ label: "Block providers that may train on or store data",
+ from: "Off",
+ to: "On",
+ },
+ {
+ key: "order",
+ label: "Providers for this model in try order",
+ from: "None",
+ to: "deepinfra, novita",
+ },
+ { key: "only", label: "Use only these providers", from: "Off", to: "On" },
+ ]);
+ expect(posts()).toHaveLength(0);
+
+ const saving = dialog.props.onConfirm() as Promise;
+ tree = await settle(block(), own);
expect(statusLines(tree).join(" ")).toContain("Saving routing");
const post = requests.find((request) => request.path === SAVE)!;
expect(post.method).toBe("POST");
@@ -439,11 +472,76 @@ it("saves the choice with the snapshot revision, answers at once, and reloads th
});
pending.resolve({ body: { revision: "rev-10", provider: {} } });
+ await saving;
tree = await settle(block(), own);
expect(statusLines(tree).join(" ")).toContain("Routing saved.");
expect(requests.some((request) => request.path === "/api/settings")).toBe(true);
});
+it("opens the dialog with an empty change list when no routing choice changed, and saves only on confirm", async () => {
+ requests = installFetch((request) => {
+ if (request.path.startsWith(LIST)) return { body: { ok: true, providers: rows } };
+ if (request.path === SAVE) return { body: { revision: "rev-10", provider: {} } };
+ return { body: { revision: "rev-10", settings: {} } };
+ });
+ let tree = await settle(block(), own);
+ (buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block(), own);
+
+ // Save routing stays on when nothing changed. The dialog opens with nothing to list.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(rowsOf(dialogOf(tree)!)).toEqual([]);
+ expect(posts()).toHaveLength(0);
+ await confirm(tree);
+ tree = await settle(block(), own);
+ expect(posts()).toHaveLength(1);
+ expect(posts()[0]!.body).toMatchObject({ revision: "rev-9" });
+ expect(posts()[0]!.body.routing).toBeDefined();
+ expect(statusLines(tree).join(" ")).toContain("Routing saved.");
+});
+
+it("lists a saved provider that the save leaves out, because the list shows what is saved", async () => {
+ requests = installFetch((request) =>
+ request.path.startsWith(LIST)
+ ? { body: { ok: true, providers: rows } }
+ : { body: { revision: "rev-10", settings: {} } }
+ );
+ // With ZDR on, `together` (may keep data) shows unticked, and a save leaves it out of the order.
+ const saved = { zdr: true, order: ["together", "deepinfra"] };
+ let tree = await settle(block({ saved }), own);
+ (buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block({ saved }), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "order",
+ label: "Providers for this model in try order",
+ from: "together, deepinfra",
+ to: "deepinfra",
+ },
+ ]);
+ expect(posts()).toHaveLength(0);
+});
+
+it("sends nothing on Cancel, and the ticks stay as they were", async () => {
+ requests = installFetch((request) =>
+ request.path.startsWith(LIST) ? { body: { ok: true, providers: rows } } : { body: {} }
+ );
+ let tree = await settle(block(), own);
+ tick(tree, "deepinfra");
+ tree = await settle(block(), own);
+ (buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block(), own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(block(), own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(posts()).toHaveLength(0);
+ expect(box(tree, "openrouter-provider-deepinfra").props.checked).toBe(true);
+ expect(statusLines(tree).join(" ")).not.toContain("Routing saved.");
+});
+
it("shows the server error when the save fails and keeps the ticks", async () => {
requests = installFetch((request) => {
if (request.path.startsWith(LIST)) return { body: { ok: true, providers: rows } };
@@ -456,6 +554,11 @@ it("shows the server error when the save fails and keeps the ticks", async () =>
tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block(), own);
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toEqual({ success: false, error: "Settings changed elsewhere" });
+ tree = await settle(block(), own);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(dialogOf(tree)).toBeDefined();
const alerts = tree
.filter((node) => node.props.role === "alert")
.map((n) => text(n.props.children));
@@ -724,6 +827,8 @@ it("clears Routing saved. as soon as any routing control changes", async () => {
let tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block(), own);
+ await confirm(tree);
+ tree = await settle(block(), own);
expect(statusLines(tree).join(" ")).toContain("Routing saved.");
const edits: Array<(tree: Node[]) => void> = [
@@ -737,6 +842,8 @@ it("clears Routing saved. as soon as any routing control changes", async () => {
tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block(), own);
+ await confirm(tree);
+ tree = await settle(block(), own);
expect(statusLines(tree).join(" ")).toContain("Routing saved.");
edit(tree);
tree = await settle(block(), own);
@@ -771,6 +878,8 @@ it("clears Routing saved. when Use only these providers changes", async () => {
let tree = await settle(block({ saved: { order: ["deepinfra"] } }), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block({ saved: { order: ["deepinfra"] } }), own);
+ await confirm(tree);
+ tree = await settle(block({ saved: { order: ["deepinfra"] } }), own);
expect(statusLines(tree).join(" ")).toContain("Routing saved.");
(box(tree, "openrouter-only").props.onCheckedChange as (v: boolean) => void)(true);
tree = await settle(block({ saved: { order: ["deepinfra"] } }), own);
@@ -856,6 +965,9 @@ it("has Chinese and Arabic text for Preset, Custom and every new string", () =>
"Custom",
SAVE_REASON,
STALE,
+ "Save OpenRouter routing?",
+ "Providers for this model in try order",
+ "None",
"Remove OpenRouter routing",
"Remove OpenRouter routing?",
"Requests to this endpoint will no longer carry the routing choices.",
@@ -1071,6 +1183,8 @@ it("saves no order, only or allow_fallbacks with the switch on, and keeps the pr
flip(tree, "openrouter-chooses", true);
tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block(), own);
+ await confirm(tree);
await settle(block(), own);
expect(requests.find((request) => request.path === SAVE)!.body).toEqual({
revision: "rev-9",
@@ -1089,6 +1203,8 @@ it("keeps the choice across a save and a reload when both privacy switches are o
flip(tree, "openrouter-chooses", true);
tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block(), own);
+ await confirm(tree);
await settle(block(), own);
const post = requests.find((request) => request.path === SAVE)!.body as Record;
// The routing is empty, so the page must also say that OpenRouter chooses.
@@ -1119,6 +1235,8 @@ it("sends no chooses field while the switch is off", async () => {
tick(tree, "deepinfra");
tree = await settle(block(), own);
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
+ tree = await settle(block(), own);
+ await confirm(tree);
await settle(block(), own);
expect(requests.find((request) => request.path === SAVE)!.body).toEqual({
revision: "rev-9",
@@ -1178,6 +1296,8 @@ it("orders rows by the ticks that show, so a blocked saved tick does not lead",
// Saving drops the blocked tick from the order too, so the rows stay put.
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block({ saved }), own);
+ await confirm(tree);
+ tree = await settle(block({ saved }), own);
expect(slugsOf(tree)).toEqual(["deepinfra", "novita", "together"]);
});
@@ -1197,6 +1317,8 @@ it("does not move a row on a tick, and reorders after a save", async () => {
(buttonNamed(tree, "Save routing").props.onClick as () => void)();
tree = await settle(block(), own);
+ await confirm(tree);
+ tree = await settle(block(), own);
expect(slugsOf(tree)).toEqual(["together", "deepinfra", "novita"]);
});
diff --git a/web/tests/profile-learning-section.spec.tsx b/web/tests/profile-learning-section.spec.tsx
index d691951a5..9268cb5fe 100644
--- a/web/tests/profile-learning-section.spec.tsx
+++ b/web/tests/profile-learning-section.spec.tsx
@@ -130,10 +130,18 @@ function stubFetch(patch: () => { ok: boolean; body: unknown }, reloadFails = fa
}
const patchBody = () =>
JSON.parse(String(calls.find((call) => call.init?.method === "PATCH")!.init!.body));
+/** A fresh render of the section, with the shared hook cursor reset as `tree` does. */
+const shown = (): Node[] => {
+ cursor = 0;
+ return find(ProfileLearningSettingsSection(), () => true);
+};
+const dialogOf = (nodes: Node[]) => nodes.find((node) => node.type === SettingsConfirmDialog)!;
+/** Submit the form, then confirm the dialog the save opens, as the user does. */
const submitForm = async (nodes: Node[]) => {
(submit(nodes).props.onSubmit as (event: { preventDefault: () => void }) => void)({
preventDefault: () => {},
});
+ await (dialogOf(shown()).props.onConfirm as () => Promise<{ success: boolean }>)();
for (let i = 0; i < 6; i++) await new Promise((resolve) => setTimeout(resolve, 0));
};
@@ -247,6 +255,53 @@ it("saves only the changed keys, clears the draft and says so", async () => {
);
});
+it("asks before it saves, and sends nothing until the user confirms", () => {
+ stubFetch(() => ({ ok: true, body: { success: true } }));
+ const nodes = tree({ draft: { userProfileWithoutEmail: "skip" } });
+ (submit(nodes).props.onSubmit as (event: { preventDefault: () => void }) => void)({
+ preventDefault: () => {},
+ });
+ const dialog = dialogOf(shown());
+ expect(dialog.props.title).toBe("Save learning settings?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(dialog.props.body.props.changes).toEqual([
+ { key: "userProfileWithoutEmail", label: "No user email", from: "Learn anyway", to: "Skip" },
+ ]);
+ expect(calls).toHaveLength(0);
+});
+
+it("sends nothing on Cancel, and the choices stay in the draft", () => {
+ stubFetch(() => {
+ throw new Error("no request expected");
+ });
+ const nodes = tree({ draft: { userProfileDecayBeforeMerge: true } });
+ (submit(nodes).props.onSubmit as (event: { preventDefault: () => void }) => void)({
+ preventDefault: () => {},
+ });
+ (dialogOf(shown()).props.onClose as () => void)();
+ expect(calls).toHaveLength(0);
+ expect(states[1]).toEqual({ userProfileDecayBeforeMerge: true });
+ const after = shown();
+ expect(dialogOf(after)).toBeUndefined();
+ expect(after.filter((node) => node.type === Select)[1]!.props.value).toBe("true");
+});
+
+it("keeps a save refusal inside the dialog, which stays open", async () => {
+ stubFetch(() => ({ ok: false, body: { error: "Settings are locked by the administrator." } }));
+ const nodes = tree({ draft: { userProfileWithoutEmail: "skip" } });
+ (submit(nodes).props.onSubmit as (event: { preventDefault: () => void }) => void)({
+ preventDefault: () => {},
+ });
+ const dialog = dialogOf(shown());
+ const result = await (
+ dialog.props.onConfirm as () => Promise<{ success: boolean; error?: string }>
+ )();
+ expect(result.success).toBe(false);
+ expect(result.error).toContain("Settings are locked by the administrator");
+ expect(dialogOf(shown())).toBeDefined();
+ expect(states[1]).toEqual({ userProfileWithoutEmail: "skip" });
+});
+
it("keeps the values the server confirmed when the reload after a save fails", async () => {
stubFetch(() => ({ ok: true, body: { success: true } }), true);
await submitForm(tree({ draft: { userProfileDecayBeforeMerge: true } }));
diff --git a/web/tests/reasoning-level.spec.tsx b/web/tests/reasoning-level.spec.tsx
index f8805a922..13f70c012 100644
--- a/web/tests/reasoning-level.spec.tsx
+++ b/web/tests/reasoning-level.spec.tsx
@@ -71,6 +71,17 @@ const pick = (tree: Node[], value: string) =>
(select(tree).props.onChange as (event: unknown) => void)({ target: { value } });
const saveButton = (tree: Node[]) =>
byType(tree, Button).find((node) => text(node.props.children).includes("Save reasoning level"))!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const posts = () => requests.filter((request) => request.path === SAVE);
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
it("offers the levels of the model and names its default effort", async () => {
const tree = await settle(card(), own);
@@ -103,6 +114,8 @@ it("offers on and off for a model with reasoning but no effort list, and posts t
pick(tree, "on");
tree = await settle(card({ savedModel: "x/toggle" }), own);
(saveButton(tree).props.onClick as () => void)();
+ tree = await settle(card({ savedModel: "x/toggle" }), own);
+ await confirm(tree);
await settle(card({ savedModel: "x/toggle" }), own);
expect(requests.find((r) => r.path === SAVE)!.body).toEqual({
revision: "rev-9",
@@ -173,6 +186,8 @@ it("posts the revision and the level, then reloads the settings", async () => {
tree = await settle(card(), own);
(saveButton(tree).props.onClick as () => void)();
tree = await settle(card(), own);
+ await confirm(tree);
+ tree = await settle(card(), own);
const post = requests.find((request) => request.path === SAVE)!;
expect(post.method).toBe("POST");
expect(post.body).toEqual({ revision: "rev-9", level: "low" });
@@ -203,7 +218,12 @@ it("drops a pending pick that the new saved endpoint does not offer", async () =
expect(options(tree)).not.toContain("off");
expect(select(tree).props.value).toBe("default");
(saveButton(tree).props.onClick as () => void)();
- await settle(card(other), own);
+ tree = await settle(card(other), own);
+ // The level on screen is the saved one, so the dialog opens with nothing to list.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(rowsOf(dialogOf(tree)!)).toEqual([]);
+ expect(posts()).toHaveLength(0);
+ await confirm(tree);
expect(requests.find((request) => request.path === SAVE)!.body).toEqual({
revision: "rev-9",
level: "default",
@@ -232,6 +252,8 @@ it("keeps the submitted level on screen when the settings reload fails after a s
tree = await settle(card(), own);
(saveButton(tree).props.onClick as () => void)();
tree = await settle(card(), own);
+ await confirm(tree);
+ tree = await settle(card(), own);
expect(requests.some((request) => request.path === "/api/settings")).toBe(true);
expect(allText(tree)).toContain("Reasoning level saved.");
expect(select(tree).props.value).toBe("low");
@@ -249,17 +271,20 @@ it("turns the Select off while a save runs, so a later pick cannot be lost", asy
tree = await settle(card(), own);
(saveButton(tree).props.onClick as () => void)();
tree = await settle(card(), own);
+ // Nothing runs until the user confirms; the pick is only a draft meanwhile.
+ expect(posts()).toHaveLength(0);
+ const saving = dialogOf(tree)!.props.onConfirm() as Promise;
+ tree = await settle(card(), own);
expect(allText(tree)).toContain("Saving reasoning level");
expect(select(tree).props.disabled).toBe(true);
release({ body: { revision: "rev-10" } });
+ await saving;
tree = await settle(card(), own);
expect(select(tree).props.disabled).toBeFalsy();
});
const HAND_WRITTEN = { reasoning: { max_tokens: 2000 } };
-const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
-const posts = () => requests.filter((request) => request.path === SAVE);
it("asks before it replaces a hand-written value, and sends nothing until confirmed", async () => {
const props = { saved: HAND_WRITTEN };
@@ -314,8 +339,12 @@ it("shows a server error inside the dialog and leaves the card without a saved n
expect(allText(tree)).not.toContain("Reasoning level saved.");
});
-it("saves straight away, with no dialog, when no hand-written value is saved", async () => {
- for (const saved of [{}, { reasoning: { effort: "high" } }]) {
+it("asks before an ordinary save, and sends nothing until the user confirms", async () => {
+ const cases = [
+ [{}, "Default (High)"],
+ [{ reasoning: { effort: "high" } }, "High"],
+ ] as const;
+ for (const [saved, from] of cases) {
resetRender();
requests = installFetch(() => ({ body: { revision: "rev-10", settings: {} } }));
let tree = await settle(card({ saved }), own);
@@ -323,11 +352,82 @@ it("saves straight away, with no dialog, when no hand-written value is saved", a
tree = await settle(card({ saved }), own);
(saveButton(tree).props.onClick as () => void)();
tree = await settle(card({ saved }), own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save reasoning level?");
+ expect(dialog.props.confirmLabel).toBe("Save reasoning level");
+ expect(rowsOf(dialog)).toEqual([{ key: "level", label: "Reasoning level", from, to: "Low" }]);
+ expect(posts()).toHaveLength(0);
+
+ await confirm(tree);
+ tree = await settle(card({ saved }), own);
expect(dialogOf(tree)).toBeUndefined();
expect(posts()).toHaveLength(1);
+ expect(posts()[0]!.body).toEqual({ revision: "rev-9", level: "low" });
}
});
+it("sends nothing on Cancel, and the picked level stays as a draft", async () => {
+ let tree = await settle(card(), own);
+ pick(tree, "low");
+ tree = await settle(card(), own);
+ (saveButton(tree).props.onClick as () => void)();
+ tree = await settle(card(), own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(card(), own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(posts()).toHaveLength(0);
+ expect(allText(tree)).not.toContain("Reasoning level saved.");
+ // The pick stays, so Save can be used again.
+ expect(select(tree).props.value).toBe("low");
+ (saveButton(tree).props.onClick as () => void)();
+ tree = await settle(card(), own);
+ await confirm(tree);
+ await settle(card(), own);
+ expect(posts()).toHaveLength(1);
+});
+
+it("keeps a server refusal inside the ordinary-save dialog, which stays open", async () => {
+ requests = installFetch((request) =>
+ request.path === SAVE
+ ? { status: 409, body: { error: "The settings changed. Reload and try again." } }
+ : { body: { revision: "rev-10", settings: {} } }
+ );
+ let tree = await settle(card(), own);
+ pick(tree, "low");
+ tree = await settle(card(), own);
+ (saveButton(tree).props.onClick as () => void)();
+ tree = await settle(card(), own);
+ const result = await dialogOf(tree)!.props.onConfirm();
+ expect(result).toMatchObject({
+ success: false,
+ error: "The settings changed. Reload and try again.",
+ });
+ tree = await settle(card(), own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(posts()).toHaveLength(1);
+ expect(allText(tree)).not.toContain("Reasoning level saved.");
+});
+
+it("opens the dialog with an empty change list for a level that did not change, and saves only on confirm", async () => {
+ // Save stays on for an unchanged level, and it sends the same request as before this rule.
+ const same = { saved: { reasoning: { effort: "high" } } };
+ let tree = await settle(card(same), own);
+ expect(select(tree).props.value).toBe("high");
+ (saveButton(tree).props.onClick as () => void)();
+ tree = await settle(card(same), own);
+
+ expect(dialogOf(tree)).toBeDefined();
+ expect(rowsOf(dialogOf(tree)!)).toEqual([]);
+ expect(posts()).toHaveLength(0);
+ await confirm(tree);
+ tree = await settle(card(same), own);
+ expect(posts()).toHaveLength(1);
+ expect(posts()[0]!.body).toEqual({ revision: "rev-9", level: "high" });
+ expect(allText(tree)).toContain("Reasoning level saved.");
+});
+
it("shows the replace dialog in Arabic", async () => {
setLanguage("ar");
const props = { saved: HAND_WRITTEN };
diff --git a/web/tests/reranker-section.spec.tsx b/web/tests/reranker-section.spec.tsx
index 3f4f6fb6e..be5245096 100644
--- a/web/tests/reranker-section.spec.tsx
+++ b/web/tests/reranker-section.spec.tsx
@@ -82,6 +82,11 @@ const click = async (tree: Node[], label: string) => {
await byText(tree, Button, label)[0]!.props.onClick();
await flush();
};
+/** Confirms the dialog a Save opened, as the user does, and lets the request finish. */
+const confirm = async () => {
+ await byType(after(), SettingsConfirmDialog)[0]!.props.onConfirm();
+ await flush();
+};
beforeEach(() => {
resetRender();
@@ -206,6 +211,7 @@ it("saves a pasted key to a private file first, then the other settings, with th
request.path === "/api/settings/external-api/key" ? { body: { revision: "rev-2" } } : undefined
);
await click(after(), "Save");
+ await confirm();
const writes = requests.filter((r) => r.method !== "GET");
expect(writes.map((r) => `${r.method} ${r.path}`)).toEqual([
"POST /api/settings/external-api/key",
@@ -238,6 +244,7 @@ it("saves an environment variable key through the same route", async () => {
keyField(tree).props.onChoice("env");
keyField(after()).props.onInput({ name: "RERANK_KEY", path: "", value: "" });
await click(after(), "Save");
+ await confirm();
const key = requests.find((r) => r.path === "/api/settings/external-api/key")!;
expect(key.body).toMatchObject({ source: "env", name: "RERANK_KEY", setting: "rerankerApiKey" });
});
@@ -258,8 +265,13 @@ it("asks before it replaces an existing key file, and sends nothing else until i
);
await click(after(), "Save");
expect(requests.some((r) => r.method === "PATCH")).toBe(false);
+ // The shared dialog is the confirmation of the Save; the server then asks about the key file.
+ await byType(after(), SettingsConfirmDialog)[0]!.props.onConfirm();
+ await flush();
+ expect(requests.some((r) => r.method === "PATCH")).toBe(false);
const dialog = byType(after(), SettingsConfirmDialog)[0]!;
expect(dialog).toBeTruthy();
+ expect(dialog.props.title).toBe("Replace the key file?");
const result = await dialog.props.onConfirm();
await flush();
expect(result.success).toBe(true);
@@ -274,11 +286,139 @@ it("removes the saved key only when the user chooses No key", async () => {
keyField(tree).props.onChoice("none");
typeInto(after(), "reranker-model", "m");
await click(after(), "Save");
+ await confirm();
expect(requests.some((r) => r.path === "/api/settings/external-api/key")).toBe(false);
const patch = requests.find((r) => r.method === "PATCH")!;
expect(patch.body.edits.rerankerApiKey).toBeNull();
});
+it("asks before it saves, and sends nothing until the user confirms", async () => {
+ const tree = await fillServer(await load());
+ typeInto(tree, "reranker-timeout", "6000");
+ requests.length = 0;
+ await click(after(), "Save");
+ const dialog = byType(after(), SettingsConfirmDialog)[0]!;
+ expect(dialog.props.title).toBe("Save the reranker settings?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(dialog.props.body.props.changes).toEqual([
+ { key: "rerankerEnabled", label: "Reorder results with a reranker", from: "Off", to: "On" },
+ { key: "rerankerApiUrl", label: "Reranker server address", from: "Not set", to: SERVER },
+ { key: "rerankerModel", label: "Reranker model", from: "Not set", to: "Qwen3-Reranker-0.6B" },
+ {
+ key: "rerankerTimeoutMs",
+ label: "Reranker wait time",
+ from: "4000 milliseconds",
+ to: "6000 milliseconds",
+ },
+ ]);
+ expect(requests.filter((r) => r.method !== "GET")).toHaveLength(0);
+ // Cancel keeps the typed values as a draft, and sends nothing.
+ dialog.props.onClose();
+ await flush();
+ expect(byType(after(), SettingsConfirmDialog)).toHaveLength(0);
+ expect(requests.filter((r) => r.method !== "GET")).toHaveLength(0);
+ expect(field(after(), "reranker-url").props.value).toBe(SERVER);
+ expect(field(after(), "reranker-timeout").props.value).toBe("6000");
+});
+
+it("lists the key change in words, never the key itself", async () => {
+ const tree = await fillServer(await load({ set: true, source: "env", reference: "RERANK_KEY" }));
+ keyField(tree).props.onChoice("paste");
+ keyField(after()).props.onInput({ name: "rerank", path: "", value: "sk-secret" });
+ await click(after(), "Save");
+ const dialog = byType(after(), SettingsConfirmDialog)[0]!;
+ const row = (dialog.props.body.props.changes as { key: string }[]).find(
+ (change) => change.key === "rerankerApiKey"
+ )!;
+ expect(row).toEqual({
+ key: "rerankerApiKey",
+ label: "Reranker key",
+ from: "Environment variable RERANK_KEY",
+ to: "Key file rerank",
+ });
+ expect(JSON.stringify(dialog.props.body)).not.toContain("sk-secret");
+});
+
+it("lists a key that changes but keeps its source, so a new key is never left out", async () => {
+ const keyRow = () =>
+ (byType(after(), SettingsConfirmDialog)[0]!.props.body.props.changes as { key: string }[]).find(
+ (change) => change.key === "rerankerApiKey"
+ );
+ // A new pasted key lands in a file too, so the source words alone would not change.
+ const saved = {
+ set: true,
+ source: "file",
+ reference: "/home/me/.config/omms/secrets/reranker.key",
+ };
+ keyField(await fillServer(await load(saved))).props.onChoice("paste");
+ keyField(after()).props.onInput({ name: "rerank", path: "", value: "sk-secret" });
+ await click(after(), "Save");
+ expect(keyRow()).toMatchObject({
+ from: "Key file /home/me/.config/omms/secrets/reranker.key",
+ to: "Key file rerank",
+ });
+ expect(JSON.stringify(keyRow())).not.toContain("sk-secret");
+
+ // Another variable name is a new key too.
+ resetRender();
+ const first = await fillServer(await load({ set: true, source: "env", reference: "RERANK_KEY" }));
+ keyField(first).props.onInput({ name: "OTHER_KEY", path: "", value: "" });
+ await click(after(), "Save");
+ expect(keyRow()).toMatchObject({
+ from: "Environment variable RERANK_KEY",
+ to: "Environment variable OTHER_KEY",
+ });
+});
+
+it("opens the dialog with an empty change list when nothing changed, and saves only on confirm", async () => {
+ const MODEL = "Qwen3-Reranker-0.6B";
+ const entry = (value: unknown) => ({ value, source: "global", globalValue: value });
+ const same = {
+ revision: "rev-1",
+ settings: {
+ rerankerEnabled: entry(true),
+ rerankerApiUrl: entry(SERVER),
+ rerankerModel: entry(MODEL),
+ rerankerTimeoutMs: entry(4000),
+ },
+ secrets: { rerankerApiKey: { set: false, source: null, reference: null } },
+ };
+ await load(undefined, (request) => (request.method === "GET" ? { body: same } : undefined));
+ requests.length = 0;
+ await click(after(), "Save");
+
+ // Nothing changed, so the dialog opens with no rows and sends nothing yet.
+ const dialog = byType(after(), SettingsConfirmDialog)[0]!;
+ expect(dialog.props.body.props.changes).toEqual([]);
+ expect(requests.find((request) => request.method === "PATCH")).toBeUndefined();
+ await dialog.props.onConfirm();
+ await flush();
+ const patch = requests.find((request) => request.method === "PATCH")!;
+ expect(patch.body.edits).toEqual({
+ rerankerEnabled: true,
+ rerankerApiUrl: SERVER,
+ rerankerModel: MODEL,
+ rerankerTimeoutMs: 4000,
+ });
+});
+
+it("keeps a save refusal inside the dialog, which stays open", async () => {
+ const REFUSED = "Config changed. Reload settings and save again.";
+ await fillServer(
+ await load(undefined, (request) =>
+ request.method === "PATCH" ? { status: 409, body: { error: REFUSED } } : undefined
+ )
+ );
+ await click(after(), "Save");
+ const dialog = byType(after(), SettingsConfirmDialog)[0]!;
+ expect(await dialog.props.onConfirm()).toEqual({ success: false, error: REFUSED });
+ await flush();
+ expect(byType(after(), SettingsConfirmDialog)).toHaveLength(1);
+ expect(allText(after())).toContain(REFUSED);
+ // The drafts stay, so the user can save again.
+ expect(field(after(), "reranker-url").props.value).toBe(SERVER);
+});
+
it("tests the values in the form, with the key source from the form", async () => {
const tree = await fillServer(await load());
typeInto(tree, "reranker-timeout", "6000");
diff --git a/web/tests/settings-catalogue.spec.ts b/web/tests/settings-catalogue.spec.ts
index 183facbc9..7289c6ddc 100644
--- a/web/tests/settings-catalogue.spec.ts
+++ b/web/tests/settings-catalogue.spec.ts
@@ -109,6 +109,8 @@ it("has every text that the shared pieces show in Chinese and Arabic", () => {
"web/src/lib/components/settings/SettingsConfirmDialog.tsx",
"web/src/lib/components/settings/SettingsSearch.tsx",
"web/src/lib/components/settings/ConfigProblemBanner.tsx",
+ "web/src/lib/components/settings/SettingsChangeList.tsx",
+ "web/src/hooks/useSettingsChanges.ts",
];
const missing: string[] = [];
for (const file of files) {
diff --git a/web/tests/settings-change-list.spec.tsx b/web/tests/settings-change-list.spec.tsx
new file mode 100644
index 000000000..fbb7650e2
--- /dev/null
+++ b/web/tests/settings-change-list.spec.tsx
@@ -0,0 +1,101 @@
+import { beforeEach, expect, it } from "bun:test";
+import { allText, installReact, resetRender, settle, text, type Node } from "./space-kit.tsx";
+
+installReact();
+
+const { SettingsChangeList } =
+ await import("../src/lib/components/settings/SettingsChangeList.tsx");
+const { useSettingsChanges } = await import("../src/hooks/useSettingsChanges.ts");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+type SettingsChange = import("../src/lib/settings-changes.ts").SettingsChange;
+
+const own = [SettingsChangeList];
+const rows = [
+ { key: "maxMemories", label: "Maximum memories", from: "10", to: "20" },
+ { key: "similarityThreshold", label: "Similarity threshold", from: "0.6", to: "Default (0.6)" },
+];
+const list = (changes: readonly SettingsChange[] = rows) => (
+
+);
+const typed = (tree: Node[], type: string) =>
+ tree.filter((node) => node.type === type).map((node) => text(node.props.children));
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+});
+
+it("lists each change with its name, its saved value, then its new value", async () => {
+ const tree = await settle(list(), own);
+ expect(typed(tree, "dt")).toEqual(["Maximum memories", "Similarity threshold"]);
+ expect(typed(tree, "dd")).toEqual(["10changes to20", "0.6changes toDefault (0.6)"]);
+});
+
+it("strikes the saved value through and leaves the new value plain", async () => {
+ const tree = await settle(list(), own);
+ expect(typed(tree, "s")).toEqual(["10", "0.6"]);
+ expect(typed(tree, "s")).toEqual(rows.map((row) => row.from));
+});
+
+it("keeps the arrow out of the reading order and mirrors it for Arabic", async () => {
+ const tree = await settle(list(), own);
+ const arrow = tree.find((node) => node.props["aria-hidden"] === "true");
+ expect(arrow?.props.className).toContain("rtl:-scale-x-100");
+});
+
+it("reads the link between the values in Arabic", async () => {
+ setLanguage("ar");
+ const tree = await settle(list(), own);
+ expect(allText(tree)).toContain("يتغير إلى");
+ expect(allText(tree)).not.toContain("changes to");
+});
+
+it("says that nothing changes when the save changes nothing", async () => {
+ const tree = await settle(list([]), own);
+ expect(allText(tree).trim()).toBe("Nothing changes. Saving writes the current values again.");
+ expect(typed(tree, "dt")).toEqual([]);
+});
+
+it("gives the helper the words and the setting names of the page", async () => {
+ let listed: SettingsChange[] = [];
+ let names: string[] = [];
+ const fields = [
+ { key: "autoCaptureEnabled", label: "Automatic capture" },
+ { key: "maxMemories", label: "Maximum memories", default: 10 },
+ { key: "claudeFolder", label: "Claude Code folder" },
+ ];
+ const KEYS = ["autoCaptureEnabled", "maxMemories", "claudeFolder", "not.a.setting"];
+ const Probe = () => {
+ const { changes, name } = useSettingsChanges();
+ listed = changes(
+ { autoCaptureEnabled: true, maxMemories: 20 },
+ { autoCaptureEnabled: false, maxMemories: null, claudeFolder: "/tmp/claude" },
+ fields
+ );
+ names = KEYS.map(name);
+ return null;
+ };
+ await settle( , [Probe]);
+ expect(listed).toEqual([
+ { key: "autoCaptureEnabled", label: "Automatic capture", from: "On", to: "Off" },
+ { key: "maxMemories", label: "Maximum memories", from: "20", to: "Default (10)" },
+ { key: "claudeFolder", label: "Claude Code folder", from: "Not set", to: "/tmp/claude" },
+ ]);
+ // A setting the catalogue does not know keeps its key.
+ expect(names).toEqual([
+ "Save memories automatically",
+ "Memories per search",
+ "claudeFolder",
+ "not.a.setting",
+ ]);
+
+ setLanguage("ar");
+ await settle( , [Probe]);
+ expect(listed).toEqual([
+ { key: "autoCaptureEnabled", label: "Automatic capture", from: "قيد التشغيل", to: "متوقف" },
+ { key: "maxMemories", label: "Maximum memories", from: "20", to: "افتراضي (10)" },
+ { key: "claudeFolder", label: "Claude Code folder", from: "غير محدد", to: "/tmp/claude" },
+ ]);
+ expect(names[0]).toMatch(/[-ۿ]/);
+ expect(names[3]).toBe("not.a.setting");
+});
diff --git a/web/tests/settings-changes.spec.ts b/web/tests/settings-changes.spec.ts
new file mode 100644
index 000000000..e91f15cf4
--- /dev/null
+++ b/web/tests/settings-changes.spec.ts
@@ -0,0 +1,99 @@
+import { expect, it } from "bun:test";
+import {
+ settingsChanges,
+ type SettingsChangeField,
+ type SettingsChangeWords,
+} from "../src/lib/settings-changes.ts";
+
+const words: SettingsChangeWords = {
+ on: "On",
+ off: "Off",
+ notSet: "Not set",
+ default: (value) => `Default (${value})`,
+};
+const limits: readonly SettingsChangeField[] = [
+ { key: "maxMemories", label: "Maximum memories", default: 10 },
+ { key: "similarityThreshold", label: "Similarity threshold", default: 0.6 },
+];
+const list = (
+ saved: Record,
+ edits: Record,
+ fields: readonly SettingsChangeField[] = limits
+) => settingsChanges(saved, edits, fields, words);
+
+it("lists nothing when the save changes nothing", () => {
+ // The same value as saved, next to a field the save does not touch.
+ expect(list({ maxMemories: 20, similarityThreshold: 0.6 }, { maxMemories: 20 })).toEqual([]);
+ // An empty request.
+ expect(list({ maxMemories: 20 }, {})).toEqual([]);
+ // The same value in another type, and a key the request drops (`undefined`).
+ expect(list({ maxMemories: "20" }, { maxMemories: 20 })).toEqual([]);
+ expect(list({ maxMemories: 20 }, { maxMemories: undefined })).toEqual([]);
+});
+
+it("lists one change with its saved value and its new value", () => {
+ expect(list({ maxMemories: 10 }, { maxMemories: 20 })).toEqual([
+ { key: "maxMemories", label: "Maximum memories", from: "10", to: "20" },
+ ]);
+});
+
+it("lists two changes in the order of the fields, not of the request", () => {
+ const rows = list(
+ { maxMemories: 10, similarityThreshold: 0.6 },
+ { similarityThreshold: 0.5, maxMemories: 20 }
+ );
+ expect(rows.map((row) => row.key)).toEqual(["maxMemories", "similarityThreshold"]);
+});
+
+it("reads a switch as On and Off, in both directions", () => {
+ const fields = [{ key: "autoCapture", label: "Automatic capture" }];
+ expect(list({ autoCapture: true }, { autoCapture: false }, fields)[0]).toMatchObject({
+ from: "On",
+ to: "Off",
+ });
+ expect(list({ autoCapture: false }, { autoCapture: true }, fields)[0]).toMatchObject({
+ from: "Off",
+ to: "On",
+ });
+});
+
+it("shows a reset to default as the default value", () => {
+ expect(list({ maxMemories: 20 }, { maxMemories: null })).toEqual([
+ { key: "maxMemories", label: "Maximum memories", from: "20", to: "Default (10)" },
+ ]);
+});
+
+it("reads a nested key as the request spells it", () => {
+ const fields = [{ key: "compaction.enabled", label: "Restore compaction", default: true }];
+ expect(list({ "compaction.enabled": true }, { "compaction.enabled": false }, fields)).toEqual([
+ { key: "compaction.enabled", label: "Restore compaction", from: "On", to: "Off" },
+ ]);
+ expect(list({ "compaction.enabled": false }, { "compaction.enabled": null }, fields)[0]?.to).toBe(
+ "Default (On)"
+ );
+});
+
+it("uses the field's own words for a value", () => {
+ const names: Record = { en: "English", cy: "Cymraeg" };
+ const fields = [
+ {
+ key: "summaryLanguage",
+ label: "Summary language",
+ print: (value: unknown) => names[String(value)],
+ },
+ ];
+ expect(list({ summaryLanguage: "en" }, { summaryLanguage: "cy" }, fields)[0]).toMatchObject({
+ from: "English",
+ to: "Cymraeg",
+ });
+});
+
+it("reads a value that was never saved as Not set", () => {
+ expect(list({}, { maxMemories: 20 })[0]?.from).toBe("Not set");
+});
+
+it("refuses a request key that no field describes, so the dialog never omits a change", () => {
+ expect(() => list({ maxMemories: 10 }, { maxMemories: 20, other: 1 })).toThrow(
+ 'settingsChanges: no field describes "other"'
+ );
+});
diff --git a/web/tests/settings-confirm-retry.spec.tsx b/web/tests/settings-confirm-retry.spec.tsx
new file mode 100644
index 000000000..b5a33f6dc
--- /dev/null
+++ b/web/tests/settings-confirm-retry.spec.tsx
@@ -0,0 +1,86 @@
+import { beforeEach, expect, it } from "bun:test";
+import { byType, installReact, resetRender, settle, type Node } from "./space-kit.tsx";
+
+installReact();
+
+const { useSettingsConfirm } = await import("../src/hooks/useSettingsConfirm.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const STALE = "Close this dialog and save again, so it shows the current settings.";
+type Result = { success: boolean; error?: string };
+
+let ask: ReturnType["ask"];
+/** A card with nothing but the shared confirm: the spec asks through `ask`. */
+function Card() {
+ const confirm = useSettingsConfirm();
+ ask = confirm.ask;
+ return {confirm.dialog}
;
+}
+const own = [Card];
+const el = () => ;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+});
+
+function request(run: () => Promise) {
+ return { title: "Save?", body: "Body", confirmLabel: "Save", run };
+}
+
+it("turns confirm off after a failed run, so a retry cannot resend the values from the click", async () => {
+ let runs = 0;
+ await settle(el(), own);
+ ask(request(async () => (runs++, { success: false, error: "Config changed." })));
+ let tree = await settle(el(), own);
+ expect(dialogOf(tree)!.props.blocked).toBeUndefined();
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toEqual({
+ success: false,
+ error: "Config changed.",
+ });
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)!.props.blocked).toBe(STALE);
+ expect(runs).toBe(1);
+});
+
+it("starts the next question with confirm on again", async () => {
+ await settle(el(), own);
+ ask(request(async () => ({ success: false, error: "No." })));
+ let tree = await settle(el(), own);
+ await dialogOf(tree)!.props.onConfirm();
+ tree = await settle(el(), own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)).toBeUndefined();
+
+ ask(request(async () => ({ success: true })));
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)!.props.blocked).toBeUndefined();
+});
+
+it("does not block a follow-up question that the run asked", async () => {
+ await settle(el(), own);
+ ask(
+ request(async () => {
+ // As the External API card does when the key-file dialog takes over the click.
+ ask({ ...request(async () => ({ success: true })), title: "Replace the key file?" });
+ return { success: false, error: "" };
+ })
+ );
+ let tree = await settle(el(), own);
+ await dialogOf(tree)!.props.onConfirm();
+ tree = await settle(el(), own);
+ expect(dialogOf(tree)!.props.title).toBe("Replace the key file?");
+ expect(dialogOf(tree)!.props.blocked).toBeUndefined();
+});
+
+it("keeps the card's own blocked reason when nothing has failed", async () => {
+ await settle(el(), own);
+ ask({ ...request(async () => ({ success: true })), blocked: "The count could not be read." });
+ const tree = await settle(el(), own);
+ expect(dialogOf(tree)!.props.blocked).toBe("The count could not be read.");
+});
diff --git a/web/tests/skill-learning-confirm.spec.tsx b/web/tests/skill-learning-confirm.spec.tsx
new file mode 100644
index 000000000..749ebcee5
--- /dev/null
+++ b/web/tests/skill-learning-confirm.spec.tsx
@@ -0,0 +1,281 @@
+import { beforeEach, expect, it } from "bun:test";
+import { isValidElement } from "react";
+import {
+ allText,
+ byText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { SkillLearningSection, SkillLearningCard, Switch } =
+ await import("../src/lib/components/settings/SkillLearningSection.tsx");
+const { RecordPast, RecordPastView } = await import("../src/lib/components/skills/RecordPast.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Switch: SwitchControl } = await import("../src/lib/components/ui/switch.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { SettingsChangeList } =
+ await import("../src/lib/components/settings/SettingsChangeList.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [SkillLearningSection, SkillLearningCard, Switch, RecordPast, RecordPastView];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+/** The file answers every read with what the last save left, as the real one does. */
+let recording: boolean | undefined;
+let redact: boolean | undefined;
+let refusal: string | undefined;
+let startRefusal: string | undefined;
+let requests: Request[];
+
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ const edits = request.body.edits as Record;
+ if ("skillLearning" in edits) recording = edits.skillLearning;
+ if ("skillLearningRedact" in edits) redact = edits.skillLearningRedact;
+ }
+ if (request.path === "/api/skills/record-past")
+ return startRefusal
+ ? { status: 500, body: { success: false, error: startRefusal } }
+ : {
+ body: {
+ success: true,
+ data: {
+ job: { id: "j1", dryRun: false, state: "done", summary: { skillTurnsRecorded: 7 } },
+ },
+ },
+ };
+ if (request.path === "/api/skills/stats")
+ return {
+ body: {
+ success: true,
+ data: { turns: 340, fileSize: 2048, recording, redact: redact !== false },
+ },
+ };
+ return {
+ body: {
+ revision: "r1",
+ settings: {
+ skillLearning: { value: recording, globalValue: recording, source: "global" },
+ skillLearningRedact: { value: redact, globalValue: redact, source: "global" },
+ },
+ },
+ };
+};
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ recording = false;
+ redact = true;
+ refusal = undefined;
+ startRefusal = undefined;
+ requests = installFetch(reply);
+});
+
+/** The card's switches are the shared Switch: recording first, redaction second. */
+const switches = (tree: Node[]) => byType(tree, SwitchControl);
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** The change list inside a dialog body, which may hold more than the list. */
+function findList(node: unknown): Node | undefined {
+ if (Array.isArray(node)) return node.map(findList).find(Boolean);
+ if (!isValidElement(node)) return undefined;
+ if (node.type === SettingsChangeList) return node as Node;
+ return findList(node.props.children);
+}
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => findList(dialog.props.body)!.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+const recordStarts = () => requests.filter((request) => request.path === "/api/skills/record-past");
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
+
+it("asks before the recording switch saves, and the switch shows its saved value after Cancel", async () => {
+ let tree = await settle( , own);
+ switches(tree)[0]!.props.onCheckedChange(true);
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Turn on skill learning?");
+ expect(dialog.props.confirmLabel).toBe("Turn on");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "skillLearning", label: "Learn from skill use", from: "Off", to: "On" },
+ ]);
+ expect(patches()).toHaveLength(0);
+ // The switch shows the picked value while the dialog asks.
+ expect(switches(tree)[0]!.props.checked).toBe(true);
+
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(switches(tree)[0]!.props.checked).toBe(false);
+});
+
+it("sends the same body as before once the recording switch is confirmed", async () => {
+ let tree = await settle( , own);
+ switches(tree)[0]!.props.onCheckedChange(true);
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { skillLearning: true } });
+ // The reloaded snapshot now holds the saved value, so the switch stays on without a pending one.
+ expect(switches(tree)[0]!.props.checked).toBe(true);
+ expect(allText(tree)).toContain("Saved.");
+});
+
+it("asks before the recording switch turns off", async () => {
+ recording = true;
+ let tree = await settle( , own);
+ switches(tree)[0]!.props.onCheckedChange(false);
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)!.props.title).toBe("Turn off skill learning?");
+ expect(dialogOf(tree)!.props.confirmLabel).toBe("Turn off");
+ expect(rowsOf(dialogOf(tree)!)).toEqual([
+ { key: "skillLearning", label: "Learn from skill use", from: "On", to: "Off" },
+ ]);
+ expect(patches()).toHaveLength(0);
+});
+
+it("replaces the inline warning: turning redaction off asks in the dialog with the same warning", async () => {
+ let tree = await settle( , own);
+ // No inline question sits on the card before or after the click.
+ expect(allText(tree)).not.toContain("Stop removing private text and secrets?");
+ switches(tree)[1]!.props.onCheckedChange(false);
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Stop removing private text and secrets?");
+ expect(dialog.props.confirmLabel).toBe("Turn off");
+ expect(dialog.props.destructive).toBe(true);
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "skillLearningRedact",
+ label: "Hide private text in skill records",
+ from: "On",
+ to: "Off",
+ },
+ ]);
+ // The dialog carries the warning the inline callout used to carry.
+ expect(text(dialog.props.body)).toContain("New turns will be stored as written.");
+ expect(patches()).toHaveLength(0);
+
+ // Cancel leaves redaction on and the switch shows it.
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(patches()).toHaveLength(0);
+ expect(switches(tree)[1]!.props.checked).toBe(true);
+});
+
+it("turning redaction back on also asks, and confirm sends the same body", async () => {
+ redact = false;
+ let tree = await settle( , own);
+ switches(tree)[1]!.props.onCheckedChange(true);
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Remove private text and secrets?");
+ expect(dialog.props.confirmLabel).toBe("Turn on");
+ expect(dialog.props.destructive).toBeFalsy();
+ expect(rowsOf(dialog)).toEqual([
+ {
+ key: "skillLearningRedact",
+ label: "Hide private text in skill records",
+ from: "Off",
+ to: "On",
+ },
+ ]);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { skillLearningRedact: true } });
+ expect(switches(tree)[1]!.props.checked).toBe(true);
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle( , own);
+ switches(tree)[0]!.props.onCheckedChange(true);
+ tree = await settle( , own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+ // Cancel after the refusal puts the saved value back on the switch.
+ expect(switches(tree)[0]!.props.checked).toBe(false);
+});
+
+it("asks before Record past turns starts, with one sentence, and starts nothing on Cancel", async () => {
+ recording = true;
+ let tree = await settle( , own);
+ byText(tree, Button, "Record past turns")[0]!.props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Record past turns?");
+ expect(dialog.props.confirmLabel).toBe("Record past turns");
+ expect(text(dialog.props.body)).toContain(
+ "OMMS records skill turns from the past sessions of every set-up host, with no model call."
+ );
+ expect(recordStarts()).toHaveLength(0);
+
+ dialog.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(recordStarts()).toHaveLength(0);
+
+ byText(tree, Button, "Record past turns")[0]!.props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(recordStarts()).toHaveLength(1);
+ expect(allText(tree)).toContain("Recorded 7 past turns.");
+});
+
+it("keeps a refused Record past turns start inside the dialog, which stays open", async () => {
+ const reason = "The history could not be read. Try again.";
+ startRefusal = reason;
+ recording = true;
+ let tree = await settle( , own);
+ byText(tree, Button, "Record past turns")[0]!.props.onClick();
+ tree = await settle( , own);
+ const dialog = dialogOf(tree)!;
+
+ expect(await dialog.props.onConfirm()).toEqual({ success: false, error: reason });
+ tree = await settle( , own);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(dialogOf(tree)).toBeDefined();
+ expect(allText(tree)).toContain(reason);
+ expect(allText(tree)).not.toContain("Recorded 7 past turns.");
+
+ // The same dialog can try again.
+ startRefusal = undefined;
+ await dialogOf(tree)!.props.onConfirm();
+ dialogOf(tree)!.props.onClose();
+ await settle( , own);
+ expect(recordStarts()).toHaveLength(2);
+});
diff --git a/web/tests/skills-components.spec.tsx b/web/tests/skills-components.spec.tsx
index 112daa644..1a360979e 100644
--- a/web/tests/skills-components.spec.tsx
+++ b/web/tests/skills-components.spec.tsx
@@ -247,14 +247,14 @@ it("shows the recording warning and Record past turns when recording is on", ()
expect(html).toContain("Record past turns");
});
-it("shows the danger callout while redaction is off and a question before it turns off", () => {
+it("shows the danger callout while redaction is off, and asks nothing inline before it turns off", () => {
const off = card({ redact: false });
expect(off).toContain('data-tone="danger"');
expect(off).toContain("will be stored as written and sent to the external API");
expect(card()).not.toContain('data-tone="danger"');
- const asking = card({ confirm: "redact" });
- expect(asking).toContain("Stop removing private text and secrets?");
- expect(asking).toContain(">Turn off<");
+ // The shared confirm dialog asks before the switch turns off, not an inline callout.
+ expect(card()).not.toContain("Stop removing private text and secrets?");
+ expect(card()).not.toContain(">Turn off<");
});
it("states the count in the delete confirmation", () => {
diff --git a/web/tests/turn-on-confirm.spec.tsx b/web/tests/turn-on-confirm.spec.tsx
index 4521c36dc..e24c40d4b 100644
--- a/web/tests/turn-on-confirm.spec.tsx
+++ b/web/tests/turn-on-confirm.spec.tsx
@@ -1,7 +1,16 @@
import { beforeEach, expect, it } from "bun:test";
import { Button } from "../src/lib/components/ui/button";
+import { Switch } from "../src/lib/components/ui/switch";
import { setLanguage } from "../src/lib/i18n/index";
-import { allText, installReact, resetRender, settle, text, type Node } from "./space-kit.tsx";
+import {
+ allText,
+ byType,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+} from "./space-kit.tsx";
installReact();
const { TurnOnAction, TurnOnDialog } = await import("../src/lib/components/memory/TurnOnAction");
@@ -59,20 +68,24 @@ it("reads the question in Chinese and Arabic", async () => {
});
const { HostSettings } = await import("../src/lib/components/memory/HostSettings");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
function fakeBackfill(on: boolean, saves: Record[]) {
return {
snapshot: { settings: { autoBackfill: { globalValue: on } }, secrets: {} },
lists: {},
busy: false,
- save: async (edits: Record) => void saves.push(edits),
+ save: async (edits: Record) => {
+ saves.push(edits);
+ return { success: true };
+ },
saveModel: () => {},
} as never;
}
const autoImportBox = (tree: Node[]) =>
tree.find((node) => node.props.id === "memory-section-auto-import")!;
-const checkbox = (tree: Node[]) =>
- tree.find((node) => node.type === "input" && node.props.type === "checkbox")!;
+const checkbox = (tree: Node[]) => byType(tree, Switch)[0]!;
it("asks with the Turn on dialog before the settings checkbox turns automatic import on", async () => {
const saves: Record[] = [];
@@ -80,7 +93,7 @@ it("asks with the Turn on dialog before the settings checkbox turns automatic im
const views = [HostSettings, TurnOnDialog];
let tree = await settle(element, views);
expect(autoImportBox(tree)).toBeDefined();
- checkbox(tree).props.onChange({ target: { checked: true } });
+ checkbox(tree).props.onCheckedChange(true);
tree = await settle(element, views);
expect(saves).toHaveLength(0);
expect(allText(tree)).toContain("Turn on automatic import?");
@@ -90,20 +103,31 @@ it("asks with the Turn on dialog before the settings checkbox turns automatic im
expect(saves).toHaveLength(0);
expect(allText(tree)).not.toContain("Turn on automatic import?");
// Confirm saves once.
- checkbox(tree).props.onChange({ target: { checked: true } });
+ checkbox(tree).props.onCheckedChange(true);
tree = await settle(element, views);
buttons(tree, "Turn on").at(-1)!.props.onClick();
expect(allText(await settle(element, views))).not.toContain("Turn on automatic import?");
expect(saves).toEqual([{ autoBackfill: true }]);
});
-it("turns automatic import off from the settings checkbox at once, with no dialog", async () => {
+it("asks before the settings checkbox turns automatic import off, then saves the same edit", async () => {
const saves: Record[] = [];
const element = ;
const views = [HostSettings, TurnOnDialog];
let tree = await settle(element, views);
- checkbox(tree).props.onChange({ target: { checked: false } });
+ checkbox(tree).props.onCheckedChange(false);
tree = await settle(element, views);
+ expect(saves).toHaveLength(0);
+ const dialog = tree.find((node) => node.type === SettingsConfirmDialog)!;
+ expect(dialog.props.title).toBe("Turn automatic import off?");
+ // Cancel keeps the box ticked and saves nothing.
+ dialog.props.onClose();
+ tree = await settle(element, views);
+ expect(saves).toHaveLength(0);
+ expect(checkbox(tree).props.checked).toBe(true);
+ // Confirm saves the same edit as before the rule.
+ checkbox(tree).props.onCheckedChange(false);
+ tree = await settle(element, views);
+ await tree.find((node) => node.type === SettingsConfirmDialog)!.props.onConfirm();
expect(saves).toEqual([{ autoBackfill: false }]);
- expect(allText(tree)).not.toContain("Turn on automatic import?");
});
diff --git a/web/tests/web-app-confirm.spec.tsx b/web/tests/web-app-confirm.spec.tsx
new file mode 100644
index 000000000..4dd220ad2
--- /dev/null
+++ b/web/tests/web-app-confirm.spec.tsx
@@ -0,0 +1,125 @@
+import { beforeEach, expect, it } from "bun:test";
+import {
+ allText,
+ byType,
+ installFetch,
+ installReact,
+ resetRender,
+ settle,
+ text,
+ type Node,
+ type Request,
+} from "./space-kit.tsx";
+
+installReact();
+
+const { WebAppSection } = await import("../src/lib/components/settings/WebAppSection.tsx");
+const { Button } = await import("../src/lib/components/ui/button.tsx");
+const { Checkbox } = await import("../src/lib/components/ui/checkbox.tsx");
+const { SettingsConfirmDialog } =
+ await import("../src/lib/components/settings/SettingsConfirmDialog.tsx");
+const { setLanguage } = await import("../src/lib/i18n/index.ts");
+
+const own = [WebAppSection];
+const REFUSED = "Config changed. Reload settings and save again.";
+
+/** The file answers every read with what the last save left, as the real one does. */
+let autostart: boolean;
+let refusal: string | undefined;
+let requests: Request[];
+
+const reply = (request: Request) => {
+ if (request.method === "PATCH") {
+ if (refusal) return { status: 409, body: { error: refusal } };
+ autostart = request.body.edits.webServerAutoStart;
+ }
+ if (request.path === "/api/settings/web-autostart") return { body: { state: "installed" } };
+ if (request.path === "/api/settings/version")
+ return { body: { running: "4.3.2", global: null, relation: "missing" } };
+ return { body: { revision: "r1", settings: { webServerAutoStart: { globalValue: autostart } } } };
+};
+
+beforeEach(() => {
+ resetRender();
+ setLanguage("en");
+ autostart = true;
+ refusal = undefined;
+ requests = installFetch(reply);
+});
+
+const box = (tree: Node[]) => byType(tree, Checkbox)[0]!;
+const buttonOf = (tree: Node[], label: string) =>
+ byType(tree, Button).find((node) => text(node.props.children).trim() === label)!;
+const dialogOf = (tree: Node[]) => byType(tree, SettingsConfirmDialog)[0];
+/** What the dialog lists: one row per setting the save changes. */
+const rowsOf = (dialog: Node) => dialog.props.body.props.changes as unknown[];
+const patches = () => requests.filter((request) => request.method === "PATCH");
+/** Confirm the open dialog, then let it close as it does when the request succeeds. */
+async function confirm(tree: Node[]) {
+ const dialog = dialogOf(tree)!;
+ const result = await dialog.props.onConfirm();
+ dialog.props.onClose();
+ return result;
+}
+
+it("opens the dialog when Save is selected and sends nothing until the user confirms", async () => {
+ let tree = await settle( , own);
+ box(tree).props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+
+ const dialog = dialogOf(tree)!;
+ expect(dialog.props.title).toBe("Save web app settings?");
+ expect(dialog.props.confirmLabel).toBe("Save");
+ expect(rowsOf(dialog)).toEqual([
+ { key: "webServerAutoStart", label: "Start the web app at login", from: "On", to: "Off" },
+ ]);
+ expect(patches()).toHaveLength(0);
+ // The box shows the picked value while the dialog asks.
+ expect(box(tree).props.checked).toBe(false);
+});
+
+it("sends nothing on Cancel and keeps the change as a draft", async () => {
+ let tree = await settle( , own);
+ box(tree).props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+
+ expect(dialogOf(tree)).toBeUndefined();
+ expect(patches()).toHaveLength(0);
+ expect(allText(tree)).not.toContain("Saved.");
+ // The picked value stays, so Save can be used again.
+ expect(box(tree).props.checked).toBe(false);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+ await confirm(tree);
+ tree = await settle( , own);
+ expect(patches()).toHaveLength(1);
+ expect(patches()[0]!.body).toEqual({ revision: "r1", edits: { webServerAutoStart: false } });
+ expect(allText(tree)).toContain("Saved.");
+});
+
+it("keeps a server refusal inside the dialog, which stays open until the user decides", async () => {
+ refusal = REFUSED;
+ let tree = await settle( , own);
+ box(tree).props.onCheckedChange(false);
+ tree = await settle( , own);
+ buttonOf(tree, "Save").props.onClick();
+ tree = await settle( , own);
+
+ expect(await dialogOf(tree)!.props.onConfirm()).toMatchObject({ success: false, error: REFUSED });
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeDefined();
+ expect(patches()).toHaveLength(1);
+ // The reason sits in the dialog, which stays open, and on the card.
+ expect(allText(tree)).toContain(REFUSED);
+ expect(allText(tree)).not.toContain("Saved.");
+
+ dialogOf(tree)!.props.onClose();
+ tree = await settle( , own);
+ expect(dialogOf(tree)).toBeUndefined();
+});