diff --git a/CLAUDE.md b/CLAUDE.md index 245016ee..e69b1c66 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -186,7 +186,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **DeepSeek web UI** (`POST`/`GET`/`DELETE /api/deepseek/web`, `deepseek-web-server.ts`): the Run menu's "DeepSeek web UI..." entry supervises ONE background `dsh web` child process, deliberately **NOT a shell session**. ⚠️ Every piece is load-bearing: exactly one server (a second click REUSES it), restarted when the browser authority changes (`--trusted-host`, last asker wins), killed on shutdown via `stopDeepSeekWeb()` (the detached child would otherwise outlive Codeman and hold its port), and failures returned to the caller. ⚠️ Never hardcode the port: search from 3080 across 40, detect free ports by BINDING, then wait for the server to really answer. ⚠️ Both `POST` and `DELETE` must stay behind `canUsernameRunPrivilegedCommands` (booting a profile runs its plugin code; the server is shared). → [architecture-invariants#deepseek-web-ui](docs/architecture-invariants.md#deepseek-web-ui) -**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `/projects/` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`. +**Case rename** (`POST /api/cases/:name/rename`, `src/case-rename.ts`; `docs/wiki/Core-Concepts.md#case`): a case under the cases dir is its folder name and always moves; a linked case renames its alias and moves its real folder only with `renameFolder`; remote and Docker cases are refused. ⚠️ A folder that sessions have open is the hazard: live sessions at or under it make the route answer `409 requiresStop` with their names, and only `stopSessions: true` ends them (via `ctx.cleanupSession`: closed like a tab close, uploads included, nothing is restarted); the free-target pre-check runs before that and refuses a dangling symlink too (`lstat`, as `moveCaseFolder` does), so no session is ended for a move that cannot happen. `withCaseLock` holds the old and new paths for the whole operation (`isCasePathLocked`; the `Session` constructor throws for a working directory inside a held path, so nothing is constructed mid-move). ⚠️ A create awaits the owner's layout lock and a settings read between `new Session` and the server's map, where the rename looks for open sessions, so the constructor also records the session (`noteCaseSessionStarting`) until `registerSessionWithLayout()` or `stop()` settles it (30 s TTL for one that never registers), and a folder move refuses `409` with `renameCode: "BUSY"` while one is recorded at or under the folder (`isCaseSessionStarting`, checked in the same tick that takes the lock); an alias-only rename is not refused. A create whose path was validated before the move but whose `Session` is constructed after it is not covered (the plain check-then-use race of any create path), `moveCaseFolder` refuses an existing target itself (POSIX `rename` would silently replace an EMPTY directory) and retries `EBUSY`/`EPERM`/`EACCES` before answering `423 LOCKED`. If the registries (`linked-cases.json`, `caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`) fail after the move, `settings.json` and the folder are put back (a failed move-back says the folder is now at the new path), and an error after `stopSessions` carries `stoppedSessions`. Claude Code keys history by path (`claudeProjectDirName`: every non-alphanumeric becomes `-`), so `/projects/` is renamed too, or merged entry by entry, never overwriting, into one already at the new key (case delete never removes history, so an earlier case of the new name leaves one); other CLIs' history, Docker bind mounts, `git worktree` links, cron jobs' `workingDir`, Claude history of subfolder sessions and Claude Code's per-project entry in `~/.claude.json` (local-scope `mcpServers`, `allowedTools`, trust; writing another CLI's config is the opt-in MCP sync's job) are NOT migrated. The history scanner prefers the decoded project key over a transcript's `cwd` that no longer exists, so Resume follows a rename. Only an admin's rename touches the server-wide `settings.json` (`caseOrder`, `lastUsedCase`, `lastPickedCase`, `caseSettings`); the owner's default session group is carried across with `TabLayoutService`. `settings.json` is written before `linked-cases.json`, so a failed or refused registry write puts `settings.json` back and leaves the registry as it was. ⚠️ Every write to `linked-cases.json` (link, unlink, rename, and a create or clone into a custom folder) goes through `mutateLinkedCases()` (`src/web/linked-cases-writer.ts`: serialized, temp file + rename, and a file that does not parse is refused, never read as `{}`; the one direct writer is config-backup restore, `restoreConfigBackup()`, which must work on such a file), and a check that must still hold when the entry is written (the name is free; for a rename, the old entry still names the folder) runs INSIDE its callback: two clones that claimed one name used to both pass a re-read made outside it and both answer success. Pinned by `test/linked-cases-writer.test.ts`, and for a rename by `test/routes/case-rename-routes.test.ts`. **Custom Model Endpoint Profiles** (opt-in, `customModelEndpointsEnabled`, SYNCED, default OFF; `docs/custom-model-endpoints.md`): points a session at a user-configured OpenAI-compatible endpoint (store `custom-model-hosts.ts`, `~/.codeman/custom-model-hosts.json`, 0600). `authStyle` is `bearer` or `api-key`, never both headers (hangs the server). The per-CLI redirect is registry data, `capabilities.customModelInjection` (`env` / `configContentEnv` / `configDir` / `unsupported`), computed by the pure `custom-model-injection.ts`; ⚠️ `configDir` writes an isolated per-session config, NEVER the user's real `~/.codex`/`~/.pi`/`~/.omp`/grok config; the one exception is a recipe's `linkFromRealHome` (deepseek's `profiles`, `sessions`, `settings.yaml`), which symlinks those named entries back out of the real home so they survive the redirect. ⚠️ Claude applies via `Session.restartCli()` (a relaunch in the existing pane, so the conversation is pinned as `resumeSessionId`), the rest one-shot at launch; retired env keys must also be `setenv -u`'d (`_pendingEnvUnsets`), since tmux env survives `respawn-pane`. ⚠️ Remote/Docker sessions are refused (400). ⚠️ Persist only KEYS (`__customModel`), never values (they carry the API key); the one exception is `ownEnv`'s `homeEnvVar` entry, the session's OWN home path (absolute only: a `clis.json` override can name any variable there), which `setCustomModel()` puts back on clear and recovery clamps, since the selection overwrote the tmux `setenv` that held it. ⚠️ Every redirectable var must be in that CLI's `privilegedEnvKeys`, and `ANTHROPIC_*` stays out of claude's `allowedPrefixes`. ⚠️ The Run-menu picker builds entries from `window.__codemanCustomModelClis` (escaped via `escapeScriptJson()`), never a hardcoded CLI id list, and launches through `run()` via a temporary `_runMode` swap, never `setRunMode()`. ⚠️ Every write of `custom-model-hosts.json` goes through `mutateCustomModelHosts()` (`src/custom-model-hosts-writer.ts`: one at a time, temp file + rename, the route's check inside the callback, and a file that does not parse is refused with 409, never read as `[]` and replaced); the one direct writer is config-backup restore. The endpoint id `local-ollama` is reserved for the local model install (see Local model install). Pinned by `test/custom-model-hosts-writer.test.ts`. → [architecture-invariants#custom-model-endpoint-profiles](docs/architecture-invariants.md#custom-model-endpoint-profiles) @@ -265,7 +265,7 @@ The terminal provider scans `terminalLinkLine()`, which extends `terminalPathLin **Web tabs** (dashboard URLs as tabs): a saved URL renders as a tab beside sessions, **NOT a `SessionMode`**, and is proxied through Codeman's own origin (`/webview//...`). ⚠️ The proxy is NOT an API surface: its capability-based auth exemption stays fenced to safe methods and non-route paths (`test/webview-auth-exemption.test.ts`). ⚠️ Iframes omit `allow-same-origin` unless `trusted`, and `Authorization`/`codeman_session` are stripped upstream in both modes. ⚠️ **Egress guard**: link-local and cloud-metadata targets are refused at save time, by a sync hostname check at each connect (IP literals skip DNS), AND on the resolved address (`webview-egress.ts`); use the `undici` package's own `fetch` + `Agent`, never Node's global fetch. ⚠️ Loopback links in agent output auto-open as proxied web tabs (`openLinkThroughWebTabIfLoopback`), but never auto-route `*.localhost` (prompt-injectable DNS). Capabilities are revoked on logout (`revokeOwner`). → [architecture-invariants#web-tabs](docs/architecture-invariants.md#web-tabs), `docs/web-tabs.md` -**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md` +**Multi-user mode** (opt-in `--multiuser` / `CODEMAN_MULTIUSER=1`, OFF by default): named users with scrypt-hashed passwords in `~/.codeman/users.json`. Gated everywhere by `isMultiUserMode()`; when OFF, behavior is byte-identical to single-user because every scoping helper short-circuits. ⚠️ **Not a security boundary at the agent layer**: every session still runs as the SAME OS account. This separates WORKSPACES; it does not sandbox users (Docker cases are the isolation story). Ownership threads through `Session.owner` and is enforced in `findSessionOrFail`, list endpoints, SSE routing (fail-closed), WS, search, and file-preview. ⚠️ `settings.json` is ONE server-wide file, so every write to it is admin-only (`PUT /api/settings`, `/api/execution/model-config`, `/api/cases/order`, plus `PUT /api/config`: 403 `FORBIDDEN` before parsing), a non-admin's quick-start/Ralph start skips `lastUsedCase`, its GET hides `voiceSettings.apiKey`/`caseOrder`/`lastUsedCase`/`lastPickedCase`/`caseSettings` from a non-admin (`settingsForNonAdmin`), and the browser skips those writes for a non-admin via `_settingsReadOnly()` (settings-ui.js; also true once a write came back 403 `FORBIDDEN`, since `/api/me` can be slow or fail; their run mode and respawn presets stay per-device, `_applyOwnSettings`) (`test/routes/system-routes-settings-admin-only.test.ts`). System ops are admin-only too (`/api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate`, `/api/cleanup-state`), and a non-admin's `/api/auth/revoke` revokes only their own logins (`test/routes/system-routes-system-ops-admin-only.test.ts`). → [architecture-invariants#multi-user-mode](docs/architecture-invariants.md#multi-user-mode), `docs/multi-user-plan.md` **Away digest**: `GET /api/away-digest` aggregates what happened while you were away from the lifecycle log, run-summary events, live sessions, token stats, and recent subagents. Pure aggregator in `web/away-digest.ts`. ⚠️ Returns `{success:true,digest}`, a legacy raw-ish shape consistent with the other raw GET handlers in `system-routes.ts`; frontend and tests read `.digest`. → [architecture-invariants#away-digest](docs/architecture-invariants.md#away-digest) diff --git a/docs/api-reference.md b/docs/api-reference.md index e57e944f..a780b3a5 100644 --- a/docs/api-reference.md +++ b/docs/api-reference.md @@ -1595,12 +1595,12 @@ A local case whose folder is the top of a git repository can keep **worktrees** ## Settings -`~/.codeman/settings.json` is one file for the whole server: the synced App Settings (feature switches, the plan-usage collection switch `showPlanUsageLimits`, `runMode`, `respawnPresets`, `tunnelEnabled`, ...), plus `modelConfig`, `caseOrder` and `lastUsedCase`. Reads are open to every signed-in user; in multi-user mode a non-admin reads it without what is the admin's (`voiceSettings.apiKey`, the Deepgram key an admin saved, and the admin's case names in `caseOrder` and `lastUsedCase`). **In multi-user mode every write is admin only:** for a non-admin the routes below answer `403 FORBIDDEN` before the body is even validated, so nothing is written, no watcher is toggled and no tunnel is started. Single-user mode is unaffected. Every write to the file (these routes, and the `lastUsedCase` that `POST /api/quick-start` and `POST /api/ralph-loop/start` record before they answer) runs one at a time and replaces the file atomically (mode `0600`); the one write outside that queue is a config-backup restore, which must work on a file that does not parse. A write to a `settings.json` that exists but is not a JSON object is refused rather than starting from `{}`, which would erase every other setting: the routes below answer `409 CONFLICT` with a message naming the fix and leave the file untouched, the two starts skip their `lastUsedCase`, and an admin's `POST /api/cases/:name/rename` answers the same `409 CONFLICT`, checked before it ends any session or moves the folder. A missing or empty file still starts from `{}`. +`~/.codeman/settings.json` is one file for the whole server: the synced App Settings (feature switches, the plan-usage collection switch `showPlanUsageLimits`, `runMode`, `respawnPresets`, `tunnelEnabled`, ...), plus `modelConfig`, `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings`. Reads are open to every signed-in user; in multi-user mode a non-admin reads it without what is the admin's (`voiceSettings.apiKey`, the Deepgram key an admin saved, and the admin's case names in `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings`). **In multi-user mode every write is admin only:** for a non-admin the routes below answer `403 FORBIDDEN` before the body is even validated, so nothing is written, no watcher is toggled and no tunnel is started. Single-user mode is unaffected. Every write to the file (these routes, and the `lastUsedCase` that `POST /api/quick-start` and `POST /api/ralph-loop/start` record before they answer) runs one at a time and replaces the file atomically (mode `0600`); the one write outside that queue is a config-backup restore, which must work on a file that does not parse. A write to a `settings.json` that exists but is not a JSON object is refused rather than starting from `{}`, which would erase every other setting: the routes below answer `409 CONFLICT` with a message naming the fix and leave the file untouched, the two starts skip their `lastUsedCase`, and an admin's `POST /api/cases/:name/rename` answers the same `409 CONFLICT`, checked before it ends any session or moves the folder. A missing or empty file still starts from `{}`. | Method | Path | Body | Notes | | ------ | ----------------------------- | ------------------------------------ | ----- | -| `GET` | `/api/settings` | none | The stored settings object. Never writes. For a non-admin in multi-user mode, without `voiceSettings.apiKey`, `caseOrder` and `lastUsedCase`. | -| `PUT` | `/api/settings` | partial settings (strict schema) | Merged into the stored file; services (watchers, tunnel, tmux history limit) reconcile to the merged result. `403 FORBIDDEN` for a non-admin in multi-user mode. A tunnel enable with no login (no `CODEMAN_PASSWORD`, not multi-user) is refused separately (`403 OPERATION_FAILED`, resend with `acknowledgeUnauthTunnel: true`) unless the server runs with `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` or `--allow-unauthenticated-tunnel`. `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` does not count; when it is set, the refusal says so. An enable without that authorization is accepted only while the tunnel is already running and never stores `tunnelEnabled: true`; if the tunnel stops before the request would start it, it is not restarted and the answer is the same `403 OPERATION_FAILED` (the request's other settings are saved). | +| `GET` | `/api/settings` | none | The stored settings object. Never writes. For a non-admin in multi-user mode, without `voiceSettings.apiKey`, `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings`. | +| `PUT` | `/api/settings` | partial settings (strict schema) | Merged into the stored file; services (watchers, tunnel, tmux history limit) reconcile to the merged result. `caseSettings` (per-case run options, `{ [case]: { agentTeams, opusContext1m } }`) is merged per case inside the serialised writer, so devices saving different cases never overwrite each other; it is ignored while `syncCaseState` is not `true` and answers `400` past 500 cases. `403 FORBIDDEN` for a non-admin in multi-user mode. A tunnel enable with no login (no `CODEMAN_PASSWORD`, not multi-user) is refused separately (`403 OPERATION_FAILED`, resend with `acknowledgeUnauthTunnel: true`) unless the server runs with `CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL=1` or `--allow-unauthenticated-tunnel`. `CODEMAN_ALLOW_UNAUTHENTICATED_NETWORK` does not count; when it is set, the refusal says so. An enable without that authorization is accepted only while the tunnel is already running and never stores `tunnelEnabled: true`; if the tunnel stops before the request would start it, it is not restarted and the answer is the same `403 OPERATION_FAILED` (the request's other settings are saved). | | `GET` | `/api/tunnel/status` | none | `{ running, url, loginConfigured }`. `loginConfigured` is `true` when a login protects the server (`CODEMAN_PASSWORD` set or multi-user mode on), the same test the tunnel guard above applies; with `false` the browser asks before every tunnel enable. Neither opt-in variable makes it `true`. | | `GET` | `/api/execution/model-config` | none | `modelConfig` (cron's and the plan orchestrator's default model). | | `PUT` | `/api/execution/model-config` | `{ defaultModel?, agentTypeOverrides?, ... }` | Replaces `modelConfig`. `403 FORBIDDEN` for a non-admin in multi-user mode. | @@ -1609,7 +1609,7 @@ A local case whose folder is the top of a git repository can keep **worktrees** A non-admin's `POST /api/quick-start` and `POST /api/ralph-loop/start` work as before but do not record their case as `lastUsedCase` (a server-wide key). -`POST /api/cases/:name/rename` (body `{ newName, renameFolder?, stopSessions? }`, strict) renames a case. It is not one of the admin-only writes above: in multi-user mode a non-admin renames their own cases, and only the `settings.json` part is skipped for them. A case under the cases directory is its folder, so it always moves; a linked case renames its alias in `linked-cases.json` and moves its real folder (next to the old one, named `newName`) only with `renameFolder: true`. Remote and Docker cases are `400`. The new name must be free in every namespace the list merges (`409`). Live sessions whose working directory is at or inside the folder that would move make it `409` with `requiresStop: true` and `sessions: [{ id, name }]`; retry with `stopSessions: true` to end them first (they are closed as by `DELETE /api/sessions/:id`, nothing is restarted); another user's session is `403`. The folder is held by an in-process lock for the whole operation (an overlapping rename is `409 BUSY`, and `new Session` refuses a working directory inside it); a session that is still being created in the folder (constructed, not yet registered, so it can be neither listed nor stopped) makes a folder move `409` with `renameCode: "BUSY"` too, and a retry once it is registered lists it like any open session; the move is retried for a transient `EBUSY`/`EPERM`/`EACCES` and then answers `423` with `renameCode: "LOCKED"`, a cross-device move is `400`, and if the registries cannot be written afterwards `settings.json` and the folder are put back (when the folder cannot be moved back, the answer is `500` and says it is now at the new path). A failed write is `500`. A linked case's entry is checked again where it is written, after any folder move, and a refusal there puts everything back the same way: a new name linked since the first check is `409 ALREADY_EXISTS` with `renameCode: "EXISTS"`, an old entry unlinked or changed since then is `409 CONFLICT` with `renameCode: "BUSY"`, and a `linked-cases.json` that stopped being readable or a JSON object is `409 CONFLICT` with no `renameCode` (one already damaged when the rename starts reads as empty, so a linked name answers `404`). An error from the rename itself carries `stoppedSessions`: how many sessions it ended before it failed. On success the response is `{ oldName, newName, oldPath, newPath, folderMoved, stoppedSessions }`; `caseOrder` and `lastUsedCase` (in multi-user mode, by an admin's rename only), `linked-cases.json` and Claude Code's `projects/` history are updated (history already at the new path is merged into, never overwritten), and `case:renamed` is broadcast. A linked case is admin only in multi-user mode: for a non-admin the name is looked up in their own case space only (`404` when they have no case of that name). +`POST /api/cases/:name/rename` (body `{ newName, renameFolder?, stopSessions? }`, strict) renames a case. It is not one of the admin-only writes above: in multi-user mode a non-admin renames their own cases, and only the `settings.json` part is skipped for them. A case under the cases directory is its folder, so it always moves; a linked case renames its alias in `linked-cases.json` and moves its real folder (next to the old one, named `newName`) only with `renameFolder: true`. Remote and Docker cases are `400`. The new name must be free in every namespace the list merges (`409`). Live sessions whose working directory is at or inside the folder that would move make it `409` with `requiresStop: true` and `sessions: [{ id, name }]`; retry with `stopSessions: true` to end them first (they are closed as by `DELETE /api/sessions/:id`, nothing is restarted); another user's session is `403`. The folder is held by an in-process lock for the whole operation (an overlapping rename is `409 BUSY`, and `new Session` refuses a working directory inside it); a session that is still being created in the folder (constructed, not yet registered, so it can be neither listed nor stopped) makes a folder move `409` with `renameCode: "BUSY"` too, and a retry once it is registered lists it like any open session; the move is retried for a transient `EBUSY`/`EPERM`/`EACCES` and then answers `423` with `renameCode: "LOCKED"`, a cross-device move is `400`, and if the registries cannot be written afterwards `settings.json` and the folder are put back (when the folder cannot be moved back, the answer is `500` and says it is now at the new path). A failed write is `500`. A linked case's entry is checked again where it is written, after any folder move, and a refusal there puts everything back the same way: a new name linked since the first check is `409 ALREADY_EXISTS` with `renameCode: "EXISTS"`, an old entry unlinked or changed since then is `409 CONFLICT` with `renameCode: "BUSY"`, and a `linked-cases.json` that stopped being readable or a JSON object is `409 CONFLICT` with no `renameCode` (one already damaged when the rename starts reads as empty, so a linked name answers `404`). An error from the rename itself carries `stoppedSessions`: how many sessions it ended before it failed. On success the response is `{ oldName, newName, oldPath, newPath, folderMoved, stoppedSessions }`; `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings` (in multi-user mode, by an admin's rename only), `linked-cases.json` and Claude Code's `projects/` history are updated (history already at the new path is merged into, never overwritten), and `case:renamed` is broadcast. A linked case is admin only in multi-user mode: for a non-admin the name is looked up in their own case space only (`404` when they have no case of that name). ### System operations diff --git a/docs/multi-user-plan.md b/docs/multi-user-plan.md index f44902ff..f9652944 100644 --- a/docs/multi-user-plan.md +++ b/docs/multi-user-plan.md @@ -161,7 +161,7 @@ Codeman now ships a global **Startup Mode** picker (App Settings, Claude CLI tab | Screenshots `/api/screenshots` (deprecated) | Deprecated: removed in a later MAJOR, so no per-user subdir is planned; the replacement `POST /api/sessions/:id/paste-image` is already session-scoped. Former plan: per-user subdir `~/.codeman/screenshots//` in multi-user mode. Note: `GET /:name` deliberately rejects `/` in names as traversal, so derive the subdir server-side from `req.authUser` and keep client-visible names flat | | Attachments | Already session-scoped; inherits the session owner check. `attachmentConfineToWorkspace` is a global, default-OFF setting today: in multi-user mode it is FORCED ON for non-admins regardless of the setting (their attachments must resolve inside their own space); the setting keeps meaning what it means for admins | | File routes (browse/preview) | Path allowlist adds: non-admin paths must resolve (realpath) inside their own space or their own sessions' workingDirs | -| Settings (`settings.json`) | Global, admin-only writes in multi-user mode; reads allowed (per-device display keys stay in localStorage as today). **Implemented (1.42.0):** `PUT /api/settings`, `PUT /api/execution/model-config`, `PUT /api/config` and `PUT /api/cases/order` answer 403 `FORBIDDEN` to a non-admin before parsing anything; quick-start and Ralph loop start skip a non-admin's `lastUsedCase`; the browser skips those writes for a non-admin (`_settingsReadOnly()`, settings-ui.js) and keeps their own run mode and respawn presets on the device; a non-admin's `GET /api/settings` omits `voiceSettings.apiKey`, `caseOrder` and `lastUsedCase` (`settingsForNonAdmin`). Per-user server settings: out of scope v1| +| Settings (`settings.json`) | Global, admin-only writes in multi-user mode; reads allowed (per-device display keys stay in localStorage as today). **Implemented (1.42.0):** `PUT /api/settings`, `PUT /api/execution/model-config`, `PUT /api/config` and `PUT /api/cases/order` answer 403 `FORBIDDEN` to a non-admin before parsing anything; quick-start and Ralph loop start skip a non-admin's `lastUsedCase`; the browser skips those writes for a non-admin (`_settingsReadOnly()`, settings-ui.js) and keeps their own run mode and respawn presets on the device; a non-admin's `GET /api/settings` omits `voiceSettings.apiKey`, `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings` (`settingsForNonAdmin`). Per-user server settings: out of scope v1| | System ops (self-update, tunnel toggle, span-displays, docker image build) | Admin-only. **Implemented (1.42.0):** `POST /api/system/update`, `/api/system/span-displays`, `/api/tunnel/qr/regenerate` and `/api/cleanup-state` answer 403 `FORBIDDEN` to a non-admin; a non-admin's `POST /api/auth/revoke` revokes only their own login sessions and `GET /api/tunnel/info` lists only those | | `getLightState` init snapshot | Filtered per connection. Actual contents to filter (verified): `sessions`, `scheduledRuns`, `respawnStatus`, `subagents`, `workflowRuns`, `planUsage` (host-plan telemetry: admin-only); `globalStats` stays coarse-global. Cron jobs are NOT in the snapshot (they have their own REST route; filter there). The snapshot is cached process-wide (`LIGHT_STATE_CACHE_TTL_MS`): either key the cache per role/user or filter AFTER the cache on each send | diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index e2949177..39703ee3 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -230,7 +230,7 @@ on. Details: [Custom Model Endpoints](Custom-Model-Endpoints#a-model-that-runs-o | Bypass approvals and sandbox | Starts new Codex sessions with `--dangerously-bypass-approvals-and-sandbox`. Read [Agent CLIs](Agent-CLIs) before enabling. | | Allow network access | Starts new local Codex sessions (Run menu, Resume and the API; not scheduled jobs) with `sandbox_workspace_write.network_access=true`, so commands in Codex's workspace-write sandbox can use the network. The [Codeman Skill](Codeman-Skill) needs it to reach this server from a Codex session. It applies to every such session, and those commands can then call Codeman's API, which can start a session outside the sandbox with no approval prompt, even when a password is set: see [Security](Security#what-codeman-does-not-protect-against). It applies where Codex runs the folder in workspace-write (a project you trusted in Codex) and does not change Codex's sandbox mode: a folder Codex runs read-only keeps the network closed, and Codex asks for approval per command. Synced, off by default; forced off for users without the privileged-commands grant in multi-user mode. | | Animated status effects | Cosmetic. | -| Sync cases across devices | Keeps each case's **Agent Teams** and **Opus 1M** options on the server (`caseSettings` in `settings.json`) and, when you return to a tab, switches it to the case you last chose on another device. Synced, off by default. Without it each browser keeps its own options for a case (the case list itself is always shared). The case names are stored in the shared settings file, so a non-admin in multi-user mode neither reads, writes nor follows them. Each save sends only that case and the server merges it, so devices saving different cases never overwrite each other; a case renamed in Codeman keeps its options, and deleting or unlinking it removes them. A save the server refuses leaves the choice on that device and says so. If another device turns this off, this one stops following, and the server ignores case options sent while it is off. Turning it off leaves the stored options in `settings.json`, so turning it back on brings them back. A device that already has options for a case keeps them until a device changes that case's options while this is on. | +| Sync cases across devices | Keeps each case's **Agent Teams** and **Opus 1M** options on the server (`caseSettings` in `settings.json`) and, when you return to a tab, switches it to the case you last chose on another device. Synced, off by default. Without it each browser keeps its own options for a case (the case list itself is always shared). The case names are stored in the shared settings file, so a non-admin in multi-user mode neither reads, writes nor follows them. Each save sends only that case and the server merges it, so devices saving different cases never overwrite each other; a case renamed in Codeman keeps its options, and deleting or unlinking it removes them. A save the server refuses leaves the choice on that device only until the next sync, which brings the server's copy back, and says so. Only a case picked in a case picker is followed, not one a quick-start or an agent's spawned worker used. If another device turns this off, this one stops following, and the server ignores case options sent while it is off. Turning it off leaves the stored options in `settings.json`, so turning it back on brings them back. A device that already has options for a case keeps them until a device changes that case's options while this is on. | | MCP server sync | Copies the MCP servers each installed, enabled CLI (Claude, Codex, Gemini, OpenCode, Antigravity) and GitHub Copilot CLI has into the others' own config files. Synced, off by default, admin only in multi-user mode. Turn it on and **Apply** or **Save** (Apply keeps Settings open), then **Preview** shows what would change and **Sync now** applies it. It only adds missing servers, keeps the previous file as `.codeman-bak`, and leaves a file that receives env values or headers readable by you only. A config dir moved by `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, `XDG_CONFIG_HOME`, `GEMINI_CLI_HOME` or `COPILOT_HOME` in Codeman's own environment is followed. | ### Notifications diff --git a/src/config-backup.ts b/src/config-backup.ts index e3425dc9..320b7fa9 100644 --- a/src/config-backup.ts +++ b/src/config-backup.ts @@ -226,7 +226,7 @@ const VOLATILE_KEYS: Readonly> = { // per user), a session started in another case, every captured prompt, and a Docker case's // conversation id after a /clear, and a web tab being opened. 'users.json': ['lastLoginAt'], - 'settings.json': ['lastUsedCase'], + 'settings.json': ['lastUsedCase', 'lastPickedCase'], 'intents.json': ['recentPrompts', 'updatedAt'], 'docker-cases.json': ['lastClaudeSessionId'], 'webviews.json': ['lastOpenedAt'], diff --git a/src/web/public/session-ui.js b/src/web/public/session-ui.js index ff5aea9c..aefd27fa 100644 --- a/src/web/public/session-ui.js +++ b/src/web/public/session-ui.js @@ -644,10 +644,13 @@ Object.assign(CodemanApp.prototype, { // PUT is admin-only (403), so it is not sent (_settingsReadOnly, settings-ui.js). if (this._settingsReadOnly?.()) return; try { + // lastPickedCase is only what a person chose on a device (never a quick-start or an agent's spawn), + // so it is what other devices follow when case sync is on. + const body = this._caseStateSyncOn?.() ? { lastUsedCase: caseName, lastPickedCase: caseName } : { lastUsedCase: caseName }; await fetch('/api/settings', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ lastUsedCase: caseName }) + body: JSON.stringify(body) }); } catch (err) { console.error('Failed to save last used case:', err); @@ -3706,18 +3709,6 @@ Object.assign(CodemanApp.prototype, { return this._caseSyncChain; }, - /** Why a settings write did not land, or '' when it did (HTTP status and the response's own error both count). */ - async _caseSyncError(res) { - if (!res) return 'the server could not be reached'; - let body = null; - try { - body = await (typeof res.clone === 'function' ? res.clone() : res).json(); - } catch { /* not JSON: the status is all there is */ } - if (!res.ok) return body?.error || `HTTP ${res.status}`; - if (body && (body.success === false || body.error)) return body.error || 'the server refused it'; - return ''; - }, - async _pushCaseSettings(caseName, entry) { let res = null; try { @@ -3729,10 +3720,8 @@ Object.assign(CodemanApp.prototype, { } catch (err) { console.error('Failed to sync case settings:', err); } - // The admin-only refusal marks this page read-only (settings-ui.js), so nothing more is sent from it. - if (await this._noteSettingsWriteRefusal?.(res)) return; - const error = await this._caseSyncError(res); - if (error) this.showToast?.(`Options for "${caseName}" saved on this device, not synced: ${error}`, 'warning'); + // A refusal or failure keeps the choice on this device only until the next sync brings the server's copy back. + await this._noteSettingsWriteResult?.(res, `Options for "${caseName}" (until the next sync)`); }, /** Server copy wins, except for a case this device is still saving: write its options into the local keys getCaseSettings() reads. */ @@ -3741,13 +3730,24 @@ Object.assign(CodemanApp.prototype, { // A non-admin never receives the map (the server redacts it) and must not apply one it was handed. if (this._settingsReadOnly?.()) return; try { + let changed = false; for (const [name, s] of Object.entries(server.caseSettings)) { if (!s || typeof s !== 'object' || this._caseSyncPending?.has(name)) continue; - localStorage.setItem('caseSettings_' + name, JSON.stringify({ agentTeams: s.agentTeams === true, opusContext1m: s.opusContext1m === true })); + const next = JSON.stringify({ agentTeams: s.agentTeams === true, opusContext1m: s.opusContext1m === true }); + if (localStorage.getItem('caseSettings_' + name) === next) continue; + localStorage.setItem('caseSettings_' + name, next); + changed = true; } + // An open popover still shows the options it was filled with: closing it keeps a tick from writing them into another case. + if (changed) this._closeCaseSettingsPopovers(); } catch { /* storage blocked: this device keeps what it has */ } }, + _closeCaseSettingsPopovers() { + document.getElementById('caseSettingsPopover')?.classList.add('hidden'); + document.getElementById('caseSettingsPopoverMobile')?.classList.add('hidden'); + }, + /** The server decides whether sync is on: when it says otherwise, this device's cached switch follows it. */ _adoptServerCaseSyncPreference(server) { if (typeof server?.syncCaseState !== 'boolean') return; @@ -3773,12 +3773,10 @@ Object.assign(CodemanApp.prototype, { if (server.syncCaseState !== true) return; this._applyServerCaseSettings(server); const select = document.getElementById('quickStartCase'); - const last = server.lastUsedCase; + const last = server.lastPickedCase; if (select && last && last !== select.value && this.cases?.some((c) => c.name === last)) { - select.value = last; - this.updateDirDisplayForCase(last); - this.updateMobileCaseLabel(last); - this.updateCasePickerInput(last); + this._closeCaseSettingsPopovers(); + this.selectQuickStartCase(last, { save: false }); } } catch { /* offline: try again next time the tab is shown */ } }, diff --git a/src/web/routes/case-routes.ts b/src/web/routes/case-routes.ts index 5d8033ea..4bcaaed4 100644 --- a/src/web/routes/case-routes.ts +++ b/src/web/routes/case-routes.ts @@ -2024,6 +2024,7 @@ export function registerCaseRoutes( // The settings.json values this rename replaced, set only once it wrote them. A failure puts back // these keys alone, so a settings save that landed in between is kept. let settingsUndo: Record | undefined; + let sharedRenamed = false; try { // settings.json is server-wide and caseOrder/lastUsedCase name the admin's cases, so only the // admin's rename touches it (a non-admin's own rename must not rewrite someone else's list). @@ -2032,19 +2033,24 @@ export function registerCaseRoutes( const { before, after } = await mutateSettingsFile((existing) => { const order = renameInOrder(existing.caseOrder, name, newName); const last = existing.lastUsedCase === name ? newName : undefined; + const picked = existing.lastPickedCase === name ? newName : undefined; // The shared run options (syncCaseState) follow the case to its new name. const shared = renameCaseSettings(existing.caseSettings, name, newName); - if (!order && !last && !shared) return undefined; + if (!order && !last && !picked && !shared) return undefined; return { ...existing, ...(order ? { caseOrder: order } : {}), ...(last ? { lastUsedCase: last } : {}), + ...(picked ? { lastPickedCase: picked } : {}), ...(shared ? { caseSettings: shared } : {}), }; }); if (after) { - const keys = ['caseOrder', 'lastUsedCase', 'caseSettings'].filter((k) => after[k] !== before[k]); + // caseSettings is undone by renaming its entry back (below), not by restoring the whole map, so a + // per-case save from another device that landed since is kept. + const keys = ['caseOrder', 'lastUsedCase', 'lastPickedCase'].filter((k) => after[k] !== before[k]); settingsUndo = Object.fromEntries(keys.map((k) => [k, before[k]])); + sharedRenamed = after.caseSettings !== before.caseSettings; } } if (isLinked) { @@ -2065,7 +2071,12 @@ export function registerCaseRoutes( // The folder moved but the registries did not follow: put settings.json and the folder back // rather than leave a case whose name and folder disagree. const undo = settingsUndo; - if (undo) await mutateSettingsFile((current) => ({ ...current, ...undo })).catch(() => {}); + if (undo) { + await mutateSettingsFile((current) => { + const back = sharedRenamed ? renameCaseSettings(current.caseSettings, newName, name) : null; + return { ...current, ...undo, ...(back ? { caseSettings: back } : {}) }; + }).catch(() => {}); + } if (moveFolder) { const movedBack = await fs.rename(newPath, oldPath).then( () => true, diff --git a/src/web/routes/system-routes.ts b/src/web/routes/system-routes.ts index 8b662a7a..85cfffa1 100644 --- a/src/web/routes/system-routes.ts +++ b/src/web/routes/system-routes.ts @@ -161,7 +161,7 @@ export function resolveSpanUrl(hostHeader: string | undefined, fallbackPort = '3 * What GET /api/settings answers a NON-ADMIN in multi-user mode: settings.json minus what * belongs to the server's admin rather than to the reader. `voiceSettings.apiKey` is the * Deepgram key an admin saved, a credential (the reader's browser seeded it into its own - * voice config and dictated on the admin's account); `caseOrder`, `lastUsedCase` and `caseSettings` name + * voice config and dictated on the admin's account); `caseOrder`, `lastUsedCase`, `lastPickedCase` and `caseSettings` name * the admin's cases. Everything else stays readable, because the page reads the synced feature * switches from it. Writes are admin-only there (PUT /api/settings). Exported for unit testing. */ @@ -170,6 +170,7 @@ export function settingsForNonAdmin(settings: unknown): unknown { const out: Record = { ...(settings as Record) }; delete out.caseOrder; delete out.lastUsedCase; + delete out.lastPickedCase; delete out.caseSettings; const voice = out.voiceSettings; if (voice && typeof voice === 'object' && !Array.isArray(voice) && 'apiKey' in voice) { diff --git a/src/web/schemas.ts b/src/web/schemas.ts index aa50cb63..33732e03 100644 --- a/src/web/schemas.ts +++ b/src/web/schemas.ts @@ -1461,6 +1461,8 @@ export const SettingsUpdateSchema = z defaultClaudeMdPath: z.string().max(500).optional(), defaultWorkingDir: z.string().max(500).optional(), lastUsedCase: z.string().max(200).optional(), + /** The case a person last picked in a case picker; what other devices follow while `syncCaseState` is on. */ + lastPickedCase: z.string().max(200).optional(), /** * Opt-in, SYNCED, default OFF: per-case run options (Agent Teams, Opus 1M) are kept here instead of * only in each browser, and a device follows the selected case another device chose. diff --git a/test/sync-case-state-server.test.ts b/test/sync-case-state-server.test.ts index e01b037e..dae78644 100644 --- a/test/sync-case-state-server.test.ts +++ b/test/sync-case-state-server.test.ts @@ -94,10 +94,16 @@ describe('shared case options', () => { const oldName = caseName(); const newName = caseName(); mkdirSync(join(getCasesDir(), oldName), { recursive: true }); - seed({ syncCaseState: true, caseOrder: [oldName], caseSettings: { [oldName]: on, keep: off } }); + seed({ + syncCaseState: true, + caseOrder: [oldName], + lastPickedCase: oldName, + caseSettings: { [oldName]: on, keep: off }, + }); const renamed = await send('POST', `/api/cases/${oldName}/rename`, { newName }); expect(renamed.body.success).toBe(true); expect(readSettings().caseSettings).toEqual({ [newName]: on, keep: off }); + expect(readSettings().lastPickedCase).toBe(newName); const deleted = await send('DELETE', `/api/cases/${newName}`); expect(deleted.body.success).toBe(true); expect(readSettings().caseSettings).toEqual({ keep: off }); @@ -110,6 +116,7 @@ describe('what a non-admin is given', () => { syncCaseState: true, caseOrder: ['a'], lastUsedCase: 'a', + lastPickedCase: 'a', caseSettings: { a: on }, agentSkillEnabled: true, }); diff --git a/test/sync-case-state.test.ts b/test/sync-case-state.test.ts index 0fb48d35..a35f1d94 100644 --- a/test/sync-case-state.test.ts +++ b/test/sync-case-state.test.ts @@ -9,6 +9,8 @@ import vm from 'node:vm'; import { SettingsUpdateSchema } from '../src/web/schemas.js'; const SRC = readFileSync(new URL('../src/web/public/session-ui.js', import.meta.url), 'utf-8'); +// The real write-result handling the case sync reuses (a toast for a failed save, read-only after a 403). +const SETTINGS_SRC = readFileSync(new URL('../src/web/public/settings-ui.js', import.meta.url), 'utf-8'); type Reply = { status?: number; body?: unknown } | 'throw'; type Handler = (url: string, init?: { method?: string; body?: string }) => Reply | Promise; @@ -18,11 +20,16 @@ function makeApp(settings: Record, onFetch: Handler = () => ({ const calls: { method: string; body: unknown }[] = []; const toasts: string[] = []; const select = { value: 'alpha' }; + const hidden = new Set(); + const popover = (id: string) => ({ classList: { add: (c: string) => c === 'hidden' && void hidden.add(id) } }); function CodemanApp(this: unknown) {} const ctx = vm.createContext({ CodemanApp, window: {}, - document: { getElementById: () => select, addEventListener: () => {} }, + document: { + getElementById: (id: string) => (id.startsWith('caseSettingsPopover') ? popover(id) : select), + addEventListener: () => {}, + }, localStorage: { getItem: (k: string) => store.get(k) ?? null, setItem: (k: string, v: string) => void store.set(k, v), @@ -38,6 +45,7 @@ function makeApp(settings: Record, onFetch: Handler = () => ({ console, }); vm.runInContext(SRC, ctx); + vm.runInContext(SETTINGS_SRC, ctx); const app = Object.create((CodemanApp as unknown as { prototype: object }).prototype) as Record; app.loadAppSettingsFromStorage = () => settings; app.saveAppSettingsToStorage = (s: Record) => Object.assign(settings, s); @@ -46,7 +54,8 @@ function makeApp(settings: Record, onFetch: Handler = () => ({ app.updateDirDisplayForCase = () => {}; app.updateMobileCaseLabel = () => {}; app.updateCasePickerInput = () => {}; - return { app, store, calls, toasts, select, settings }; + app.closeCasePicker = () => {}; + return { app, store, calls, toasts, select, settings, hidden }; } const settle = () => new Promise((r) => setTimeout(r, 0)); @@ -103,7 +112,6 @@ describe('saving a case', () => { it.each([ ['an HTTP 500', { status: 500, body: { success: false, error: 'boom' } }], - ['a refusal answered with HTTP 200', { body: { success: false, error: 'settings.json is not valid' } }], ['a dropped connection', 'throw' as const], ])('keeps the local choice and says it was not synced after %s', async (_label, reply) => { const { app, store, toasts } = makeApp({ syncCaseState: true }, () => reply as Reply); @@ -111,7 +119,8 @@ describe('saving a case', () => { await app._caseSyncChain; expect(JSON.parse(store.get('caseSettings_demo')!)).toEqual(entry); expect(toasts).toHaveLength(1); - expect(toasts[0]).toContain('not synced'); + expect(toasts[0]).toContain('not on the server'); + expect(toasts[0]).toContain('until the next sync'); }); it('hands an admin-only refusal to the read-only handling, without a toast', async () => { @@ -130,6 +139,17 @@ describe('saving a case', () => { }); }); +describe('recording the picked case', () => { + it('writes lastPickedCase with lastUsedCase only while sync is on', async () => { + const on = makeApp({ syncCaseState: true }); + await on.app.saveLastUsedCase('beta'); + expect(on.calls[0].body).toEqual({ lastUsedCase: 'beta', lastPickedCase: 'beta' }); + const off = makeApp({}); + await off.app.saveLastUsedCase('beta'); + expect(off.calls[0].body).toEqual({ lastUsedCase: 'beta' }); + }); +}); + describe('taking the server copy', () => { const server = { syncCaseState: true, caseSettings: { demo: entry } }; @@ -170,7 +190,7 @@ describe('returning to the tab', () => { it('follows the selected case and the options while sync is on', async () => { const { app, select, store } = makeApp({ syncCaseState: true }, () => - env({ syncCaseState: true, lastUsedCase: 'beta', caseSettings: { beta: entry } }) + env({ syncCaseState: true, lastPickedCase: 'beta', caseSettings: { beta: entry } }) ); await app._syncCaseStateFromServer(); expect(select.value).toBe('beta'); @@ -179,7 +199,7 @@ describe('returning to the tab', () => { it('stops following when another device turned sync off, and the cached switch follows the server', async () => { const { app, select, store, settings } = makeApp({ syncCaseState: true }, () => - env({ syncCaseState: false, lastUsedCase: 'beta', caseSettings: { beta: entry } }) + env({ syncCaseState: false, lastPickedCase: 'beta', caseSettings: { beta: entry } }) ); await app._syncCaseStateFromServer(); expect(select.value).toBe('alpha'); @@ -188,6 +208,28 @@ describe('returning to the tab', () => { expect(app._caseStateSyncOn()).toBe(false); }); + it('does not follow a case a quick-start or an agent started, only one picked in a picker', async () => { + const { app, select } = makeApp({ syncCaseState: true }, () => + env({ syncCaseState: true, lastUsedCase: 'beta', lastPickedCase: 'alpha' }) + ); + await app._syncCaseStateFromServer(); + expect(select.value).toBe('alpha'); + }); + + it('closes an open case-options popover when the follow or an import changes what it shows', async () => { + const followed = makeApp({ syncCaseState: true }, () => env({ syncCaseState: true, lastPickedCase: 'beta' })); + await followed.app._syncCaseStateFromServer(); + expect([...followed.hidden].sort()).toEqual(['caseSettingsPopover', 'caseSettingsPopoverMobile']); + const imported = makeApp({ syncCaseState: true }, () => + env({ syncCaseState: true, caseSettings: { alpha: entry } }) + ); + await imported.app._syncCaseStateFromServer(); + expect(imported.hidden.size).toBe(2); + const unchanged = makeApp({ syncCaseState: true }, () => env({ syncCaseState: true, lastPickedCase: 'alpha' })); + await unchanged.app._syncCaseStateFromServer(); + expect(unchanged.hidden.size).toBe(0); + }); + it('asks for nothing on a tab return while this device has sync off', async () => { const { app, select, calls } = makeApp({}, () => env({ syncCaseState: true, lastUsedCase: 'beta' })); await app._syncCaseStateFromServer();