Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(search): opt-in include-archived so archived sessions stay findable (#1089)

Qi Qi807d1eee27e9
diff --git a/core/services/sessions.py b/core/services/sessions.py
index 77fb0d810..2b3f84878 100644
--- a/core/services/sessions.py
+++ b/core/services/sessions.py
@@ -37,6 +37,7 @@ from typing import Optional
from config import paths
from storage.workbench_sessions_service import (
+ SessionArchivedError,
SessionBackendLockedError,
archive_session,
backfill_session_title,
@@ -53,8 +54,11 @@ from storage.workbench_sessions_service import (
touch_session,
update_session,
)
+from vibe.i18n import t as i18n_t
__all__ = [
+ "SESSION_ARCHIVED_I18N_KEY",
+ "SessionArchivedError",
"SessionBackendLockedError",
"archive_session",
"backfill_session_title",
@@ -68,6 +72,7 @@ __all__ = [
"list_sessions_page",
"reset_running_agent_status",
"set_agent_status",
+ "session_archived_message",
"touch_session",
"update_session",
"reserve_agent_session",
@@ -75,6 +80,38 @@ __all__ = [
]
+# --- Localized copy for the terminal-archive refusal ------------------
+#
+# ``SessionArchivedError`` carries a developer-facing sentence (it names the
+# session id), but the ``message`` a route puts in its 409 body is USER-visible:
+# direct API/CLI consumers read it verbatim, and a Web UI client that lacks the
+# ``errors.session_archived`` translation renders it as the fallback. So it has to
+# come from ``vibe/i18n`` rather than an English literal at the route (AGENTS.md
+# §6). Shaped exactly like ``core.show_session_events.localized_show_event_error``:
+# a module-level key constant beside the error it describes (so the parity guard in
+# ``tests/test_i18n_backend_keys.py`` can pin it) plus a factory that resolves the
+# user's configured language and degrades to English if the config is unreadable.
+SESSION_ARCHIVED_I18N_KEY = "error.sessionArchived"
+
+
+def session_archived_message(lang: Optional[str] = None) -> str:
+ """User-facing copy for a write refused because the session is archived.
+
+ ``lang`` defaults to the configured UI language; an unreadable/missing config
+ (a brand-new install, a partially-written file) falls back to English rather
+ than failing the response.
+ """
+
+ if not lang:
+ from config.v2_config import V2Config
+
+ try:
+ lang = V2Config.load().language
+ except Exception:
+ lang = "en"
+ return i18n_t(SESSION_ARCHIVED_I18N_KEY, lang)
+
+
# --- Reservation helpers (IM-style scope_key + session_anchor) --------
#
# These wrap the legacy ``SQLiteSessionsService`` methods so the CLI and
diff --git a/docs/plans/workbench-search-include-archived.md b/docs/plans/workbench-search-include-archived.md
new file mode 100644
index 000000000..8c3aaafda
--- /dev/null
+++ b/docs/plans/workbench-search-include-archived.md
@@ -0,0 +1,884 @@
+# Workbench search: opt-in "Include archived"
+
+Issue: https://github.com/avibe-bot/avibe/issues/1082
+Branch: `feat/search-include-archived`
+
+## Background
+
+Archived sessions are currently unfindable. `search_messages()` hard-excludes them at
+`storage/messages_service.py:291` (`.where(agent_sessions.c.status != "archived")`), so global
+message search never returns them. The transcript still exists, the API still serves it, and
+`ChatPage` still renders it — there is simply no way to find it. The only route back in is typing
+`/chat/<id>` by hand, which requires already knowing the id.
+
+Archive is also the only way to clear a session out of the sidebar, so it doubles as "I'm done with
+this, get it out of my way" — a routine action. Every routine archive therefore drops a transcript
+out of reach.
+
+## Goal
+
+Add an **opt-in** `include archived` flag to Workbench search. Default behaviour stays
+byte-identical to today. When enabled, archived sessions appear in results, are visually marked,
+and open **read-only**.
+
+**Hard constraint:** the terminal-archive invariant is untouched. No un-archive, restore, resume, or
+fork. `archive_session()` unchanged. `tests/test_session_archive.py` must pass unmodified.
+
+## Resolved design decisions
+
+1. **One boolean `include_archived`, session dimension only.** It lifts only
+ `agent_sessions.status != 'archived'` (`messages_service.py:291`). The archived-**project**
+ exclusion (`scope_settings.enabled = 0`, `:296`) stays unconditional: project archive is
+ reversible (implicit un-archive at `storage/projects_service.py:224-230`) and has its own restore
+ flow. Documented in the docstring; a second flag can be added later without breaking this one.
+2. **Boolean, not tri-state.** "Archived only" has no demonstrated use case. Use the `Switch`
+ primitive, not `SegmentedRadio`.
+3. **Not sticky.** Mobile `SearchPage` carries it in the URL (`?archived=1`, mirroring the existing
+ `?q=` back-nav contract at `SearchPage.tsx:26-51`); the desktop palette resets it off on every
+ open (it already resets the query in `onOpenAutoFocus`, `SearchPalette.tsx:137`). An opt-in that
+ silently persists would violate "default byte-identical".
+4. **Keep the `visibility == 'foreground'` filters unchanged** in both `search_messages` (`:292`)
+ and `list_sessions` (`workbench_sessions_service.py:142`). `archive_session` never touches
+ `visibility` (`:957-966`), so archived rows stay `foreground` and pass the filter; background rows
+ are internal and must stay hidden. No title/content inconsistency arises.
+5. **No title-search backend change.** `SearchPalette` and `SearchPage` do server *content* search
+ (`useMessageSearch`) plus client-side app-registry filtering (`search/appSearch.ts`); they never
+ call `/api/sessions?q=`. That param serves the composer `#`-mention (`ui_server.py:6130-6131`),
+ which must keep excluding archived — you cannot reference an archived session into a new turn.
+6. **Include the `update_session` archived guard in this PR.** Small, and it is the server-side
+ backstop the read-only UI depends on. New `SessionArchivedError` raised in the service, mapped to
+ a `409` carrying code `session_archived` in the PATCH route — same status and code as the
+ messages-POST semantics at `ui_server.py:7713`, but in the structured error *body* (see round 4b;
+ the flat body those routes use is unreadable to the Web UI's error parser). CLI is already safe
+ (`vibe/cli.py:5118` calls `get_active_session` first).
+7. **Read-only composer via the existing `disabled`/`placeholder` props** (`Composer.tsx:105-108`),
+ not a replacement notice bar — smaller diff, reuses the busy-placeholder pattern at `:591`.
+8. **New chat-scoped i18n for the 409.** Leave `errors.session_archived` (`en.json:993`) untouched —
+ it is consumed by the global `handleApiError` mapper (`ApiContext.tsx:1921`) and its copy is
+ Show-Page-specific. Re-affirmed in round 4b, where the PATCH 409 started actually resolving that
+ key: the wording is imprecise for a rename but still states the real reason, and generalizing a
+ string shared with every Show Page mutation is a separate call.
+
+## Work items
+
+### 1. `search_messages` flag + `archived` field — `storage/messages_service.py`
+
+- `search_messages()` (`:227`): add kwarg `include_archived: bool = False`.
+- Make the filter at `:291` conditional: `if not include_archived:` add the
+ `status != "archived"` predicate. All other `.where` clauses unchanged.
+- Add `agent_sessions.c.status` to the select (`:268-280`) and `"archived": row["status"] ==
+ "archived"` to the session bucket (`:312-318`). Always present (additive; `False` in default mode).
+- Docstring (`:235-259`): state the flag, and that archived-**project** exclusion is deliberate and
+ unconditional.
+
+Tests in the same commit — `tests/test_message_search.py` (`_seed_session(..., status="archived")`
+already exists at `:40`):
+
+- `test_search_include_archived_returns_archived_session` — archived matches surface with
+ `archived: True`; active groups carry `archived: False`.
+- `test_search_include_archived_still_excludes_archived_project_scope` — mirror
+ `test_search_excludes_archived_project_scope` (`:266`).
+- `test_search_include_archived_still_excludes_background_visibility`.
+- Extend `test_search_excludes_archived_session` (`:249`) to also assert `archived is False` on
+ returned groups. Do not weaken it.
+
+### 2. Route: `GET /api/search/messages` — `vibe/ui_server.py:6830-6851`
+
+- Parse `include_archived = request.args.get("include_archived") in {"1", "true", "yes"}` — same
+ idiom as `:5728` and `:6158`.
+- Pass `include_archived=include_archived` at `:6850`.
+- Fix the docstring at `:6834-6836` ("excluding archived sessions" → "archived sessions excluded by
+ default; `include_archived=1` opts in").
+- Cheap addition: route test in `tests/test_ui_server_fastapi.py` (no `/api/search` coverage today)
+ asserting param plumb-through for `0`/`1`.
+
+### 3. Archived guard on `update_session` + PATCH 409
+
+- `storage/workbench_sessions_service.py`: define `class SessionArchivedError(Exception)` near
+ `SessionBackendLockedError`. In `update_session` (`:392`), add `agent_sessions.c.status` to the
+ `existing` select (`:408-417`) and raise `SessionArchivedError(session_id)` when
+ `existing.status == "archived"`, immediately after the `None`/404 check at `:418-419`.
+- `core/services/sessions.py`: re-export it (imports `:46-54`, `__all__` `:64-72`).
+- `vibe/ui_server.py` `sessions_update` (`:6531-6624`): catch in the try at `:6598-6614` → `409`
+ with the repo's structured error body,
+ `{"ok": false, "error": {"code": "session_archived", "message": ...}, "code": ..., "message": ...}`
+ (revised in round 4b — the first cut used a flat string `error`, which the Web UI parser reads as
+ the code). The pre-flight backend-lock read at `:6580` uses `get_session` and is unaffected.
+- Tests: `tests/test_core_services_sessions.py` — archived row raises `SessionArchivedError` for
+ `title` and for `agent_name` re-route.
+
+### 4. Frontend API layer
+
+`ui/src/context/ApiContext.tsx`:
+
+- `MessageSearchSession` (`:1057-1063`): add `archived: boolean`.
+- `searchMessages` signature (`:596`): `opts?: { limit?: number; includeArchived?: boolean }`;
+ impl (`:2694-2699`): `if (opts?.includeArchived) search.set('include_archived', '1');` — matches
+ the `getProjects` pattern at `:2604`.
+
+`ui/src/lib/useMessageSearch.ts`: add `includeArchived?: boolean` to `UseMessageSearchOptions`; pass
+to `searchMessages(trimmed, { includeArchived })` at `:65`; add to the effect deps at `:85`.
+
+### 5. The toggle
+
+- `ui/src/components/workbench/SearchPage.tsx`: derive `includeArchived` from
+ `searchParams.get('archived') === '1'`; the toggle writes/deletes the param via the existing
+ `setSearchParams(..., { replace: true })` pattern (`:40-51`); pass into
+ `useMessageSearch(query, { includeArchived })` (`:31`). Render a `Switch`
+ (`ui/src/components/ui/switch.tsx`) + `<label>` row at the top of the results body (above the
+ hint/results, `:135`), labelled `t('workbench.search.includeArchived')`.
+- `ui/src/components/workbench/search/SearchPalette.tsx`:
+ `const [includeArchived, setIncludeArchived] = useState(false)`; reset to `false` inside
+ `onOpenAutoFocus` (`:133-140`) alongside `setQuery('')`; pass to `useMessageSearch` (`:42`). Place
+ the labelled `Switch` in the footer row (`:213-219`), left of the flexible spacer.
+
+### 6. Archived results visually distinct
+
+`ui/src/components/workbench/search/SearchResultGroup.tsx`: when `session.archived`, render
+`<Badge variant="secondary">{t('common.archived')}</Badge>` in the group header (after the label,
+before the count, `:26-32`) plus muted styling (e.g. `opacity-70` on the group, or `text-muted` on
+the label; match `design.pen` if visual fidelity matters). Add `useTranslation` to the component —
+the repo norm — rather than threading a pre-translated label from callers.
+
+### 7. Read-only `ChatPage` — `ui/src/components/workbench/ChatPage.tsx`
+
+- Derive `const readOnly = session?.status === 'archived'` (`status` is already on
+ `WorkbenchSession`, `ApiContext.tsx:759`).
+- `ComposeProps` (`:2299-2309`) + `Compose` (`:2311`): add `readOnly: boolean`; pass to `<Composer>`
+ (`:2320-2331`) as `disabled={readOnly}` and
+ `placeholder={readOnly ? t('chat.compose.placeholderArchived') : undefined}`; suppress `autoFocus`
+ when readOnly. Pass `readOnly` at the usage site (`:1932-1943`).
+- `ChatHeaderBar` (`:2335-2481`): add `readOnly` prop (pass at `:1823-1837`). When readOnly, render
+ the title as a static truncated `<span>` (add `readOnly?: boolean` to `TitleFieldProps`
+ `:2483-2486`, early-returning the non-editing branch without the button/pencil at `:2502-2512`),
+ and replace `AgentRoutePicker` (`:2409-2425`) with static text (agent name or the default label)
+ plus `<Badge variant="secondary">{t('common.archived')}</Badge>`. ~~Keep the Show Page toggle —
+ viewing works and mutations are already rejected server-side.~~ **Reversed in review round 3 (see
+ follow-up 3): viewing does not work either, so the whole Show Page cluster is withdrawn.**
+- `sendMessage` 409 handling (`:1221-1223`): before the generic throw, branch
+ `if (response.status === 409 && body?.code === 'session_archived')` →
+ `setError(t('chat.archived.sendBlocked')); return false;`. Also fix the generic fallback: routes
+ return `{"error": ...}`, not `detail`, so use ``body?.error ?? body?.detail ?? `HTTP ${status}` ``.
+- `Composer.tsx` hardening (shared component, fix at the right layer): the plain-`textarea` path
+ (`:618-635`) never applies `disabled` — add `disabled={disabled}`; gate the attach `+` and mic
+ buttons (`:552-584`) with `disabled` too. ChatPage uses the `MentionEditor` path, which already
+ honours it at `:592`; this closes the gap for other callers.
+- Leave the `onSessionActivity` archived→`goBack()` handler (`:1067-1071`) alone: it fires only on a
+ *live* archive event, which cannot recur for an already-archived session.
+
+### 8. i18n — add to both `ui/src/i18n/en.json` and `zh.json`
+
+| Key | en | zh |
+| --- | --- | --- |
+| `common.archived` | `Archived` | `已归档` |
+| `workbench.search.includeArchived` (block at en `:1385`) | `Include archived` | `包含已归档` |
+| `chat.compose.placeholderArchived` (in `chat.compose`, en `:2867`, beside `placeholderBusy`) | `This session is archived — read-only` | `会话已归档,仅可查看` |
+| `chat.archived.sendBlocked` (new `chat.archived` object under `chat`, en `:2769`) | `This session is archived and read-only.` | `该会话已归档,无法发送消息。` |
+
+Do **not** edit `errors.session_archived` (en `:993`).
+
+## Test plan
+
+- `tests/test_message_search.py` — item 1 cases. Fixture helpers `_seed_session` / `_insert_msg`
+ already support `status=` and `scope_settings`.
+- `tests/test_core_services_sessions.py` — `update_session` archived-guard cases (item 3). This file
+ already covers `list_sessions` (`:169`, `:203`); no `list_sessions` change, so no new cases there.
+- `tests/test_ui_server_fastapi.py` — route-param test for `/api/search/messages?include_archived=1`
+ and PATCH-archived → 409 `session_archived`.
+- `tests/test_session_archive.py` — **run untouched; must pass.**
+- Scenario catalog: no capability in `tests/scenarios/INDEX.yaml` covers Workbench search, so no
+ entry applies. State this explicitly in the PR description per CLAUDE.md §7.
+- UI: vitest tests exist under `search/` (`SearchResultRow.test.ts`, `appSearch.test.ts`). No new
+ logic-bearing module is introduced, so no new vitest file is required; `npm run build` type-checks
+ the `MessageSearchSession.archived` threading.
+
+## Breakage risks
+
+- **`search_messages` callers** — only the route (`ui_server.py:6850`) and tests
+ (`test_message_search.py`, `test_message_type_catalog.py:77`, which calls with defaults). The new
+ `archived` payload field is additive.
+- **Unread counting / inbox** — untouched by design. `unread_counts` (`:978-992`),
+ `unread_counts_by_session` (`:1021-1032`) and `list_inbox_sessions` (`:1167-1171`) keep their
+ archived exclusions, so badges can never count archived sessions.
+- **`update_session` guard** — two production callers: the PATCH route, and `vibe/cli.py:5119`
+ (pre-guarded by `get_active_session` at `:5118`, which already 404s archived). `archive_session`
+ writes the row directly, not via `update_session`, so archiving cannot trip the guard. Residual:
+ any future internal caller mutating an archived row now raises — the intended contract.
+- **`errors.session_archived` copy** — shared via `handleApiError` (`ApiContext.tsx:1913-1921`), so
+ the new PATCH 409 surfaces that Show-Page-worded string for non-ChatPage callers. Acceptable (only
+ stale or hand-crafted requests reach it); ChatPage uses the new chat-scoped keys.
+- **Palette keyboard nav** — archived groups join `flatTargets` (`SearchPalette.tsx:49-62`)
+ automatically; opening one routes to the read-only chat. No nav change needed.
+- **Composer disabled state** — `archive_session` resets `agent_status` to `idle` (`:962`), so `busy`
+ is false and the archived placeholder (not `placeholderBusy`) wins at `Composer.tsx:591`.
+
+## Review follow-ups (Codex, PR #1089)
+
+All three findings were the same root cause: `readOnly` was threaded into the composer but no
+further. The shared seam is now `ui/src/components/workbench/sessionArchived.ts` — one module
+owning `isSessionReadOnly`, `isSessionArchivedConflict`, `markSessionArchived` and
+`transcriptSelectionActions`, so the decisions are unit-testable without mounting `ChatPage`
+(the `harnessRuns.ts` pattern).
+
+1. **The archived 409 must converge, not just report** (amends item 7's `sendMessage` bullet).
+ A backgrounded/offline tab can miss the archive SSE for a session that already has a
+ `native_session_id`; `refreshSessionRowUntilNativeBound` then early-returns on every
+ reconnect/focus, so the 409 on the first send is the only point where that tab learns the
+ truth. The branch now patches local `session.status` to `archived` — which flips `readOnly`
+ and disables the composer — and *then* fires a best-effort authoritative refresh.
+ **Patch first, reload second**: the 409 *is* the server's answer, and this is precisely the
+ tab whose connectivity is in doubt, so a `getSession` that fails must not leave the chat
+ writable. `refreshSessionRowUntilNativeBound` was split so the plain
+ `refreshSessionRow` reload is reusable.
+2. **The transcript must lose its write controls too.** `Transcript` takes `readOnly`, and:
+ - quick replies stay rendered (which options were offered, and the ✓ on the chosen one, are
+ part of the transcript) but the group is **locked** via a new `QuickReplies` `readOnly`
+ prop, reusing the "answered" lock it already had. Nothing is clickable, so no doomed POST.
+ - `SelectionQuoteToolbar.onQuote` became optional and is omitted; `onAskInNew` is omitted too
+ (fork is refused server-side for an archived source, and archive is terminal). Separators
+ moved to before-each-item-after-the-first, and the toolbar renders nothing when only the
+ touch-only Copy would remain on a pointer device.
+
+ Same class, found in the same pass and fixed with it — each one writes to a session that can
+ never accept a write, and each is reachable from a stale tab holding pre-archive state:
+ - `QueueStrip` (Send now POSTs the flush; Recall appends into the disabled composer)
+ - `VaultChatRequests` / `VaultApprovalFloat` approve/deny
+ - `ShowPageAnnotateControl` — annotating enqueues an annotation *message* into the session,
+ so it is hidden on an archived chat. ~~This narrows item 7's "keep the Show Page toggle":
+ the toggle and the Share control stay (the Show Page store already refuses archived
+ mutations), the annotate control does not.~~ **Superseded by follow-up 3 — the toggle and
+ Share go too.**
+ - the Show Page open path's prompt **retry** (`showPagePromptRetryRef`) — the store refuses
+ to *create* a page for an archived session, but a session archived after a failed prompt
+ stays in the retry set and would re-prompt into a 409.
+
+3. **The Show Page controls go too — item 7's "keep the Show Page toggle" was wrong.**
+ The round-2 rationale ("the store already refuses archived mutations") is the
+ clickable-but-erroring pattern, not a fix: server-side refusal is a backstop, not a
+ substitute for withdrawing a dead action. And *viewing* does not work either —
+ `archive_session` forces every existing page to `visibility="offline"`
+ (`storage/workbench_sessions_service.py`) and `ensure_active` refuses to create a missing
+ one (`409 session_archived`, `core/show_pages.py`). So Visualize ends in a 409 toast when no
+ page exists, or frames an offline page when one does; Share's popover re-`ensure`s on open
+ and every one of its mutations (`update_visibility` / `set_share_id` / `rotate_share`) hits
+ the same guard. All three controls — Visualize, Share, annotate — are now withdrawn via
+ `showPageControlActions` in `sessionArchived.ts`. **No read-only page-serving path was
+ added**: that would change Show Page archive semantics and is out of scope here.
+
+ The stale-tab shape of the same defect: a tab already *in* Show Page mode when the archived
+ 409 converges would lose back-to-chat (it is the Visualize button) and sit on a hidden chat
+ surface with no iframe — a blank chat. So Show Page mode is **derived**, not stored:
+ `isShowPageActive(readOnly, showPageMode)` puts that tab back on the transcript in the same
+ render that flips `readOnly` (an effect would paint one blank frame first).
+
+ Found in the same sweep: `Composer`'s `onPasteFiles` was the one media affordance round 2
+ left ungated (the picker and mic got `disabled`). A pasted file can never be sent, and
+ `POST /api/sessions/<id>/attachments` has no archive guard, so it would persist an orphan
+ upload. Gated on `!disabled` at the shared-component layer.
+
+Regression coverage: `ui/src/components/workbench/ChatArchivedReadOnly.test.tsx`.
+
+### Archived-chat affordance sweep (round 3)
+
+Three rounds of the same defect class warranted an enumeration instead of more eyeballing. Every
+interactive affordance reachable from an archived chat — `ChatPage.tsx` and every component it
+renders — classified as **safe** (pure read / local UI state / machine-scoped pref), **gated**
+(already withdrawn), or **fixed** (this round).
+
+| Affordance | Site | Class | Why |
+| --- | --- | --- | --- |
+| Visualize / back-to-chat toggle | `ChatHeaderBar` | **fixed** | page forced offline + `ensure_active` 409 |
+| `ShowPageShareControl` (visibility, share id, rotate, copy, pin-to-Dock) | `ChatHeaderBar` | **fixed** | popover re-`ensure`s → 409; all mutations refused |
+| Framed Show Page (stale tab already in it) | `ChatPage` iframe | **fixed** | derived `isShowPageActive` returns to the transcript |
+| `MentionEditor` paste-to-upload | `Composer` | **fixed** | orphan attachment; upload route has no archive guard |
+| `ShowPageAnnotateControl` | `ChatHeaderBar` | gated (r2) | annotation is a session message |
+| Composer text / Send / Enter / attach `+` / mic | `Composer` | gated (r2) | `disabled` ⇒ `canSubmit` false; editor non-editable |
+| Chat-wide file drag-and-drop | `useFileDrop` | gated (r2) | `disabled: readOnly` no-ops every handler |
+| Sidebar "reference this session" → `insertSessionReference` | `composerTarget` | gated (r2) | target is `null` when read-only |
+| Quick replies | `MessageRow`→`QuickReplies` | gated (r2) | `readOnly` reuses the answered lock |
+| Selection Quote / Ask-in-new | `SelectionQuoteToolbar` | gated (r2) | both handlers omitted; bar renders nothing on pointer devices |
+| `QueueStrip` Send-now / Recall / Remove | `ChatPage` | gated (r2) | strip not rendered |
+| Vault approve/deny (cards + float) | `VaultChatRequests`/`Float` | gated (r2) | not rendered |
+| Title click-to-edit | `TitleField` | gated (r2) | static `<span>` |
+| `AgentRoutePicker` | `ChatHeaderBar` | gated (r2) | static text + Archived badge |
+| Show Page prompt retry (`showPagePromptRetryRef`) | `toggleShowPage` | gated (r2) | `!readOnly` backstop; toggle no longer rendered |
+| Back button, `ForkSourceBanner` link, harness trigger links, activity-row navigation, "Manage in Harness" | header / transcript / `ActivityStrip` | safe | navigation only |
+| Scroll: load-older, jump-to-latest, deep-link jump, anchor restore | `Transcript` | safe | reads `GET /messages` |
+| Activity chip expand / retry-detail / activity-card jump | `AgentActivityGroup` | safe | reads `GET /activity`; retry is a re-read |
+| Tool-row eye toggle | `ActivityCard`/`Chip` | safe | machine-scoped `config.ui.show_tool_calls` |
+| Harness-row expand, `QueueRow` expand, image lightbox, `FileCard`/`FileViewer` | transcript | safe | local UI state / media reads |
+| Debounced draft save + unmount flush | `onDraftChange` | safe | composer inert ⇒ never armed; and `PUT /draft` already drops an archived save with `{ok: true}` |
+| Inbox mark-read | unread effect | safe | read-cursor write, accepted; archived rows aren't counted anyway |
+| `Composer` Stop + busy placeholder (busy branch) | `Composer` | **fixed (r4)** | ~~safe — `readOnly && busy` is unreachable~~ **Wrong: it is reachable on a fresh load during the async-cancel window.** See round 4 below. |
+| `SecretRequestCard` (`$<NAME>` in an agent reply) | `Markdown` | **fixed (r5)** | ~~safe — writes a machine-scoped vault secret, not the session, and the server accepts it~~ **Wrong, and wrong on the wrong axis.** Whether the write lands was never the question: archive **expired the session's provision requests**, so an enabled Provide button asserts that an agent is waiting for this secret when none is. The defect is the affordance claiming a live request. Now **locked, not hidden** — see round 5. |
+
+Out of scope of "reachable from an archived chat" as ChatPage renders it: the sidebar / AppShell
+session actions (rename, archive, fork), which are not ChatPage's children. Their archived
+handling is pre-existing and untouched by this PR.
+
+### Round 4
+
+#### 4a. The Stop row above was wrong — `readOnly && busy` is reachable
+
+The round-3 "safe" verdict rested on two true-but-insufficient facts (archive resets
+`agent_status` to `idle`; the 409 convergence path clears `working` before flipping `readOnly`).
+Both describe a session that is *already loaded*. Neither covers a **fresh load inside the
+async-cancel window**, which is exactly the path this PR opens up — a search hit on an archived
+session:
+
+- `archive_session`'s own docstring: cancelling an in-flight chat turn "can't live here … so the
+ DELETE endpoint does that (best-effort) after this commits". The status flip is durable
+ immediately; the controller turn keeps running for as long as that internal-socket call takes
+ (or forever, if the controller is unreachable — it is best-effort).
+- `ChatPage` bootstraps the Stop state from `bootstrap.turn_state.foreground === 'running'`, i.e.
+ the **controller's** view, not the row's `agent_status`. The `agent_status` reset is therefore
+ irrelevant to the load path.
+
+So a chat opened in that window renders `readOnly && busy`. `disabled={readOnly}` alone does not
+make that composer inert: the busy branch renders an **enabled** Stop button (it never consulted
+`disabled`) and `placeholderBusy` overrides `placeholderArchived`, so the user is told to "type to
+queue" on a session that can never run another turn.
+
+Fixed at the **shared-component layer**, not the call site: `busy && disabled` is incoherent for
+every `Composer` caller, so `Composer` derives `busyControls = busy && !disabled` and uses it for
+both placeholders and the busy/idle branch. A disabled composer now always falls back to the
+ordinary Send button, which `canSubmit` already renders inert. Patching only ChatPage would have
+left the next caller to rediscover the same trap. Coverage: four cases in
+`ChatArchivedReadOnly.test.tsx` (two of them fail against the pre-fix component).
+
+#### 4b. The PATCH 409 body must carry a machine-readable code
+
+Item 3 shipped `409 {"error": "session is archived", "code": "session_archived"}`, copying the
+message-append routes. That flat shape defeats `handleApiError` (`ApiContext.tsx:1921`), which
+prefers `data.error` and only falls back to top-level `data.code`: a **string** `error` is taken as
+the code, so `ApiError.code` becomes `"session is archived"`, `errors.session_archived` never
+resolves, and a Chinese-locale user sees raw English — an AGENTS.md §6 i18n violation.
+
+The route now returns the repo's structured shape,
+`{"ok": false, "error": {"code", "message"}, "code", "message"}` (`_show_page_error_response`,
+`_dock_error_response`, `_project_not_found`, the vault/icon handlers), which the same parser reads
+correctly while keeping the flat top-level `code`/`message` for CLI/direct consumers. Fixed in the
+route, not the parser: the parser's precedence is load-bearing for the many routes whose `error` is
+a human string with no code at all (it is what turns those into a readable toast), and the nested
+shape is the established convention — the parser is not the outlier, this route was.
+
+`errors.session_archived` stays as-is (design decision 8): its copy is Show-Page-worded, which for a
+stale rename is imprecise but true, and the localization regression the finding is about — raw
+English under `zh` — is what preserving the code fixes.
+
+Coverage. `test_sessions_patch_on_archived_session_is_409` previously asserted only `body["code"]`,
+which is exactly the field the frontend does *not* read — it passed while the UI was broken. Three
+layers now:
+
+- that test pins the nested `error` object (and that `error` is never a bare string);
+- `test_sessions_patch_archived_conflict_survives_ui_error_parse` applies the parser's own
+ three-line precedence rule to the real response body, for a rename *and* an agent re-route;
+- `ui/src/context/ApiErrorParse.test.ts` runs the real parser. The selection step was extracted from
+ `handleApiError` into an exported `selectApiErrorFields` — behaviour-preserving, including the
+ deliberate throw on a non-object body — because the parser lives inside `ApiProvider`'s closure and
+ the repo has no DOM test environment to mount it in. The test pins the structured body → correct
+ code, the flat body → mangled code (as a negative, so the contract is explicit), and the two
+ pre-existing shapes.
+
+Both Python assertions fail against the pre-fix route. The vitest cases cannot: the parser is
+unchanged, so they document the contract the route must satisfy rather than re-detecting the bug.
+
+Same latent defect, **not** fixed here: the pre-existing flat 409s on
+`POST /api/sessions/<id>/messages` (`ui_server.py:7723`, `:7796`), `_session_fork_error_response`
+(`:6231`, five codes) and `_backend_locked_response` (`:6457`). `ChatPage` reads `body.code` from
+its own `fetch` for the messages POST, and `sessionArchived.ts:isSessionArchivedConflict` consumes
+that raw body, so the archived-send path this PR relies on is unaffected; the fork and
+backend-locked paths do route through `handleApiError` and do mangle their codes today. Left as
+follow-ups: they are pre-existing, each needs its own regression coverage, and converting them here
+would change response bodies for routes this PR does not otherwise touch.
+
+### Round 5
+
+Four findings; two of them are the *same* round-N mistake repeated (a per-verb fix
+and a "safe" classification that looked at the wrong axis), so both are answered by
+moving the decision up a layer rather than adding another branch.
+
+#### 5a. The archived 409 must converge for EVERY verb — so convergence moved to the API layer
+
+Round 1's convergence was wired into `sendMessage` only. The next verb the reviewer
+tried (rename / agent re-route) stored the 409 as error text and left the title
+editor and route picker live, re-issuing a permanently rejected PATCH. Patching
+`patch()` would have set up round 6 for `forkSession`, then `ensureShowPage`, then
+the Share control.
+
+**Enumeration — every call reachable from `ChatPage` (or a component it renders)
+that the server can answer `409 session_archived`:**
+
+| Call | Site | Server source | Converges via |
+| --- | --- | --- | --- |
+| `POST /api/sessions/<id>/messages` (raw `apiFetch`) | `sendMessage` | `ui_server.py` pre-flight + atomic re-check | direct `convergeSessionArchived` call (r1, rewired r5) |
+| `api.updateSession` (PATCH) | `patch` — title, agent re-route, model, pin, scope | `SessionArchivedError` → `_session_archived_response` | **API seam (r5)** |
+| `api.forkSession` | `askInNewSession` (Quote → Ask in a new session) | `_session_fork_error_response` | ~~**API seam (r5)**~~ **FALSE WHEN WRITTEN — flat body, code destroyed. Fixed r6.** |
+| `api.ensureShowPage` | `toggleShowPage` | `core/show_pages.ensure_active` | **API seam (r5)**, re-verified r6 |
+| `api.setShowPageVisibility` / `rotateShowPageShare` / `uploadShowPageIcon` (+ its `api.updateSession` rename) | `ShowPageShareControl` → `useShowPages` store | `core/show_pages` guards, `vibe/api.py:1235` | **API seam (r5)**, re-verified r6 |
+| `api.setShowPageShareId` | `ShowPageShareIdField` (inside the Share popover) | `core/show_pages` guard | **API seam (r5)**, re-verified r6 |
+| Show-event POST (annotation submit) | the annotation overlay **inside the Show Page iframe** | `core/show_session_events.py:165` | out of reach — see below |
+
+**The "converges via API seam" column was an assertion, not a verification** — see
+round 6 for the empirical per-row check and the two rows it corrected.
+
+The one row the seam structurally cannot reach: `ShowPageAnnotateControl` /
+`useShowPageAnnotation` only `postMessage` into the iframe
+(`avibe:annotation:control`); the actual show-event POST is issued by the annotation
+overlay running in that **separate document**, with its own fetch and its own React
+tree, so no `ApiProvider` of the host page sees its 409. Left as-is rather than bridged:
+it is already withdrawn twice over on a read-only session — the annotate control only
+renders while the page is framed, and `isShowPageActive` un-frames it the moment
+`readOnly` flips — and a host↔iframe error channel is Show Page architecture, not this
+PR's scope.
+
+Verified **not** `session_archived`-capable, so deliberately not in the seam:
+`api.cancelSession` (`/cancel` has no archive guard), `api.removeQueuedMessage`
+(`DELETE /queue/<id>`, no guard), `api.sendQueuedNow` (`internal_client.send_now` →
+`SessionTurnManager.send_now`, whose only 409 is `stop_failed`),
+`api.setSessionDraft` (drops an archived save with `{ok: true}`, never a 409), the
+vault approve/deny routes (machine-scoped), attachment upload, and every GET.
+
+**Centralised, in the API layer.** `handleApiError` is the single funnel every JSON
+helper's error passes through, so it announces the fact once via a new
+`api.onSessionArchived(handler)` subscription; `ChatPage` subscribes once and applies
+`markSessionArchived` + the best-effort authoritative reload in one
+`convergeSessionArchived`. Consequences:
+
+- `patch()` needed **no** convergence code of its own — the elegance test for the
+ layer choice. Only its *message* is per-verb: `errors.session_archived` (what
+ `handleApiError` resolves) is Show-Page-worded and wrong for a rename, so the
+ catch substitutes the new `chat.archived.editBlocked`.
+- the child-component calls (Share visibility / rotate / share-id / icon, and the
+ store's own rename) converge without ChatPage plumbing a callback into any of them.
+- a future session-scoped write inherits it.
+
+`sendMessage` stays the one explicit caller because it *cannot* use the seam: it
+uses a raw `apiFetch` so it can read `queued` / `already_answered` off a non-2xx-aware
+response, and never reaches `handleApiError`. It now calls the same converger rather
+than keeping its own copy of the reducer + reload.
+
+Which session the announcement is about comes from the request path
+(`archivedConflictSessionId(code, path)`, exported from `ApiContext` for testing like
+`selectApiErrorFields`). Both `409 session_archived` route families are session-id-first
+(`/api/sessions/<id>…`, `/api/show-pages/<session_id>…`). The pattern is deliberately
+**unanchored** because `updateSession` passes a *label* (`"PATCH /api/sessions/<id>"`)
+rather than a bare path — i.e. exactly the route this round is about.
+
+#### 5b. `SecretRequestCard` — the round-3 "safe" call was wrong
+
+The r3 rationale ("it writes a machine-scoped vault secret, not the session, and the
+server accepts it") answered a question nobody asked. Archive **expired the session's
+provision requests**; an enabled Provide button therefore tells the reader an agent
+is blocked waiting for this secret when nothing is. The affordance is the defect.
+
+**Locked, not hidden** — the same resolution the quick-reply group got, for the same
+tension: the card is the transcript record of *what the agent asked for*, so deleting
+it would erase a line of the conversation (hiding it degrades the marker to bare text,
+losing the "this was a secret request" framing entirely). It renders as the same badge,
+`disabled`, with a `title` stating why (`vaults.request.expired`).
+
+Implemented by **splitting the component**, not by an early return inside it:
+`SecretRequestCard` now dispatches to `ExpiredSecretRequest` (pure, i18n only) or
+`LiveSecretRequest` (the existing `useApi` + provision lookup + `VaultSecretDialog`).
+The locked card mounts **no** provide machinery at all — no request fetch, no dialog,
+no reachable vault write — rather than a disabled button in front of a live one.
+`Markdown` gained a narrow `readOnly` prop (documented as locking only the interactive
+markers it can mint; reads — images, file cards, links — stay usable on a read-only
+transcript), threaded from `MessageRow`'s existing `readOnly`.
+
+#### 5c. Backend i18n for the archived 409 `message`
+
+Round 4b introduced `message = "session is archived"` in the route — an AGENTS.md §6
+violation this PR created. Surveyed the file first: **most** `ui_server.py` JSON error
+bodies do hardcode English (`jsonify({"error": str(err)})`), and the only `t()` calls
+in the file serve the pre-auth OAuth error *page*. But there is a clear established
+pattern for a **localized, machine-coded, user-visible** error, and it is not the
+majority one:
+
+`core/show_session_events.py` — a `*_I18N_KEYS` constant beside the error class, a
+`localized_*_error()` factory that resolves `V2Config.load().language` (bare `except`
+→ `"en"`), the route serializing `str(exc)`/`exc.code`, and a parametrized
+resolution guard in `tests/test_i18n_backend_keys.py`. `vibe/api.py` uses
+`backend_t(...)` the same way for its `message` fields, and `ui_server.py:6276`
+already reads the configured language for a user-visible string in this very route
+family (`title_lang` for the fork title).
+
+So: `SESSION_ARCHIVED_I18N_KEY = "error.sessionArchived"` and
+`session_archived_message(lang=None)` live in `core/services/sessions.py` (the service
+facade that already re-exports `SessionArchivedError`), and `ui_server.py` gained one
+shared `_session_archived_response()` used by both the pre-flight and the exception
+catch. `error.sessionArchived` added to both backend bundles.
+
+**Not** converted, and stated as a gap: the pre-existing flat English 409s on
+`POST /api/sessions/<id>/messages` (`:7743`, `:7816`). Round 4b already deferred those
+for shape reasons; localizing their `error` string without also nesting the code would
+mean the mangled `ApiError.code` becomes a *Chinese* sentence, and changing the shape
+alters response bodies for a route this PR does not otherwise touch.
+
+#### 5d. Archive must outrank the backend-lock preflight
+
+Same async-cancel window as 4a, one layer out. `archive_session` cannot cancel an
+in-flight turn inside its transaction, so the DELETE route commits the archive first
+and cancels best-effort afterwards. A stale cross-backend PATCH landing in that window
+hit the controller-consulting preflight first and came back `409 backend_locked` — a
+**retryable** code masking a **terminal** state, so no client could recognize
+`session_archived` and converge (5a's whole mechanism is defeated).
+
+Fixed by short-circuiting archived rows at the **top** of `sessions_update`, before
+`derive_backend_for_agent_name` and before the controller is consulted, using the same
+`is_session_archived` write-guard the messages POST uses. Non-archived behaviour is
+unchanged by construction: `is_session_archived` is "exists AND archived", so the 404s
+and the 400 for an empty patch are untouched, the backend-lock ordering for every
+live row is exactly as before, and a live PATCH pays one extra indexed read. The
+`SessionArchivedError` catch stays as the commit-time race backstop.
+
+#### Round 5 coverage
+
+- `tests/test_ui_server_fastapi.py`
+ - `test_sessions_patch_on_archived_session_is_409` — extended to assert the
+ `message` **equals the resolved i18n value** (so an inlined literal fails) and
+ is not the pre-fix sentence.
+ - `test_sessions_patch_archived_message_follows_configured_language` — writes a
+ `zh` config and pins the body against the `zh` string, covering config language →
+ `vibe/i18n` → response body.
+ - `test_sessions_patch_archived_outranks_the_backend_lock_preflight` — archived row
+ answers `session_archived` **and** `internal_client.turn_state` is never awaited
+ for it, with a live row in the same test as the positive `backend_locked` control.
+ - `test_sessions_patch_missing_session_is_still_404` — the short-circuit doesn't
+ swallow 404/400.
+ - All three fail against the pre-fix route (verified by reverting both edits).
+- `tests/test_i18n_backend_keys.py` — `test_session_archived_message_resolves_in_every_language`,
+ following the `SHOW_EVENT_ERROR_I18N_KEYS` guard; the existing key-parity and
+ no-blank-translation tests cover the new bundle entry.
+- `tests/test_core_services_sessions.py` — `test_public_surface_is_stable` extended
+ for the two new exports.
+- `ui/src/context/ApiErrorParse.test.ts` — `archivedConflictSessionId` across every
+ `session_archived`-capable route family, the `updateSession` label form, non-archive
+ codes (a `backend_locked` on a session path must announce nothing), query strings,
+ escaped and malformed ids, and non-session paths.
+- `ui/src/components/workbench/ChatArchivedReadOnly.test.tsx` — `isSessionArchivedError`
+ on an `ApiError` vs a plain network `Error`; the shared reducer + a read-only header
+ render proving the rejected PATCH cannot be re-issued; distinct `editBlocked` /
+ `sendBlocked` copy; the locked secret card (disabled, reason present, no dialog
+ mounted); `readOnly` threading `MessageRow` → `Markdown` → card; and the pre-existing
+ authorship gate re-pinned so `readOnly` isn't mistaken for what governs it. The
+ threading case fails against the pre-fix call site.
+
+**Stated gaps.** There is no DOM test environment in `ui/` (no jsdom/happy-dom, no
+testing-library), so the *wiring* is not covered end to end: `handleApiError`'s
+subscriber fan-out and ChatPage's `useEffect` subscription have no test. The whole
+*decision* was extracted into `archivedConflictSessionId(code, path)` precisely so
+everything except the `Set` iteration is pinned — the same mitigation round 4b used
+for `selectApiErrorFields`. Also uncovered: the two deferred flat 409s in 5c, and the
+`title`-only affordance of the locked secret card (SSR markup is asserted, hover
+behaviour is not).
+
+### Round 6
+
+One finding: `POST /api/sessions/<id>/fork` still answered the **flat** coded body, so
+`selectApiErrorFields` took its human sentence as the code,
+`archivedConflictSessionId` returned null, and a stale tab whose first rejected action
+is "Ask in a new session" kept every mutating control live after a *permanent*
+refusal. Round 4b had already recorded that exact defect at that exact site — and
+deferred it.
+
+#### 6a. Why the round-4b deferral rule failed
+
+4b's criterion was "**nothing in this PR depends on it**". That was true when written
+and *stopped* being true one round later without anyone re-reading it: round 5a made
+`handleApiError` the single load-bearing funnel for archive convergence, which
+promoted every flat coded body reachable through the JSON helpers from "cosmetic
+pre-existing wart" to "silently breaks the mechanism this PR added". The rule failed
+because it measured dependency **at the moment of deferral** and nothing re-evaluated
+it when the architecture moved underneath.
+
+Worse, round 5's enumeration table then listed `api.forkSession` as *"converges via
+API seam"* — a claim falsified by a decision recorded in this same document, twelve
+lines above it. The table enumerated **call sites**, which is the easy half, and
+assumed the **body shape** at the other end, which is the half that actually decides
+whether convergence happens.
+
+Two rules replacing it:
+
+1. **Deferral needs an expiry condition, not a snapshot.** "Nothing depends on it
+ *today*" is only valid alongside "and here is what would make it depend on it" —
+ for these bodies, that trigger was "anything that makes a machine code
+ load-bearing in the shared error path".
+2. **An enumeration row is a claim about the whole path.** Listing a caller proves
+ nothing about the response it parses; the row is unverified until the *body* at the
+ far end has been read. Hence 6b, and hence the test that now checks it
+ mechanically instead of by eye.
+
+#### 6b. Per-row empirical re-verification of the round-5 enumeration
+
+Every "converges via API seam" row traced to the response builder its route actually
+returns (`vibe/ui_server.py`), then to a body assertion. Two rows were wrong:
+
+| Row | Body it really emits | Verdict |
+| --- | --- | --- |
+| `api.updateSession` | `_session_archived_response` → structured | held (r4b/r5) |
+| `api.forkSession` | `_session_fork_error_response` → **flat `{"error": "<sentence>", "code": …}`** | **WRONG — code destroyed. Fixed** |
+| `api.ensureShowPage` | `_show_page_error_response` → structured | held |
+| `api.setShowPageVisibility` | `_show_page_error_response` → structured | held |
+| `api.setShowPageShareId` | `_show_page_error_response` → structured | held |
+| `api.rotateShowPageShare` | `_show_page_error_response` → structured | held |
+| `api.uploadShowPageIcon` | `_show_page_icon_upload_error` → structured | held |
+| store rename (`useShowPages` → `api.updateSession`) | same as `updateSession` | held |
+| `api.cancelSession` / `removeQueuedMessage` / `sendQueuedNow` / `setSessionDraft` | no archive guard at all | held (not `session_archived`-capable) |
+| Show-event POST (annotation overlay) | flat, but in a **separate document** with its own fetch | held (out of the host seam) |
+| `POST /api/sessions/<id>/messages` | flat — ChatPage's raw fetch reads top-level `body.code` | **incomplete claim, see 6c** |
+
+Two side notes from the same trace, neither a defect: the Show Page family answers
+`session_archived` with **400**, not 409 (`_show_page_error_response` reserves 409 for
+`not_public`/`share_id_taken`) — convergence is keyed on the code, not the status, so
+it is unaffected; and `_backend_locked_response` was flat, which 5d's own
+archive-outranks-the-lock contract depends on (see 6d).
+
+**How each row was verified**, since "verified" is the word that failed last round:
+
+- the *path* side by reading each `api.*` implementation in `ApiContext.tsx`
+ (`:2530-2545`, `:2745`, `:2753`) — all are `/api/sessions/<id>…` or
+ `/api/show-pages/<id>…`, so `archivedConflictSessionId` extracts an id from each;
+- the *body* side by following the route's `except` clause to its response builder in
+ `vibe/ui_server.py` and reading the dict literal it emits — **not** by trusting a
+ docstring that claims the shape;
+- then mechanically, so it is not a one-time read: an AST scan of `ui_server.py` for
+ the anti-shape (`jsonify` with a machine `code` **and** a non-object `error`) which
+ enumerated exactly 15 such sites pre-fix, and is now a test (below).
+
+#### 6c. Scope decisions
+
+**Fixed — `_session_fork_error_response` (all six codes) + the route's `LookupError`.**
+In scope by dependency, not by choice. All branches, not just `session_archived`: they
+share one builder, and fixing one branch of a six-branch mapping is the per-verb
+mistake rounds 4a/5a were both about.
+
+**Fixed — `_backend_locked_response`.** By the 4b rule this was a follow-up ("nothing
+depends on its code"). That rule is retired, and this one has a stronger reason than
+"cheap": round 5d deliberately made `sessions_update` answer the **terminal**
+`session_archived` *ahead of* the **retryable** `backend_locked` precisely so a client
+could tell them apart — and a client cannot tell them apart while one of the two codes
+is being replaced by its own error sentence. So it is a dependency of 5d's contract,
+which is this PR's. Cost: one delegation + one table row. No user-visible change (no
+`errors.backend_locked` key exists, so the toast still falls back to the server
+message); `ApiError.code` becomes correct. Existing assertions read the top-level
+`code`, which is preserved (`test_ui_session_stream.py:726/1115/1324`,
+`test_ui_server_fastapi.py:410`).
+
+**Fixed — the two flat 409s in `POST /api/sessions/<id>/messages` (5c's stated gap).**
+4b's reasoning that these are independent *held for the reachable caller*: ChatPage
+uses a raw `apiFetch` and `isSessionArchivedConflict` reads top-level `body.code`,
+which the structured shape keeps. But the reasoning was **incomplete** — `ApiContext`
+also exposes `api.sendSessionMessage` (`:2792`) on the seam, currently with zero
+callers, so the first caller to use it would inherit the mangled code silently. Both
+sites now call `_session_archived_response()`, which also **closes 5c's localization
+gap** (they were hardcoded English; nesting the code is what makes localizing the
+message safe, since the sentence is no longer the code).
+
+**Not fixed, with reasons** — the five remaining flat coded bodies, now an explicit
+allowlist in the guard test rather than a memory:
+
+- `POST /api/control` (`restart_in_progress`) — `StatusContext.control()` uses a raw
+ `apiFetch` and reads top-level `body?.code` itself (`StatusContext.tsx:92-96`), the
+ same pattern that made the messages POST safe for ChatPage.
+- the four public Show Page / show-event bodies — served to the **iframe document**,
+ which has its own fetch and React tree, so no host `ApiProvider` ever parses them
+ (round 5's "out of reach" row, re-confirmed).
+
+#### 6d. Fixed at the shape layer, not per route
+
+Six call sites hand-rolled the identical structured dict
+(`_show_page_error_response`, `_dock_error_response`, `_show_page_icon_upload_error`,
+`_session_archived_response`, and now fork + backend-lock). Per the reuse ladder, that
+is past the third repeat: they all delegate to one **`_coded_error_response(code,
+message, status, **extra)`**, whose docstring states *why* the nesting exists (it is
+the parser's precedence rule, and the reason the flat shape is a silent code-destroyer
+rather than a style nit). The three pre-existing delegations are byte-identical
+refactors, covered by the parametrized test below.
+
+**Not changed:** whether fork refuses an archived source (it does, unchanged —
+`core/services/session_fork.py:174`), `archive_session`, and
+`tests/test_session_archive.py`. This round changes **error body shape only**.
+
+#### 6e. i18n status of the fork messages
+
+**Not localized, and deliberately left that way.** The five `SessionForkError`
+messages are English f-strings in `core/services/session_fork.py` (`:171-183`), not
+`vibe/i18n` keys. Localizing them belongs in a **separate** change: it needs the 5c
+pattern (an `*_I18N_KEYS` constant + factory + a `test_i18n_backend_keys.py` guard) for
+five codes that have **no** frontend bundle key either, and it is not what this finding
+is about. Preserving the code is what fixes the *user-visible* localization defect
+here: with `code == "session_archived"` intact, the Web UI resolves its own
+`errors.session_archived` from the active locale and the English `message` degrades to
+a CLI/fallback string.
+
+One consequence to note rather than silently absorb: the fork path now resolves
+`errors.session_archived`, whose copy is Show-Page-worded ("…so its Show Page can't be
+changed") and is *wrong* for a fork attempt. Design decision 8 forbids editing that
+shared key, and this round honours that — but the key now has three consumers with
+three different verbs, so generalizing its copy (or keying the toast per route) is a
+real follow-up, not a hypothetical one. The user-facing impact is muted:
+`askInNewSession` shows its own `chat.selection.askFailed` toast, and this path is only
+reachable from a tab that has not converged yet.
+
+#### Round 6 coverage
+
+The test that **would** have caught this — the shape of test 4b added for PATCH,
+generalized so it cannot be route-specific again:
+
+- `tests/test_ui_server_fastapi.py`
+ - `_ui_error_code(body)` promoted to a module-level helper (the parser's three-line
+ precedence rule, previously nested inside one test).
+ - `test_machine_coded_error_bodies_survive_the_ui_error_parse` — **parametrized over
+ a table of the response builders themselves** (12 cases: archived, backend-lock,
+ all six fork codes, Show Page ×2, Dock, icon). Each asserts the parser recovers the
+ code, `error` is an object, and the flat top-level `code`/`message` survive for the
+ CLI. The next coded route is covered by adding one row.
+ - `test_no_route_hand_rolls_the_flat_coded_error_body` — the **by-construction** half:
+ an AST scan for the anti-shape, with `_FLAT_CODED_BODY_EXEMPTIONS` keyed by
+ enclosing function (not line number) and a documented reason per entry. A new route
+ that reintroduces the flat coded body fails without anyone remembering this
+ contract exists.
+ - `test_sessions_fork_on_archived_source_survives_ui_error_parse` — route-level, real
+ archived row, real 409, nested code asserted.
+ - **9 of these fail against the pre-fix `ui_server.py`** (7 builder cases, the
+ structural guard, the fork route test), verified by reverting the file.
+- `ui/src/context/ApiErrorParse.test.ts` — `ARCHIVED_CAPABLE_ROUTES`, the round-5
+ enumeration as an `it.each` table run through the **real** `selectApiErrorFields` +
+ `archivedConflictSessionId`: body in, `session_archived` and `ses_1` out. The
+ enumeration is now executable instead of prose.
+
+**Gaps.** The vitest table hardcodes body fixtures rather than importing them from the
+Python side (no cross-language fixture pipeline exists), so the Python builder test is
+the authority on the real bodies and the vitest table pins the parser contract they
+must satisfy — the same split round 4b used. Still no DOM environment in `ui/`, so the
+`handleApiError` → subscriber → `ChatPage` wiring remains untested end to end. And the
+fork `message` strings stay English (6e).
+
+### Round 7
+
+One finding, labelled P2 and actually an invariant hole: **item 3's archived guard was a
+bare read-then-write pre-check.** `update_session`'s `status == "archived"` check sat at the
+top of the function, and the UPDATE at the bottom matched on `id` alone (plus the
+backend-lock predicate, on the backend-changing path only). That read reserves nothing —
+pysqlite opens no transaction for a bare SELECT, so SQLite takes the write lock at the
+UPDATE — so an archive committing in between let the statement rename or re-route an
+already-archived row. Terminal archive is this PR's hard constraint; the guard the read-only
+UI depends on was the one write in the codebase not asserting it.
+
+#### 7a. The pattern was already in the function we edited, and the doctrine is written down
+
+Not a new idea to weigh:
+
+- `update_session`'s **own** `backend_changes` branch re-asserts its predicate inside the
+ UPDATE, with a comment saying why ("the guard above is read-then-write, and a turn start /
+ native bind can commit in between"). Our archived pre-check was added a few lines above
+ that comment.
+- `storage/sessions_service.py:725-738` states it as doctrine: *"THIS READ IS A FAST PATH,
+ NOT THE GUARD… every UPDATE in this function re-asserts the predicate itself… each
+ rowcount-0 path re-reads the status… Proven by HFR-252."*
+
+So the fix follows the in-file precedent rather than inventing one: `status != 'archived'`
+on the UPDATE **unconditionally** (not only on the backend-changing path — the
+`sessions_service` comment is explicit that *every* UPDATE carries it), and the pre-check
+demoted in comment to what it always was, a fast path that spares an already-lost caller
+the metadata/scope work.
+
+#### 7b. Rowcount-0 is now ambiguous, and archive wins
+
+Two independent predicates on one statement mean `rowcount == 0` no longer names which one
+refused — and that branch already belonged to `SessionBackendLockedError`. It now re-reads
+`(status, agent_backend)` and decides: vanished → `LookupError`, archived →
+`SessionArchivedError`, still-locked → `SessionBackendLockedError`.
+
+**Archive outranks the lock**, deliberately and for round 5d's reason one layer down:
+5d made the *route* answer the terminal `session_archived` ahead of the retryable
+`backend_locked` precisely so a client can recognize a permanent refusal and converge (5a's
+whole mechanism). A service that answers `backend_locked` for an archived row undoes that
+from underneath the route. The `not backend_changes` → `LookupError` fallback is kept
+byte-equivalent for the non-archived case.
+
+#### 7c. Audit — every write in `update_session`, and the sibling status-pre-check sites
+
+`update_session` emits exactly **one** write statement (no DELETE). Its helpers write
+nothing: `_backend_for_agent_name` and `get_session` are reads, `_load_metadata` /
+`_dumps_metadata` / `reconcile_explicit_overrides` are pure. Every metadata change is
+composed onto one `values` dict on purpose (documented at the `replaced_settings` block), so
+there is no second statement to guard — and the new predicate is unconditional, so a future
+branch that adds one inherits it only if it reuses `stmt`; a genuinely new statement would
+need its own.
+
+Sibling paths, per site:
+
+| Site | Shape | Verdict |
+| --- | --- | --- |
+| `ui_server.sessions_update` preflight (`is_session_archived`, 5d) | separate connection, then `update_session` — an even wider window than the in-function one | **closed by 7a**: the service predicate is now the guard, the preflight is the fast path, and the existing `SessionArchivedError` catch is the commit-time backstop it was always documented as |
+| `POST /api/sessions/<id>/messages` `_persist_user_row` | `is_session_archived` then `messages_service.append` + `clear_draft` + `touch_session`, inside one `engine.begin()` | **residual, pre-existing, not fixed** — see 7d |
+| `PUT /api/sessions/<id>/draft` | drops an archived save with `{ok: true}` | no session-row write; nothing to make atomic |
+| `POST /api/sessions/<id>/fork` | `session_fork` refuses an archived **source**; the write creates a *new* row | source row never mutated |
+| `core/show_pages` guards | write `show_pages`, not `agent_sessions` | out of the invariant's table; `archive_session` forces them offline in its own transaction |
+| `archive_session` | unguarded by design (it *is* the archive) | untouched, byte-identical to master |
+| `touch_session` / `set_agent_status` / `reset_running_agent_status` | bare writers, no status pre-check to be stale about | no read-then-write gap; `set_agent_status`'s pre-check is on `agent_status` |
+| `backfill_session_title` | `agent_sessions` UPDATE, correctly re-asserting its *own* (title-emptiness) predicate — but no `status` predicate anywhere on the path | **found, not fixed** — see 7d |
+
+#### 7d. Two residual archive gaps, with expiry conditions (round 6a's rule)
+
+Both are pre-existing, neither is reachable through anything this PR added, and both are
+recorded with the trigger that would make them in-scope rather than a snapshot judgement:
+
+1. **`_persist_user_row`'s atomic re-check is also read-then-write.** Its comment claims the
+ re-check is "ATOMIC with the reservation" — true of the *transaction*, not of the *lock*:
+ the SELECT still runs in autocommit, so an archive can commit before the INSERT. Impact is
+ bounded and not a session-row mutation: it appends to `messages` and bumps
+ `last_active_at`, and the controller has a third `is_session_archived` backstop
+ (`core/internal_server.py:298`) before a turn runs. Fixing it means a `status`-aware
+ predicate inside `messages_service.append`, which is a different change with its own
+ coverage. **Expiry:** the moment anything relies on "no message row can exist after the
+ archive timestamp" (e.g. an archived-transcript integrity check, or search treating
+ archived transcripts as immutable).
+2. **`backfill_session_title` can title an archived row.** It fires from a delayed async task
+ after a turn (`modules/agents/base.py:_maybe_backfill_session_title`), i.e. inside the same
+ async-cancel window 4a/5d are about, and nothing on the path (`core/session_titles.py`)
+ filters archived. It only fills a *blank* title, so it cannot overwrite a user title, but
+ "an archived transcript can never be renamed" is exactly the invariant. **Expiry:** any
+ change that makes an archived row's title user-visible as immutable, or any second writer
+ of that column.
+
+#### Round 7 coverage
+
+`tests/test_sqlite_sessions_store.py`, reusing HFR-252's own harness
+(`_commit_competing_bind_after` + the real `_archive_write` payload) rather than a new one —
+a stub of the read would prove nothing about the write lock:
+
+- `test_update_session_cannot_rename_a_session_archived_inside_its_window` — a **second real
+ connection** commits the archive when the fast-path SELECT completes; asserts
+ `SessionArchivedError`, the title unchanged, and the archive's status / anchor / agent_status
+ intact. Pre-fix: **DID NOT RAISE** — the rename landed on the archived row.
+- `test_update_session_archive_race_outranks_the_backend_lock` — one commit carries both the
+ finishing turn's native bind (which fails the lock predicate) and the archive, so both
+ predicates fail; asserts `SessionArchivedError`, not `SessionBackendLockedError`. Pre-fix:
+ raised `SessionBackendLockedError`.
+
+Both verified red against the pre-fix service (stash the file, run, restore).
+
+**Scenario catalog: `HFR-280`** in `tests/scenarios/harness_failure_recovery/catalog.yaml`.
+The round-1 claim that no entry applied was correct for *Workbench search* and wrong for
+*this*: `update_session` is the fourth session writer in the HFR-251/253/254 read-then-write
+family, and HFR-252 is the archive-terminal half of it. Unlike HFR-252's proofs, HFR-280 is
+red-green.
+
+`archive_session` and `tests/test_session_archive.py` are untouched; `git diff master --
+storage/workbench_sessions_service.py` is confined to `SessionArchivedError` and
+`update_session`.
+
+## Validation (pre-push)
+
+```bash
+ruff check storage/messages_service.py storage/workbench_sessions_service.py \
+ core/services/sessions.py vibe/ui_server.py
+python3 -m pytest tests/test_message_search.py tests/test_core_services_sessions.py \
+ tests/test_session_archive.py -q
+python3 -m pytest tests/test_ui_server_fastapi.py -q
+cd ui && npm run build && npm run test
+```
diff --git a/storage/messages_service.py b/storage/messages_service.py
index bea64c370..c4d8462c9 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -231,6 +231,7 @@ def search_messages(
platform: str = "avibe",
types: Optional[Iterable[str]] = None,
limit: int = 50,
+ include_archived: bool = False,
) -> dict[str, Any]:
"""Global message-content search, grouped by session.
@@ -238,12 +239,17 @@ def search_messages(
to one ``platform`` (Workbench = ``avibe``) and a set of transcript-visible
``types`` (human prompts + harness prompts + the agent's rendered ``result``
replies + Show annotations — all land on a message the chat
- actually renders, so a clicked result is always jumpable). Archived sessions
- are excluded, as are messages under an archived PROJECT —
+ actually renders, so a clicked result is always jumpable). Archived SESSIONS
+ are excluded unless ``include_archived=True`` opts them in (archive is
+ terminal, so those transcripts are read-only — the flag only makes them
+ findable). Messages under an archived PROJECT are excluded
+ UNCONDITIONALLY, independent of ``include_archived``:
``projects_service.archive_project``
disables a project by setting ``scope_settings.enabled = 0`` (its sessions
stay ``active``), so the scope's disabled state is the authoritative
- "archived project" signal here. A scope with no ``scope_settings`` row is
+ "archived project" signal here, and project archive is reversible through its
+ own restore flow rather than through search. A scope with no
+ ``scope_settings`` row is
treated as enabled (legacy / folder-less projects never got one). ``limit``
caps the number of
MATCHED messages scanned (newest first), so it bounds total work; the matches
@@ -253,7 +259,9 @@ def search_messages(
Returns ``{"sessions": [...], "total": <#matches>, "session_count": <#sessions>}``
where each session is ``{session_id, title, project_id, project_name,
- matches: [{id, author, source, type, created_at, snippet}]}``. Sessions are
+ archived, matches: [{id, author, source, type, created_at, snippet}]}``.
+ ``archived`` is always present and is ``False`` for every group in the
+ default (opt-out) mode. Sessions are
ordered by their most-recent match; matches are newest-first within a session.
An empty / whitespace query short-circuits to an empty result.
"""
@@ -264,6 +272,9 @@ def search_messages(
like = escape_sql_like(cleaned)
type_list = list(types if types is not None else types_with("searchable"))
effective_limit = min(max(int(limit), 1), 200)
+ # Applied in place below so the default (opt-out) statement keeps exactly the
+ # predicates — and the predicate order — it had before the flag existed.
+ archived_session_filters = () if include_archived else (agent_sessions.c.status != "archived",)
stmt = (
select(
@@ -275,6 +286,7 @@ def search_messages(
messages.c.content_text,
messages.c.created_at,
agent_sessions.c.title,
+ agent_sessions.c.status,
scopes.c.native_id.label("project_id"),
scopes.c.display_name.label("project_name"),
)
@@ -287,8 +299,9 @@ def search_messages(
.where(messages.c.type.in_(type_list))
.where(messages.c.content_text.is_not(None))
.where(messages.c.content_text.ilike(f"%{like}%", escape="\\"))
- # Archived sessions are soft-deleted — never surface their messages.
- .where(agent_sessions.c.status != "archived")
+ # Archived sessions are soft-deleted — never surface their messages
+ # unless the caller explicitly opted in via ``include_archived``.
+ .where(*archived_session_filters)
.where(agent_sessions.c.visibility == "foreground")
# Archived PROJECTS are modelled as scope_settings.enabled = 0 (the
# sessions stay active), so exclude a disabled scope's messages too. A
@@ -314,6 +327,7 @@ def search_messages(
"title": row["title"],
"project_id": row["project_id"],
"project_name": row["project_name"],
+ "archived": row["status"] == "archived",
"matches": [],
}
grouped[session_id] = bucket
diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.py
index 75a96db92..d17e1a3de 100644
--- a/storage/workbench_sessions_service.py
+++ b/storage/workbench_sessions_service.py
@@ -389,6 +389,24 @@ class SessionBackendLockedError(Exception):
)
+class SessionArchivedError(Exception):
+ """Raised when a caller tries to mutate an archived session.
+
+ Archive is terminal: an archived transcript stays readable forever but can
+ never be re-routed, renamed, re-scoped or resumed. ``archive_session`` writes
+ the row directly (not through ``update_session``), so archiving itself can
+ never trip this guard. Callers map it to ``409 {"code": "session_archived"}``,
+ matching the message-append routes.
+
+ Raised from TWO places in ``update_session``: the fast-path read at the top,
+ and the rowcount-0 branch of the UPDATE itself (whose ``status != 'archived'``
+ predicate is the actual guard — see there)."""
+
+ def __init__(self, session_id: str):
+ self.session_id = session_id
+ super().__init__(f"Session {session_id} is archived and cannot be modified.")
+
+
def update_session(
conn: Connection,
session_id: str,
@@ -413,10 +431,20 @@ def update_session(
agent_sessions.c.native_session_id,
agent_sessions.c.agent_status,
agent_sessions.c.metadata_json,
+ agent_sessions.c.status,
).where(agent_sessions.c.id == session_id)
).first()
if existing is None:
raise LookupError(f"Session not found: {session_id}")
+ # THIS READ IS A FAST PATH, NOT THE GUARD. It reserves nothing — pysqlite
+ # opens no transaction for a bare SELECT, so SQLite only takes the write lock
+ # at the UPDATE below — meaning an archive can commit after it and before the
+ # write. The ``status != 'archived'`` predicate ON the UPDATE is what makes
+ # the terminal archive hold; this read only spares an already-lost caller the
+ # rest of the work (and answers the common case before the metadata/scope
+ # reads). Same split as ``sessions_service.bind_agent_session_by_id``.
+ if existing.status == "archived":
+ raise SessionArchivedError(session_id)
derived_backend = False
if agent_name is not _UNSET and agent_backend is _UNSET:
@@ -551,7 +579,20 @@ def update_session(
existing_metadata = reconcile_explicit_overrides(existing_metadata, cleared=replaced_settings)
values["metadata_json"] = _dumps_metadata(existing_metadata)
- stmt = update(agent_sessions).where(agent_sessions.c.id == session_id)
+ # Re-assert the terminal archive INSIDE the UPDATE, for exactly the reason the
+ # backend lock does just below: the status check at the top of this function is
+ # read-then-write and reserves nothing, and an archive is precisely what
+ # another connection commits in that window — ``archive_session`` cannot cancel
+ # an in-flight turn inside its transaction, so the DELETE route commits the
+ # archive FIRST and cancels best-effort afterwards, which is the window a stale
+ # PATCH lands in. Without this predicate that PATCH would rename or re-route an
+ # already-archived row and break "archive is terminal". Unconditional: every
+ # write this function makes must carry it, not just the backend-changing one.
+ stmt = (
+ update(agent_sessions)
+ .where(agent_sessions.c.id == session_id)
+ .where(agent_sessions.c.status != "archived")
+ )
if backend_changes:
# Re-assert the lock INSIDE the UPDATE: the guard above is read-then-
# write, and a turn start / native bind can commit in between (the
@@ -573,10 +614,26 @@ def update_session(
)
result = conn.execute(stmt.values(**values))
if result.rowcount == 0:
+ # Two independent predicates now share one statement, so a rowcount of 0 no
+ # longer names which one refused: re-read the row and decide from its
+ # current state.
+ #
+ # ARCHIVE WINS when both apply. Archive is terminal while the backend lock
+ # is retryable, and answering the retryable code for a permanently dead row
+ # is the exact defect round 5d fixed in the route (a client told
+ # ``backend_locked`` retries forever instead of converging on the archive).
+ # That ordering has to hold here too, or the route's precedence is undone by
+ # the service underneath it.
current = conn.execute(
- select(agent_sessions.c.agent_backend).where(agent_sessions.c.id == session_id)
+ select(agent_sessions.c.status, agent_sessions.c.agent_backend).where(
+ agent_sessions.c.id == session_id
+ )
).first()
- if current is None or not backend_changes:
+ if current is None:
+ raise LookupError(f"Session not found: {session_id}")
+ if current.status == "archived":
+ raise SessionArchivedError(session_id)
+ if not backend_changes:
raise LookupError(f"Session not found: {session_id}")
raise SessionBackendLockedError(
session_id=session_id,
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 5cc7d178b..90e242697 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -1424,6 +1424,39 @@ scenarios:
# verdict is pinned separately:
# tests/test_scheduled_tasks.py::test_a_retry_classification_that_cannot_read_keeps_the_entry
test: tests/test_scheduled_tasks.py::test_an_adopted_reservation_is_dropped_from_the_retry_record_without_being_touched
+ - id: HFR-280
+ name: >-
+ a Workbench PATCH cannot mutate a session archived inside its window, and the
+ archive outranks the backend lock
+ status: covered
+ kind: safety
+ layer: contract
+ backend: shared
+ # The FOURTH session writer with the HFR-251/253/254 shape, and the last public one:
+ # workbench_sessions_service.update_session, the service behind PATCH /api/sessions/
+ # <id>. RED, unlike HFR-252's proofs -- its archive guard was ONLY a read-then-write
+ # pre-check at the top of the function, and its single UPDATE matched on id alone
+ # (plus the backend-lock predicate, on the backend-changing path). That read reserves
+ # nothing, so a stale tab's rename or re-route landed on an already-archived row.
+ # The production window is not hypothetical: archive_session cannot cancel an
+ # in-flight chat turn inside its transaction, so the DELETE route commits the archive
+ # FIRST and cancels best-effort afterwards -- and the route's own is_session_archived
+ # pre-flight runs on a separate connection, widening the same window further.
+ # FIX: status != 'archived' on the UPDATE (unconditional, so every write this
+ # function makes carries it), the pre-check demoted in comment to what it always was
+ # -- a fast path -- and the rowcount-0 branch re-reading the row to say WHICH
+ # predicate refused.
+ # PRECEDENCE IS PART OF THE INVARIANT, not a detail: two predicates on one statement
+ # make rowcount 0 ambiguous, and the branch previously belonged to the backend lock.
+ # Reporting the RETRYABLE backend_locked for a TERMINAL archived row is the exact
+ # defect this PR's round 5d fixed one layer out in the route, so archive wins here
+ # whenever both apply. Second test, with one commit carrying both the finishing
+ # turn's native bind (which locks the backend) and the archive:
+ # tests/test_sqlite_sessions_store.py::test_update_session_archive_race_outranks_the_backend_lock
+ # Both fail against the pre-fix service: the rename lands silently (DID NOT RAISE),
+ # the re-route answers SessionBackendLockedError. Same _commit_competing_bind_after
+ # harness and the same real _archive_write payload as HFR-252.
+ test: tests/test_sqlite_sessions_store.py::test_update_session_cannot_rename_a_session_archived_inside_its_window
manual_evidence:
- local Incus backend process death after prompt acceptance
- local Incus controller restart with persisted queued successor
diff --git a/tests/test_core_services_sessions.py b/tests/test_core_services_sessions.py
index 4b4cc3419..66a9fd7c8 100644
--- a/tests/test_core_services_sessions.py
+++ b/tests/test_core_services_sessions.py
@@ -85,10 +85,16 @@ def test_public_surface_is_stable():
"reserve_standalone_agent_session",
# Backend-pin guard raised by update_session on a cross-backend switch:
"SessionBackendLockedError",
+ # Terminal-archive guard raised by update_session on an archived row:
+ "SessionArchivedError",
+ # Localized user-facing copy for that guard's 409 body:
+ "session_archived_message",
}
- assert set(sessions_service.__all__) == expected
+ assert set(sessions_service.__all__) == expected | {"SESSION_ARCHIVED_I18N_KEY"}
for name in expected:
assert callable(getattr(sessions_service, name))
+ # The one non-callable member: the i18n key constant the parity guard pins.
+ assert isinstance(sessions_service.SESSION_ARCHIVED_I18N_KEY, str)
def test_each_workbench_function_delegates_to_storage():
@@ -308,6 +314,31 @@ def test_archive_marks_session(isolated_state):
assert page["sessions"] == [], "archived sessions should not appear in the active list"
+def test_update_session_rejects_archived_session(isolated_state):
+ """Archive is terminal: an archived row can never be renamed or re-routed.
+
+ ``archive_session`` itself writes the row directly, so archiving does not trip
+ the guard — only a later mutation attempt does. The archived payload stays
+ fully readable via ``get_session`` (search + the read-only chat depend on it)."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_avibe_scope(conn)
+ sid = sessions_service.create_session(
+ conn, scope_id=scope_id, agent_backend="claude", agent_name="claude", title="Before"
+ )["id"]
+ sessions_service.archive_session(conn, sid)
+
+ with pytest.raises(sessions_service.SessionArchivedError):
+ sessions_service.update_session(conn, sid, title="Renamed")
+ with pytest.raises(sessions_service.SessionArchivedError):
+ sessions_service.update_session(conn, sid, agent_name="codex", agent_backend="codex")
+ # Nothing was written, and the transcript row stays readable.
+ after = sessions_service.get_session(conn, sid)
+ assert after["title"] == "Before"
+ assert after["agent_backend"] == "claude"
+ assert after["status"] == "archived"
+
+
def test_update_session_present_null_clears_model_and_effort(isolated_state):
"""Switching to an agent with no default model/effort sends present nulls;
update_session must CLEAR the columns (drop the prior agent's override),
diff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.py
index 3e60f3821..b43a81e34 100644
--- a/tests/test_i18n_backend_keys.py
+++ b/tests/test_i18n_backend_keys.py
@@ -17,6 +17,7 @@ import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.run_settlement import SETTLEMENT_I18N_KEYS, SWEEP_I18N_KEYS
+from core.services.sessions import SESSION_ARCHIVED_I18N_KEY, session_archived_message
from core.show_session_events import SHOW_EVENT_ERROR_I18N_KEYS
from storage.background import (
SWEEP_REASON_ORPHANED,
@@ -92,3 +93,15 @@ def test_every_show_event_error_resolves(code: str, key: str) -> None:
resolved = t(key, lang)
assert resolved != key, f"{key} is not translated in {lang} (code={code})"
assert resolved.strip()
+
+
+def test_session_archived_message_resolves_in_every_language() -> None:
+ # This string ships in the ``409 session_archived`` response body, which direct
+ # API/CLI consumers read verbatim and the Web UI renders as its fallback when
+ # ``errors.session_archived`` is missing — so an unresolved key would leak the
+ # dotted path to a user, and a missing translation would leak English.
+ for lang in get_supported_languages():
+ resolved = session_archived_message(lang)
+ assert resolved != SESSION_ARCHIVED_I18N_KEY, f"{SESSION_ARCHIVED_I18N_KEY} is not translated in {lang}"
+ assert resolved.strip()
+ assert resolved == t(SESSION_ARCHIVED_I18N_KEY, lang)
diff --git a/tests/test_message_search.py b/tests/test_message_search.py
index 648b3a01c..815031ff8 100644
--- a/tests/test_message_search.py
+++ b/tests/test_message_search.py
@@ -37,7 +37,7 @@ def _seed_scope(conn, native_id: str = "proj_test", display_name: str = "My Proj
return scope_id
-def _seed_session(conn, scope_id, session_id, title=None, *, status="active") -> None:
+def _seed_session(conn, scope_id, session_id, title=None, *, status="active", visibility="foreground") -> None:
now = messages_service._utc_now_iso()
conn.execute(
agent_sessions.insert().values(
@@ -49,6 +49,7 @@ def _seed_session(conn, scope_id, session_id, title=None, *, status="active") ->
native_session_id="",
title=title,
status=status,
+ visibility=visibility,
metadata_json="{}",
created_at=now,
updated_at=now,
@@ -261,6 +262,93 @@ def test_search_excludes_archived_session(isolated_state):
assert result["session_count"] == 1
assert result["sessions"][0]["session_id"] == "ses_live"
+ # The default mode still reports the flag, always False.
+ assert all(s["archived"] is False for s in result["sessions"])
+
+
+def test_search_include_archived_returns_archived_session(isolated_state):
+ """``include_archived=True`` opts archived sessions back in and marks them.
+
+ Active groups keep ``archived: False`` so the client can style only the
+ archived ones; the flag is a pure additive read — nothing un-archives."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_live", "Live", status="active")
+ _seed_session(conn, scope_id, "ses_arch", "Archived", status="archived")
+ _insert_msg(conn, scope_id, "ses_live", "user", "deploy here", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_arch", "user", "deploy there", "2026-06-01T10:01:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy", include_archived=True)
+
+ assert result["session_count"] == 2
+ assert result["total"] == 2
+ # Newest match first: ses_arch (10:01) ranks ahead of ses_live (10:00).
+ assert {s["session_id"]: s["archived"] for s in result["sessions"]} == {
+ "ses_arch": True,
+ "ses_live": False,
+ }
+ # The archived session's row identity/snippet is fully populated, so a click
+ # can still deep-link into the read-only transcript.
+ archived = next(s for s in result["sessions"] if s["session_id"] == "ses_arch")
+ assert archived["title"] == "Archived"
+ assert archived["matches"][0]["snippet"]["match"] == "deploy"
+
+
+def test_search_include_archived_still_excludes_archived_project_scope(isolated_state):
+ """``include_archived`` lifts the SESSION filter only.
+
+ Project archive (``scope_settings.enabled = 0``) is reversible and has its own
+ restore flow, so its sessions stay out of search either way."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ live_scope = _seed_scope(conn, native_id="proj_live", display_name="Live Project")
+ _seed_session(conn, live_scope, "ses_live", "Live", status="active")
+ _insert_msg(conn, live_scope, "ses_live", "user", "deploy here", "2026-06-01T10:00:00Z")
+ arch_scope = _seed_scope(conn, native_id="proj_arch", display_name="Archived Project")
+ # Both an active and an archived session under the disabled scope.
+ _seed_session(conn, arch_scope, "ses_arch_proj", "Under Archived", status="active")
+ _insert_msg(conn, arch_scope, "ses_arch_proj", "user", "deploy there", "2026-06-01T10:01:00Z")
+ _seed_session(conn, arch_scope, "ses_arch_both", "Archived Under Archived", status="archived")
+ _insert_msg(conn, arch_scope, "ses_arch_both", "user", "deploy elsewhere", "2026-06-01T10:02:00Z")
+ now = messages_service._utc_now_iso()
+ conn.execute(
+ scope_settings.insert().values(
+ scope_id=arch_scope,
+ enabled=0,
+ settings_version=1,
+ settings_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy", include_archived=True)
+
+ assert result["session_count"] == 1
+ assert result["sessions"][0]["session_id"] == "ses_live"
+
+
+def test_search_include_archived_still_excludes_background_visibility(isolated_state):
+ """Background sessions stay internal — ``include_archived`` does not reveal
+ them, archived or not."""
+ engine = create_sqlite_engine()
+ with engine.begin() as conn:
+ scope_id = _seed_scope(conn)
+ _seed_session(conn, scope_id, "ses_fg", "Foreground", status="archived", visibility="foreground")
+ _seed_session(conn, scope_id, "ses_bg", "Background", status="active", visibility="background")
+ _seed_session(conn, scope_id, "ses_bg_arch", "Background Archived", status="archived", visibility="background")
+ _insert_msg(conn, scope_id, "ses_fg", "user", "deploy one", "2026-06-01T10:00:00Z")
+ _insert_msg(conn, scope_id, "ses_bg", "user", "deploy two", "2026-06-01T10:01:00Z")
+ _insert_msg(conn, scope_id, "ses_bg_arch", "user", "deploy three", "2026-06-01T10:02:00Z")
+
+ with engine.connect() as conn:
+ result = messages_service.search_messages(conn, query="deploy", include_archived=True)
+
+ assert [s["session_id"] for s in result["sessions"]] == ["ses_fg"]
+ assert result["sessions"][0]["archived"] is True
def test_search_excludes_archived_project_scope(isolated_state):
@@ -298,6 +386,7 @@ def test_search_excludes_archived_project_scope(isolated_state):
assert result["session_count"] == 1
assert result["sessions"][0]["session_id"] == "ses_live"
+ assert result["sessions"][0]["archived"] is False
def test_search_treats_like_metachars_literally(isolated_state):
diff --git a/tests/test_sqlite_sessions_store.py b/tests/test_sqlite_sessions_store.py
index ba6a6ef27..8c8d1329e 100644
--- a/tests/test_sqlite_sessions_store.py
+++ b/tests/test_sqlite_sessions_store.py
@@ -2957,6 +2957,168 @@ def test_native_bind_by_id_idempotent_rebind_cannot_resurrect_an_archived_sessio
assert row["agent_status"] == "idle"
+# --- HFR-280: update_session is the Workbench PATCH writer with the same shape ---
+#
+# RED, not a proof. Unlike HFR-252's three statements, ``update_session``'s single
+# UPDATE did NOT re-assert ``status != 'archived'``: the guard was a bare
+# read-then-write pre-check at the top of the function, which reserves nothing (the
+# constant below is that read, and pysqlite opens no transaction for it, so SQLite
+# only takes the write lock at the UPDATE). Both cases here fail against the pre-fix
+# function -- the first renames an archived row, the second re-routes one -- and the
+# competing write is the same real ``_archive_write`` payload HFR-252 uses.
+
+#: The fast-path read at the top of ``update_session``. Keyed on so the archive lands
+#: in the window between it and the UPDATE that acts on its answer.
+_UPDATE_SESSION_FAST_PATH_SELECT = (
+ "SELECT agent_sessions.id, agent_sessions.scope_id, agent_sessions.agent_backend, "
+ "agent_sessions.native_session_id, agent_sessions.agent_status, "
+ "agent_sessions.metadata_json, agent_sessions.status FROM agent_sessions "
+ "WHERE agent_sessions.id = ?"
+)
+
+
+def _seed_update_session_row(service: SQLiteSessionsService, tmp_path: Path, anchor: str) -> str:
+ with service.engine.begin() as conn:
+ scope_id = resolve_scope_from_legacy_key(
+ conn, "slack::channel::C123", now="2026-07-28T00:00:00Z"
+ )
+ assert scope_id is not None
+ return create_agent_session_row(
+ conn,
+ scope_id=scope_id,
+ session_anchor=anchor,
+ agent_backend="opencode",
+ agent_variant="opencode",
+ agent_id="agent-opencode",
+ agent_name="review-opencode",
+ native_session_id="",
+ title="Before",
+ workdir=str(tmp_path),
+ )
+
+
+def test_update_session_cannot_rename_a_session_archived_inside_its_window(
+ tmp_path: Path,
+) -> None:
+ """HFR-280 — a Workbench PATCH loses to an archive that commits after its read.
+
+ The production interleaving is the one round 5d of this PR already documented in
+ the route: ``archive_session`` cannot cancel an in-flight chat turn inside its
+ transaction, so the DELETE endpoint commits the archive FIRST and cancels
+ best-effort afterwards. A stale tab's rename lands in exactly that window --
+ ``ui_server.sessions_update``'s own ``is_session_archived`` pre-flight is a
+ separate connection and an even wider window than this one.
+
+ The bare-``id`` UPDATE this call emits (no backend change, so the backend-lock
+ predicate is not added) is the same dangerous shape HFR-252's idempotent-re-bind
+ half covers: nothing but the id, on a row another connection has just made
+ terminal. Its ``status != 'archived'`` predicate is what refuses it, and the
+ rowcount-0 branch is what turns that refusal into ``SessionArchivedError``
+ instead of a bogus ``LookupError``.
+ """
+ from storage.workbench_sessions_service import SessionArchivedError, update_session
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = _seed_update_session_row(service, tmp_path, "slack_C123:race_patch_rename")
+
+ # The user archives the session the instant after the fast-path read said
+ # "not archived".
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_UPDATE_SESSION_FAST_PATH_SELECT,
+ values=_archive_write(session_id),
+ )
+
+ with pytest.raises(SessionArchivedError) as raised:
+ with service.engine.begin() as conn:
+ update_session(conn, session_id, title="Renamed by a stale tab")
+ assert raised.value.session_id == session_id
+ row = service.get_agent_session_by_id(session_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing "
+ "about the read — the keyed read is no longer the SQL the code emits"
+ )
+ assert row is not None
+ assert row["title"] == "Before", (
+ f"the stale PATCH renamed an archived session to {row['title']!r}; the "
+ "terminal transcript is no longer the one the user archived"
+ )
+ assert row["status"] == "archived", (
+ f"the stale PATCH flipped a terminal session back to {row['status']!r}"
+ )
+ assert row["session_anchor"] == f"archived:{session_id}", (
+ "the stale PATCH undid the archive's anchor vacation, so the next inbound "
+ "message on that thread resolves to the archived row"
+ )
+ assert row["agent_status"] == "idle"
+
+
+def test_update_session_archive_race_outranks_the_backend_lock(tmp_path: Path) -> None:
+ """HFR-280, precedence half — a rowcount of 0 must name the ARCHIVE.
+
+ With two predicates on one statement, ``rowcount == 0`` no longer says which one
+ refused, and the backend-lock branch already owned that branch. Which error comes
+ out is not cosmetic: round 5d of this PR deliberately made the route answer the
+ TERMINAL ``session_archived`` ahead of the RETRYABLE ``backend_locked``, so a
+ client can recognize a permanent refusal and converge instead of retrying a dead
+ row forever. A service that reports ``backend_locked`` for an archived row undoes
+ that from underneath the route.
+
+ Both predicates fail here, from one real competing commit: the in-flight turn
+ binds its native id (which locks the backend -- bound native AND concrete
+ backend) while the user's archive lands, which is the same async-cancel window as
+ the case above. The requested backend differs from the row's, so the
+ ``agent_backend == requested`` escape cannot match either.
+ """
+ from storage.workbench_sessions_service import SessionArchivedError, update_session
+
+ db_path = tmp_path / "vibe.sqlite"
+ service = SQLiteSessionsService(db_path)
+ try:
+ session_id = _seed_update_session_row(service, tmp_path, "slack_C123:race_patch_route")
+
+ race = _commit_competing_bind_after(
+ service.engine,
+ db_path,
+ read=_UPDATE_SESSION_FAST_PATH_SELECT,
+ # One commit, both facts: the finishing turn's native bind and the
+ # archive. Ordering between them is irrelevant to the caller -- it read
+ # the row before either.
+ values={**_archive_write(session_id), "native_session_id": "native-late"},
+ )
+
+ with pytest.raises(SessionArchivedError) as raised:
+ with service.engine.begin() as conn:
+ update_session(
+ conn, session_id, agent_backend="codex", agent_name="nightly-codex"
+ )
+ assert raised.value.session_id == session_id
+ row = service.get_agent_session_by_id(session_id)
+ finally:
+ service.close()
+
+ assert race["fired"] == 1, (
+ "the archive never landed inside the window, so this test proved nothing — "
+ "the keyed read is no longer the SQL the code emits"
+ )
+ assert row is not None
+ assert row["status"] == "archived"
+ assert row["agent_backend"] == "opencode", (
+ f"the stale PATCH re-routed an archived row to {row['agent_backend']!r}; the "
+ "archived transcript is now attributed to a backend that never produced it"
+ )
+ assert row["agent_name"] == "review-opencode"
+ assert row["native_session_id"] == "native-late", (
+ "the stale PATCH overwrote the winner's native id"
+ )
+
+
# --- HFR-253 / HFR-254: the other two read-then-write session writers ---
#
# HFR-251 closed the two windows in ``bind_agent_session_by_id``. The two writers
diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.py
index 0f7c71193..2f4e302e4 100644
--- a/tests/test_ui_server_fastapi.py
+++ b/tests/test_ui_server_fastapi.py
@@ -191,6 +191,524 @@ def test_sessions_activity_endpoint_summary_detail_and_404(monkeypatch, tmp_path
assert client.get("/api/sessions/ses_missing/activity").status_code == 404
+def _seed_search_corpus(tmp_path, monkeypatch):
+ """One active + one archived session, each with a matching message."""
+ from storage.db import create_sqlite_engine
+ from storage.models import agent_sessions, messages
+ from storage.settings_service import upsert_scope
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ now = "2026-06-01T10:00:00Z"
+ with engine.begin() as conn:
+ scope = upsert_scope(conn, platform="avibe", scope_type="project", native_id="proj_search", now=now)
+ for sid, status in (("ses_search_live", "active"), ("ses_search_arch", "archived")):
+ conn.execute(
+ agent_sessions.insert().values(
+ id=sid,
+ scope_id=scope,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_" + sid,
+ native_session_id="",
+ status=status,
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ conn.execute(
+ messages.insert().values(
+ id="msg_" + sid,
+ scope_id=scope,
+ session_id=sid,
+ platform="avibe",
+ author="user",
+ type="user",
+ source="user",
+ content_text="deploy the searchable thing",
+ content_json="{}",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ return engine
+
+
+def test_search_messages_route_plumbs_include_archived(monkeypatch, tmp_path):
+ """GET /api/search/messages excludes archived sessions by default and opts
+ them in for ``include_archived=1``, marking each group with ``archived``."""
+ _seed_search_corpus(tmp_path, monkeypatch)
+ client = app.test_client()
+
+ default = client.get("/api/search/messages?q=deploy")
+ explicit_off = client.get("/api/search/messages?q=deploy&include_archived=0")
+ included = client.get("/api/search/messages?q=deploy&include_archived=1")
+
+ assert default.status_code == 200
+ assert [s["session_id"] for s in default.get_json()["sessions"]] == ["ses_search_live"]
+ assert default.get_json()["sessions"][0]["archived"] is False
+ # Anything that is not 1/true/yes stays opt-out.
+ assert explicit_off.get_json() == default.get_json()
+
+ assert included.status_code == 200
+ flags = {s["session_id"]: s["archived"] for s in included.get_json()["sessions"]}
+ assert flags == {"ses_search_live": False, "ses_search_arch": True}
+
+
+def _ui_error_code(body: dict):
+ """The Web UI parser's own precedence rule, in its three lines.
+
+ ``selectApiErrorFields`` (``ui/src/context/ApiContext.tsx``): take ``error`` if
+ present, else a top-level ``{code, message}`` — and a STRING ``error`` *is* the
+ code. Replicated here (mirrored by ui/src/context/ApiErrorParse.test.ts, which runs
+ the real function) so a route that regresses to the flat coded shape fails on the
+ server side, where the body is authored, instead of shipping a mangled
+ ``ApiError.code`` and raw English to every locale.
+ """
+ raw = body.get("error") or ({"code": body["code"], "message": body.get("message")} if body.get("code") else None)
+ return raw if isinstance(raw, str) else (raw or {}).get("code")
+
+
+def _machine_coded_error_builders():
+ """Every ``vibe/ui_server.py`` helper that answers with a MACHINE-READABLE code.
+
+ One table, one assertion loop: the next coded route is covered by adding its
+ builder here, not by writing another near-duplicate test — and the structural guard
+ below fails for any coded body that skips the shared builder entirely, so a route
+ cannot quietly opt out of this list.
+ """
+ from core.services.session_fork import SessionForkError
+ from storage.workbench_sessions_service import SessionBackendLockedError
+
+ class _Coded(Exception):
+ def __init__(self, message: str, code: str) -> None:
+ super().__init__(message)
+ self.code = code
+
+ locked = SessionBackendLockedError(
+ session_id="ses_1", current_backend="claude", requested_backend="codex"
+ )
+ return [
+ # The archived 409 the whole read-only convergence hangs off (PATCH + messages POST).
+ ("session_archived", lambda: ui_server._session_archived_response(), "session_archived", 409),
+ # Round 5d: terminal archive vs retryable lock, on the same route. A client can
+ # only tell them apart if BOTH codes survive.
+ ("backend_locked", lambda: ui_server._backend_locked_response(locked), "backend_locked", 409),
+ # Fork — every branch, since they share one body builder (this round's finding).
+ (
+ "fork_archived",
+ lambda: ui_server._session_fork_error_response(SessionForkError("agent session is archived: ses_1")),
+ "session_archived",
+ 409,
+ ),
+ (
+ "fork_not_found",
+ lambda: ui_server._session_fork_error_response(SessionForkError("agent session id not found: ses_1")),
+ "session_not_found",
+ 404,
+ ),
+ (
+ "fork_not_bound",
+ lambda: ui_server._session_fork_error_response(
+ SessionForkError("agent session has no native session id to fork: ses_1")
+ ),
+ "session_not_bound",
+ 409,
+ ),
+ (
+ "fork_backend_unsupported",
+ lambda: ui_server._session_fork_error_response(SessionForkError("session backend cannot be forked: x")),
+ "session_backend_unsupported",
+ 409,
+ ),
+ (
+ "fork_backend_mismatch",
+ lambda: ui_server._session_fork_error_response(SessionForkError("session backend does not match: x")),
+ "session_backend_mismatch",
+ 409,
+ ),
+ (
+ "fork_failed",
+ lambda: ui_server._session_fork_error_response(SessionForkError("something else broke")),
+ "session_fork_failed",
+ 400,
+ ),
+ # Show Page / Dock / icon families — already structured; pinned so the shared
+ # builder they now delegate to cannot regress them either.
+ (
+ "show_page",
+ lambda: ui_server._show_page_error_response(_Coded("nope", "session_archived")),
+ "session_archived",
+ 400,
+ ),
+ (
+ "show_page_conflict",
+ lambda: ui_server._show_page_error_response(_Coded("taken", "share_id_taken")),
+ "share_id_taken",
+ 409,
+ ),
+ ("dock", lambda: ui_server._dock_error_response(_Coded("nope", "show_page_not_found")), "show_page_not_found", 404),
+ (
+ "show_page_icon",
+ lambda: ui_server._show_page_icon_upload_error("session_archived", "nope"),
+ "session_archived",
+ 400,
+ ),
+ ]
+
+
+ "label,build,expected_code,expected_status",
+ [pytest.param(*case, id=case[0]) for case in _machine_coded_error_builders()],
+)
+def test_machine_coded_error_bodies_survive_the_ui_error_parse(
+ monkeypatch, tmp_path, label, build, expected_code, expected_status
+):
+ """Every machine-coded error body must hand the Web UI back its CODE, not a sentence.
+
+ This is the contract round 4b established for the PATCH 409 and round 6 found
+ violated on ``POST /api/sessions/<id>/fork``: the parser reads ``error`` first and a
+ string there *is* the code, so the flat ``{"error": "<sentence>", "code": "<code>"}``
+ shape destroys it. Asserting only the top-level ``code`` — which is what these
+ routes' existing tests do — passes while every client branch keyed on the code is
+ dead, which is exactly how the fork body survived two review rounds.
+
+ Parametrized over the builders rather than duplicated per route so the next coded
+ route inherits the assertion by adding one table row.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ response, status = build()
+ body = json.loads(response.body)
+
+ assert status == expected_status, label
+ # What the Web UI actually resolves ``errors.<code>`` and its branches from.
+ assert _ui_error_code(body) == expected_code, label
+ assert isinstance(body["error"], dict), label
+ # And the flat top-level fields the CLI / direct consumers read stay put.
+ assert body["code"] == expected_code, label
+ assert isinstance(body["message"], str) and body["message"], label
+ assert body["error"]["message"] == body["message"], label
+
+
+# Coded bodies that deliberately keep the flat shape, each with the reason it cannot
+# reach the Web UI's shared parser. Keyed by enclosing function so line churn can't
+# silently widen the exemption.
+_FLAT_CODED_BODY_EXEMPTIONS = {
+ # POST /api/control — StatusContext.control() uses a raw ``apiFetch`` and reads the
+ # top-level ``body.code`` itself, exactly like ChatPage's messages POST.
+ "control",
+ # Public Show Page document + its annotation overlay: a SEPARATE document with its
+ # own fetch and React tree, so no host ``ApiProvider`` ever parses these bodies
+ # (round 5's "out of reach" row).
+ "_show_session_event_error_response",
+ "_show_event_response_from_payload",
+ "serve_public_show_page",
+}
+
+
+def test_no_route_hand_rolls_the_flat_coded_error_body():
+ """Structural guard: a NEW coded route can't reintroduce the flat shape unnoticed.
+
+ Three review rounds spent on the same one-line defect (the PATCH body in 4b, the
+ fork body in round 6) because each was found by reading rather than by a test. The
+ anti-shape is mechanically detectable — a ``jsonify`` dict literal carrying both a
+ machine ``code`` and a non-object ``error`` — so detect it, and require any new
+ instance to be either routed through ``_coded_error_response`` or added to the
+ exemption set with a reason. That is the by-construction half of the coverage; the
+ parametrized test above is the positive half.
+ """
+ import ast
+ import pathlib
+
+ source = pathlib.Path(ui_server.__file__).read_text()
+ tree = ast.parse(source)
+
+ # Widest spans first so an inner handler overwrites its enclosing route function:
+ # the exemption should name the function that actually authors the body.
+ functions = [n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))]
+ owner_by_line: dict[int, str] = {}
+ for node in sorted(functions, key=lambda n: (n.end_lineno or n.lineno) - n.lineno, reverse=True):
+ for line in range(node.lineno, (node.end_lineno or node.lineno) + 1):
+ owner_by_line[line] = node.name
+
+ offenders = []
+ for node in ast.walk(tree):
+ if not (isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "jsonify"):
+ continue
+ if not node.args or not isinstance(node.args[0], ast.Dict):
+ continue
+ payload = node.args[0]
+ if not all(isinstance(key, ast.Constant) for key in payload.keys):
+ continue
+ keys = [key.value for key in payload.keys]
+ if "code" not in keys or "error" not in keys:
+ continue
+ if isinstance(payload.values[keys.index("error")], ast.Dict):
+ continue
+ owner = owner_by_line.get(node.lineno, "<module>")
+ if owner not in _FLAT_CODED_BODY_EXEMPTIONS:
+ offenders.append(f"{owner} (line {node.lineno})")
+
+ assert not offenders, (
+ "These responses pair a machine code with a flat string ``error``, which the Web UI's "
+ "parser reads as the code itself — route them through ``_coded_error_response`` or add "
+ f"them to _FLAT_CODED_BODY_EXEMPTIONS with the reason they can't reach it: {offenders}"
+ )
+
+
+def test_sessions_patch_on_archived_session_is_409(monkeypatch, tmp_path):
+ """Archive is terminal — PATCH /api/sessions/<id> on an archived row answers
+ 409 ``session_archived`` (the backstop the read-only chat UI relies on).
+
+ The body must use the STRUCTURED error shape. The Web UI's shared parser
+ (``selectApiErrorFields`` in ``ui/src/context/ApiContext.tsx``) reads ``error``
+ before the top-level ``code`` and treats a string ``error`` as the machine code,
+ so a flat ``{"error": "session is archived", "code": ...}`` hands callers
+ ``ApiError.code == "session is archived"``, never resolves
+ ``errors.session_archived``, and renders that English sentence under every
+ locale. Asserting only ``body["code"]`` passed while that was broken — the field
+ the frontend consumes is the nested one, so pin both.
+
+ The ``message`` must also come from ``vibe/i18n`` rather than a literal in the
+ route (AGENTS.md §6): direct API/CLI consumers read it verbatim, and a Web UI
+ client missing ``errors.session_archived`` renders it as the fallback.
+ """
+ from core.services.sessions import SESSION_ARCHIVED_I18N_KEY, session_archived_message
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import archive_session, create_session, get_session
+ from vibe.i18n import t as i18n_t
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ sid = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Before")["id"]
+
+ client = app.test_client()
+ ok = client.patch(f"/api/sessions/{sid}", json={"title": "Live rename"}, headers=csrf_headers(client))
+ assert ok.status_code == 200
+
+ with engine.begin() as conn:
+ archive_session(conn, sid)
+
+ blocked = client.patch(f"/api/sessions/{sid}", json={"title": "Nope"}, headers=csrf_headers(client))
+ assert blocked.status_code == 409
+ body = blocked.get_json()
+ # Sourced from the i18n bundle, NOT a literal in the route. Resolving the key
+ # here (rather than pinning the English sentence) is what makes a hardcoded
+ # regression fail: an inlined string would no longer equal the bundle value.
+ expected_message = i18n_t(SESSION_ARCHIVED_I18N_KEY, "en")
+ assert expected_message != SESSION_ARCHIVED_I18N_KEY # the key really resolves
+ assert body["message"] == expected_message == session_archived_message("en")
+ # ...and the pre-fix literal is gone for good.
+ assert body["message"] != "session is archived"
+ # What the Web UI parser consumes: a nested object carrying the machine code.
+ assert body["error"] == {"code": "session_archived", "message": expected_message}
+ # Kept flat as well for the CLI / any direct consumer.
+ assert body["code"] == "session_archived"
+ assert body["ok"] is False
+ # Whatever the shape, ``error`` must never be a bare string here — that is the
+ # exact form the parser mis-reads as the code.
+ assert not isinstance(body["error"], str)
+ with engine.connect() as conn:
+ assert get_session(conn, sid)["title"] == "Live rename"
+
+
+def test_sessions_patch_archived_message_follows_configured_language(monkeypatch, tmp_path):
+ """The 409 ``message`` is localized, not just centralized.
+
+ A direct API/CLI consumer reads this field verbatim, and a Web UI client without
+ the ``errors.session_archived`` key falls back to it — so under a ``zh`` config
+ it must not be English. Guards the whole path (config language → ``vibe/i18n``
+ → response body), which is what a hardcoded literal or a hardwired ``lang="en"``
+ would break.
+ """
+ from config import paths
+ from core.services.sessions import session_archived_message
+ from core.services.settings import default_config
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import archive_session, create_session
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ config = default_config()
+ config.language = "zh"
+ config.save(paths.get_config_path())
+
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ sid = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Before")["id"]
+ archive_session(conn, sid)
+
+ client = app.test_client()
+ blocked = client.patch(f"/api/sessions/{sid}", json={"title": "Nope"}, headers=csrf_headers(client))
+ assert blocked.status_code == 409
+ body = blocked.get_json()
+ assert body["message"] == session_archived_message("zh")
+ assert body["message"] != session_archived_message("en")
+ assert body["error"]["message"] == body["message"]
+
+
+def test_sessions_patch_archived_outranks_the_backend_lock_preflight(monkeypatch, tmp_path):
+ """Archive is TERMINAL, so it must win over the transient backend lock.
+
+ ``archive_session`` cannot cancel an in-flight chat turn inside its transaction
+ (the turn lives in the controller process), so the DELETE route commits the
+ archive first and cancels best-effort afterwards. A stale cross-backend PATCH
+ landing in that window used to hit the controller-consulting preflight first and
+ come back ``409 backend_locked`` — a retryable code that masked the terminal
+ state, so the client could never recognize ``session_archived`` and converge.
+
+ Pinned two ways: the archived row answers ``session_archived`` AND the controller
+ is never consulted at all; the live row keeps its existing ``backend_locked``
+ answer, so the ordering change is scoped to archived sessions only.
+ """
+ from unittest.mock import AsyncMock, patch
+
+ from core.vibe_agents import VibeAgentStore
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import archive_session, create_session
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ live = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Live")["id"]
+ archived = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Gone")["id"]
+ archive_session(conn, archived)
+
+ store = VibeAgentStore()
+ try:
+ store.create(name="reviewer", backend="codex")
+ finally:
+ store.close()
+
+ client = app.test_client()
+ headers = csrf_headers(client)
+ in_flight = AsyncMock(return_value={"status_code": 200, "body": {"ok": True, "in_flight": True}})
+
+ with patch("vibe.internal_client.turn_state", in_flight):
+ # Positive control: an ACTIVE session with a live turn still refuses the
+ # cross-backend switch with the transient lock, via the controller.
+ locked = client.patch(f"/api/sessions/{live}", json={"agent_name": "reviewer"}, headers=headers)
+ assert locked.status_code == 409
+ assert locked.get_json()["code"] == "backend_locked"
+ assert in_flight.await_count == 1
+
+ blocked = client.patch(f"/api/sessions/{archived}", json={"agent_name": "reviewer"}, headers=headers)
+
+ assert blocked.status_code == 409
+ body = blocked.get_json()
+ assert body["code"] == "session_archived"
+ assert body["error"]["code"] == "session_archived"
+ # Short-circuited BEFORE the controller: no extra turn-state call was made.
+ assert in_flight.await_count == 1
+
+
+def test_sessions_patch_missing_session_is_still_404(monkeypatch, tmp_path):
+ """The archived short-circuit must not swallow the not-found case.
+
+ ``is_session_archived`` is "exists AND archived", so an unknown id falls through
+ to the 404 the route always returned.
+ """
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ client = app.test_client()
+ missing = client.patch("/api/sessions/ses_nope", json={"title": "x"}, headers=csrf_headers(client))
+ assert missing.status_code == 404
+ # And an empty patch is still a 400 (validated before any row read).
+ empty = client.patch("/api/sessions/ses_nope", json={}, headers=csrf_headers(client))
+ assert empty.status_code == 400
+
+
+def test_sessions_patch_archived_conflict_survives_ui_error_parse(monkeypatch, tmp_path):
+ """Apply the Web UI parser's own precedence rule to the real 409 body.
+
+ ``selectApiErrorFields`` (ApiContext.tsx) is: take ``error`` if present, else a
+ top-level ``{code, message}``; a STRING ``error`` *is* the code. Replicated here
+ — kept to those three lines, and mirrored by ui/src/context/ApiErrorParse.test.ts
+ which runs the real function — so a route that regresses to the flat shape fails
+ on the server side too, instead of shipping raw English to every locale.
+ """
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import archive_session, create_session
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ sid = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Before")["id"]
+ archive_session(conn, sid)
+
+ client = app.test_client()
+
+ # Both mutation kinds a stale tab can attempt: a rename, and an agent re-route.
+ for payload in ({"title": "Nope"}, {"agent_name": "codex"}):
+ res = client.patch(f"/api/sessions/{sid}", json=payload, headers=csrf_headers(client))
+ assert res.status_code == 409, payload
+ assert _ui_error_code(res.get_json()) == "session_archived", payload
+
+
+def test_sessions_fork_on_archived_source_survives_ui_error_parse(monkeypatch, tmp_path):
+ """Fork refuses an archived source — and must say so in a way the Web UI can read.
+
+ ``askInNewSession`` (Quote -> "Ask in a new session") goes through the shared JSON
+ helpers, so its 409 reaches ``handleApiError`` and is the *first* rejected action a
+ stale tab can take. With the flat body this route used to return, the parser took
+ the human sentence as the code, ``archivedConflictSessionId`` returned null, the
+ ``onSessionArchived`` subscription never fired, and the chat stayed fully writable
+ after a permanent refusal.
+
+ Refusal itself is unchanged (archive is terminal, fork stays forbidden) — only the
+ body shape is.
+ """
+ from storage.db import create_sqlite_engine
+ from storage.projects_service import create_project
+ from storage.workbench_sessions_service import archive_session, create_session
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ ensure_sqlite_state()
+ engine = create_sqlite_engine()
+ project_dir = tmp_path / "project"
+ project_dir.mkdir()
+ with engine.begin() as conn:
+ project = create_project(conn, str(project_dir), display_name="Project")
+ sid = create_session(conn, scope_id=project["scope_id"], agent_backend="claude", title="Source")["id"]
+ archive_session(conn, sid)
+
+ client = app.test_client()
+ res = client.post(f"/api/sessions/{sid}/fork", json={}, headers=csrf_headers(client))
+
+ assert res.status_code == 409
+ body = res.get_json()
+ assert _ui_error_code(body) == "session_archived"
+ # The nested object is what the parser reads; a bare string there is the defect.
+ assert isinstance(body["error"], dict)
+ # Flat top-level code/message stay for the CLI and any direct consumer.
+ assert body["code"] == "session_archived"
+ assert isinstance(body.get("message"), str) and body["message"]
+
+
def test_doctor_post_runs_fast_diagnostics_by_default(monkeypatch):
from vibe import cli
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsx
index 9c0bcad5c..d2f921b77 100644
--- a/ui/src/components/ui/markdown.tsx
+++ b/ui/src/components/ui/markdown.tsx
@@ -121,7 +121,21 @@ export const Markdown: React.FC<{
* or quoted text could mint an "agent asked for this secret" card that creates a vault
* secret on click. */
secretRequests?: boolean;
-}> = ({ content, className, interactive = true, softBreaks = false, references, secretRequests = false }) => {
+ /** The surface can never accept another write (an archived session's transcript).
+ * Narrow by design: it locks the interactive markers this renderer can mint —
+ * today the secret-request cards — and deliberately does NOT touch reads
+ * (images, file cards, links), which stay fully usable on a read-only
+ * transcript. Ignored unless `secretRequests` is on. */
+ readOnly?: boolean;
+}> = ({
+ content,
+ className,
+ interactive = true,
+ softBreaks = false,
+ references,
+ secretRequests = false,
+ readOnly = false,
+}) => {
// Stable ``remarkPlugins`` + ``components`` identities across re-renders.
// ReactMarkdown keys its rendered tree on the component functions it is handed;
// the old inline object minted fresh functions every render, so ReactMarkdown
@@ -187,9 +201,12 @@ export const Markdown: React.FC<{
// Vault `$<NAME>` dynamic-ask marker → inline secure-input card. Gated on
// ``secretRequests`` (agent-reply surface only), NOT just ``interactive`` — otherwise a
// user who literally typed `[x](avibe-secret:FOO)` in their own bubble could mint a card.
+ // ``readOnly`` keeps the card (it records what the agent asked for) but locks it:
+ // archiving expired the session's provision requests, so an enabled Provide button
+ // would claim an agent is waiting when none is.
if (url.startsWith(`${SECRET_LINK_SCHEME}:`)) {
const name = url.slice(SECRET_LINK_SCHEME.length + 1);
- return secretRequests ? <SecretRequestCard name={name} /> : <span>{children}</span>;
+ return secretRequests ? <SecretRequestCard name={name} readOnly={readOnly} /> : <span>{children}</span>;
}
if (interactive && url && isProxyMediaUrl(url)) {
return <FileCard href={url}>{children}</FileCard>;
@@ -227,7 +244,7 @@ export const Markdown: React.FC<{
),
}),
}),
- [interactive, secretRequests],
+ [interactive, secretRequests, readOnly],
);
// Mention markers are rewritten to `avibe-mention:` links BEFORE markdown sees
diff --git a/ui/src/components/ui/secret-request-card.tsx b/ui/src/components/ui/secret-request-card.tsx
index b5bfa7fee..2790ab458 100644
--- a/ui/src/components/ui/secret-request-card.tsx
+++ b/ui/src/components/ui/secret-request-card.tsx
@@ -7,11 +7,52 @@ import { useApi, type VaultRequest } from '@/context/ApiContext';
import { cn } from '@/lib/utils';
/**
- * Inline rendering of a `$<NAME>` dynamic-ask marker in an agent message. The badge
- * opens the shared {@link VaultSecretDialog} (same dialog as the Vaults "Add" flow), so
- * the provide experience is identical everywhere. Browser-side sealing happens in the form.
+ * Inline rendering of a `$<NAME>` dynamic-ask marker in an agent message.
+ *
+ * `readOnly` is for a read-only transcript (an archived session). Archiving EXPIRED the
+ * session's provision requests, so an enabled Provide button would assert that an agent
+ * is waiting for this secret when nothing is — the defect is the affordance claiming a
+ * live request, not whether the write would land (it would: the value is a machine-scoped
+ * vault secret and the server accepts it).
+ *
+ * Locked rather than hidden, matching how the quick-reply group resolves the same
+ * tension: the card is also the transcript record of what the agent asked for, so it
+ * stays legible while nothing about it is actionable. Split into its own branch so the
+ * locked card mounts NO provide machinery at all — no request lookup, no dialog, no
+ * vault write path to reach.
*/
-export const SecretRequestCard: React.FC<{ name: string; requestId?: string }> = ({ name, requestId }) => {
+export const SecretRequestCard: React.FC<{ name: string; requestId?: string; readOnly?: boolean }> = ({
+ name,
+ requestId,
+ readOnly = false,
+}) =>
+ readOnly ? (
+ <ExpiredSecretRequest name={name} />
+ ) : (
+ <LiveSecretRequest name={name} requestId={requestId} />
+ );
+
+/** The recorded ask on a read-only transcript: same badge, disabled, and the `title`
+ * states why (the session is archived, so the request has expired). */
+const ExpiredSecretRequest: React.FC<{ name: string }> = ({ name }) => {
+ const { t } = useTranslation();
+ return (
+ <button
+ type="button"
+ disabled
+ title={t('vaults.request.expired')}
+ className={cn(badgeVariants({ variant: 'warning' }), 'align-baseline font-medium opacity-60')}
+ >
+ <KeyRound className="mr-1 inline size-3" />
+ {name} — {t('vaults.request.provide')}
+ </button>
+ );
+};
+
+/** The live ask: the badge opens the shared {@link VaultSecretDialog} (same dialog as the
+ * Vaults "Add" flow), so the provide experience is identical everywhere. Browser-side
+ * sealing happens in the form. */
+const LiveSecretRequest: React.FC<{ name: string; requestId?: string }> = ({ name, requestId }) => {
const { t } = useTranslation();
const api = useApi();
const [open, setOpen] = useState(false);
diff --git a/ui/src/components/ui/switch.tsx b/ui/src/components/ui/switch.tsx
index f5d418ee6..0d12295c7 100644
--- a/ui/src/components/ui/switch.tsx
+++ b/ui/src/components/ui/switch.tsx
@@ -6,15 +6,27 @@ export interface SwitchProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonE
onCheckedChange: (next: boolean) => void;
/** ARIA label so screen readers can describe what the switch toggles. */
label?: string;
+ /**
+ * ``sm`` is the same rail scaled to 28x16 with a 12x12 thumb, for dense rows
+ * (e.g. the ⌘K palette footer) where the 44x24 default would dominate. Rail,
+ * thumb travel and radius stay proportional — only the metrics change.
+ */
+ size?: 'default' | 'sm';
}
+const SIZES = {
+ default: { rail: 'h-6 w-11 p-0.5', thumb: 'size-5', on: 'translate-x-5' },
+ sm: { rail: 'h-4 w-7 p-0.5', thumb: 'size-3', on: 'translate-x-3' },
+} as const;
+
// Mirrors design.pen c8fiq/fcMl6 (Switch/Checked + Switch/Unchecked):
// 44x24 rail, padding 2, 20x20 thumb. Rail flips `$--primary` (mint) ↔
// `$--border-strong`; thumb stays `$--background` in both states so it
// reads white in light mode and dark surface in dark mode without a
// hardcoded fill color per side.
export const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
- ({ className, checked, onCheckedChange, label, disabled, ...props }, ref) => {
+ ({ className, checked, onCheckedChange, label, disabled, size = 'default', ...props }, ref) => {
+ const metrics = SIZES[size];
return (
<button
ref={ref}
@@ -25,7 +37,8 @@ export const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
disabled={disabled}
onClick={() => onCheckedChange(!checked)}
className={cn(
- 'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full p-0.5 transition-colors',
+ 'relative inline-flex shrink-0 items-center rounded-full transition-colors',
+ metrics.rail,
'disabled:cursor-not-allowed disabled:opacity-50',
checked ? 'bg-primary' : 'bg-border-strong',
className,
@@ -34,8 +47,9 @@ export const Switch = React.forwardRef<HTMLButtonElement, SwitchProps>(
>
<span
className={cn(
- 'inline-block size-5 rounded-full bg-background shadow-[0_1px_3px_rgba(0,0,0,0.15),0_4px_8px_rgba(0,0,0,0.1)] transition-transform',
- checked ? 'translate-x-5' : 'translate-x-0',
+ 'inline-block rounded-full bg-background shadow-[0_1px_3px_rgba(0,0,0,0.15),0_4px_8px_rgba(0,0,0,0.1)] transition-transform',
+ metrics.thumb,
+ checked ? metrics.on : 'translate-x-0',
)}
/>
</button>
diff --git a/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
new file mode 100644
index 000000000..f8065949b
--- /dev/null
+++ b/ui/src/components/workbench/ChatArchivedReadOnly.test.tsx
@@ -0,0 +1,492 @@
+import { createInstance } from 'i18next';
+import type { ReactElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import en from '../../i18n/en.json';
+import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import { ChatHeaderBar, MessageRow } from './ChatPage';
+import { Composer } from './Composer';
+import { QuickReplies } from './QuickReplies';
+import {
+ isSessionArchivedConflict,
+ isSessionArchivedError,
+ isSessionReadOnly,
+ isShowPageActive,
+ markSessionArchived,
+ showPageControlActions,
+ transcriptSelectionActions,
+} from './sessionArchived';
+import { SecretRequestCard } from '../ui/secret-request-card';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const render = (ui: ReactElement) =>
+ renderToStaticMarkup(
+ <I18nextProvider i18n={i18n}>
+ <MemoryRouter>{ui}</MemoryRouter>
+ </I18nextProvider>,
+ );
+
+const session = (over: Partial<WorkbenchSession> = {}): WorkbenchSession =>
+ ({
+ id: 'ses_01J8XK5M8T',
+ scope_id: 'scope-1',
+ project_id: 'proj-1',
+ title: 'Model Hub',
+ agent_id: 'agt-1',
+ agent_name: 'claude',
+ agent_backend: 'claude_code',
+ agent_variant: null,
+ model: null,
+ reasoning_effort: null,
+ status: 'active',
+ pinned: false,
+ agent_status: 'idle',
+ workdir: null,
+ native_session_id: 'native-1',
+ created_at: '2026-07-27T04:00:00Z',
+ updated_at: '2026-07-27T04:00:00Z',
+ last_active_at: '2026-07-27T04:00:00Z',
+ metadata: {},
+ ...over,
+ }) as WorkbenchSession;
+
+// An agent reply carrying a quick-reply group, which is the transcript control
+// that POSTs a new message when clicked.
+const agentWithQuickReplies = (over: Record<string, unknown> = {}): WorkbenchMessage =>
+ ({
+ id: 'msg_01J8XK5M8T',
+ type: 'result',
+ author: 'agent',
+ source: null,
+ author_name: 'claude',
+ text: 'Ship it now, or wait for review?',
+ content: { quick_replies: ['Ship it', 'Wait'], ...over },
+ metadata: {},
+ created_at: '2026-07-27T04:04:00Z',
+ }) as unknown as WorkbenchMessage;
+
+// Count rendered <button …> elements that carry the disabled attribute. SSR emits
+// ``disabled=""``, so a locked group has one per option and a live one has none.
+const countButtons = (markup: string) => (markup.match(/<button/g) ?? []).length;
+const countDisabledButtons = (markup: string) => (markup.match(/<button[^>]*disabled=""/g) ?? []).length;
+
+// ── Codex review #1 (ChatPage.tsx:1242) ───────────────────────────────────────
+// A backgrounded / offline tab can miss the archive SSE for a session that
+// already has a native_session_id, and refreshSessionRowUntilNativeBound then
+// early-returns on every reconnect/focus — so the archived 409 on the first send
+// is the ONLY point at which that tab learns the truth. It has to converge there,
+// not just print a message, or the composer stays live and the user retries a
+// permanently rejected send forever.
+describe('archived 409 convergence', () => {
+ it('recognizes the archived conflict and nothing else', () => {
+ expect(isSessionArchivedConflict(409, { code: 'session_archived' })).toBe(true);
+ // Same status, different reason (e.g. a backend lock) must stay a normal error.
+ expect(isSessionArchivedConflict(409, { code: 'session_backend_locked' })).toBe(false);
+ expect(isSessionArchivedConflict(409, null)).toBe(false);
+ expect(isSessionArchivedConflict(409, undefined)).toBe(false);
+ // The code alone is not enough — only a 409 states the row is archived.
+ expect(isSessionArchivedConflict(200, { code: 'session_archived' })).toBe(false);
+ expect(isSessionArchivedConflict(500, { code: 'session_archived' })).toBe(false);
+ });
+
+ it('turns the stale row read-only, which is what disables the composer', () => {
+ const stale = session({ status: 'active' });
+ expect(isSessionReadOnly(stale)).toBe(false);
+
+ const converged = markSessionArchived(stale, stale.id);
+
+ expect(converged?.status).toBe('archived');
+ expect(isSessionReadOnly(converged)).toBe(true);
+ // Only the status moves — the rest of the loaded row is left alone (the
+ // best-effort authoritative refresh that follows picks up the frozen fields).
+ expect({ ...converged, status: 'active' }).toEqual(stale);
+ });
+
+ it('never stamps one chat’s archive onto the chat the user moved to', () => {
+ const other = session({ id: 'ses_other' });
+ expect(markSessionArchived(other, 'ses_01J8XK5M8T')).toBe(other);
+ expect(markSessionArchived(null, 'ses_01J8XK5M8T')).toBeNull();
+ });
+
+ it('is identity-stable once archived, so it cannot spin a re-render', () => {
+ const archived = session({ status: 'archived' });
+ expect(markSessionArchived(archived, archived.id)).toBe(archived);
+ });
+});
+
+// ── Codex review #2 (ChatPage.tsx:1971) ───────────────────────────────────────
+// readOnly reached the composer but not the transcript, so an archived chat still
+// offered controls that write to it: an old quick reply POSTed a message (409),
+// and Quote called the composer's imperative appendText, planting an unsendable
+// draft in the disabled editor.
+describe('read-only transcript withdraws session writes', () => {
+ it('offers neither Quote nor Ask-in-a-new-session on an archived session', () => {
+ // Live session with a bound native: both actions available (unchanged).
+ expect(transcriptSelectionActions(session(), false)).toEqual({ quote: true, askInNew: true });
+ // Pre-existing gate: forking needs a bound native.
+ expect(transcriptSelectionActions(session({ native_session_id: null }), false)).toEqual({
+ quote: true,
+ askInNew: false,
+ });
+ // Archived: Quote would land in a disabled composer, and the fork endpoint
+ // refuses an archived source outright (archive is terminal — no fork out).
+ expect(transcriptSelectionActions(session({ status: 'archived' }), true)).toEqual({
+ quote: false,
+ askInNew: false,
+ });
+ expect(transcriptSelectionActions(session({ status: 'archived', native_session_id: null }), true)).toEqual({
+ quote: false,
+ askInNew: false,
+ });
+ });
+
+ it('locks the quick-reply group instead of leaving it clickable', () => {
+ const live = render(<QuickReplies options={['Ship it', 'Wait']} onChoose={() => undefined} />);
+ expect(countButtons(live)).toBe(2);
+ expect(countDisabledButtons(live)).toBe(0);
+
+ const archived = render(<QuickReplies options={['Ship it', 'Wait']} readOnly onChoose={() => undefined} />);
+ // The group is still THERE — which options the agent offered is part of the
+ // transcript — but no click can start a send.
+ expect(archived).toContain('Ship it');
+ expect(archived).toContain('Wait');
+ expect(countDisabledButtons(archived)).toBe(2);
+ });
+
+ it('keeps the recorded answer visible while read-only', () => {
+ const archived = render(
+ <QuickReplies options={['Ship it', 'Wait']} chosen="Wait" readOnly onChoose={() => undefined} />,
+ );
+ expect(countDisabledButtons(archived)).toBe(2);
+ // The chosen option keeps its aria-pressed marker (and its ✓).
+ expect(archived).toContain('aria-pressed="true"');
+ });
+
+ it('threads readOnly from the transcript row into the group', () => {
+ const live = render(
+ <MessageRow
+ message={agentWithQuickReplies()}
+ session={session()}
+ messageFontSize={13}
+ onQuickReply={() => undefined}
+ />,
+ );
+ expect(live).toContain('Ship it');
+ expect(countDisabledButtons(live)).toBe(0);
+
+ const archived = render(
+ <MessageRow
+ message={agentWithQuickReplies()}
+ session={session({ status: 'archived' })}
+ messageFontSize={13}
+ onQuickReply={() => undefined}
+ readOnly
+ />,
+ );
+ // Same row, same options, nothing left to click.
+ expect(archived).toContain('Ship it');
+ expect(archived).toContain('Ship it now, or wait for review?');
+ expect(countDisabledButtons(archived)).toBe(2);
+ });
+});
+
+// ── Codex review #3 (ChatPage.tsx:2540) ───────────────────────────────────────
+// The previous round kept the Show Page toggle and the Share control on the
+// theory that the store already refuses archived mutations. That is the
+// clickable-but-erroring pattern, not a fix: archive forces every existing page
+// to visibility="offline" (storage/workbench_sessions_service.py) and
+// ensure_active refuses to create a missing one (core/show_pages.py), so
+// Visualize either 409s or frames a dead page, and every Share mutation can only
+// 409. All of it is withdrawn now.
+describe('read-only header withdraws the Show Page controls', () => {
+ it('offers no Show Page control at all on an archived session', () => {
+ // Live, in chat view: Visualize only (Share + annotate are Show-Page-mode).
+ expect(showPageControlActions(false, false)).toEqual({
+ visualize: true,
+ share: false,
+ annotate: false,
+ });
+ // Live, framing the page: back-to-chat + Share + the annotation control.
+ expect(showPageControlActions(false, true)).toEqual({
+ visualize: true,
+ share: true,
+ annotate: true,
+ });
+ // Archived: nothing, in either mode. Not "disabled" — absent.
+ expect(showPageControlActions(true, false)).toEqual({
+ visualize: false,
+ share: false,
+ annotate: false,
+ });
+ expect(showPageControlActions(true, true)).toEqual({
+ visualize: false,
+ share: false,
+ annotate: false,
+ });
+ });
+
+ it('falls back out of Show Page mode when the session turns read-only', () => {
+ // The stale-tab shape: this tab was already framing the page when the
+ // archived 409 converged. Back-to-chat IS the withdrawn Visualize button, so
+ // staying framed would strand the reader on an offline page — and leave the
+ // chat surface hidden with no iframe, i.e. blank.
+ expect(isShowPageActive(false, true)).toBe(true);
+ expect(isShowPageActive(true, true)).toBe(false);
+ // Unchanged in chat view.
+ expect(isShowPageActive(false, false)).toBe(false);
+ expect(isShowPageActive(true, false)).toBe(false);
+ });
+
+ it('renders an archived header with the title and badge but no Show Page button', () => {
+ // Only the read-only header is reachable here: the live one renders
+ // AgentRoutePicker, which calls useApi() and throws without an ApiProvider.
+ // The pure matrix above covers the live side.
+ const markup = render(
+ <ChatHeaderBar
+ session={session({ status: 'archived' })}
+ agents={[]}
+ defaultAgentName={null}
+ onPatch={async () => undefined}
+ onBack={() => undefined}
+ working={false}
+ showPageMode={false}
+ showPageBusy={false}
+ onToggleShowPage={() => undefined}
+ annotation={{
+ state: null,
+ iframeRef: { current: null },
+ handleIframeLoad: () => undefined,
+ enable: () => undefined,
+ disable: () => undefined,
+ setMode: () => undefined,
+ }}
+ readOnly
+ />,
+ );
+ // The header did render (so the absences below are not a blank component).
+ expect(markup).toContain('Model Hub');
+ expect(markup).toContain('Archived');
+ expect(markup).toContain('Back');
+ // …and offers no Show Page affordance, disabled or otherwise.
+ expect(markup).not.toContain('Visualize');
+ expect(markup).not.toContain('Back to chat');
+ expect(markup).not.toContain('Share');
+ // The title is static text, not a click-to-edit button (round-two behaviour,
+ // re-asserted here so the header render is checked as a whole).
+ expect(countButtons(markup)).toBe(1); // just Back
+ });
+});
+
+// ── Codex review #4 (Composer.tsx / ChatPage.tsx:2426) ────────────────────────
+// Round 3 classified the Stop button as "safe — readOnly && busy is unreachable".
+// That was wrong. archive_session cannot cancel an in-flight chat turn inside its
+// transaction (the turn lives in the controller process, reachable only over the
+// internal socket), so the DELETE route commits the archive FIRST and cancels
+// best-effort afterwards. ChatPage bootstraps ``busy`` from the controller's
+// ``turn_state.foreground`` — not the row's ``agent_status``, which archive does
+// reset — so an archived chat opened inside that cancellation window loads with
+// readOnly AND busy true. In that state the busy branch rendered an ENABLED Stop
+// button and its "working" placeholder overrode placeholderArchived.
+//
+// ``busy && disabled`` is incoherent for every Composer caller, not just this
+// one, so it is resolved in the shared component (``busyControls``) rather than
+// by pre-clearing ``busy`` at the call site.
+describe('a disabled composer has no live-turn controls', () => {
+ const composer = (props: { busy?: boolean; disabled?: boolean }) =>
+ render(
+ <Composer
+ onSend={() => undefined}
+ onStop={() => undefined}
+ placeholder={en.chat.compose.placeholderArchived}
+ {...props}
+ />,
+ );
+
+ it('keeps Stop and the busy placeholder while busy and writable', () => {
+ const markup = composer({ busy: true });
+ // Unchanged live behaviour: Stop is offered, and "working" wins over the
+ // caller's idle placeholder override.
+ expect(markup).toContain(`aria-label="${en.chat.compose.stop}"`);
+ expect(markup).toContain(en.chat.compose.placeholderBusy);
+ expect(markup).not.toContain(en.chat.compose.placeholderArchived);
+ });
+
+ it('withdraws Stop when the same turn is showing in a read-only chat', () => {
+ const markup = composer({ busy: true, disabled: true });
+ expect(markup).not.toContain(`aria-label="${en.chat.compose.stop}"`);
+ // Not merely hidden-Stop: the row falls back to the ordinary Send button,
+ // which is inert because ``disabled`` already clears ``canSubmit``.
+ expect(markup).toContain(`aria-label="${en.chat.compose.send}"`);
+ expect(countDisabledButtons(markup)).toBe(countButtons(markup));
+ });
+
+ it('lets the archived placeholder win over the busy one, so the reason is readable', () => {
+ const markup = composer({ busy: true, disabled: true });
+ // This is the i18n-visible half of the same defect: placeholderBusy is not the
+ // truth for a session that can never accept a queued message.
+ expect(markup).toContain(en.chat.compose.placeholderArchived);
+ expect(markup).not.toContain(en.chat.compose.placeholderBusy);
+ // And the textarea is inert (the plain path honours ``disabled`` since r2).
+ expect(markup).toContain('<textarea');
+ expect(markup).toContain('disabled=""');
+ });
+
+ // The busy branch's sibling "send to queue" button needs no case of its own: it
+ // is gated on ``canSubmit``, which ``disabled`` already clears, so it never
+ // rendered here even before this fix.
+});
+
+// ── Codex review #5a (ChatPage.tsx:1280) ──────────────────────────────────────
+// Round 2 wired convergence into ``sendMessage`` only. The next verb the reviewer
+// tried — a rename / agent re-route — got its 409 stored as error text while the
+// title editor and route picker stayed live, so it could re-issue a permanently
+// rejected PATCH forever. Rather than add a second per-verb branch (which is what
+// produced this finding three rounds running), convergence moved UP to the API
+// layer: ``handleApiError`` announces every ``session_archived`` body via
+// ``onSessionArchived`` and ChatPage subscribes once. ``isSessionArchivedError`` is
+// the classifier for that layer's already-parsed ``ApiError``; the path→session-id
+// half is pinned in ui/src/context/ApiErrorParse.test.ts.
+describe('archived conflicts converge whatever the verb', () => {
+ it('recognizes the archived conflict on an ApiError, not just a raw body', () => {
+ // What ``updateSession``/``forkSession``/``ensureShowPage`` reject with, once
+ // handleApiError has parsed the structured body.
+ expect(isSessionArchivedError({ name: 'ApiError', status: 409, code: 'session_archived' })).toBe(true);
+ // Every other rejection stays an ordinary, reportable error.
+ expect(isSessionArchivedError({ name: 'ApiError', status: 409, code: 'backend_locked' })).toBe(false);
+ expect(isSessionArchivedError({ name: 'ApiError', status: 404, code: null })).toBe(false);
+ // A network failure is a plain Error with no code — must not be mistaken for a
+ // terminal archive, or an offline tab would freeze itself read-only.
+ expect(isSessionArchivedError(new Error('Failed to fetch'))).toBe(false);
+ expect(isSessionArchivedError(null)).toBe(false);
+ expect(isSessionArchivedError(undefined)).toBe(false);
+ });
+
+ it('converges the same way for every verb, because they share one reducer', () => {
+ // Whichever write reported it, the applied fact is identical: the loaded row
+ // turns archived, which is what flips readOnly and withdraws the controls that
+ // issued the doomed request in the first place.
+ const stale = session({ status: 'active' });
+ const converged = markSessionArchived(stale, stale.id);
+ expect(isSessionReadOnly(converged)).toBe(true);
+ // ...and with readOnly true, the title editor and the route picker are both
+ // gone, so a rejected PATCH cannot be re-issued from this render.
+ const markup = render(
+ <ChatHeaderBar
+ session={converged!}
+ agents={[]}
+ defaultAgentName={null}
+ onPatch={async () => undefined}
+ onBack={() => undefined}
+ working={false}
+ showPageMode={false}
+ showPageBusy={false}
+ onToggleShowPage={() => undefined}
+ annotation={{
+ state: null,
+ iframeRef: { current: null },
+ handleIframeLoad: () => undefined,
+ enable: () => undefined,
+ disable: () => undefined,
+ setMode: () => undefined,
+ }}
+ readOnly
+ />,
+ );
+ expect(markup).toContain('Model Hub');
+ expect(countButtons(markup)).toBe(1); // Back only: no pencil, no route picker
+ });
+
+ it('has distinct copy for a blocked edit and a blocked send', () => {
+ // ``errors.session_archived`` (what handleApiError resolves) is Show-Page-worded
+ // and wrong for a rename, so the PATCH path says so in its own words. Both keys
+ // must exist and differ, or one of the two verbs reports the other's reason.
+ expect(en.chat.archived.editBlocked).toBeTruthy();
+ expect(en.chat.archived.sendBlocked).toBeTruthy();
+ expect(en.chat.archived.editBlocked).not.toBe(en.chat.archived.sendBlocked);
+ });
+});
+
+// ── Codex review #5b (ChatPage.tsx:3257) ──────────────────────────────────────
+// Round 3 classified this "safe" because the write is a MACHINE-scoped vault secret
+// the server accepts. That missed the point: archiving expired the session's
+// provision requests, so an enabled Provide button tells the reader an agent is
+// waiting for a secret when none is. The defect is the affordance asserting a live
+// request, not the write. Locked (not hidden) for the same reason the quick-reply
+// group is: the card is the transcript record of what was asked.
+describe('read-only transcript locks the secret-request cards', () => {
+ it('renders the recorded ask, disabled, with the reason', () => {
+ const locked = render(<SecretRequestCard name="OPENAI_API_KEY" readOnly />);
+ // Still legible as a transcript entry...
+ expect(locked).toContain('OPENAI_API_KEY');
+ expect(locked).toContain(en.vaults.request.provide);
+ // ...and inert, with the expiry stated rather than implied.
+ expect(countDisabledButtons(locked)).toBe(countButtons(locked));
+ expect(countButtons(locked)).toBe(1);
+ expect(locked).toContain(en.vaults.request.expired);
+ // No dialog is mounted at all, so there is no path to the vault write. (The
+ // live card can't be rendered here for contrast: it calls useApi().)
+ expect(locked).not.toContain(en.vaults.request.title);
+ });
+
+ it('threads readOnly from the transcript row through Markdown into the card', () => {
+ // ``$<NAME>`` in an AGENT reply is what mints the card (linkifySecretRequests).
+ const ask = agentWithQuickReplies();
+ const message = { ...ask, text: 'I need $<OPENAI_API_KEY> to continue.', content: {} } as WorkbenchMessage;
+
+ const archived = render(
+ <MessageRow
+ message={message}
+ session={session({ status: 'archived' })}
+ messageFontSize={13}
+ onQuickReply={() => undefined}
+ readOnly
+ />,
+ );
+ expect(archived).toContain('OPENAI_API_KEY');
+ // The row's only button is the locked card — nothing clickable survives.
+ expect(countButtons(archived)).toBe(1);
+ expect(countDisabledButtons(archived)).toBe(1);
+ expect(archived).toContain(en.vaults.request.expired);
+ });
+
+ it('leaves the marker plain text on a NON-agent bubble, read-only or not', () => {
+ // Pre-existing security gate (``secretRequests`` is keyed to authorship), pinned
+ // here so the new readOnly prop can't be read as the thing that governs it.
+ const userMessage = {
+ id: 'msg_user',
+ type: 'user',
+ author: 'user',
+ source: 'user',
+ author_name: null,
+ text: 'my key is $<OPENAI_API_KEY>',
+ content: {},
+ metadata: {},
+ created_at: '2026-07-27T04:05:00Z',
+ } as unknown as WorkbenchMessage;
+
+ for (const readOnly of [false, true]) {
+ const markup = render(
+ <MessageRow
+ message={userMessage}
+ session={session({ status: readOnly ? 'archived' : 'active' })}
+ messageFontSize={13}
+ onQuickReply={() => undefined}
+ readOnly={readOnly}
+ />,
+ );
+ expect(markup).toContain('OPENAI_API_KEY');
+ expect(markup).not.toContain(en.vaults.request.provide);
+ expect(countButtons(markup)).toBe(0);
+ }
+ });
+});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index c22f5d032..1ff9a6e78 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -39,7 +39,17 @@ import { ShowPageShareControl } from './ShowPageShareControl';
import { ShowPageAnnotateControl } from './ShowPageAnnotateControl';
import { useShowPageAnnotation, type AnnotationBridge } from './useShowPageAnnotation';
import { SelectionQuoteToolbar } from './SelectionQuoteToolbar';
+import {
+ isSessionArchivedConflict,
+ isSessionArchivedError,
+ isSessionReadOnly,
+ isShowPageActive,
+ markSessionArchived,
+ showPageControlActions,
+ transcriptSelectionActions,
+} from './sessionArchived';
import { InstallHint } from '../InstallHint';
+import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { ChatImage } from '../ui/chat-image';
import { FileCard } from '../ui/file-card';
@@ -152,20 +162,28 @@ export const ChatPage: React.FC = () => {
const chatSurfaceRef = useRef<HTMLDivElement>(null);
useIosKeyboardInset(chatSurfaceRef);
+ // Loaded session (null while bootstrapping — ChatPage renders a loader until
+ // it's set). Lifted above the composer bridge + show-page logic that gate on it.
+ const [session, setSession] = useState<WorkbenchSession | null>(null);
+ // Archive is terminal: an archived transcript stays fully readable (search's
+ // "include archived" opt-in links straight here) but every mutation is refused
+ // server-side, so the chat renders read-only — no composer, no rename, no
+ // re-route, no transcript control that would write to the session, and no Show
+ // Page controls (archive takes the page offline and refuses to create one, so
+ // Visualize and Share could only fail; see showPageControlActions).
+ const readOnly = isSessionReadOnly(session);
+
// Chat-page-wide drag-and-drop: dropping files anywhere over the chat surface
// (not just the input row) stages them on the composer via its imperative
// handle. Desktop-only in practice — touch fires no drag events — and disabled
- // until a session exists (the upload endpoint is session-scoped).
+ // until a session exists (the upload endpoint is session-scoped) or when the
+ // session is archived (staged files could never be sent).
const composerRef = useRef<ComposerHandle>(null);
const { dragging: fileDragging, handlers: fileDropHandlers } = useFileDrop(
(files) => composerRef.current?.addFiles(files),
- { disabled: !sessionId },
+ { disabled: !sessionId || readOnly },
);
- // Loaded session (null while bootstrapping — ChatPage renders a loader until
- // it's set). Lifted above the composer bridge + show-page logic that gate on it.
- const [session, setSession] = useState<WorkbenchSession | null>(null);
-
// Show Page toggle: swap the chat surface (transcript + composer, NOT the
// header bar) for this session's Show Page in an iframe, and back. Declared
// before the composer bridge target, which depends on showPageMode.
@@ -175,6 +193,18 @@ export const ChatPage: React.FC = () => {
// next toggle (the page row already exists, so `existed` alone won't re-prompt).
const showPagePromptRetryRef = useRef<Set<string>>(new Set());
const [showPageUrl, setShowPageUrl] = useState<string | null>(null);
+ // Show Page mode as the page actually RENDERS it. A read-only (archived)
+ // session withdraws the whole Show Page action cluster — Visualize, Share and
+ // the annotation control (see showPageControlActions) — and back-to-chat is
+ // that same Visualize button, so a tab that was ALREADY framing the page when
+ // the session went archived (the stale-tab 409-convergence path) would
+ // otherwise be stranded on a page it can no longer leave, and which archive
+ // already forced offline. Fall back to the transcript instead.
+ //
+ // Derived rather than an effect on purpose: the fallback lands in the SAME
+ // render that flips ``readOnly``. An effect would first commit one frame with
+ // the chat surface still hidden and the iframe already gone — a blank chat.
+ const showPageActive = isShowPageActive(readOnly, showPageMode);
// True while the share popover is open. The popover floats over the Show Page
// iframe; making the iframe inert lets an outside tap there reach the parent
// document so the (non-modal) popover dismisses, without modal-blocking the
@@ -190,7 +220,7 @@ export const ChatPage: React.FC = () => {
// closing then reopening the SAME session's page (showPageUrl unchanged) would
// show the stale enabled/mode and could send control messages to the freshly
// remounted overlay before it rebroadcasts. Re-points reset via the URL change.
- const annotation = useShowPageAnnotation(showPageMode ? showPageUrl : null);
+ const annotation = useShowPageAnnotation(showPageActive ? showPageUrl : null);
useEffect(() => {
// ChatPage is reused across :sessionId — clear all show-page state so the
// next chat starts in chat view with a live (not stuck-busy) toggle.
@@ -254,10 +284,15 @@ export const ChatPage: React.FC = () => {
// mounted + insertable: a chat is open (sessionId), its session has loaded
// (before that ChatPage shows a loader — the composer isn't rendered yet), and
// the Show Page iframe hasn't replaced the composer. Otherwise an insert would
- // silently no-op against a null composerRef.
+ // silently no-op against a null composerRef. An archived (read-only) chat is
+ // also not insertable — its composer is disabled, so the insert would land in a
+ // box that can never be sent.
const composerTarget = useMemo<ComposerInsertTarget | null>(
- () => (sessionId && session != null && !showPageMode ? { sessionId, insertSessionReference } : null),
- [sessionId, session, showPageMode, insertSessionReference],
+ () =>
+ sessionId && session != null && !showPageActive && !readOnly
+ ? { sessionId, insertSessionReference }
+ : null,
+ [sessionId, session, showPageActive, readOnly, insertSessionReference],
);
useRegisterComposerTarget(composerTarget);
@@ -594,19 +629,63 @@ export const ChatPage: React.FC = () => {
cancelled = true;
};
}, [api]);
- const refreshSessionRowUntilNativeBound = useCallback(async () => {
+ // Authoritative reload of the loaded session row, guarded so a late resolve
+ // can't stamp one chat's row onto the chat the user moved to. Best-effort by
+ // contract: every caller must already be correct if the request never lands.
+ const refreshSessionRow = useCallback(async () => {
const id = sessionIdRef.current;
- if (!id || hasNativeRef.current) return;
+ if (!id) return;
try {
// cache:false — an earlier refresh (page open / reconnect) may have
- // cached the still-native-less row; a quick turn ending inside the read
- // cache's TTL would reuse it and leave the picker unlocked.
+ // cached a stale row; reusing it inside the read cache's TTL is exactly
+ // what the callers are trying to escape.
const row = await api.getSession(id, { cache: false });
setSession((prev) => (prev && prev.id === row.id && row.id === sessionIdRef.current ? row : prev));
} catch {
// Best-effort: the next recovery point retries.
}
}, [api]);
+ const refreshSessionRowUntilNativeBound = useCallback(async () => {
+ if (hasNativeRef.current) return;
+ await refreshSessionRow();
+ }, [refreshSessionRow]);
+
+ // ── Converging on a terminal archive this tab missed ────────────────────────
+ //
+ // A backgrounded / offline tab can miss the archive SSE for a session that
+ // already has a native_session_id, and refreshSessionRowUntilNativeBound then
+ // early-returns on every reconnect/focus — so a 409 ``session_archived`` from
+ // the FIRST write the user attempts is the only point at which this tab learns
+ // the truth. Whichever write that is: sending, renaming, re-routing the agent,
+ // forking a quote out, or any Show Page mutation. Converging per-verb is what
+ // produced the same review finding three rounds running, so the fact is applied
+ // ONCE here and the verbs just report their own message.
+ //
+ // Patch first, reload second: the 409 IS the server's answer, and this is
+ // precisely the tab whose connectivity is in doubt, so a ``getSession`` that
+ // fails must not leave the chat writable. Patching ``status`` flips ``readOnly``,
+ // which disables the composer and withdraws every other mutating control; the
+ // authoritative refresh then follows, best-effort, for the rest of the frozen row.
+ const convergeSessionArchived = useCallback(
+ (archivedSessionId: string) => {
+ // A late response for a chat the user already left must not stamp its
+ // archive onto the chat now mounted (markSessionArchived guards the row
+ // identity too; this also skips the needless refresh).
+ if (archivedSessionId !== sessionIdRef.current) return;
+ setSession((prev) => markSessionArchived(prev, archivedSessionId));
+ void refreshSessionRow();
+ },
+ [refreshSessionRow],
+ );
+
+ // Every write that goes through the shared JSON helpers (updateSession,
+ // forkSession, ensureShowPage, the Show Page visibility / share-id / rotate /
+ // icon mutations …) reports its archived 409 through this one API-layer
+ // subscription, including the ones issued by components this page owns rather
+ // than by the page itself. ``sendMessage`` is the exception by construction: it
+ // uses a raw ``apiFetch`` so it can read ``queued``/``already_answered`` off a
+ // non-2xx-aware response, so it calls the same converger directly.
+ useEffect(() => api.onSessionArchived(convergeSessionArchived), [api, convergeSessionArchived]);
useEffect(() => {
oldestLoadedIdRef.current = messages[0]?.id ?? null;
@@ -1218,9 +1297,23 @@ export const ChatPage: React.FC = () => {
// error on the chat they moved to (Codex P2). The turn still ran for the
// original session; its rows live there.
if (sessionId !== sessionIdRef.current) return;
+ if (isSessionArchivedConflict(response.status, body)) {
+ // Archive is terminal, so this is not a retryable failure — it is state
+ // this tab missed. Raw ``apiFetch`` never reaches ``handleApiError``, so
+ // the shared subscription can't see this one: call the same converger
+ // directly. Only the turn state and the message are send-specific.
+ setWorking(false);
+ setError(t('chat.archived.sendBlocked'));
+ convergeSessionArchived(sessionId);
+ return false;
+ }
if (!response.ok) {
setWorking(false);
- throw new Error(body?.detail ? String(body.detail) : `HTTP ${response.status}`);
+ // Routes answer ``{"error": ...}``; ``detail`` is only FastAPI's own
+ // validation shape. Try both before the bare status code.
+ throw new Error(
+ body?.error ? String(body.error) : body?.detail ? String(body.detail) : `HTTP ${response.status}`,
+ );
}
if (body?.already_answered) {
// A duplicate quick-reply the backend already had (stale tab / missed
@@ -1263,7 +1356,7 @@ export const ChatPage: React.FC = () => {
}
}
},
- [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages],
+ [sessionId, appendMessage, refreshQueue, markWorking, reloadLatestMessages, convergeSessionArchived, t],
);
// @ mention source: all enabled Agents, filtered client-side (the set is small
@@ -1331,7 +1424,12 @@ export const ChatPage: React.FC = () => {
// build the visualization. sendMessage returns false on a failed send;
// track it so the NEXT toggle retries — the page row exists after this,
// so `existed` alone would never re-prompt a created-but-unprompted page.
- if (res.existed === false || showPagePromptRetryRef.current.has(sid)) {
+ // Never on a read-only (archived) session: the store refuses to CREATE a
+ // page there, but a session archived after a failed prompt is still in the
+ // retry set, and re-prompting it would only 409. The header no longer
+ // offers the toggle at all once the session reads archived, so this is the
+ // callback-level backstop for an invocation that raced that render.
+ if (!readOnly && (res.existed === false || showPagePromptRetryRef.current.has(sid))) {
void sendMessage(t('chat.showPage.prompt')).then((sent) => {
if (sent === false) showPagePromptRetryRef.current.add(sid);
else showPagePromptRetryRef.current.delete(sid);
@@ -1346,7 +1444,7 @@ export const ChatPage: React.FC = () => {
// strand the shared busy flag on a session the user switched to).
setShowPageBusy(false);
}
- }, [sessionId, showPageMode, api, sendMessage, t]);
+ }, [sessionId, showPageMode, readOnly, api, sendMessage, t]);
// When the share control resolves the page (open) or flips its visibility, the
// serving route changes (private → /show/, public → /p/). Re-point the iframe
@@ -1648,10 +1746,17 @@ export const ChatPage: React.FC = () => {
if (patchedId !== sessionIdRef.current) return;
setSession(updated);
} catch (err: any) {
- if (patchedId === sessionIdRef.current) setError(err?.message ?? String(err));
+ if (patchedId !== sessionIdRef.current) return;
+ // The archive itself has already converged through the shared
+ // ``onSessionArchived`` subscription (the title editor and route picker are
+ // gone by the next render, so this PATCH cannot be re-issued). Only the
+ // wording is per-verb: the global ``errors.session_archived`` copy that
+ // ``handleApiError`` resolved is Show-Page-worded, which is wrong for a
+ // rename or a re-route.
+ setError(isSessionArchivedError(err) ? t('chat.archived.editBlocked') : (err?.message ?? String(err)));
}
},
- [api, session],
+ [api, session, t],
);
// Ordered media-proxy image URLs across the whole session — feeds the lightbox
@@ -1827,16 +1932,17 @@ export const ChatPage: React.FC = () => {
onPatch={patch}
onBack={goBack}
working={working}
- showPageMode={showPageMode}
+ showPageMode={showPageActive}
showPageBusy={showPageBusy}
onToggleShowPage={toggleShowPage}
onShowPageVisibilityChange={handleShowPagePayload}
onShareOpenChange={setShareOpen}
annotation={annotation}
onAnnotateOpenChange={setAnnotateOpen}
+ readOnly={readOnly}
/>
- {showPageMode && showPageUrl && (
+ {showPageActive && showPageUrl && (
// The session's Show Page (same-origin /show/<id>/ private or /p/<share>/
// public; URL resolved from ensureShowPage) fills the chat area while the
// header bar stays. The chat surface below is kept mounted but hidden.
@@ -1867,7 +1973,7 @@ export const ChatPage: React.FC = () => {
{/* Chat surface stays MOUNTED while the Show Page is shown — just hidden —
so unsent composer text + staged attachments survive the toggle instead
of being discarded on unmount. */}
- <div className={clsx('flex min-h-0 flex-1 flex-col', showPageMode && 'hidden')}>
+ <div className={clsx('flex min-h-0 flex-1 flex-col', showPageActive && 'hidden')}>
{error && (
<div className="mx-auto mt-3 w-full max-w-[1080px] rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive">
{error}
@@ -1890,6 +1996,7 @@ export const ChatPage: React.FC = () => {
onQuickReply={handleQuickReply}
onQuoteSelection={quoteSelectionToComposer}
onAskInNewSession={askInNewSession}
+ readOnly={readOnly}
followingTailRef={followingTailRef}
activity={{
enabled: showAgentActivity,
@@ -1909,7 +2016,13 @@ export const ChatPage: React.FC = () => {
onToggleTools: toggleToolCalls,
}}
footer={
- sessionId ? (
+ // Archive expires every pending vault request for the session in the
+ // same transaction that flips the status, so these cards are already
+ // empty for a freshly-loaded archived chat. A tab that loaded them
+ // BEFORE the archive still holds them in state, though — the same
+ // stale-tab case that reaches the archived 409 — and their
+ // approve/deny buttons would write to a session that can't accept it.
+ sessionId && !readOnly ? (
<VaultChatRequests
requests={vaultRequests}
onResolved={refreshVaultRequests}
@@ -1923,8 +2036,14 @@ export const ChatPage: React.FC = () => {
sessionId={sessionId ?? ''}
enabled={bannerEnabled === true}
/>
- <QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
- {sessionId && pendingApprovals.length > 0 ? (
+ {/* Archive reclaims all unsent input (queued rows, pending rows, draft),
+ so an archived chat loads with an empty queue. A stale tab can still be
+ holding pre-archive rows, and every button here writes: Send now POSTs
+ the flush, Recall appends into the disabled composer. */}
+ {!readOnly && (
+ <QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
+ )}
+ {sessionId && !readOnly && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
) : null}
{/* key by session so the composer remounts per session — its draft-seeding
@@ -1940,6 +2059,7 @@ export const ChatPage: React.FC = () => {
onDraftChange={onDraftChange}
onSearchAgents={searchAgents}
onSearchSessions={searchSessions}
+ readOnly={readOnly}
/>
</div>
</div>
@@ -2306,31 +2426,46 @@ interface ComposeProps {
onDraftChange: (text: string) => void;
onSearchAgents: ComposerProps['onSearchAgents'];
onSearchSessions: ComposerProps['onSearchSessions'];
+ // Archived session: the composer is inert and explains why.
+ readOnly: boolean;
}
-const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions }) => (
- // shrink-0 pins the bar at the bottom of the fixed-height chat container; the
- // gradient fades the transcript out behind it (no opaque band / hard border)
- // so the input sits close to the bottom edge. The input row is the shared
- // <Composer>, also used by the Workbench home.
- <div
- className="shrink-0 px-4 pb-[calc(1rem+env(safe-area-inset-bottom))] pt-3 md:px-8 md:pb-4"
- style={{ background: 'linear-gradient(to top, var(--background) 65%, transparent)' }}
- >
- <Composer
- ref={composerRef}
- onSend={onSend}
- onStop={onStop}
- busy={busy}
- sessionId={sessionId}
- initialDraft={initialDraft}
- onDraftChange={onDraftChange}
- onSearchAgents={onSearchAgents}
- onSearchSessions={onSearchSessions}
- autoFocus
- />
- </div>
-);
+const Compose: React.FC<ComposeProps> = ({ composerRef, onSend, onStop, busy, sessionId, initialDraft, onDraftChange, onSearchAgents, onSearchSessions, readOnly }) => {
+ const { t } = useTranslation();
+ return (
+ // shrink-0 pins the bar at the bottom of the fixed-height chat container; the
+ // gradient fades the transcript out behind it (no opaque band / hard border)
+ // so the input sits close to the bottom edge. The input row is the shared
+ // <Composer>, also used by the Workbench home.
+ <div
+ className="shrink-0 px-4 pb-[calc(1rem+env(safe-area-inset-bottom))] pt-3 md:px-8 md:pb-4"
+ style={{ background: 'linear-gradient(to top, var(--background) 65%, transparent)' }}
+ >
+ <Composer
+ ref={composerRef}
+ onSend={onSend}
+ onStop={onStop}
+ busy={busy}
+ sessionId={sessionId}
+ initialDraft={initialDraft}
+ onDraftChange={onDraftChange}
+ onSearchAgents={onSearchAgents}
+ onSearchSessions={onSearchSessions}
+ // Read-only archived session: reuse the composer's own disabled +
+ // placeholder props rather than swapping in a notice bar. ``busy`` is NOT
+ // reliably false here — archive commits before the controller turn is
+ // cancelled, and this page bootstraps ``working`` from the controller's
+ // turn state — so the composer itself suppresses the busy branch while
+ // ``disabled`` (``busyControls``), which is what keeps Stop off an archived
+ // chat and lets this placeholder win. autoFocus is dropped so opening an
+ // archived chat doesn't pop the keyboard on an inert box.
+ disabled={readOnly}
+ placeholder={readOnly ? t('chat.compose.placeholderArchived') : undefined}
+ autoFocus={!readOnly}
+ />
+ </div>
+ );
+};
interface ChatHeaderBarProps {
session: WorkbenchSession;
@@ -2339,6 +2474,8 @@ interface ChatHeaderBarProps {
onPatch: (changes: Partial<WorkbenchSession>) => Promise<void>;
onBack: () => void;
working: boolean;
+ // The EFFECTIVE mode (ChatPage passes ``showPageActive``): whether the page is
+ // actually framed right now, which a read-only session is never.
showPageMode: boolean;
showPageBusy: boolean;
onToggleShowPage: () => void;
@@ -2346,10 +2483,19 @@ interface ChatHeaderBarProps {
onShareOpenChange?: (open: boolean) => void;
annotation: AnnotationBridge;
onAnnotateOpenChange?: (open: boolean) => void;
+ // Archived session: the title and the agent route render as static text — the
+ // server refuses both edits with 409 — and the Show Page action cluster is
+ // withdrawn entirely (see showPageControlActions).
+ readOnly: boolean;
}
-const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange }) => {
+// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
+// which renders the header alone rather than mounting the whole page. Note the
+// live (non-readOnly) header pulls in AgentRoutePicker → useApi, so only the
+// read-only rendering is reachable without an ApiProvider.
+export const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultAgentName, onPatch, onBack, working, showPageMode, showPageBusy, onToggleShowPage, onShowPageVisibilityChange, onShareOpenChange, annotation, onAnnotateOpenChange, readOnly }) => {
const { t } = useTranslation();
+ const showPageActions = showPageControlActions(readOnly, showPageMode);
const defaultAgent = defaultAgentName ? agents.find((agent) => agent.name === defaultAgentName) : null;
// Backend locks once a NATIVE conversation exists — a native can only be
// resumed by the backend that created it — or while a turn is RUNNING (the
@@ -2403,9 +2549,21 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
>
<ArrowLeft className="size-3.5" />
</Button>
- <TitleField key={session.id} title={session.title} onCommit={(title) => onPatch({ title })} />
- {/* Hidden while the Show Page is open so the view gets the full width. */}
- {!showPageMode && (
+ <TitleField key={session.id} title={session.title} onCommit={(title) => onPatch({ title })} readOnly={readOnly} />
+ {/* Hidden while the Show Page is open so the view gets the full width.
+ On an archived session the route is frozen, so show it as static text
+ plus an Archived badge instead of an interactive picker. */}
+ {!showPageMode && readOnly && (
+ <div className="flex min-w-0 shrink-0 items-center gap-1.5">
+ <span className="truncate text-[12px] font-medium text-muted">
+ {session.agent_name || (defaultAgent ? defaultAgent.name : t('newSession.defaultAgent'))}
+ </span>
+ <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-bold">
+ {t('common.archived')}
+ </Badge>
+ </div>
+ )}
+ {!showPageMode && !readOnly && (
<AgentRoutePicker
value={session}
agents={agents}
@@ -2436,45 +2594,53 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
{/* In Show Page mode the order is: annotation control · back-to-chat ·
Share. The annotation control sits immediately left of back-to-chat;
the Share control stays rightmost. In chat mode only the Visualize
- toggle shows. */}
- <div className="ml-auto flex items-center gap-1.5">
- {showPageMode && (
- <ShowPageAnnotateControl
- state={annotation.state}
- onEnable={annotation.enable}
- onDisable={annotation.disable}
- onSetMode={annotation.setMode}
- onPopoverOpenChange={onAnnotateOpenChange}
- />
- )}
- <Button
- type="button"
- variant={showPageMode ? 'secondary' : 'ghost'}
- onClick={onToggleShowPage}
- disabled={showPageBusy}
- aria-label={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- title={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- className="h-7 shrink-0 gap-1.5 px-2"
- >
- {showPageBusy ? (
- <Loader2 className="size-3.5 animate-spin" />
- ) : showPageMode ? (
- <MessageSquare className="size-3.5" />
- ) : (
- <Presentation className="size-3.5" />
+ toggle shows.
+
+ The whole cluster is withdrawn on an archived session — archive takes
+ its Show Page offline and refuses to create a missing one, so none of
+ the three can do anything but 409 or frame a dead page. There is no
+ read-only page-serving path to offer instead; see
+ showPageControlActions for the per-control reasoning. */}
+ {showPageActions.visualize && (
+ <div className="ml-auto flex items-center gap-1.5">
+ {showPageActions.annotate && (
+ <ShowPageAnnotateControl
+ state={annotation.state}
+ onEnable={annotation.enable}
+ onDisable={annotation.disable}
+ onSetMode={annotation.setMode}
+ onPopoverOpenChange={onAnnotateOpenChange}
+ />
)}
- <span className="hidden text-xs font-medium md:inline">
- {showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
- </span>
- </Button>
- {showPageMode && (
- <ShowPageShareControl
- sessionId={session.id}
- onPayloadChange={onShowPageVisibilityChange}
- onOpenChange={onShareOpenChange}
- />
- )}
- </div>
+ <Button
+ type="button"
+ variant={showPageMode ? 'secondary' : 'ghost'}
+ onClick={onToggleShowPage}
+ disabled={showPageBusy}
+ aria-label={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
+ title={showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
+ className="h-7 shrink-0 gap-1.5 px-2"
+ >
+ {showPageBusy ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : showPageMode ? (
+ <MessageSquare className="size-3.5" />
+ ) : (
+ <Presentation className="size-3.5" />
+ )}
+ <span className="hidden text-xs font-medium md:inline">
+ {showPageMode ? t('chat.showPage.backToChat') : t('chat.showPage.open')}
+ </span>
+ </Button>
+ {showPageActions.share && (
+ <ShowPageShareControl
+ sessionId={session.id}
+ onPayloadChange={onShowPageVisibilityChange}
+ onOpenChange={onShareOpenChange}
+ />
+ )}
+ </div>
+ )}
</div>
</div>
);
@@ -2483,9 +2649,11 @@ const ChatHeaderBar: React.FC<ChatHeaderBarProps> = ({ session, agents, defaultA
interface TitleFieldProps {
title: string | null;
onCommit: (next: string | null) => void;
+ // Archived session: render the title as plain text, with no edit affordance.
+ readOnly?: boolean;
}
-const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit }) => {
+const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit, readOnly }) => {
const { t } = useTranslation();
const [editing, setEditing] = useState(false);
const [value, setValue] = useState(title ?? '');
@@ -2499,6 +2667,14 @@ const TitleField: React.FC<TitleFieldProps> = ({ title, onCommit }) => {
if (editing) inputRef.current?.focus();
}, [editing]);
+ if (readOnly) {
+ return (
+ <span className="min-w-0 flex-1 truncate text-[16px] font-bold text-foreground">
+ {title || t('chat.untitled')}
+ </span>
+ );
+ }
+
if (!editing) {
return (
<button
@@ -2562,6 +2738,11 @@ interface TranscriptProps {
// ask in a new session seeded with the quote.
onQuoteSelection: (text: string) => void;
onAskInNewSession: (text: string) => void;
+ // Archived session: the transcript stays fully readable, but every control
+ // that would write to THIS session is withdrawn — an old quick reply would
+ // POST a message (409), and Quote would insert into a composer that can never
+ // send. Hidden/frozen rather than left clickable-and-erroring.
+ readOnly: boolean;
// Owned by ChatPage, driven here: true while the viewport follows the live
// tail. Lifted so the retained-window trim (ChatPage.appendMessage) can tell
// when dropping the oldest rows is safe (reader pinned to the bottom).
@@ -2606,11 +2787,13 @@ const Transcript: React.FC<TranscriptProps> = ({
onQuickReply,
onQuoteSelection,
onAskInNewSession,
+ readOnly,
followingTailRef,
activity,
footer,
}) => {
const { t } = useTranslation();
+ const selectionActions = transcriptSelectionActions(session, readOnly);
const forkSourceSessionId =
typeof session.metadata?.fork_source_session_id === 'string'
? session.metadata.fork_source_session_id
@@ -2955,10 +3138,12 @@ const Transcript: React.FC<TranscriptProps> = ({
<div className="relative flex min-h-0 flex-1 flex-col">
<SelectionQuoteToolbar
containerRef={scrollRef}
- onQuote={onQuoteSelection}
- // Forking needs a bound native session (mirrors the sidebar's fork gate);
- // omit the action otherwise so it isn't offered just to 409.
- onAskInNew={session.native_session_id ? onAskInNewSession : undefined}
+ // Both write actions are omitted rather than offered just to fail —
+ // see transcriptSelectionActions. On an archived session that leaves only
+ // the touch Copy fallback, and on desktop the toolbar renders nothing.
+ onQuote={selectionActions.quote ? onQuoteSelection : undefined}
+ // Forking needs a bound native session (mirrors the sidebar's fork gate).
+ onAskInNew={selectionActions.askInNew ? onAskInNewSession : undefined}
/>
<div ref={scrollRef} onScroll={handleScroll} className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8">
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
@@ -2984,6 +3169,7 @@ const Transcript: React.FC<TranscriptProps> = ({
session={session}
messageFontSize={messageFontSize}
onQuickReply={onQuickReply}
+ readOnly={readOnly}
highlighted={message.id === highlightedId}
/>
{after?.map((group) => renderActivityChip(group))}
@@ -3081,6 +3267,10 @@ type MessageRowProps = {
session: WorkbenchSession;
messageFontSize: number;
onQuickReply?: (messageId: string, choice: string) => boolean | void | Promise<boolean | void>;
+ // Archived session: the row still renders in full — including the quick-reply
+ // group and which option was chosen, which is part of the transcript — but the
+ // group is frozen, so an old quick reply can no longer POST a doomed message.
+ readOnly?: boolean;
// When true, this row was the deep-link jump target — wrap it in a brief mint
// fade (``msg-highlight``). Drives the only visual difference for the matched
// message; included in the memo's shallow compare so the highlight on/off
@@ -3096,7 +3286,9 @@ type MessageRowProps = {
// scrolling. The props are referentially stable per row (the message/session
// objects only change when that row's data does, and onQuickReply is a
// useCallback), so the default shallow compare is correct here.
-const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, highlighted }: MessageRowProps) {
+// Exported for the read-only regression test (ChatArchivedReadOnly.test.tsx),
+// which renders a single row rather than mounting the whole page.
+export const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, readOnly, highlighted }: MessageRowProps) {
const { t } = useTranslation();
const navigate = useNavigate();
// Harness rows are collapsed by default; this tracks the per-row expand state.
@@ -3170,6 +3362,9 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
<QuickReplies
options={quickReplyOptions}
chosen={quickReplyChosen}
+ // Archived: keep the record (which options were offered, which was
+ // chosen) but lock the group so no click can start a rejected send.
+ readOnly={readOnly}
onChoose={(choice) => onQuickReply(message.id, choice)}
/>
) : null;
@@ -3194,6 +3389,10 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
// card). Keyed to authorship, not to the card family, so the agent's reverse annotation
// keeps the card it had before that row had its own type.
secretRequests={agentAuthored}
+ // …and on an archived transcript the card is locked: archiving EXPIRED the
+ // session's provision requests, so an enabled Provide button would tell the
+ // reader an agent is waiting for this secret when none is.
+ readOnly={readOnly}
className="vr-markdown--inherit-size"
/>
) : drawsEmptyBodyPlaceholder(row, messageAttachments.length > 0) ? (
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 679c4534a..1ffd53374 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -94,7 +94,8 @@ export interface ComposerProps {
attachments?: ComposerAttachment[],
references?: MentionReference[],
) => boolean | void | Promise<boolean | void>;
- /** A turn is running — the send button becomes a Stop button. */
+ /** A turn is running — the send button becomes a Stop button. Ignored while
+ * ``disabled`` (see the ``busyControls`` note in the body). */
busy?: boolean;
/** Pressed while busy. */
onStop?: () => void;
@@ -102,9 +103,12 @@ export interface ComposerProps {
initialDraft?: string | null;
/** Persist draft changes (chat sessions). */
onDraftChange?: (text: string) => void;
- /** Idle placeholder override; while busy the chat "working" placeholder wins. */
+ /** Idle placeholder override; while busy the chat "working" placeholder wins —
+ * except while ``disabled``, where this override always wins so the caller's
+ * reason (e.g. "archived, read-only") is what the user reads. */
placeholder?: string;
- /** Disable sending (e.g. while the caller creates a session + navigates). */
+ /** Disable sending (e.g. while the caller creates a session + navigates).
+ * Also suppresses every live-turn control — see ``busyControls``. */
disabled?: boolean;
/** Override the row container — e.g. a narrower max-width on the home canvas. */
className?: string;
@@ -446,6 +450,19 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// recording so neither the Send button nor the Enter key can fire mid-record.
const canSubmit =
(hasComposerText || readyAttachments.length > 0) && !uploading && !disabled && !recording;
+ // ``busy && disabled`` is an incoherent pair for ANY caller: ``disabled`` means
+ // this composer may not act on the session, yet the busy branch renders an
+ // ENABLED Stop button (it never consulted ``disabled``) and its "working"
+ // placeholder overrides the caller's own reason for disabling. Resolve it here,
+ // at the shared component, so no call site has to remember to pre-clear ``busy``.
+ //
+ // It is reachable, not theoretical: archiving a session with a running turn
+ // commits the status flip and only THEN cancels the controller turn over the
+ // internal socket (``archive_session``'s docstring — it can't join the
+ // transaction). ChatPage bootstraps ``busy`` from the controller's
+ // ``turn_state.foreground``, not the row's ``agent_status``, so an archived chat
+ // opened inside that window loads read-only AND busy.
+ const busyControls = busy && !disabled;
const update = (next: string) => {
setValue(next);
@@ -556,6 +573,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
variant="ghost"
size="icon"
onClick={() => fileInputRef.current?.click()}
+ // A disabled composer cannot send, so staging attachments (or
+ // recording) is a dead end — gate both media affordances too.
+ disabled={disabled}
aria-label={t('chat.compose.attach')}
className="h-9 w-7 shrink-0"
>
@@ -569,7 +589,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
variant={recording ? 'secondary' : 'ghost'}
size="icon"
onClick={toggleRecording}
- disabled={transcribing}
+ disabled={transcribing || disabled}
aria-label={t(recording ? 'chat.compose.stopRecording' : 'chat.compose.voice')}
className={clsx('h-9 w-7 shrink-0', recording && 'animate-pulse')}
>
@@ -588,7 +608,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
<MentionEditor
ref={mentionRef}
className="flex-1"
- placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
+ placeholder={busyControls ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
disabled={disabled}
autoFocus={autoFocus}
initialText={initialDraft}
@@ -597,7 +617,13 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// Paste-to-upload: only when this composer has an upload target
// (a session), mirroring the picker + drag-drop. uploadFiles itself
// no-ops without a session, so this gate is also defense in depth.
- onPasteFiles={mediaEnabled ? (files) => void uploadFiles(files) : undefined}
+ // ``!disabled`` for the same reason the picker and mic are gated: a
+ // pasted file could never be sent, and the upload endpoint has no
+ // archive guard, so it would persist an orphan attachment. The
+ // editor is also set non-editable while disabled, which should keep
+ // the paste event from reaching Lexical at all — this is the
+ // explicit gate rather than a reliance on that.
+ onPasteFiles={mediaEnabled && !disabled ? (files) => void uploadFiles(files) : undefined}
onChange={(text, references, isDraftSeed) => {
// The editor owns the text; keep the live copy in a ref (no
// re-render) so a fast IME isn't interrupted mid-insert, and only
@@ -630,7 +656,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}
}}
rows={1}
- placeholder={busy ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
+ // The MentionEditor path honours ``disabled``; this plain path never
+ // did, so a disabled composer still accepted typing (only the Send
+ // button was inert). Fixed here so every caller inherits it.
+ disabled={disabled}
+ placeholder={busyControls ? t('chat.compose.placeholderBusy') : placeholder ?? t('chat.compose.placeholder')}
className="max-h-40 min-h-9 flex-1 resize-none bg-transparent py-2 text-[13px] leading-5 text-foreground outline-none placeholder:text-muted"
/>
)}
@@ -651,7 +681,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
)}
{/* 36px (size-9) icon buttons: pink-soft Stop while a turn runs, else a
flat mint Send — design-system variants, not a glowy brand CTA. */}
- {busy ? (
+ {busyControls ? (
<>
{/* Sending while a turn runs is allowed — the backend enqueues it
(202) instead of refusing (Enter does this too). Surface a visible
diff --git a/ui/src/components/workbench/QuickReplies.tsx b/ui/src/components/workbench/QuickReplies.tsx
index 5c18ba6de..f31aa9068 100644
--- a/ui/src/components/workbench/QuickReplies.tsx
+++ b/ui/src/components/workbench/QuickReplies.tsx
@@ -17,11 +17,17 @@ import { Button } from '../ui/button';
export const QuickReplies: React.FC<{
options: string[];
chosen?: string | null;
+ // Read-only transcript (an archived session): the group renders exactly as
+ // recorded — options, and the ✓ on the chosen one — but is locked outright.
+ // The lock already existed for "answered"; a session that can never accept
+ // another message is the same non-interactive state, so it reuses it instead
+ // of hiding the group and losing part of the transcript.
+ readOnly?: boolean;
onChoose: (choice: string) => boolean | void | Promise<boolean | void>;
-}> = ({ options, chosen, onChoose }) => {
+}> = ({ options, chosen, readOnly = false, onChoose }) => {
const [clicked, setClicked] = React.useState<string | null>(null);
const selected = clicked ?? chosen ?? null;
- const locked = selected !== null;
+ const locked = readOnly || selected !== null;
// Once the authoritative answer arrives (``chosen`` loaded from the agent
// message), drop the optimistic lock and let ``chosen`` own the displayed state
diff --git a/ui/src/components/workbench/SearchPage.tsx b/ui/src/components/workbench/SearchPage.tsx
index 8fd01c0c1..1c19e7925 100644
--- a/ui/src/components/workbench/SearchPage.tsx
+++ b/ui/src/components/workbench/SearchPage.tsx
@@ -6,6 +6,7 @@ import { AlertCircle, ChevronLeft, Loader2, Search, X } from 'lucide-react';
import { useMessageSearch } from '../../lib/useMessageSearch';
import { Button } from '../ui/button';
import { Input } from '../ui/input';
+import { Switch } from '../ui/switch';
import { AppSearchResultSection } from './search/AppSearchResults';
import { SearchResultGroup } from './search/SearchResultGroup';
import { useAppSearchResults, useOpenSearchApp } from './search/useAppSearch';
@@ -28,7 +29,12 @@ export const SearchPage: React.FC = () => {
// input from the param on mount and mirror every keystroke back into it.
const [searchParams, setSearchParams] = useSearchParams();
const [query, setQuery] = useState(() => searchParams.get('q') ?? '');
- const { results, loading, error } = useMessageSearch(query);
+ // The archived opt-in rides the URL for the same reason ?q= does: opening a
+ // result and coming back must restore the toggle. It is deliberately NOT
+ // persisted anywhere else — a silently sticky opt-in would change the default
+ // result set for every later search.
+ const includeArchived = searchParams.get('archived') === '1';
+ const { results, loading, error } = useMessageSearch(query, { includeArchived });
const { results: appResults, loading: appsLoading } = useAppSearchResults(query);
const openSearchApp = useOpenSearchApp();
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -50,6 +56,20 @@ export const SearchPage: React.FC = () => {
);
};
+ // Same in-place URL write as the query: flipping the opt-in must not push a
+ // history entry the Back gesture would have to step through.
+ const updateIncludeArchived = (next: boolean) => {
+ setSearchParams(
+ (prev) => {
+ const params = new URLSearchParams(prev);
+ if (next) params.set('archived', '1');
+ else params.delete('archived');
+ return params;
+ },
+ { replace: true },
+ );
+ };
+
// Autofocus the field on mount so typing flows straight in (the search page
// exists only to search). iOS sometimes needs the focus deferred a tick past
// the route transition for the soft keyboard to come up.
@@ -133,6 +153,15 @@ export const SearchPage: React.FC = () => {
{/* Body — own scroll surface. Empty-query hint / no-results / grouped
results, mirroring the desktop palette's states. */}
<div className="min-h-0 flex-1 overflow-y-auto px-4 pb-[calc(1.5rem+env(safe-area-inset-bottom))] pt-3">
+ {/* Archived opt-in — off by default; archived hits open read-only. */}
+ <label className="flex items-center gap-2 px-2.5 pb-1 text-[12px] font-medium text-muted">
+ <Switch
+ checked={includeArchived}
+ onCheckedChange={updateIncludeArchived}
+ label={t('workbench.search.includeArchived')}
+ />
+ {t('workbench.search.includeArchived')}
+ </label>
{showHint && (
<div className="px-2.5 py-12 text-center text-[13px] text-muted">
{t('workbench.search.hint')}
diff --git a/ui/src/components/workbench/SelectionQuoteToolbar.tsx b/ui/src/components/workbench/SelectionQuoteToolbar.tsx
index 2a8ecbf30..7448d9d15 100644
--- a/ui/src/components/workbench/SelectionQuoteToolbar.tsx
+++ b/ui/src/components/workbench/SelectionQuoteToolbar.tsx
@@ -13,17 +13,21 @@ const GAP = 8;
const EDGE = 8;
// A floating toolbar that appears over a text selection inside the chat
-// transcript. "Quote" appends the (quoted) selection to the current composer;
-// "Ask in a new session" forks + prefills the fork's draft (only offered when
-// the session is forkable); "Copy" (touch only) is a fallback for when the OS
-// selection menu doesn't cooperate. It follows the selection through scrolling
-// (hides while scrolling, re-shows at the new spot) and only disappears when
-// the selection is cleared — so the user can scroll to dodge the OS menu.
+// transcript. "Quote" appends the (quoted) selection to the current composer
+// (only offered when the composer can accept it); "Ask in a new session" forks +
+// prefills the fork's draft (only offered when the session is forkable); "Copy"
+// (touch only) is a fallback for when the OS selection menu doesn't cooperate. It
+// follows the selection through scrolling (hides while scrolling, re-shows at the
+// new spot) and only disappears when the selection is cleared — so the user can
+// scroll to dodge the OS menu.
export const SelectionQuoteToolbar: React.FC<{
containerRef: React.RefObject<HTMLDivElement | null>;
- onQuote: (text: string) => void;
- // Omitted when the session can't be forked yet (no native id) — the action is
- // hidden rather than offered just to 409.
+ // Both write actions are optional and hidden rather than offered just to fail.
+ // ``onQuote`` is omitted for a read-only (archived) transcript, whose composer
+ // is disabled — inserting there would only leave an unsendable draft.
+ onQuote?: (text: string) => void;
+ // Omitted when the session can't be forked (no native id yet, or archived —
+ // archive is terminal, so the fork endpoint refuses it).
onAskInNew?: (text: string) => void;
}> = ({ containerRef, onQuote, onAskInNew }) => {
const { t } = useTranslation();
@@ -87,9 +91,12 @@ export const SelectionQuoteToolbar: React.FC<{
// (label widths vary by locale + which actions are shown).
useLayoutEffect(() => {
if (sel && toolbarRef.current) setWidth(toolbarRef.current.offsetWidth);
- }, [sel, onAskInNew, isTouch]);
+ }, [sel, onQuote, onAskInNew, isTouch]);
if (!sel) return null;
+ // Nothing left to offer (read-only transcript on a pointer device, where the
+ // OS already provides copy) — render no chrome rather than an empty bar.
+ if (!onQuote && !onAskInNew && !isTouch) return null;
const dismiss = () => {
window.getSelection()?.removeAllRanges();
@@ -97,7 +104,7 @@ export const SelectionQuoteToolbar: React.FC<{
setCopied(false);
};
const runQuote = () => {
- onQuote(sel.text);
+ onQuote?.(sel.text);
dismiss();
};
const runAsk = () => {
@@ -162,13 +169,17 @@ export const SelectionQuoteToolbar: React.FC<{
style={{ position: 'fixed', top, left, maxWidth: 'calc(100vw - 16px)', transform: 'translateX(-50%)', zIndex: 60 }}
className="flex items-center overflow-x-auto rounded-lg border border-border-strong bg-surface-2 shadow-[0_12px_30px_-8px_rgba(0,0,0,0.7)]"
>
- <Button variant="ghost" className={itemClass} {...activate(runQuote)}>
- <TextQuote className="size-3.5 text-muted" />
- {t('chat.selection.quote')}
- </Button>
+ {/* Separators sit BEFORE each item after the first, so a hidden action
+ never leaves a dangling divider at the edge of the bar. */}
+ {onQuote && (
+ <Button variant="ghost" className={itemClass} {...activate(runQuote)}>
+ <TextQuote className="size-3.5 text-muted" />
+ {t('chat.selection.quote')}
+ </Button>
+ )}
{onAskInNew && (
<>
- <span className="h-5 w-px bg-border" />
+ {onQuote && <span className="h-5 w-px bg-border" />}
<Button variant="ghost" className={itemClass} {...activate(runAsk)}>
<GitFork className="size-3.5 text-muted" />
{t('chat.selection.askInNew')}
@@ -177,7 +188,7 @@ export const SelectionQuoteToolbar: React.FC<{
)}
{isTouch && (
<>
- <span className="h-5 w-px bg-border" />
+ {(onQuote || onAskInNew) && <span className="h-5 w-px bg-border" />}
<Button variant="ghost" className={itemClass} {...activate(runCopy)}>
{copied ? <Check className="size-3.5 text-mint" /> : <Copy className="size-3.5 text-muted" />}
{t('chat.selection.copy')}
diff --git a/ui/src/components/workbench/search/SearchPalette.tsx b/ui/src/components/workbench/search/SearchPalette.tsx
index 260e3a36d..197037511 100644
--- a/ui/src/components/workbench/search/SearchPalette.tsx
+++ b/ui/src/components/workbench/search/SearchPalette.tsx
@@ -7,6 +7,7 @@ import { AlertCircle, Loader2, Search } from 'lucide-react';
import { useMessageSearch } from '../../../lib/useMessageSearch';
import { Dialog, DialogOverlay, DialogPortal, DialogTitle } from '../../ui/dialog';
import { Input } from '../../ui/input';
+import { Switch } from '../../ui/switch';
import { AppSearchResultSection } from './AppSearchResults';
import { SearchResultGroup } from './SearchResultGroup';
import { useAppSearchResults, useOpenSearchApp } from './useAppSearch';
@@ -39,7 +40,11 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
const { t } = useTranslation();
const navigate = useNavigate();
const [query, setQuery] = useState('');
- const { results, loading, error } = useMessageSearch(query);
+ // Opt-in only, and reset on every open (see onOpenAutoFocus) — the palette
+ // already resets the query there, and a sticky archived filter would quietly
+ // change what ⌘K returns by default.
+ const [includeArchived, setIncludeArchived] = useState(false);
+ const { results, loading, error } = useMessageSearch(query, { includeArchived });
const { results: appResults, loading: appsLoading } = useAppSearchResults(query, open);
const openSearchApp = useOpenSearchApp();
const inputRef = useRef<HTMLInputElement | null>(null);
@@ -136,6 +141,7 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
e.preventDefault();
setQuery('');
setSelectedKey(null);
+ setIncludeArchived(false);
inputRef.current?.focus();
}}
aria-describedby={undefined}
@@ -214,6 +220,16 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
<FooterHint keyLabel="↑↓" label={t('workbench.search.kbdNavigate')} />
<FooterHint keyLabel="↵" label={t('workbench.search.kbdOpen')} />
<FooterHint keyLabel={t('workbench.search.kbdEsc')} label={t('workbench.search.kbdClose')} />
+ {/* Archived opt-in — off on every open; archived hits open read-only. */}
+ <label className="flex items-center gap-1.5 text-[11px] text-muted">
+ <Switch
+ checked={includeArchived}
+ onCheckedChange={setIncludeArchived}
+ label={t('workbench.search.includeArchived')}
+ size="sm"
+ />
+ {t('workbench.search.includeArchived')}
+ </label>
<span className="flex-1" />
<span className="truncate text-[11px] text-muted">{t('workbench.search.footerNote')}</span>
</div>
diff --git a/ui/src/components/workbench/search/SearchResultGroup.tsx b/ui/src/components/workbench/search/SearchResultGroup.tsx
index 0d69b226a..b5f182f91 100644
--- a/ui/src/components/workbench/search/SearchResultGroup.tsx
+++ b/ui/src/components/workbench/search/SearchResultGroup.tsx
@@ -1,6 +1,8 @@
+import { useTranslation } from 'react-i18next';
import { Folder } from 'lucide-react';
import type { MessageSearchMatch, MessageSearchSession } from '../../../context/ApiContext';
+import { Badge } from '../../ui/badge';
import { SearchResultRow } from './SearchResultRow';
type SearchResultGroupProps = {
@@ -13,21 +15,30 @@ type SearchResultGroupProps = {
// A session group: a muted header (folder glyph + "project · session" label +
// match count) followed by its matching rows. Presentational — selection state
// and navigation are passed through from the consumer.
+// An archived session (only reachable with the "include archived" opt-in) gets a
+// badge in the header and a dimmed group, so a read-only hit is recognizable
+// before it is opened.
export const SearchResultGroup: React.FC<SearchResultGroupProps> = ({
session,
selectedId,
onSelect,
}) => {
+ const { t } = useTranslation();
const projectLabel = session.project_name || session.project_id || '—';
const sessionLabel = session.title || session.session_id;
return (
- <div className="flex flex-col">
+ <div className={`flex flex-col${session.archived ? ' opacity-70' : ''}`}>
<div className="flex items-center gap-1.5 px-2.5 py-1.5">
<Folder className="size-[13px] shrink-0 text-muted" />
<span className="min-w-0 flex-1 truncate font-mono text-[11px] font-bold text-muted">
{projectLabel} · {sessionLabel}
</span>
+ {session.archived && (
+ <Badge variant="secondary" className="shrink-0 px-1.5 py-0 text-[10px] font-bold">
+ {t('common.archived')}
+ </Badge>
+ )}
<span className="shrink-0 font-mono text-[10px] text-muted">{session.matches.length}</span>
</div>
<div className="flex flex-col">
diff --git a/ui/src/components/workbench/sessionArchived.ts b/ui/src/components/workbench/sessionArchived.ts
new file mode 100644
index 000000000..6f79cdc85
--- /dev/null
+++ b/ui/src/components/workbench/sessionArchived.ts
@@ -0,0 +1,101 @@
+// Archive is terminal — the read-only derivations for the chat surface.
+//
+// A session whose lifecycle ``status`` is ``archived`` can never accept another
+// write: the server refuses the messages POST, the sessions PATCH, the fork and
+// every Show Page mutation (create / republish / re-share) with
+// ``409 {"code": "session_archived"}``, and archive itself takes any existing
+// Show Page offline. Search's "include archived" opt-in links straight into such
+// a chat, so this is a normal entry path rather than an edge case, and the
+// transcript must stay fully readable while every mutating affordance is
+// withdrawn — hidden, not left clickable-and-erroring.
+//
+// These live beside ChatPage rather than inside it (the harnessRuns.ts pattern)
+// so the decisions are unit-tested without mounting a 3000-line component — the
+// page just reads the answers.
+import type { WorkbenchSession } from '../../context/ApiContext';
+
+/** One predicate owns "this session can never accept another write", so the
+ * composer, header, transcript, queue strip and vault cards all derive the same
+ * fact instead of each site re-deriving it. */
+export const isSessionReadOnly = (session: WorkbenchSession | null): boolean =>
+ session?.status === 'archived';
+
+/** A ``409 {"code": "session_archived"}`` from any session-scoped write is the
+ * server stating this row is archived. Same shape for the messages POST and the
+ * sessions PATCH, so the classifier is shared rather than inlined per caller. */
+export const isSessionArchivedConflict = (status: number, body: unknown): boolean =>
+ status === 409 && (body as { code?: unknown } | null | undefined)?.code === 'session_archived';
+
+/** The same fact for a rejection that came back through the shared JSON helpers
+ * rather than a raw ``apiFetch``: ``handleApiError`` already parsed the body and
+ * threw an ``ApiError`` carrying its machine code. Duck-typed on ``code`` so this
+ * module stays free of the ApiContext import (and so a plain ``Error`` — a
+ * network failure — is correctly not an archive conflict). */
+export const isSessionArchivedError = (err: unknown): boolean =>
+ (err as { code?: unknown } | null | undefined)?.code === 'session_archived';
+
+/** Apply that server truth to the loaded row.
+ *
+ * Identity-stable when the row already says archived (so it cannot spin a
+ * re-render) or belongs to another session (so a late response cannot stamp one
+ * chat's archive onto the chat the user moved to). */
+export const markSessionArchived = (
+ prev: WorkbenchSession | null,
+ sessionId: string,
+): WorkbenchSession | null =>
+ prev && prev.id === sessionId && prev.status !== 'archived' ? { ...prev, status: 'archived' } : prev;
+
+/** Which text-selection actions the transcript offers.
+ *
+ * "Quote" appends into the composer and "Ask in a new session" forks — a
+ * read-only session can do neither: its composer is disabled, and the fork
+ * endpoint refuses an archived source outright (archive is terminal, there is no
+ * resume or fork out of it). Fork also needs a bound native, the pre-existing
+ * gate. Both are hidden rather than offered just to fail. */
+export const transcriptSelectionActions = (
+ session: WorkbenchSession,
+ readOnly: boolean,
+): { quote: boolean; askInNew: boolean } => ({
+ quote: !readOnly,
+ askInNew: !readOnly && Boolean(session.native_session_id),
+});
+
+/** Whether the chat surface is replaced by the session's framed Show Page.
+ *
+ * A read-only session withdraws the entire Show Page action cluster — including
+ * the back-to-chat button, which IS the Visualize toggle — so a tab that was
+ * already framing the page when the session went archived would be stranded on
+ * a page it cannot leave and that archive already forced offline. Answering
+ * ``false`` here puts it back on the transcript. ChatPage derives this rather
+ * than resetting ``showPageMode`` from an effect, so the fallback lands in the
+ * same render that flips ``readOnly``. */
+export const isShowPageActive = (readOnly: boolean, showPageMode: boolean): boolean =>
+ showPageMode && !readOnly;
+
+/** Which Show Page controls the chat header offers.
+ *
+ * Archive takes the Show Page with it, so ALL THREE go on a read-only session —
+ * there is no read-only page-serving path to fall back to:
+ * - ``archive_session`` forces every existing page to ``visibility="offline"``
+ * (``storage/workbench_sessions_service.py``), and ``ensure_active`` refuses
+ * to create a missing one (``409 session_archived``, ``core/show_pages.py``).
+ * So Visualize can only end in that 409, or frame a page that is offline —
+ * never a working view.
+ * - Share's mutations (``update_visibility``, ``set_share_id``, ``rotate_share``)
+ * are refused by the same guard, and its popover re-ensures the page on open,
+ * so it 409s before it can render anything.
+ * - Annotating enqueues an annotation *message* into the session, which the
+ * messages POST refuses.
+ *
+ * ``visualize`` is the one member that does not also depend on Show Page mode,
+ * so it doubles as "the header's action cluster has anything left to draw".
+ */
+export const showPageControlActions = (
+ readOnly: boolean,
+ showPageMode: boolean,
+): { visualize: boolean; share: boolean; annotate: boolean } => {
+ // Share and the annotation control only exist while the page is framed, so
+ // they follow the same fact that decides whether it is framed at all.
+ const framed = isShowPageActive(readOnly, showPageMode);
+ return { visualize: !readOnly, share: framed, annotate: framed };
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index bb887c280..84481e634 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -580,6 +580,14 @@ export type ApiContextType = {
getSessionBootstrap: (sessionId: string) => Promise<WorkbenchSessionBootstrap>;
updateSession: (sessionId: string, payload: Partial<WorkbenchSessionUpdate>) => Promise<WorkbenchSession>;
archiveSession: (sessionId: string) => Promise<WorkbenchSession>;
+ /** Subscribe to "the server just refused a write because that session is
+ * archived". Fires for EVERY request whose error body carries
+ * ``session_archived``, whatever the verb — the messages POST, the sessions
+ * PATCH, fork, and every Show Page mutation — so a surface holding a stale
+ * pre-archive row converges once, here, instead of each call site
+ * re-implementing it (and the next verb re-introducing the same defect).
+ * Returns an unsubscribe. */
+ onSessionArchived: (handler: (sessionId: string) => void) => () => void;
/** Counts of resources permanently reclaimed when archiving this session
* (bound tasks/watches + active runs) — drives the irreversible-confirm dialog. */
getArchivePreview: (sessionId: string) => Promise<{ tasks: number; watches: number; runs: number; queued: number }>;
@@ -592,8 +600,13 @@ export type ApiContextType = {
// Full-text search over message content across all sessions. Backed by the
// non-cached GET /api/search/messages (the query string varies per keystroke,
// so caching would only bloat the read cache). Results group matches by
- // session, sessions ordered most-recent-match first.
- searchMessages: (q: string, opts?: { limit?: number }) => Promise<MessageSearchResult>;
+ // session, sessions ordered most-recent-match first. ``includeArchived`` opts
+ // archived sessions in (they stay excluded by default); archived groups are
+ // flagged and open read-only.
+ searchMessages: (
+ q: string,
+ opts?: { limit?: number; includeArchived?: boolean },
+ ) => Promise<MessageSearchResult>;
sendSessionMessage: (sessionId: string, payload: { text?: string; content?: Record<string, unknown>; metadata?: Record<string, unknown>; author_id?: string; author_name?: string }) => Promise<WorkbenchMessage>;
markSessionRead: (sessionId: string, untilMessageId?: string) => Promise<{ updated: number; unread_counts: Record<string, number>; unread_by_session: Record<string, number> }>;
cancelSession: (
@@ -1059,6 +1072,9 @@ export type MessageSearchSession = {
title: string | null;
project_id: string | null;
project_name: string | null;
+ // True when the session is archived (only possible with includeArchived) —
+ // the group is marked in the results and the chat opens read-only.
+ archived: boolean;
matches: MessageSearchMatch[];
};
@@ -1877,6 +1893,59 @@ export class ApiError extends Error {
}
}
+/** Pick the machine code + human fallback out of an error response body.
+ *
+ * Accepts the legacy ``error`` shape (a bare string, or ``{ code, message }``) AND the
+ * top-level ``{ code, message }`` shape newer routes use (e.g. /api/vault/*), so callers
+ * always get a real ``ApiError.code`` to branch on instead of a generic status string.
+ *
+ * Note the precedence, which is a CONTRACT for route authors: ``error`` is consulted
+ * first, and a STRING ``error`` is taken as the code — so a route that pairs a human
+ * sentence in ``error`` with the real code alongside it in a top-level ``code`` loses that
+ * code here, and its message is rendered verbatim in every locale. Routes with a machine
+ * code must nest it: ``{"error": {"code", "message"}}`` (see ``_show_page_error_response``
+ * in ``vibe/ui_server.py``). Extracted from ``handleApiError`` unchanged so that contract
+ * is directly testable — see ApiErrorParse.test.ts. */
+export const selectApiErrorFields = (
+ data: any,
+ defaultMessage: string,
+): { code: string | null; fallback: string } | null => {
+ // Not ``data?.error``: a non-object JSON body (``null``) must keep THROWING here so
+ // handleApiError's catch falls back to the status text, exactly as before.
+ const rawErr = data.error ?? (data.code ? { code: data.code, message: data.message } : undefined);
+ if (!rawErr) return null;
+ const code = typeof rawErr === 'string' ? rawErr : rawErr?.code;
+ const fallback = typeof rawErr === 'string' ? rawErr : rawErr?.message ?? rawErr?.code ?? defaultMessage;
+ return { code: typeof code === 'string' ? code : null, fallback };
+};
+
+/** Which session an error response says is archived, or ``null`` if it says no such
+ * thing. The WHOLE decision — the code guard and the id lookup — so it is testable
+ * without a DOM (this repo has no DOM test environment; same reason
+ * ``selectApiErrorFields`` was extracted). ``handleApiError`` only fans the answer
+ * out to subscribers.
+ *
+ * Every route that can answer ``409 session_archived`` puts the session id in the
+ * first segment after its collection: ``/api/sessions/<id>`` (PATCH), plus
+ * ``/messages`` and ``/fork`` under it, and ``/api/show-pages/<session_id>/…``
+ * (ensure / visibility / share-id / rotate-share / icon). One pattern therefore
+ * covers all of them, and a future session-scoped route inherits it.
+ *
+ * Deliberately UNANCHORED: some callers pass a human LABEL rather than a bare
+ * path (``updateSession`` sends ``"PATCH /api/sessions/<id>"``), and that label
+ * belongs to the very route this convergence was added for. */
+export const archivedConflictSessionId = (code: string | null, path: string): string | null => {
+ if (code !== 'session_archived') return null;
+ const match = /\/api\/(?:sessions|show-pages)\/([^/?#\s]+)/.exec(path);
+ if (!match) return null;
+ try {
+ return decodeURIComponent(match[1]) || null;
+ } catch {
+ // A malformed escape must not throw inside an error handler.
+ return match[1] || null;
+ }
+};
+
const ApiContext = createContext<ApiContextType | undefined>(undefined);
const CONFIG_CACHE_TTL_MS = 30_000;
@@ -1900,6 +1969,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const eventReconnectLoopRef = useRef<WorkbenchEventReconnectLoop | null>(null);
const wakeWorkbenchEventsRef = useRef<() => void>(() => {});
const stopWorkbenchEventsRef = useRef<() => void>(() => {});
+ const sessionArchivedHandlersRef = useRef(new Set<(sessionId: string) => void>());
const handleApiError = async (res: Response, path: string) => {
let errorMessage = `Request failed: ${path} (${res.status})`;
@@ -1907,18 +1977,14 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
try {
const data = await res.json();
- // Accept the legacy ``error`` shape (string code or ``{ code, message }``) AND the
- // top-level ``{ code, message }`` shape newer routes use (e.g. /api/vault/*), so callers
- // always get a real ``ApiError.code`` to branch on instead of a generic status string.
- const rawErr = data.error ?? (data.code ? { code: data.code, message: data.message } : undefined);
- if (rawErr) {
+ const parsed = selectApiErrorFields(data, errorMessage);
+ if (parsed) {
// Localize by code, falling back to the server-provided message so we never render a
// key like ``errors.[object Object]``.
- const code = typeof rawErr === 'string' ? rawErr : rawErr?.code;
- const fallback =
- typeof rawErr === 'string' ? rawErr : rawErr?.message ?? rawErr?.code ?? errorMessage;
- errorCode = typeof code === 'string' ? code : null;
- errorMessage = errorCode ? t(`errors.${errorCode}`, { defaultValue: fallback }) : fallback;
+ errorCode = parsed.code;
+ errorMessage = parsed.code
+ ? t(`errors.${parsed.code}`, { defaultValue: parsed.fallback })
+ : parsed.fallback;
}
} catch {
// Response is not JSON, use status text
@@ -1935,9 +2001,33 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
// Show toast to user
showToast(errorMessage, 'error');
+ // Archive is TERMINAL, so this particular refusal is not a failure to retry
+ // but a state change the client missed (a backgrounded/offline tab can drop
+ // the archive SSE). Announce it once, from the one place every JSON helper
+ // funnels its errors through, so any subscriber converges no matter WHICH
+ // session-scoped write tripped it. Best-effort and non-throwing: a subscriber
+ // must never change whether/what this handler throws.
+ const archivedSessionId = archivedConflictSessionId(errorCode, path);
+ if (archivedSessionId) {
+ for (const handler of Array.from(sessionArchivedHandlersRef.current)) {
+ try {
+ handler(archivedSessionId);
+ } catch (err) {
+ console.error('[API] session-archived subscriber failed', err);
+ }
+ }
+ }
+
throw new ApiError(errorMessage, res.status, errorCode);
};
+ const onSessionArchived = (handler: (sessionId: string) => void) => {
+ sessionArchivedHandlersRef.current.add(handler);
+ return () => {
+ sessionArchivedHandlersRef.current.delete(handler);
+ };
+ };
+
const getJson = async (path: string, { handleError = true }: { handleError?: boolean } = {}) => {
const res = await apiFetch(path);
if (!res.ok && handleError) {
@@ -2669,6 +2759,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return payloadJson;
},
archiveSession: (sessionId) => deleteJson(`/api/sessions/${encodeURIComponent(sessionId)}`),
+ onSessionArchived,
getArchivePreview: (sessionId) =>
getJson(`/api/sessions/${encodeURIComponent(sessionId)}/archive-preview`),
listSessionMessages: (sessionId, params) => {
@@ -2695,6 +2786,7 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const search = new URLSearchParams();
search.set('q', q);
if (opts?.limit) search.set('limit', String(opts.limit));
+ if (opts?.includeArchived) search.set('include_archived', '1');
return getJson(`/api/search/messages?${search.toString()}`);
},
sendSessionMessage: (sessionId, payload) =>
diff --git a/ui/src/context/ApiErrorParse.test.ts b/ui/src/context/ApiErrorParse.test.ts
new file mode 100644
index 000000000..644b06a7a
--- /dev/null
+++ b/ui/src/context/ApiErrorParse.test.ts
@@ -0,0 +1,174 @@
+import { describe, expect, it } from 'vitest';
+
+import { archivedConflictSessionId, selectApiErrorFields } from './ApiContext';
+
+// ── Codex review #4 (ui_server.py:6611) ───────────────────────────────────────
+// PATCH /api/sessions/<id> on an archived session answered
+// {"error": "session is archived", "code": "session_archived"}
+// and the round-3 test asserted body["code"], which passed — while the field the
+// Web UI actually consumes was the FLAT ``error`` string. handleApiError reads
+// ``error`` first and treats a string ``error`` AS the code, so the machine code
+// was dropped: ApiError.code became the English sentence, errors.session_archived
+// never resolved, and a zh-locale user read raw English.
+//
+// The bodies below are copied from the route (asserted server-side in
+// tests/test_ui_server_fastapi.py::test_sessions_patch_on_archived_session_is_409,
+// which now pins the nested object too — the pair is what closes the loop).
+const DEFAULT = 'Request failed: PATCH /api/sessions/ses_1 (409)';
+
+describe('error-body parsing preserves the machine code', () => {
+ it('reads the code out of the structured shape the routes use', () => {
+ // The archived-PATCH 409, verbatim.
+ expect(
+ selectApiErrorFields(
+ {
+ ok: false,
+ error: { code: 'session_archived', message: 'session is archived' },
+ code: 'session_archived',
+ message: 'session is archived',
+ },
+ DEFAULT,
+ ),
+ ).toEqual({ code: 'session_archived', fallback: 'session is archived' });
+ });
+
+ it('drops the code when a route pairs a string error with a top-level code', () => {
+ // The defect, pinned as a NEGATIVE so the contract is explicit rather than
+ // folklore: ``error`` wins, and a string ``error`` is the code. Any route that
+ // needs a machine code must nest it.
+ expect(
+ selectApiErrorFields({ error: 'session is archived', code: 'session_archived' }, DEFAULT),
+ ).toEqual({ code: 'session is archived', fallback: 'session is archived' });
+ });
+
+ it('still accepts the two pre-existing shapes unchanged', () => {
+ // Bare human string, no code at all (the majority of routes) — the message is
+ // both "code" and fallback, and t() misses harmlessly.
+ expect(selectApiErrorFields({ error: 'Session not found: ses_1' }, DEFAULT)).toEqual({
+ code: 'Session not found: ses_1',
+ fallback: 'Session not found: ses_1',
+ });
+ // Top-level {code, message} only (e.g. /api/vault/*).
+ expect(selectApiErrorFields({ code: 'vault_locked', message: 'Vault is locked' }, DEFAULT)).toEqual({
+ code: 'vault_locked',
+ fallback: 'Vault is locked',
+ });
+ // Nested code with no message falls back to the code, never to [object Object].
+ expect(selectApiErrorFields({ error: { code: 'session_archived' } }, DEFAULT)).toEqual({
+ code: 'session_archived',
+ fallback: 'session_archived',
+ });
+ // An object with no code at all is not a code; the caller's default carries
+ // the message rather than a stringified object.
+ expect(selectApiErrorFields({ error: { detail: 'nope' } }, DEFAULT)).toEqual({
+ code: null,
+ fallback: DEFAULT,
+ });
+ // No error field at all → nothing to localize, caller keeps its default.
+ expect(selectApiErrorFields({ ok: true }, DEFAULT)).toBeNull();
+ });
+});
+
+// ── Codex review #5 (ChatPage.tsx:1280) ───────────────────────────────────────
+// Round 2 made the archived 409 CONVERGE (patch the row read-only, then reload)
+// for the messages POST only. The next verb the reviewer tried — a PATCH rename /
+// re-route — stored the error text and left the title editor and route picker live,
+// re-issuing a permanently rejected request. Fixing it per-verb is what produced
+// the finding three rounds running, so convergence moved to the API layer:
+// ``handleApiError`` announces every ``session_archived`` body once, and the
+// session it is about is read off the request path with the helper below.
+const ARCHIVED = 'session_archived';
+
+describe('locating the session a session_archived response is about', () => {
+ it('reads the id from every session-scoped route family that can 409', () => {
+ // PATCH /api/sessions/<id> — the verb this round is about.
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1')).toBe('ses_1');
+ // ...and the nested writes under it.
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1/messages')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1/fork')).toBe('ses_1');
+ // Show Page mutations are session-keyed under their own collection: ensure,
+ // visibility, share-id, rotate-share, icon.
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/ensure')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/visibility')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/share-id')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/rotate-share')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/show-pages/ses_1/icon')).toBe('ses_1');
+ });
+
+ it('accepts the LABEL form updateSession passes, not just a bare path', () => {
+ // ``updateSession`` hands handleApiError "PATCH /api/sessions/<id>" as its error
+ // path. That is precisely the route this convergence exists for, so an anchored
+ // pattern would miss the one case that motivated it.
+ expect(archivedConflictSessionId(ARCHIVED, 'PATCH /api/sessions/ses_1')).toBe('ses_1');
+ });
+
+ it('announces nothing for any other failure', () => {
+ // A read-only chat must be entered because the SERVER said the row is terminal —
+ // never because some other request failed. A backend lock in particular is
+ // transient and shares the 409 status.
+ expect(archivedConflictSessionId('backend_locked', '/api/sessions/ses_1')).toBeNull();
+ expect(archivedConflictSessionId('session_not_found', '/api/sessions/ses_1')).toBeNull();
+ expect(archivedConflictSessionId(null, '/api/sessions/ses_1')).toBeNull();
+ });
+
+ it('ignores a query string, and decodes an escaped id', () => {
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses_1?cache=0')).toBe('ses_1');
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses%2F1/messages')).toBe('ses/1');
+ // A malformed escape must not throw inside an error handler.
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/ses%ZZ')).toBe('ses%ZZ');
+ });
+
+ it('answers null when the path names no session', () => {
+ // Collection-level and unrelated routes: nothing to converge.
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions')).toBeNull();
+ expect(archivedConflictSessionId(ARCHIVED, '/api/sessions/')).toBeNull();
+ expect(archivedConflictSessionId(ARCHIVED, '/api/projects/proj_1')).toBeNull();
+ expect(archivedConflictSessionId(ARCHIVED, '/api/vault/secrets')).toBeNull();
+ });
+});
+
+// ── Codex review #6 (ApiContext.tsx:2010) ─────────────────────────────────────
+// Round 5's enumeration listed every session_archived-capable route as "converges
+// via API seam" — but POST /api/sessions/<id>/fork still answered the FLAT body
+// (``_session_fork_error_response``), which the parser above turns into
+// ``code === "…is archived"``. So the first rejected action of a stale tab —
+// Quote → "Ask in a new session" — announced nothing and left the chat writable.
+// The claim had been recorded as verified while the deferral that contradicted it
+// sat in the same document.
+//
+// The enumeration is therefore pinned as a TABLE run through the real parser and
+// the real locator: a route is listed with the body its server helper emits, and
+// adding a row is what covers the next one. The server side of the same table is
+// tests/test_ui_server_fastapi.py::test_machine_coded_error_bodies_survive_the_ui_error_parse,
+// which builds these bodies from the actual response helpers.
+const archivedBody = (message: string) => ({
+ ok: false,
+ error: { code: 'session_archived', message },
+ code: 'session_archived',
+ message,
+});
+
+const ARCHIVED_CAPABLE_ROUTES: Array<[string, string, unknown]> = [
+ // call site → the error path handleApiError receives → the body its route emits
+ ['api.updateSession', 'PATCH /api/sessions/ses_1', archivedBody('This session is archived and can no longer be changed.')],
+ ['api.forkSession', '/api/sessions/ses_1/fork', archivedBody('agent session is archived: ses_1')],
+ ['api.ensureShowPage', '/api/show-pages/ses_1/ensure', archivedBody("This session is archived, so its Show Page can't be changed.")],
+ ['api.setShowPageVisibility', '/api/show-pages/ses_1/visibility', archivedBody('This session is archived.')],
+ ['api.setShowPageShareId', '/api/show-pages/ses_1/share-id', archivedBody('This session is archived.')],
+ ['api.rotateShowPageShare', '/api/show-pages/ses_1/rotate-share', archivedBody('This session is archived.')],
+ ['api.uploadShowPageIcon', '/api/show-pages/ses_1/icon', archivedBody("This session is archived, so its Show Page can't be changed.")],
+ // The messages POST reads its own raw response in ChatPage, but api.sendSessionMessage
+ // exists on the seam too — so its body has to survive the parser as well.
+ ['api.sendSessionMessage', '/api/sessions/ses_1/messages', archivedBody('This session is archived and can no longer be changed.')],
+];
+
+describe('every session_archived-capable route converges through the seam', () => {
+ it.each(ARCHIVED_CAPABLE_ROUTES)('%s', (_call, path, body) => {
+ const parsed = selectApiErrorFields(body, `Request failed: ${path} (409)`);
+ // The code must survive parsing...
+ expect(parsed?.code).toBe('session_archived');
+ // ...and it must be the code, not the human sentence, that the locator sees —
+ // the sentence is exactly what a flat body would have handed it.
+ expect(archivedConflictSessionId(parsed?.code ?? null, String(path))).toBe('ses_1');
+ });
+});
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 36a0a8a33..09d336694 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -52,6 +52,7 @@
"enable": "Enable",
"disable": "Disable",
"disabled": "Disabled",
+ "archived": "Archived",
"default": "Default",
"running": "Running",
"stopped": "Stopped",
@@ -1384,6 +1385,7 @@
},
"search": {
"roleYou": "You",
+ "includeArchived": "Include archived",
"roleAutomated": "Automated",
"roleAgent": "Agent",
"title": "Search",
@@ -2769,6 +2771,10 @@
"chat": {
"back": "Back",
"untitled": "Untitled session",
+ "archived": {
+ "sendBlocked": "This session is archived and read-only.",
+ "editBlocked": "This session is archived and can no longer be changed."
+ },
"selection": {
"quote": "Quote",
"askInNew": "Ask in a new session",
@@ -2867,6 +2873,7 @@
"compose": {
"placeholder": "Type a message…",
"placeholderBusy": "Type to queue while the agent works…",
+ "placeholderArchived": "This session is archived — read-only",
"hint": "Enter to send",
"send": "Send",
"queueSend": "Send to queue",
@@ -3205,6 +3212,7 @@
},
"request": {
"provide": "provide",
+ "expired": "This session is archived — this request has expired.",
"fulfilled": "provided",
"title": "Agent needs a secret",
"help": "Provide the value — it goes to the vault, never to the chat or model.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index b0afcbaff..2d32efb2a 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -52,6 +52,7 @@
"enable": "启用",
"disable": "禁用",
"disabled": "已禁用",
+ "archived": "已归档",
"default": "默认",
"running": "运行中",
"stopped": "已停止",
@@ -1384,6 +1385,7 @@
},
"search": {
"roleYou": "你",
+ "includeArchived": "包含已归档",
"roleAutomated": "自动触发",
"roleAgent": "助手",
"title": "搜索",
@@ -2769,6 +2771,10 @@
"chat": {
"back": "返回",
"untitled": "未命名会话",
+ "archived": {
+ "sendBlocked": "该会话已归档,无法发送消息。",
+ "editBlocked": "该会话已归档,无法再修改。"
+ },
"selection": {
"quote": "引用",
"askInNew": "在新会话询问",
@@ -2867,6 +2873,7 @@
"compose": {
"placeholder": "输入消息…",
"placeholderBusy": "Agent 处理中,输入将排队…",
+ "placeholderArchived": "会话已归档,仅可查看",
"hint": "Enter 发送",
"send": "发送",
"queueSend": "排队发送",
@@ -3205,6 +3212,7 @@
},
"request": {
"provide": "填写",
+ "expired": "该会话已归档,此请求已失效。",
"fulfilled": "已提供",
"title": "Agent 需要一个密钥",
"help": "提供这个值——它会进入保险库,绝不会进入聊天或模型。",
diff --git a/ui/src/lib/useMessageSearch.ts b/ui/src/lib/useMessageSearch.ts
index bbd6c2c08..8fd65889b 100644
--- a/ui/src/lib/useMessageSearch.ts
+++ b/ui/src/lib/useMessageSearch.ts
@@ -10,6 +10,9 @@ export type UseMessageSearchOptions = {
// Debounce window in ms — the query must stop changing this long before a
// request is sent. Defaults to 200.
debounceMs?: number;
+ // Opt archived sessions into the results. Off by default — archived hits are
+ // read-only, so surfacing them is an explicit user choice, never sticky.
+ includeArchived?: boolean;
};
export type UseMessageSearchState = {
@@ -29,6 +32,7 @@ export function useMessageSearch(
const { searchMessages } = useApi();
const minLength = opts?.minLength ?? 1;
const debounceMs = opts?.debounceMs ?? 200;
+ const includeArchived = opts?.includeArchived ?? false;
const [results, setResults] = useState<MessageSearchResult | null>(null);
const [loading, setLoading] = useState(false);
@@ -62,7 +66,7 @@ export function useMessageSearch(
const timer = window.setTimeout(() => {
const seq = (seqRef.current += 1);
- searchMessages(trimmed)
+ searchMessages(trimmed, { includeArchived })
.then((res) => {
if (seq !== seqRef.current) return;
setResults(res);
@@ -82,7 +86,7 @@ export function useMessageSearch(
window.clearTimeout(timer);
seqRef.current += 1;
};
- }, [query, minLength, debounceMs, searchMessages]);
+ }, [query, minLength, debounceMs, includeArchived, searchMessages]);
return { results, loading, error };
}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 9de17dddf..23e3c308f 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -103,6 +103,7 @@
}
},
"error": {
+ "sessionArchived": "This session is archived and can no longer be changed.",
"channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.",
"unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.",
"clearSession": "Error clearing session: {error}",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 6e40da8a2..ac688e7b8 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -103,6 +103,7 @@
}
},
"error": {
+ "sessionArchived": "该会话已归档,无法再修改。",
"channelNotEnabled": "此频道未启用。请前往控制面板启用它。",
"unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。",
"clearSession": "清除会话时出错:{error}",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 678304c8c..ba5820370 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3962,17 +3962,36 @@ def vault_audit_get():
return jsonify(api.get_vault_audit(secret_name=secret, limit=limit))
+def _coded_error_response(code: str, message: str, status: int, **extra: Any):
+ """THE error body for any route whose failure carries a machine-readable code.
+
+ Nested ``error`` object, because the Web UI's shared parser
+ (``selectApiErrorFields`` in ``ui/src/context/ApiContext.tsx``) reads ``data.error``
+ FIRST and treats a *string* ``error`` as the code itself. So the flat
+ ``{"error": "<sentence>", "code": "<code>"}`` shape silently DESTROYS the code:
+ callers get ``ApiError.code == "<sentence>"``, ``errors.<code>`` never resolves,
+ the sentence is rendered verbatim under every locale, and any client branch keyed
+ on the code (e.g. the archived-session convergence subscription) never fires.
+
+ The flat top-level ``code``/``message`` are kept alongside for the CLI and any
+ direct consumer that reads them. ``extra`` carries route-specific detail fields.
+
+ One builder rather than per-route dict literals so a new coded route inherits the
+ right shape; ``tests/test_ui_server_fastapi.py`` guards both directions (every
+ builder survives the parser, and no route hand-rolls the flat coded shape).
+ """
+ return (
+ jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message, **extra}),
+ status,
+ )
+
+
def _show_page_error_response(exc):
code = getattr(exc, "code", "invalid_show_page_request")
# A conflict (not a malformed request) when the page is in the wrong state or
# the chosen suffix is already claimed.
status = 409 if code in {"not_public", "share_id_taken"} else 400
- message = str(exc)
- # Structured ``error`` so the Web UI's shared handler localizes via
- # ``errors.<code>`` and falls back to the human message (not the raw code)
- # for any code without an i18n key; top-level ``code``/``message`` stay for
- # the CLI/any direct consumer.
- return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
+ return _coded_error_response(code, str(exc), status)
@app.route("/api/show-pages", methods=["GET"])
@@ -4094,8 +4113,7 @@ def _dock_error_response(exc):
# order is a 400. Structured ``error`` so the Web UI's shared handler can
# localize via ``errors.<code>`` and fall back to the human message.
status = 404 if code in {"show_page_not_found", "session_not_found"} else 400
- message = str(exc)
- return jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}), status
+ return _coded_error_response(code, str(exc), status)
@app.route("/api/dock", methods=["GET"])
@@ -6235,18 +6253,27 @@ def sessions_create():
def _session_fork_error_response(err: Exception):
+ """Map a ``SessionForkError`` to its machine code, in the STRUCTURED body.
+
+ ``session_archived`` here is the same terminal fact the PATCH route answers, so it
+ must reach the Web UI's shared archived-session convergence the same way: the flat
+ shape this used to emit fed the human sentence to callers as the code, which left
+ ``archivedConflictSessionId`` blind and every mutating control live after a
+ permanent refusal. See ``_coded_error_response`` — every code here needs the same
+ treatment, so the whole mapping goes through it rather than one patched branch.
+ """
message = str(err)
if "id not found" in message:
- return jsonify({"error": message, "code": "session_not_found"}), 404
+ return _coded_error_response("session_not_found", message, 404)
if "is archived" in message:
- return jsonify({"error": message, "code": "session_archived"}), 409
+ return _coded_error_response("session_archived", message, 409)
if "no native session id" in message:
- return jsonify({"error": message, "code": "session_not_bound"}), 409
+ return _coded_error_response("session_not_bound", message, 409)
if "backend cannot be forked" in message:
- return jsonify({"error": message, "code": "session_backend_unsupported"}), 409
+ return _coded_error_response("session_backend_unsupported", message, 409)
if "backend does not match" in message:
- return jsonify({"error": message, "code": "session_backend_mismatch"}), 409
- return jsonify({"error": message, "code": "session_fork_failed"}), 400
+ return _coded_error_response("session_backend_mismatch", message, 409)
+ return _coded_error_response("session_fork_failed", message, 400)
async def _session_turn_state_for_fork(session_id: str) -> dict[str, bool]:
@@ -6312,7 +6339,9 @@ async def sessions_fork(session_id: str):
except SessionForkError as err:
return _session_fork_error_response(err)
except LookupError as err:
- return jsonify({"error": str(err), "code": "session_not_found"}), 404
+ # Same coded shape as the branch above: this is the same route answering the
+ # same ``session_not_found`` code from a different exception type.
+ return _coded_error_response("session_not_found", str(err), 404)
broker.publish("session.activity", {"session_id": session["id"], "scope_id": session["scope_id"], "event": "created"})
return jsonify(session), 201
@@ -6465,18 +6494,38 @@ async def sessions_bootstrap(session_id: str):
)
+def _session_archived_response():
+ """Shared 409 payload for a write refused because the session is archived.
+
+ The shared ``_coded_error_response`` shape: the code MUST survive the Web UI's
+ parser or the read-only convergence never fires at all (see that builder for the
+ mechanism this refusal depends on).
+
+ The ``message`` comes from ``vibe/i18n`` (AGENTS.md §6) rather than an English
+ literal: direct API/CLI consumers read it verbatim, and a Web UI client without
+ the ``errors.session_archived`` key falls back to it too.
+ """
+ from core.services import sessions as workbench_sessions_service
+
+ return _coded_error_response("session_archived", workbench_sessions_service.session_archived_message(), 409)
+
+
def _backend_locked_response(err):
- """Shared 409 payload for a rejected cross-backend session change."""
- return (
- jsonify(
- {
- "error": str(err),
- "code": "backend_locked",
- "current_backend": err.current_backend,
- "requested_backend": err.requested_backend,
- }
- ),
+ """Shared 409 payload for a rejected cross-backend session change.
+
+ Coded shape for the same reason as the archived 409, and specifically BECAUSE it
+ shares a route with it: ``sessions_update`` deliberately answers the terminal
+ ``session_archived`` ahead of this *retryable* ``backend_locked`` so a client can
+ tell a permanent refusal from one worth retrying — which it cannot do while either
+ code is being replaced by its own error sentence. The lock's detail fields stay
+ top-level, where their existing consumers read them.
+ """
+ return _coded_error_response(
+ "backend_locked",
+ str(err),
409,
+ current_backend=err.current_backend,
+ requested_backend=err.requested_backend,
)
@@ -6566,6 +6615,22 @@ async def sessions_update(session_id: str):
return jsonify({"error": "no updatable fields supplied"}), 400
engine = _projects_engine()
+ # Archive is TERMINAL, so it outranks every transient conflict below — most
+ # importantly the cross-backend lock preflight, which consults the controller
+ # and would answer a retryable ``backend_locked`` for an archived row whose
+ # in-flight turn is still unwinding: ``archive_session`` cannot cancel that turn
+ # inside its transaction, so the DELETE route commits the archive first and
+ # cancels best-effort afterwards (``_archive_cancel_turn``). A stale
+ # cross-backend PATCH landing in that window used to have its terminal state
+ # masked, leaving the client unable to recognize ``session_archived`` and
+ # converge. Short-circuit here so the archive conflict always wins.
+ #
+ # Same shared write-guard the messages POST uses. A MISSING session reads
+ # ``False``, so the 404s below are unchanged, and every non-archived PATCH pays
+ # only one indexed read and keeps its existing preflight ordering.
+ with engine.connect() as conn:
+ if workbench_sessions_service.is_session_archived(conn, session_id):
+ return _session_archived_response()
should_check_backend_lock = "agent_backend" in updatable
requested_backend = updatable.get("agent_backend")
if "agent_name" in updatable and "agent_backend" not in updatable:
@@ -6616,6 +6681,12 @@ async def sessions_update(session_id: str):
session = workbench_sessions_service.update_session(conn, session_id, **updatable)
except LookupError as err:
return jsonify({"error": str(err)}), 404
+ except workbench_sessions_service.SessionArchivedError:
+ # Archive is terminal — the read-only chat UI relies on this backstop. The
+ # short-circuit above already answers the common case; this catches a
+ # session archived BETWEEN that read and this write, and keeps the service
+ # guard authoritative rather than trusting the route's preflight.
+ return _session_archived_response()
except (ValueError, PermissionError) as err:
return jsonify({"error": str(err)}), 400
except workbench_sessions_service.SessionBackendLockedError as err:
@@ -6843,14 +6914,18 @@ def search_messages_list():
"""Global message-content search across Workbench sessions, grouped by session.
Substring (case-insensitive) search over ``content_text`` for ``platform
- ='avibe'`` user prompts + agent ``result`` replies, excluding archived
- sessions. ``q`` is the query, ``limit`` caps the matched-message scan. The
+ ='avibe'`` user prompts + agent ``result`` replies. Archived sessions are
+ excluded by default; ``include_archived=1`` opts them in, and each returned
+ session group carries ``archived`` so the client can mark and open them
+ read-only. Messages under an archived PROJECT stay excluded either way.
+ ``q`` is the query, ``limit`` caps the matched-message scan. The
remote-access host guard + auth run in the global ``before_request`` hooks
(same as the messages list), so this handler just delegates to the service.
"""
from storage import messages_service
query = request.args.get("q") or ""
+ include_archived = request.args.get("include_archived") in {"1", "true", "yes"}
try:
limit = int(request.args.get("limit") or 50)
except (TypeError, ValueError):
@@ -6858,7 +6933,9 @@ def search_messages_list():
engine = _projects_engine()
with engine.connect() as conn:
- result = messages_service.search_messages(conn, query=query, limit=limit)
+ result = messages_service.search_messages(
+ conn, query=query, limit=limit, include_archived=include_archived
+ )
return jsonify(result)
@@ -7084,10 +7161,7 @@ def _show_page_icon_upload_error(code: str, message: str):
"icon_too_large": 413,
"invalid_icon_type": 415,
}.get(code, 400)
- return (
- jsonify({"ok": False, "error": {"code": code, "message": message}, "code": code, "message": message}),
- status,
- )
+ return _coded_error_response(code, message, status)
@app.post("/api/show-pages/{session_id}/icon", include_in_schema=False)
@@ -7721,7 +7795,7 @@ async def sessions_messages_create(session_id: str):
# even via a stale/direct request (the workbench hides them from the
# list, so this only fires on a leftover tab or a hand-crafted call).
if session.get("status") == "archived":
- return jsonify({"error": "session is archived", "code": "session_archived"}), 409
+ return _session_archived_response()
# Idempotency: a stale or duplicate quick-reply submit (a second tab, or
# one that missed the message.new event) must not start a second turn
# for an already-answered group. The answer lives on the agent message.
@@ -7794,7 +7868,7 @@ async def sessions_messages_create(session_id: str):
message = _persist_user_row()
if message is None:
# Archived between the pre-flight check and the reservation — stay terminal.
- return jsonify({"error": "session is archived", "code": "session_archived"}), 409
+ return _session_archived_response()
# No text AND no attachments: nothing for the agent to act on, so just
# promote + publish the row, no turn. Attachments WITHOUT text still run a
# turn (the agent reads the files), so they aren't caught here.