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(ui): shared Workbench shell and General Settings (#2033)

Max55718617447b
diff --git a/docs/plans/2026-09-18-workbench-general-settings.md b/docs/plans/2026-09-18-workbench-general-settings.md
new file mode 100644
index 000000000..5e49c846b
--- /dev/null
+++ b/docs/plans/2026-09-18-workbench-general-settings.md
@@ -0,0 +1,342 @@
+# Shared Workbench and General Settings — issue #2012
+
+Owner authorized parallel implementation on 2026-09-18 02:36 Asia/Shanghai. PM session: sestqz5wvu5ty. Branch feat/workbench-general-settings starts at GitHub-verified master 4019b704c99afe16223d475fccd9e1cb94a109d7 in its own worktree. #2011 is a separate active lane; #2013 remains deferred. Historical #2010-only or sequential-dispatch language is superseded by this explicit instruction.
+
+## Outcome
+
+Implement the approved shared Workbench shell, editable first-task home and General Settings from final design_desktop.pen. Preserve real projects, sessions, messages, inbox and permission-aware routes, one shared Composer and existing picker interactions. This is UI recomposition, not replacement of runtime/auth/data ownership.
+
+## Accepted design and behavior
+
+- Sidebar248: existing brand row, search/inbox with real unread badge hidden at zero, always-expanded main navigation, real project/session area or true empty state, bottom Apps/Settings, proper selected/hover/focus/status presentation.
+- Home: Explore project / Research question / Make plan cards seed and focus an editable draft and never send. Recompose shared Composer with attachment, existing AgentRoutePicker, direct DirectoryBrowser and send. Preserve project find/create, user/default selection and permission rules. No second editor.
+- One-time dismissible post-onboarding banner is conditional on the producer completion event and actual available Agent/readiness; ordinary visits have no banner. See exact cross-lane contract below.
+- Continuation links keep `/settings/remote-access` and `/settings/platforms` destinations.
+- General is the ordinary `/settings` entry (`/settings/general`), including return to app, General/AGENT/Connections/System groups, existing language ownership/autosave and explicit System/Light/Dark selection via existing ThemeProvider. Explicit deep links survive. Settings close preserves originating surface/draft/selection.
+- Preserve approved themes/locales, actual product logos, smaller-screen access, keyboard/focus. No native titlebar/menu or fake native chrome. Owner-approved native canvas governs; no new design invention. Empty, error, permission and loading UI must express actual state.
+
+## Native source and inspection
+
+Read/export `/Users/max/workspace/ai/avibe/avibe-docs/design_desktop.pen` through Pencil; never mutate/save/switch active documents. Candidate nodes n0PzOn (Workspace), DkNTK (sidebar), r6G6P (General), uifbM (existing selector reference). A read-only observer supplies `/tmp/issue2012/design/design-index.md`; implementation writer must inspect actual exported images and current component ownership before visible edits. Discover final Light/Dark/EN/ZH variants, do not assume candidate IDs cover all frames. 1200x800 is a reference window, not fixed browser dimensions. Another project owns active Pencil document; content-identity check is mandatory because unavailable filePaths can fall back silently. If design.pen is inaccessible, use confirmed desktop source plus existing picker code without changing another canvas.
+
+## Scope, testing, delivery
+
+The copied parallel contract below is the exact producer/consumer/file division. Consolidate changes into this plan without editing #2011's working copy. No backend/schema/auth code, native desktop, brand replacement, or unrelated settings internals. No new dependency expected.
+
+Use meaningful consuming tests: suggestions don't submit and preserve editability; Composer/picker/directory actions preserve draft and prior choice on cancel/Escape; route overlay restores state; real unread state; retained permission visibility; System follows OS while explicit preference and locale persist. Hermetic browser batch comparing actual renders against native exports in EN/ZH and both themes on desktop/narrow widths; fix observed defects once then targeted confirmation, no endless full matrix reruns. Run focused existing tests, UI build/lint/theme/i18n/type/catalog gates; never invent scenario IDs. Real auth/install stays #2011/manual acceptance, not claimed by screenshots.
+
+No primary checkout/runtime/service/production stores/Incus changes. Test-owned fixtures and processes only; no local Avibe restart. Pre-push concrete diff/head/tests/visuals go to PM for independent spot-check. Then non-draft PR to master, Closes #2012, explicit #2011 dependency where applicable. No manual Codex trigger; cyhhao automatically triggers. Verify full exact-head review/all lint runs/zero unresolved threads and deliver final report before Watch cleanup. No merge without owner instruction.
+
+## Frozen cross-lane interface
+
+No API-name decision is pending. PM inspected #2011's actual type, method and route at its base head
+f86a3dc683606456e491c71aa964ba468ca328de on 2026-09-18 02:45 and froze:
+
+- `BackendConnectionState`, exported from `ui/src/context/ApiContext.tsx`
+- `useApi().getBackendConnection(name: 'claude' | 'codex' | 'opencode'): Promise<BackendConnectionState>`
+- `GET /api/backend/{backend}/connection`, fields unchanged from the contract above
+
+The producer merged as PR #2032 (master 6ed01cd574328f90890680469619e0efcf87986b) and was merged into this
+branch with an ordinary merge commit. The frozen names above are the merged ones; this lane imports them and
+neither duplicates the type/method nor writes a second fetch wrapper, provider or store.
+
+**What the consumer does.** `ui/src/components/workbench/backendReadiness.ts` holds the whole seam.
+`useBackendReadiness(backend, asked)` issues at most one `getBackendConnection` per question asked — no
+polling, no start, no auth, no install, no write — and publishes `{ backend, ready }` only when the answer
+succeeded, says `ready`, and is about the backend that was asked about. Its type is `Pick<BackendConnectionState,
+'backend' | 'ready'>`, derived from the producer's type rather than restated. Anything else — pending, an
+unknown or unsupported backend name, a refused or denied read, a wrong-backend or not-ready answer — publishes
+nothing and never blocks the home. An answer whose question is no longer being asked is dropped and what was
+observed is cleared, including the A -> B -> A case where the stale answer names the backend now in effect.
+`shouldShowReadyBanner(...)` is unchanged: it refuses anything not corroborated.
+
+**The handoff is held for the page, not for the component.** The completion arrives as router state on a
+navigation that crosses the setup boundary, and crossing it is exactly what makes `AuthGuard` re-validate:
+the home is unmounted and remounted underneath it while that runs, after the history entry has already been
+consumed. A latch in component state dies with that remount and the completion can then never be announced at
+all — observed end to end in the browser, where the home issued no readiness read whatsoever. `useSetupHandoff`
+therefore holds the event, and a dismissal, for as long as the page the wizard handed over to is open. Reload
+silence is unchanged and is carried by the consumed history entry, not by the latch.
+
+**And it ends when the user leaves the visit it was made for.** The home is unmounted for two unrelated
+reasons — the guard re-validating in place, and an ordinary departure — and only the ROUTE tells them apart, so
+`useSetupHandoffDeparture` reads the route the surface is actually rendering rather than any component's
+cleanup; ending on unmount would end it during the guard's remount too, which is the bug the page scope exists
+to fix. It reads that background route rather than the shell's chrome location: Settings opened over the home
+is not a departure on either form factor, because the home is still there behind the overlay holding a banner
+the user has not answered, while the shell's own location follows the foreground URL below md.
+
+## Implementation record
+
+- **Shell** — `AppShell` sidebar at 248 on `--sidebar-background`, brand row (mark, title, `workbench.eyebrow`)
+ with Search and Inbox as siblings, always-expanded capability navigation via one `SidebarNavRow` carrying the
+ three source states on tokens, real project/session tree or true empty state, Apps/Settings footer, version and
+ live service badge. Nav-state tokens (`--nav-selected-bg`/`-border`, `--nav-hover-bg`, `--sidebar-background`,
+ `--logo-well-background`, `--illustration-card-border`, `--desktop-overlay-shadow`) and the
+ `--shadow-glow-nav-mint` role are additive; no existing token value or public API changed.
+- **Home** — three suggestion cards seed and focus the draft through the existing Composer handle and never send;
+ the shared Composer keeps its attachment, `AgentRoutePicker` and direct `DirectoryBrowser` behavior; project
+ find/create/draft/cancel/empty-send and the permission rules are the existing ones. The column is fluid.
+- **General** — `/settings/general` is the ordinary Settings landing and the returnable one. Language uses the
+ existing shared selection path and autosaves; appearance is three explicit choices through the existing
+ `ThemeProvider` (`mode`/`setMode`), so System follows the OS while Light/Dark persist. No Save button.
+- **Language operation** — one instance-wide value, so its ordering belongs to the i18n instance rather than to
+ whichever control is mounted: a private `WeakMap` in `useLanguageSelection.ts` holds the queue, the newest pick
+ and the failure a Retry may still act on, while a mounted control lends it the api and the toast for as long as
+ it is on screen. Leaving Settings mid-save no longer lets the next pick race the first, and a Retry whose
+ control is gone is inert — the pick stands locally, only the write is not re-attempted on a departed control's
+ authority. `AppShell` adopts the persisted language through the same operation, so neither a read that answers
+ late nor the second read a language change itself causes can undo the pick that caused it. The key is the
+ instance, not the object a component holds: `useTranslation` returns a fresh copy of the instance on every
+ language change, keeping the original as `__original`, so the held object is replaced by the very operation
+ being ordered — as `ApiContext`'s value already is, being memoized on `t`. Authority is asked twice and the two
+ answers are not interchangeable: whether a pick is an instance decision at all is settled by the control the user
+ made it through, so a member's local-only pick stays local even if they are granted instance rights before an
+ earlier save settles, and a write that is still ours to send reads the authority current when it runs rather than
+ the one remembered from when it was queued. A request already on the wire is not recalled.
+- **Primitive** — `SettingsPanel` gained a `preference` variant (surface-2, one 22px pad, radius 12, no divider);
+ the `panel` variant is untouched.
+
+## Deviations from the approved source
+
+Each is stated rather than silently closed:
+
+1. **Settings keeps the 248 workbench sidebar** — assessed and accepted, not inherited. The source board is a
+ native window, which is why Web also drops its titlebar and traffic lights; on Web, Settings is a route in the
+ one shell, and the overlay path deliberately keeps the sidebar visible so the origin project, session and draft
+ stay in view. Hiding it only on the direct route would give one URL two chromes and jump the layout on close.
+ What the source actually fixes is the frame beside the rail, and that is reproduced exactly: 1004 at a 1448
+ window, asserted in `geometry.spec.ts`. The visual observer confirmed no cropping or crowding; PM accepted this
+ as a bounded Web adaptation on 2026-09-18 05:13.
+2. ~~Heading is `SettingsPageShell`'s 28/700.~~ **Resolved.** `SettingsPageShell` gained an opt-in
+ `titleScale="landing"` (27/600 over a 13 muted line, source `Ozmrf`) consumed only by `SettingsGeneralPage`;
+ the fifteen sibling sections keep the 28/700 they shipped with, which is asserted from both sides.
+3. **The `a38Xy` "⌘," reminder is omitted** — the design index itself marks it macOS-menu specific.
+4. **No "⌘N" hint on the New chat row.** `DEFAULT_ACTION_SHORTCUTS` binds only voice input and Show Page
+ annotation, and the browser owns ⌘N; a visible hint for an unbound key is a false affordance.
+5. **The System miniature is drawn as a diagonal split.** The source renders System pixel-identically to Dark,
+ which the index records as a source defect; binding it to the resolved theme instead would make it identical to
+ whichever of the other two is live. Both halves use the source's own swatches.
+6. ~~The home canvas carries the `--gradient-console` wash.~~ **Resolved.** `/` alone is drawn on flat
+ `bg-background`; the wash stays with the rest of the console family (Agents, Skills, Harness, Vaults, Inbox,
+ chat). Both halves are asserted — `background-image: none` on the home, a `radial-gradient` still on `/agents`.
+7. **No attach/voice control on the first-task home.** `mediaEnabled` is `Boolean(sessionId)` and the home has no
+ session yet; a pre-session upload would need an API that does not exist.
+8. **Traffic lights, titlebar, window border and outer radius are absent**, per the index's own out-of-scope list.
+9. **Narrow layout has no native baseline** (the index confirms no narrow/mobile frame exists). The phone
+ decisions made here: sidebar drops to the existing mobile shell, suggestion cards stack, a preference card's
+ control drops under its label instead of squeezing the description, and the composer block pins itself to the
+ bottom of the scroll area one nav clearance above the tab bar (see 11).
+10. **Models and Groups rows are absent from the captures only** because the fixture leaves those features off;
+ the rail renders them from real state. The same applies to attach/mic on the first-task home (7) — neither is
+ a missing control to be drawn in for a screenshot match.
+11. **The phone composer is pinned, not in flow.** Measured at 390×844, the home is ~108px taller than its scroll
+ area, so at rest the block that ends the page — the composer's Agent, workspace and Send row — sat under the
+ fixed tab bar: `elementFromPoint` over Send returned the nav, i.e. a dead primary button, reachable only by a
+ scroll the user has no reason to make. The alternative, trimming the rhythm above it until one phone fits,
+ breaks on the next shorter phone. `--mobile-nav-clearance` now names the bar's reservation once, the shell
+ pads its scroll area by it and the composer block offsets by it, and a short fade marks the boundary the cards
+ scroll behind. Desktop is untouched.
+12. **Settings rail labels wrap instead of truncating.** At the source's 196 rail, English cut both "Messaging
+ Platforms" and "Platform Connections" to "Platform…", which are neighbouring rows leading to different pages.
+ Two lines at 12.5px still fit the row height the rail already had, so no row moves and the rail keeps its
+ width; measured as `scrollWidth === clientWidth` for every rendered rail label.
+
+## Verification evidence
+
+- `ui/e2e/workbench-general/` — a hermetic browser harness that loads the **real app** on a loopback dev server
+ pointed at a dead backend port. Every request is answered locally, allowed as a font read, or aborted and
+ recorded; `expect(denied).toEqual([])` is the proof that no write verb and no other off-origin call occurred.
+ Fixture data is deliberately non-ASCII (`中文项目`, `/Users/max/工作区/中文项目`).
+- `geometry.spec.ts` (12) measures rather than infers: sidebar 248 at 1200 and 1600 with the content taking the
+ full extra 400 (952 → 1352); settings rail 196 with the General card fluid past the shared cap (692 @1200 →
+ 1412 @1920); every other Settings page still 1180 at 1920; the Settings content frame exactly 1004 at 1448; the
+ card anatomy — radius 12, pad 22, row gap 20, `--surface-2` fill, 190×40 selector at radius 9, selected choice
+ at 2px `--mint` with equal-width siblings, 14 gutter, 88 preview at radius 6; the landing heading 27/600 against
+ a sibling section's 28/700; the home flat while `/agents` keeps its wash; the Settings overlay opening at the
+ sidebar's own measured edge and restoring the route, draft and workspace selection on close; every rail label
+ unclipped at 196; and the phone composer clear of the tab bar in EN and ZH, at rest, focused with text, and at
+ 390×667 — asserted by what `elementFromPoint` returns over Send, which visibility alone cannot answer.
+- `capture.spec.ts` (18) writes the comparison batch to the stable path
+ `ui/e2e/.artifacts/workbench-general/shots/` — both surfaces × EN/ZH × Light/Dark × desktop/narrow, plus System
+ mode under both OS answers. Playwright's `outputDir` is a sibling (`run/`) precisely because it is emptied on
+ every run, including a filtered one.
+- Defects the batch actually caught and fixed: a comment block that had leaked into the Composer's JSX and was
+ rendering as visible text; the preference card drawn at radius 16 where the source says 12; the theme
+ miniature at radius 8 where the source says 6; a truncated brand subtitle at 248; a React duplicate-key warning
+ on the mobile tab bar; and the narrow language row squeezing its description to one word.
+- Defects the observer's 18-image review caught and this lane fixed: the desktop overlay seam (the shared dialog
+ primitive's historical 240 against the shell's 248), the General heading scale, the home background family, the
+ phone composer under the tab bar, and the English rail truncation.
+- Gates, all green after the final edits: vitest 4352/4352, `typecheck:tests`, `lint` (baseline, no drift),
+ `validate:theme`, `validate:catalog`, `build`, and the 30 browser tests above. One `travellingTokens` case
+ failed once in an early full run and has not reproduced in either full run since, including the final one; it
+ is recorded rather than explained away.
+
+## Review round 1 repairs
+
+Five findings, all inside this lane's own surfaces. Each is stated by its root class, not by the comment that
+found it:
+
+1. **Redundant alt text on the sidebar brand image.** The link's accessible name is the localized brand text
+ beside it, so naming the image too read the destination twice. The image is decorative (`alt=""`,
+ `aria-hidden`). Only `WorkbenchSidebar`'s image is new in this PR; `AppShell`'s mobile header brand carries the
+ same pattern and predates it, so it is reported rather than swept in.
+2. **A phone lost an unsent composition when it followed a Settings continuation.** The home's continuations lead
+ away from an unsent draft plus the Agent and workspace it is aimed at, none of which is persisted anywhere, so
+ its Settings ingress now records an origin on mobile as well as desktop. That keeps the one Workbench instance
+ mounted behind the full-screen mobile Settings surface, and Back returns to the composition the user left. This
+ retains that one route's local state and nothing else: every other mobile route keeps its ordinary
+ unmount-on-navigate lifecycle, and a direct Settings link still invents no origin. The change is at the existing ingress owner (`settingsOverlay`); the
+ mobile chrome is unchanged, because `AppShell` keeps its own desktop guard — a retained origin changes what
+ survives behind the surface, not what is drawn over it. The one presentation seam, the dialog primitive's left
+ border at the viewport edge, is neutralized in the consumer so the surface looks identical either way.
+3. **The continuation row offered a member-and-above destination to everyone.** Both links are
+ `OWNER_ONLY_ROUTES`, so anyone else following one is bounced straight back. The whole row is gated on
+ `can_manage_instance` rather than the links alone, because the sentence around them exists only to introduce a
+ destination they cannot reach.
+4. **The retired `/settings/appearance` alias still pointed at Replies.** General took the theme controls over, so
+ the alias follows them; Account keeps pointing at Replies, which still owns it.
+5. **An installed PWA could not cold-launch back onto General.** `RESTORABLE_EXACT_PATHS` is an exact list, not a
+ prefix rule, and the new page was missing from it.
+
+What the audit established, and why the evidence is shaped the way it is:
+
+- The mobile Workbench home has exactly one Settings ingress — the two continuation links. The sidebar's Settings
+ toggle is inside a `md:flex` aside and the bottom tab bar has no Settings tab, so the origin policy covers the
+ whole chain rather than one of several doors.
+- Nothing in the product links to `/settings/appearance` any more, so the alias is reachable only as a stale
+ bookmark: a document load, which invents no origin by design. The origin-carrying alias hop is therefore
+ asserted at the boundary owner in unit scope, and the reachable flow is asserted in the browser.
+- A chosen workspace and the continuation row do appear together — through the chip's manager branch. Only the
+ `ProjectPicker` popover is mutually exclusive with the row: the server projects `can_manage_instance` from
+ member upward and `can_chat`/`can_use_files` from editor upward, so the editor who gets the picker has no
+ Settings ingress on the home at all. A member or owner gets the other branch of the same chip —
+ `NewProjectDialog` → `DirectoryBrowser` → `createProject` → `upsertSelectProject` — and `create_project` is
+ find-or-create by folder path, so opening a folder that is already a project selects that existing row. The
+ continuation round trips therefore choose their workspace through that shipped path, with no permission
+ widening, and assert the create call carried exactly that one folder and was not repeated on the way back.
+- That path cannot be driven under the dev server. `DirectoryBrowser` clears a mounted ref on unmount and never
+ restores it, so StrictMode's mount→cleanup→remount leaves every browse response discarded and the dialog stuck
+ loading — a pre-existing, development-only defect in a shared primitive this PR does not own and does not
+ touch. This file therefore runs against the production build, where StrictMode is inert, under its own config
+ and the same hermetic harness; the rest of the suite stays on the dev config, which now ignores this file.
+
+`mobile-continuation.spec.ts` (5, hermetic, built app) covers this: both continuations preserving a non-ASCII
+draft, a non-default Agent, a workspace opened through the directory browser and the same DOM instance across
+Settings-internal navigation — including General and its theme controls — and back; a control that leaves by an
+ordinary tab and returns with browser Back, the same return path the chat-apps case uses, where every one of
+those assertions fails because the home is a new one; the picker branch under the editor projection, which has no
+continuation to offer and issues no create call at all; and the retired alias landing on General with Account's
+destination unchanged. All folder and project endpoints are test-owned fixtures — no real directory is browsed
+and no project is created. Unit scope adds the mobile origin policy and its onward hops, the PWA
+write→read→resolve chain, and an `App.tsx` AST assertion that each retired alias points at the page that took its
+content over. Re-validated for this round: the five browser tests, the six affected unit files (70), `typecheck`,
+`lint` on the changed files, and `build`. The earlier full-suite and screenshot gates are not re-run here, because
+nothing in this round changes what they measure.
+
+## Review round 2 repair — the phone's way out of a retained Settings chain
+
+One finding, in the same mobile Settings navigation-lifecycle class as round 1's second repair, so the two-head
+circuit breaker applied and the whole class was inventoried before anything was edited.
+
+Retaining the home's origin on mobile gave the phone something to close *back to*, but the phone's own root
+control was never told: at `/settings` the header chevron stayed an ordinary `NavLink` to `/`. It pushed a second
+home in front of every Settings entry the user had opened, so one Back re-entered Settings — with a deeper chain,
+several Backs. The home itself came back intact, which is why the round-1 evidence passed: it asserted what the
+returning surface held, and same-path reconciliation satisfies that even when the history behind it is wrong.
+
+Every other way out already goes through one owner, `closeSettingsOverlay`, which unwinds to the recorded history
+index or replaces with the origin when there is none:
+
+- the desktop close (`X`) and the rail's back row, both via `ReturnToApp`;
+- the dialog's own dismissal (Escape, outside click) via `onOpenChange`;
+- `AppShell`'s sidebar Settings toggle;
+- the browser/OS Back button, which needs no control at all.
+
+There is no other mobile exit to fix: `AppShell` treats a Settings route as `isFullScreenMobile`, so the mobile
+brand header and the bottom tab bar are not rendered over the surface, and the chevron's Settings-internal
+destinations are navigation *inside* Settings, not a close. So the repair is one missed caller joining the
+existing owner: when the chevron's target is the Workbench it renders `ReturnToApp` like the desktop controls do,
+and keeps its label, touch size and icon. A direct visit has no origin and still gets a plain link to `/`, and
+every internal destination stays a link so the origin rides along with the push.
+
+Evidence is the property, not the control's shape. A sixth browser case builds a real predecessor (Inbox → home),
+records the home's history index, primes the draft/Agent/manager-picked workspace, walks a continuation, the
+section list, General and back to the list, leaves through the actual control, and asserts the index is the one it
+started from — then repeats through the other continuation and finally goes Back to the Inbox rather than into
+Settings. Against the unrepaired product that assertion reads 6 where it must read 1; the case locates the control
+by label so it fails on the history, not on the element type. Unit scope adds the close behaviour at the phone
+root and holds internal back destinations to links. Re-validated: the six browser cases on the built app, the five
+affected unit files (91), the browser suite's `typecheck`, `lint` on the changed files, and `build`.
+
+## Producer integration — what the end-to-end run found
+
+Wiring the merged producer into the home was one function body, as planned. Driving it end to end was not, and
+that is where the value was: `e2e/workbench-general/setup-handoff.spec.ts` walks the real wizard to its own
+Enter, lets the real completion handler save and navigate, and then holds the home's readiness read open — a
+state no unit test can stage, because the pending window only exists between a real navigation and a real
+response. The banner must stay silent until that read answers for the backend the home's Agent route actually
+runs, and the case asserts nothing was ever refused by the harness guard.
+
+The first run showed the home issuing no readiness read at all. The wizard's navigation did carry
+`{ onboardingCompleted: true }`, and the home did consume it — and was then unmounted and remounted, because
+`AuthGuard` deliberately re-validates when the setup boundary is crossed and shows Loading while it does. The
+remounted home read an entry it had already emptied, so the completion was gone before the Agent route had even
+resolved: with a latch in component state the banner could never appear after a real wizard completion, however
+ready the backend was. Every mocked suite passed throughout, because each one renders the home once.
+
+The repair keeps the accepted semantics exactly and only changes the latch's lifetime: `useSetupHandoff` holds
+the completion, and a dismissal, for the page. Nothing else moved — the history entry is still consumed on
+arrival, reload silence is still carried by that consumed entry, and `shouldShowReadyBanner` is untouched.
+`AuthGuard` is not touched either; its re-validation is deliberate, and the consumer now survives it. Both the
+new unit case and the browser case fail against the component-state latch and pass against this one.
+
+Review then found the other half of the same lifetime: it had a correct start and no end. A page-held handoff
+survives an ordinary departure too, so arriving home with a completion, leaving for another route, and coming
+back announced the setup a second time. The end is the route, not the component — see the contract above — and
+`SettingsOverlayRouteSurface` is the one place that already knows which route is being rendered behind any
+overlay, so it states the departure there instead of a second router integration. The real shell reproduces it:
+`e2e/workbench-general/setup-handoff.spec.ts` leaves the home through the sidebar's own link and returns
+through it, and that case fails without the end and passes with it. The same browser flow now also picks a
+NON-default model through the composer's own picker while the readiness read is still open, so the announcement
+arriving over a home in use, and being dismissed on it, is held to leaving the user's route untouched.
+
+## Progress
+
+- [x] Owner parallel start, latest master and isolated workspace verified.
+- [x] Native design packet and existing route/state ownership inventory.
+- [x] Independent shell, home/Composer, General implementation.
+- [x] Producer #2011 contract integration and cross-lane consumer verification — #2032 merged into this branch;
+ the home consumes the merged type/method, and `e2e/workbench-general/setup-handoff.spec.ts` drives the real
+ wizard Enter, router, `ApiProvider` and completion handler against fixture transport.
+- [x] Focused/browser verification; PM pre-push spot-check pending.
+- [ ] Non-draft PR, exact-head Codex/CI and zero unresolved threads.
+- [ ] Owner acceptance and separately authorized merge.
+
+# #2011 / #2012 parallel implementation contract
+
+PM: sestqz5wvu5ty. Owner authorized #2011 on 2026-09-18 02:16 and #2012 parallel start at 02:36 Asia/Shanghai. Both start from master 4019b704c99afe16223d475fccd9e1cb94a109d7. This explicit decision supersedes historical sequential-dispatch restrictions. Each uses its own default-branch worktree; no stacked PR and no base-branch direct commit is authorized. This outside-checkout document is authoritative until consolidated into the separate issue plans. Each lane commits its contract copy before feature edits. Do not overwrite a peer's changing plan.
+
+## Exact ownership
+
+#2011 session ses6652kpzsns owns Python/auth/install/runtime/readiness, ApiContext additions, Wizard/steps/onboarding, settings/{BackendOAuthPanel,oauth,providers,shared,BackendLifecycleChip}, wizardConfigMutations, auth_setup scenarios and direct tests. It also owns the historical shared-web-desktop-design plan consolidation, its own active plan, and onboarding fidelity tests. Its owner amendment restores the existing BrandLogo on the Web header and identical top-anchored heading/subtitle positions between both steps. Desktop behavior remains #2013.
+
+#2012 owns AppShell, Workbench, workbench/{WorkbenchSidebar,Composer,new home components}, necessary existing project/folder presentation glue and useNewSession, SettingsLayout/SettingsOverlay*/SettingsPageShell, a new SettingsGeneralPage, adminNavigation/settingsRoutes/settingsOverlay, LanguageSwitcher presentation/shared language behavior if necessary, and relevant tests. App.tsx: ONLY General import/route and ordinary Settings landing wiring; no AuthGuard changes. ThemeProvider stays the single state owner and its external contract is preserved; consume mode/resolvedTheme/setMode, do not create another theme store. Existing AgentRoutePicker/DirectoryBrowser and MentionEditor behavior is reused, not replaced. Existing providers, inbox, search, Apps and status are reused. Do not redesign internal Model Hub/Agents/Skills/Harness/Vaults/Memory pages.
+
+#2012 owns global index.css and shared primitive additions but must preserve existing values and public APIs; add scoped variants or new semantic tokens only. #2011 requests missing global tokens from PM, not unilateral global edits. Neither replaces brand assets. Shared i18n JSON overlap is limited to disjoint key ownership: #2011 onboarding/auth/provider keys; #2012 sharedWorkspace.*, settings.general.*, and necessary workbench/nav/settings-layout keys. No full-file format churn. PM checks merged key inventory and both build/test consumers after integration.
+
+## Behavior boundary
+
+Producer #2011: after explicit Enter, fresh authoritative readiness, successful required start/apply and narrow setup_completed save, navigate to `/` with React Router state `{ onboardingCompleted: true }`.
+Consumer #2012: only that transient navigation permits the one-time dismissible banner. It is not authorization or Agent data. Consume it once without dropping other router state or the underlying Settings return location; dismissal/ordinary reload/return must not recreate it. Never persist a new onboarding database or auth flag.
+
+Agent labels/default resolution come from existing `useNewSession` / `listVibeAgents({includeDisabled:false})`: actual `agents[]` with `name,display_name,backend,enabled,archived`, `default_agent_name` and effective project/user selection. Enabled alone is NOT applied authentication. Do not invent readiness fields on VibeAgentBrief, manufacture an Agent or pin a backend default.
+
+#2011 produces `GET /api/backend/{backend}/connection` with `{ok, backend, installed, enabled, auth: subscription|api_key|none|unknown, application: applied|draining|failed|stopped|unknown, ready, entry_eligible, permission_required?, message?}` and the canonical ApiContext type/method. #2012 may consume the producer's published API to corroborate banner readiness; only `ready === true` corroborates a ready claim. False/pending/error must not render a successful banner or block existing Workbench access. No auth/start/save in the banner. Exact exported TS method/type names are to be delivered by #2011 before this dependent consumer is coded. Meanwhile implement all independent shell/General/composer work. Do not write a second fetch wrapper, type owner or dummy product fallback merely to compile against unmerged code. Final #2012 integration rebases after #2011 merge; dependent readiness verification must be completed before delivery, and the PR names that dependency.
+
+Ordinary Settings opens `/settings/general` irrespective of last visited settings subsection. Explicit `/settings/backends`, `/settings/backends/{claude,codex,opencode}`, `/settings/platforms`, `/settings/remote-access` remain destinations. Overlay close preserves originating project/session/unsent draft/Agent selection and history semantics. Non-owner permissions remain intact. General language uses existing local update and permitted config autosave; theme System follows OS, explicit modes persist through current setter. No native host detection/header suppression/menu work.
+
+## Integration acceptance
+
+PM will verify the actual setup->Workbench event with producer and consumer together, non-ASCII draft/directory, Settings open/close preserving draft/project/Agent, permission-aware visibility, empty-send, suggestion-seed-without-send, theme/System persistence. Separate mocked suites cannot certify the cross-lane seam. Each lane first delivers a concrete diff/tests/native-source versus render to PM, then pushes a non-draft PR after PM spot-check. No merge without owner instruction. Never manually trigger Codex; cyhhao triggers it. Maintain lane and independent PM combined PR/CI Watches when a PR exists, forever and both timeout layers zero, durable cursor unchanged between heads. Paginate reviews/threads and apply repeated-class two-head breaker with PM diagnosis before another patch.
diff --git a/ui/e2e/workbench-general/capture.spec.ts b/ui/e2e/workbench-general/capture.spec.ts
new file mode 100644
index 000000000..469fd5e16
--- /dev/null
+++ b/ui/e2e/workbench-general/capture.spec.ts
@@ -0,0 +1,61 @@
+import { test } from '@playwright/test';
+
+import { DESKTOP, NARROW, open, serveProduct } from './support';
+
+/**
+ * The comparison batch: the two surfaces this packet adds, rendered in both
+ * languages, both themes and at both widths, so the renders can be held against
+ * the approved source instead of trusting that reused primitives came out right.
+ * These write PNGs and assert nothing — the renders are the evidence.
+ */
+
+const SHOTS = 'e2e/.artifacts/workbench-general/shots';
+
+const SURFACES = [
+ { name: 'home', path: '/', ready: 'main#app-shell-scroll' },
+ { name: 'general', path: '/settings/general', ready: '[role="radiogroup"]' },
+] as const;
+
+const LANGS = ['en', 'zh'] as const;
+const THEMES = ['light', 'dark'] as const;
+const WIDTHS = [
+ { name: 'desktop', size: DESKTOP },
+ { name: 'narrow', size: NARROW },
+] as const;
+
+for (const surface of SURFACES) {
+ for (const lang of LANGS) {
+ for (const theme of THEMES) {
+ for (const width of WIDTHS) {
+ test(`${surface.name} ${lang} ${theme} ${width.name}`, async ({ page }) => {
+ await serveProduct(page, lang);
+ await page.emulateMedia({ reducedMotion: 'reduce' });
+ await page.setViewportSize(width.size);
+ await open(page, surface.path, { lang, theme });
+ await page.locator(surface.ready).first().waitFor({ state: 'visible' });
+ await page.waitForTimeout(400);
+ await page.screenshot({
+ path: `${SHOTS}/${surface.name}-${lang}-${theme}-${width.name}.png`,
+ fullPage: width.name === 'narrow',
+ });
+ });
+ }
+ }
+ }
+}
+
+/**
+ * `system` is the one mode whose render is decided outside the app, so it is
+ * captured against both OS answers — the same explicit choice, two results.
+ */
+for (const osTheme of ['light', 'dark'] as const) {
+ test(`general system-mode with an OS set to ${osTheme}`, async ({ page }) => {
+ await page.emulateMedia({ colorScheme: osTheme, reducedMotion: 'reduce' });
+ await serveProduct(page);
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/settings/general', { theme: 'system' });
+ await page.locator('[role="radiogroup"]').waitFor({ state: 'visible' });
+ await page.waitForTimeout(400);
+ await page.screenshot({ path: `${SHOTS}/general-system-os-${osTheme}-desktop.png` });
+ });
+}
diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.ts
new file mode 100644
index 000000000..4e62870a9
--- /dev/null
+++ b/ui/e2e/workbench-general/geometry.spec.ts
@@ -0,0 +1,396 @@
+import { expect, test } from '@playwright/test';
+
+import { DESKTOP, NARROW, ORIGIN, WIDE, open, serveProduct } from './support';
+
+/**
+ * The packet's geometry claims, measured in a browser rather than inferred from
+ * class names. Two of them are fixed numbers (sidebar 248, settings rail 196)
+ * and the rest are the opposite claim — that the content beside them is fluid,
+ * which a capture at the 1200 staging width alone cannot distinguish from a
+ * column that happens to be 856 or 924 wide.
+ */
+
+const SIDEBAR = 'aside.fixed';
+const SHELL_SCROLL = 'main#app-shell-scroll';
+const SHELL_CONTENT = 'main#app-shell-scroll > div';
+const SETTINGS_RAIL = 'nav[aria-label="Settings sections"]';
+const SETTINGS_PAGE = 'nav[aria-label="Settings sections"] + section';
+const SETTINGS_CONTENT = 'nav[aria-label="Settings sections"] + section > div';
+const APPEARANCE_CARD = 'section.bg-surface-2:has([role="radiogroup"])';
+// The composer's own workspace chip, not the sidebar tree row: it is the
+// selection the overlay has to hand back, and its label carries the fixture's
+// non-ASCII path.
+const WORKSPACE_CHIP = 'Workspace: /Users/max/工作区/中文项目';
+const MOBILE_NAV = 'nav.fixed.bottom-0';
+const ULTRA = { width: 1920, height: 1000 };
+// A phone one iPhone-generation shorter. The composer has to clear the tab bar
+// because of where it is anchored, not because 844 happens to leave room.
+const NARROW_SHORT = { width: 390, height: 667 };
+
+const widthOf = async (page: import('@playwright/test').Page, selector: string) => {
+ const box = await page.locator(selector).first().boundingBox();
+ expect(box, `${selector} should be laid out`).not.toBeNull();
+ return box!.width;
+};
+
+/**
+ * What the user's finger would actually land on. `toBeVisible()` cannot answer
+ * this: an element covered by a fixed bar is still visible, still has a box, and
+ * still fails every tap.
+ */
+const topmostOver = async (
+ page: import('@playwright/test').Page,
+ locator: import('@playwright/test').Locator,
+) => {
+ const box = await locator.boundingBox();
+ expect(box, 'control should be laid out').not.toBeNull();
+ return page.evaluate(({ x, y }) => {
+ const node = document.elementFromPoint(x, y);
+ if (!node) return 'nothing';
+ const control = node.closest('button, a');
+ return control?.getAttribute('aria-label') ?? control?.textContent?.trim() ?? node.tagName;
+ }, { x: box!.x + box!.width / 2, y: box!.y + box!.height / 2 });
+};
+
+const bottomOf = async (locator: import('@playwright/test').Locator) => {
+ const box = await locator.boundingBox();
+ expect(box, 'element should be laid out').not.toBeNull();
+ return box!.y + box!.height;
+};
+
+test.describe('workbench home geometry', () => {
+ test('keeps the sidebar at 248 and lets everything beside it grow', async ({ page }) => {
+ const denied = await serveProduct(page);
+
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/');
+ await expect(page.locator(SIDEBAR)).toBeVisible();
+
+ expect(await widthOf(page, SIDEBAR)).toBe(248);
+ const atStaging = await widthOf(page, SHELL_CONTENT);
+
+ await page.setViewportSize(WIDE);
+ await page.waitForFunction(() => window.innerWidth === 1600);
+
+ // The sidebar is the fixed part; the column beside it is not. It has to take
+ // the full extra 400, because a cap of any size would swallow some of it.
+ expect(await widthOf(page, SIDEBAR)).toBe(248);
+ const atWide = await widthOf(page, SHELL_CONTENT);
+ expect(atWide - atStaging).toBe(WIDE.width - DESKTOP.width);
+
+ // eslint-disable-next-line no-console
+ console.log(`home content: ${atStaging} @1200, ${atWide} @1600`);
+ expect(denied).toEqual([]);
+ });
+
+ test('drops the sidebar on a phone and still fills the width', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(NARROW);
+ await open(page, '/');
+
+ await expect(page.locator(SIDEBAR)).toBeHidden();
+ expect(await widthOf(page, SHELL_CONTENT)).toBe(NARROW.width);
+ });
+
+ /**
+ * The phone home is taller than the screen, so whatever ends the page sits
+ * under the fixed tab bar until someone scrolls. What ends the page is the
+ * composer's own action row — Agent, workspace, Send — so the defect is a
+ * dead primary button on first paint, not a cropped screenshot. Both
+ * languages, because the row's left side is translated text whose width moves.
+ */
+ const PHONE_COMPOSER: { lang: 'en' | 'zh'; placeholder: string; send: string; lastRow: string }[] = [
+ { lang: 'en', placeholder: 'Describe a task or ask a question...', send: 'Send', lastRow: 'Continue on your phone' },
+ { lang: 'zh', placeholder: '给你的助手安排任务…', send: '发送', lastRow: '在手机 APP 上继续' },
+ ];
+
+ for (const { lang, placeholder, send, lastRow } of PHONE_COMPOSER) {
+ test(`keeps the composer's controls off the tab bar on a phone (${lang})`, async ({ page }) => {
+ const denied = await serveProduct(page, lang);
+ await page.setViewportSize(NARROW);
+ await open(page, '/', { lang });
+
+ const composer = page.getByPlaceholder(placeholder);
+ const sendButton = page.getByRole('button', { name: send });
+ const nav = page.locator(MOBILE_NAV);
+ await expect(composer).toBeVisible();
+ await expect(nav).toBeVisible();
+
+ // The premise: this page really does overflow, so clearing the bar is the
+ // anchoring and not a lucky fit. If this ever stops being true the rest of
+ // the test would pass for the wrong reason.
+ const overflow = await page.locator(SHELL_SCROLL).evaluate((node) => ({
+ top: node.scrollTop,
+ hidden: node.scrollHeight - node.clientHeight,
+ }));
+ expect(overflow.top).toBe(0);
+ expect(overflow.hidden).toBeGreaterThan(0);
+
+ // Nothing in the block may reach under the bar — asserted on the block's
+ // last row, which is below the action row.
+ const navTop = (await nav.boundingBox())!.y;
+ expect(await bottomOf(page.getByRole('link', { name: lastRow }))).toBeLessThanOrEqual(navTop);
+ // …and the primary control specifically: what a tap would hit, at rest.
+ expect(await topmostOver(page, sendButton)).toBe(send);
+
+ // Typing is when it matters, and a focused textarea is also when the page
+ // could scroll under the user. It must not have to.
+ await composer.click();
+ await composer.fill('给手机上的我写一句话');
+ await expect(composer).toBeFocused();
+ expect(await page.locator(SHELL_SCROLL).evaluate((node) => node.scrollTop)).toBe(0);
+ expect(await topmostOver(page, sendButton)).toBe(send);
+ // Playwright's own actionability check, which is the product's tap path.
+ await sendButton.click({ trial: true });
+
+ // A shorter phone has less room above, never less clearance below.
+ await page.setViewportSize(NARROW_SHORT);
+ await page.waitForFunction(() => window.innerHeight === 667);
+ expect(await topmostOver(page, sendButton)).toBe(send);
+ expect(await bottomOf(page.getByRole('link', { name: lastRow })))
+ .toBeLessThanOrEqual((await nav.boundingBox())!.y);
+
+ expect(denied).toEqual([]);
+ });
+ }
+});
+
+test.describe('settings overlay geometry', () => {
+ test('opens at the sidebar edge and gives the home back its draft on close', async ({ page }) => {
+ const denied = await serveProduct(page);
+
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/');
+
+ // A draft and a project selection are what the overlay exists to preserve,
+ // so the assertion starts by creating both. Non-ASCII on purpose.
+ const draft = '给中文项目写一份说明';
+ const composer = page.getByPlaceholder('Describe a task or ask a question...');
+ await composer.fill(draft);
+ await expect(composer).toHaveValue(draft);
+ await expect(page.getByLabel(WORKSPACE_CHIP)).toBeVisible();
+
+ await page.locator('aside [data-settings-toggle="true"]').click();
+ await expect(page).toHaveURL(/\/settings\/general$/);
+
+ const overlay = page.locator('[data-settings-overlay="true"]');
+ await expect(overlay).toBeVisible();
+
+ // The overlay covers the work area and stops exactly at the sidebar's own
+ // edge — measured off the sidebar rather than compared to a literal, so the
+ // two cannot drift apart the way a second hard-coded width did.
+ const sidebar = await page.locator(SIDEBAR).boundingBox();
+ const surface = await overlay.boundingBox();
+ expect(sidebar!.x).toBe(0);
+ expect(surface!.x).toBe(sidebar!.x + sidebar!.width);
+ expect(surface!.width).toBe(DESKTOP.width - sidebar!.width);
+ // Covering the sidebar would be the same defect from the other side.
+ await expect(page.locator(SIDEBAR)).toBeVisible();
+
+ await page.locator('aside [data-settings-toggle="true"]').click();
+ await expect(page).toHaveURL(`${ORIGIN}/`);
+ await expect(overlay).toHaveCount(0);
+ await expect(page.getByPlaceholder('Describe a task or ask a question...')).toHaveValue(draft);
+ await expect(page.getByLabel(WORKSPACE_CHIP)).toBeVisible();
+
+ expect(denied).toEqual([]);
+ });
+});
+
+test.describe('page background family', () => {
+ test('draws the home flat and leaves the console wash on its siblings', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(DESKTOP);
+
+ // Board 04 stages the home on flat $--background.
+ await open(page, '/');
+ await expect(page.locator(SIDEBAR)).toBeVisible();
+ expect(await page.locator(SHELL_SCROLL).evaluate((n) => getComputedStyle(n).backgroundImage)).toBe('none');
+
+ // …and the rest of the console family keeps the aurora it already had, which
+ // is the half of this decision a capture of the home alone cannot show.
+ await open(page, '/agents');
+ expect(await page.locator(SHELL_SCROLL).evaluate((n) => getComputedStyle(n).backgroundImage))
+ .toContain('radial-gradient');
+ });
+});
+
+test.describe('general settings geometry', () => {
+ test('keeps the rail at 196 and keeps the page fluid past the shared cap', async ({ page }) => {
+ const denied = await serveProduct(page);
+
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/settings/general');
+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
+
+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);
+ const cardAtStaging = await widthOf(page, APPEARANCE_CARD);
+
+ // Wide enough to pass the shared 1180 reading column on purpose. Measuring
+ // below it could not tell a fluid page from a capped one, which is the whole
+ // question: the source draws General as content that fills whatever the rail
+ // leaves, so a cap of any size — inherited or not — contradicts it.
+ await page.setViewportSize(ULTRA);
+ await page.waitForFunction(() => window.innerWidth === 1920);
+
+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);
+ const cardAtUltra = await widthOf(page, APPEARANCE_CARD);
+ expect(cardAtUltra).toBeGreaterThan(1180);
+ expect(cardAtUltra - cardAtStaging).toBe(ULTRA.width - DESKTOP.width);
+
+ // eslint-disable-next-line no-console
+ console.log(`general card: ${cardAtStaging} @1200, ${cardAtUltra} @1920`);
+ expect(denied).toEqual([]);
+ });
+
+ test('gives the landing its own heading block and leaves the sections alone', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(DESKTOP);
+
+ const headingOf = async (path: string) => {
+ await open(page, path);
+ const heading = page.locator(`${SETTINGS_PAGE} h1`).first();
+ await expect(heading).toBeVisible();
+ return heading.evaluate((node) => {
+ const style = getComputedStyle(node);
+ return { size: style.fontSize, weight: style.fontWeight };
+ });
+ };
+
+ // Ozmrf draws the landing at 27/600; every section keeps the 28/700 it
+ // already shipped with, which is why the variant is opt-in.
+ expect(await headingOf('/settings/general')).toEqual({ size: '27px', weight: '600' });
+ expect(await headingOf('/settings/shortcuts')).toEqual({ size: '28px', weight: '700' });
+ });
+
+ // Assessed rather than inherited: the shell sidebar stays on a direct Settings
+ // route, where the source board draws a standalone window with none. The board
+ // is a native window (the same reason Web drops its titlebar and traffic
+ // lights); on Web, Settings is a route in the one shell, and the overlay path
+ // deliberately keeps the sidebar visible so the origin work stays in view.
+ // Hiding it only on the direct route would give one URL two chromes and jump
+ // the layout on close. What the source actually fixes is the frame beside the
+ // rail, and that is reproduced exactly at a real window width.
+ test('reaches the source content frame at a real desktop width', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize({ width: 1448, height: 900 });
+ await open(page, '/settings/general');
+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
+
+ // dqfES — the source's Settings content frame.
+ expect(await widthOf(page, SETTINGS_PAGE)).toBe(1004);
+ expect(await widthOf(page, SIDEBAR)).toBe(248);
+ });
+
+ // A rail label is the only thing that says where a row goes, and English has
+ // two neighbours that both ended in "Platform…" at 196. The rail width is the
+ // source's, so the labels wrap instead.
+ test('shows every rail label in full without widening the rail', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/settings/platforms');
+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
+
+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);
+
+ // Measured, not eyeballed: a wrapped label's scrollWidth equals its
+ // clientWidth; a clipped one exceeds it.
+ const clipped = await page
+ .locator(`${SETTINGS_RAIL} a[href^="/settings"] span, ${SETTINGS_RAIL} button[aria-expanded] span`)
+ .evaluateAll((nodes) => nodes
+ .filter((node) => node.getClientRects().length > 0 && node.scrollWidth > node.clientWidth)
+ .map((node) => node.textContent?.trim() ?? ''));
+ expect(clipped).toEqual([]);
+
+ const rail = page.locator(SETTINGS_RAIL);
+ await expect(rail.getByRole('button', { name: 'Messaging Platforms' })).toBeVisible();
+ await expect(rail.getByRole('link', { name: 'Platform Connections' })).toBeVisible();
+
+ // Two lines at this size still fit the row height the rail already had, so
+ // the rows that never wrapped do not move.
+ const rows = await rail.locator('a[href^="/settings"]').evaluateAll((nodes) =>
+ nodes.map((node) => Math.round(node.getBoundingClientRect().height)));
+ expect(new Set(rows).size).toBe(1);
+ });
+
+ test('leaves the shared reading column on every other settings page', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(ULTRA);
+ await open(page, '/settings/shortcuts');
+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
+
+ // General opts out by route, so the pages that wanted the reading column
+ // still have it at a width where the difference is visible.
+ expect(await widthOf(page, SETTINGS_CONTENT)).toBe(1180);
+ });
+
+ test('draws the preference card, the selector and the selected choice to spec', async ({ page }) => {
+ await serveProduct(page);
+ await page.setViewportSize(DESKTOP);
+ await open(page, '/settings/general', { theme: 'dark' });
+
+ const card = page.locator(APPEARANCE_CARD);
+ await expect(card).toBeVisible();
+
+ const cardStyle = await card.evaluate((node) => {
+ const outer = getComputedStyle(node);
+ const inner = getComputedStyle(node.firstElementChild as Element);
+ return { radius: outer.borderRadius, pad: inner.padding, gap: inner.rowGap, bg: outer.backgroundColor };
+ });
+ // le5QU / Q8zxF1: padding 22, radius 12 — not the 16 the older `panel`
+ // variant renders, which is why `preference` is its own variant.
+ expect(cardStyle.radius).toBe('12px');
+ expect(cardStyle.pad).toBe('22px');
+ expect(cardStyle.gap).toBe('20px');
+
+ const surface2 = await page.evaluate(() => {
+ const probe = document.createElement('div');
+ probe.style.backgroundColor = 'var(--surface-2)';
+ document.body.appendChild(probe);
+ const value = getComputedStyle(probe).backgroundColor;
+ probe.remove();
+ return value;
+ });
+ expect(cardStyle.bg).toBe(surface2);
+
+ const select = page.getByLabel('Language', { exact: true });
+ const selectBox = await select.boundingBox();
+ expect(selectBox!.width).toBe(190);
+ expect(selectBox!.height).toBe(40);
+ expect(await select.evaluate((node) => getComputedStyle(node).borderRadius)).toBe('9px');
+
+ const dark = page.getByRole('radio', { name: 'Dark' });
+ await expect(dark).toHaveAttribute('aria-checked', 'true');
+ const selectedBorder = await dark.evaluate((node) => {
+ const style = getComputedStyle(node);
+ return { width: style.borderTopWidth, color: style.borderTopColor };
+ });
+ expect(selectedBorder.width).toBe('2px');
+
+ const mint = await page.evaluate(() => {
+ const probe = document.createElement('div');
+ probe.style.color = 'var(--mint)';
+ document.body.appendChild(probe);
+ const value = getComputedStyle(probe).color;
+ probe.remove();
+ return value;
+ });
+ expect(selectedBorder.color).toBe(mint);
+
+ // Picking a card must not nudge the row: the extra border pixel is absorbed
+ // by padding, so every card in the group stays the same size.
+ const boxes = await page.getByRole('radio').evaluateAll((nodes) =>
+ nodes.map((node) => node.getBoundingClientRect().width));
+ expect(new Set(boxes.map((w) => Math.round(w))).size).toBe(1);
+
+ // Q8zxF1: a 14 gutter between the three choices, and an 88-tall preview at
+ // radius 6 inside each one.
+ expect(await page.locator('[role="radiogroup"]').evaluate((n) => getComputedStyle(n).columnGap)).toBe('14px');
+ const preview = await dark.locator('[aria-hidden="true"]').first().evaluate((node) => ({
+ height: node.getBoundingClientRect().height,
+ radius: getComputedStyle(node).borderRadius,
+ }));
+ expect(preview.height).toBe(88);
+ expect(preview.radius).toBe('6px');
+ });
+});
diff --git a/ui/e2e/workbench-general/mobile-continuation.spec.ts b/ui/e2e/workbench-general/mobile-continuation.spec.ts
new file mode 100644
index 000000000..84153b72b
--- /dev/null
+++ b/ui/e2e/workbench-general/mobile-continuation.spec.ts
@@ -0,0 +1,453 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+
+import { NARROW, open, serveProduct } from './support';
+
+/**
+ * The Workbench home's two Settings continuations, on a phone.
+ *
+ * What is under test is a lifecycle, not a layout: the home holds an unsent
+ * draft, an Agent pick and a workspace target that live nowhere but in the
+ * component, so following either continuation used to throw them away. These
+ * specs drive the real product through the whole round trip — type, pick, open a
+ * workspace through the directory browser, follow, navigate inside Settings,
+ * come back the way the phone actually offers — and then read that state back
+ * off the page.
+ *
+ * The preservation claims are paired with a control that leaves the home by an
+ * ordinary tab and returns with browser Back — the same return path the
+ * chat-apps case below uses — where the identical assertions must FAIL. Without
+ * it, a reading could be re-derived rather than preserved. The phone-continuation
+ * case returns through the in-app control instead, which is the other way the
+ * phone offers out of Settings.
+ *
+ * Hermetic like the rest of the suite: every request is answered or refused by
+ * `serveProduct`, and each test asserts nothing was refused. Unlike the rest of
+ * the suite this file runs against the built app — the directory browser the
+ * workspace pick goes through cannot be driven under the dev server's StrictMode
+ * double-mount; `playwright.workbench-general-build.config.ts` explains why.
+ */
+
+const COMPOSER = 'Describe a task or ask a question...';
+const DRAFT = '把「中文项目」的日志整理成周报,并附上待办清单';
+
+// Two workspaces, because one cannot tell a preserved selection from the
+// fallback: `useNewSession` resolves an explicit pick first and the most recent
+// project second, so only a SECOND project makes the two readings differ. The
+// draft above is about the older one, so opening it is what a user would do.
+// Names and paths are non-ASCII for the same reason the shared fixture's are.
+const HOME_DIR = '/Users/max';
+const WORKSPACES_DIR = '/Users/max/工作区';
+const RECENT_WORKSPACE = {
+ id: 'proj-2',
+ scope_id: 'scope-1',
+ display_name: '设计稿归档',
+ folder_path: `${WORKSPACES_DIR}/设计稿归档`,
+ created_at: '2026-01-02T00:00:00Z',
+ last_active_at: '2026-02-02T00:00:00Z',
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+};
+const PICKED_WORKSPACE = {
+ id: 'proj-1',
+ scope_id: 'scope-1',
+ display_name: '中文项目',
+ folder_path: `${WORKSPACES_DIR}/中文项目`,
+ created_at: '2026-01-01T00:00:00Z',
+ last_active_at: '2026-01-10T00:00:00Z',
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+};
+const PROJECTS = { projects: [PICKED_WORKSPACE, RECENT_WORKSPACE], sessions: {} };
+
+/** The folders the browse endpoint answers with — test-owned, never the real disk. */
+const BROWSE: Record<string, { path: string; parent: string | null; dirs: { name: string; path: string }[] }> = {
+ '~': { path: HOME_DIR, parent: '/Users', dirs: [{ name: '工作区', path: WORKSPACES_DIR }] },
+ [HOME_DIR]: { path: HOME_DIR, parent: '/Users', dirs: [{ name: '工作区', path: WORKSPACES_DIR }] },
+ [WORKSPACES_DIR]: {
+ path: WORKSPACES_DIR,
+ parent: HOME_DIR,
+ dirs: [
+ { name: PICKED_WORKSPACE.display_name, path: PICKED_WORKSPACE.folder_path },
+ { name: RECENT_WORKSPACE.display_name, path: RECENT_WORKSPACE.folder_path },
+ ],
+ },
+ [PICKED_WORKSPACE.folder_path]: { path: PICKED_WORKSPACE.folder_path, parent: WORKSPACES_DIR, dirs: [] },
+};
+
+/**
+ * Capabilities are the boundary the product reads; the role name is only how
+ * the server spells one out. `vibe/authorization.py` projects `can_chat` and
+ * `can_use_files` from editor upward and `can_manage_instance` and
+ * `can_manage_projects` from member upward, so an editor is the real role that
+ * can work here and cannot reach either continuation destination. It is also the
+ * one that gets the workspace PICKER: opening a local folder needs
+ * `can_manage_projects && can_use_files`, and without it the same chip lists the
+ * projects that already exist instead. The manager branch of that same chip —
+ * the directory browser — is what the continuation tests above exercise.
+ */
+const EDITOR_SESSION = {
+ remote: true,
+ authenticated: true,
+ email: '[email protected]',
+ authorization_state: 'current',
+ instance_kind: 'organization',
+ instance_role: 'editor',
+ capabilities: {
+ is_instance_owner: false,
+ can_read_instance: true,
+ can_chat: true,
+ can_manage_projects: false,
+ can_manage_agents: false,
+ can_manage_instance: false,
+ can_manage_access_members: false,
+ can_use_agents: true,
+ can_use_skills: true,
+ can_use_vault_secrets: true,
+ can_use_show_pages: true,
+ can_use_terminal_files: true,
+ can_use_terminal: true,
+ can_use_files: true,
+ can_use_system: false,
+ },
+};
+
+/**
+ * Routes registered after `serveProduct` win, so each of these replaces only
+ * what it names. Two writes are answered here rather than refused — the
+ * directory browse and the find-or-create the manager path actually makes.
+ * Both are fulfilled from the fixtures above, so no real folder is ever listed
+ * and no project is ever created; the returned array records every create
+ * payload, so a second creation cannot pass unnoticed.
+ */
+const withWorkspaceApi = async (page: Page) => {
+ const creates: unknown[] = [];
+ await page.route('**/api/projects**', (route) => {
+ const request = route.request();
+ if (request.method() !== 'POST') return route.fulfill({ json: PROJECTS });
+ // create_project is find-or-create by folder path, so opening a folder that
+ // is already a project answers with that project instead of a new row.
+ const payload = request.postDataJSON() as { folder_path?: string };
+ creates.push(payload);
+ const existing = PROJECTS.projects.find((project) => project.folder_path === payload.folder_path);
+ return existing
+ ? route.fulfill({ json: existing })
+ : route.fulfill({ status: 404, json: { error: `no project fixture for ${payload.folder_path}` } });
+ });
+ await page.route('**/api/workbench/projects-bootstrap**', (route) => route.fulfill({ json: PROJECTS }));
+ await page.route('**/api/browse', (route) => {
+ const { path } = route.request().postDataJSON() as { path: string };
+ const answer = BROWSE[path];
+ return route.fulfill(
+ answer ? { json: { ok: true, ...answer } } : { json: { ok: false, error: `no folder fixture for ${path}` } },
+ );
+ });
+ return creates;
+};
+
+const asEditor = (page: Page) =>
+ page.route('**/api/session', (route) => route.fulfill({ json: EDITOR_SESSION }));
+
+const composer = (page: Page) => page.getByPlaceholder(COMPOSER);
+const agentTrigger = (page: Page) => page.getByRole('button', { name: /codex|claude/ }).first();
+// One accessible name for both chip branches: the workspace path, which is what
+// actually distinguishes the two fixtures.
+const workspaceChip = (page: Page) => page.getByRole('button', { name: /^Workspace: / });
+const popover = (page: Page) => page.locator('[data-radix-popper-content-wrapper]');
+const settingsSurface = (page: Page) => page.locator('[data-settings-overlay="true"]');
+const inboxTab = (page: Page) => page.locator('nav.fixed.bottom-0 a[href="/inbox"]');
+const brandHome = (page: Page) => page.locator('header a[href="/"]');
+// By label, not by role: what the phone's root back must do is leave Settings
+// behind, and asserting that through the control's element type would pass on a
+// link that merely pushed another home. Whether it is a close action at all is
+// the unit test's job.
+const backToWorkbench = (page: Page) => page.getByLabel('Back to Workbench');
+
+/**
+ * Where the current document sits in the session history — the number
+ * `closeSettingsOverlay` unwinds to. A push moves it forward, so a return that
+ * lands back on the recorded one proves the Settings entries were left behind
+ * rather than stacked in front of the home.
+ */
+const historyIndex = (page: Page) =>
+ page.evaluate(() => (window.history.state as { idx?: number } | null)?.idx ?? null);
+
+/**
+ * Marks the live composer element. If the home is torn down and rebuilt, the
+ * replacement carries no mark — so this proves the SAME instance survived,
+ * which is what keeps every other piece of its state alive too.
+ */
+const markInstance = (page: Page) =>
+ composer(page).evaluate((node) => {
+ (node as HTMLTextAreaElement & { __avibeMark?: string }).__avibeMark = 'home-1';
+ });
+
+const instanceSurvived = (page: Page) =>
+ composer(page).evaluate(
+ (node) => (node as HTMLTextAreaElement & { __avibeMark?: string }).__avibeMark === 'home-1',
+ );
+
+/** Picks the non-default Agent through the real picker. */
+async function pickClaude(page: Page) {
+ await expect(agentTrigger(page)).toHaveText(/codex/);
+ await agentTrigger(page).click();
+ await popover(page).getByRole('button', { name: 'claude', exact: true }).click();
+ await expect(agentTrigger(page)).toHaveText(/claude/);
+}
+
+/**
+ * Opens the non-default workspace the way someone who can manage projects
+ * actually does it: the chip opens the directory browser, the browser walks to
+ * a real folder, and the confirm card fires create_project — which is
+ * find-or-create by path, so opening a folder that is already a project selects
+ * that project. No product code is aware of this test; only the endpoints are.
+ */
+async function openPickedWorkspace(page: Page) {
+ await workspaceChip(page).click();
+ const browser = page.getByRole('dialog', { name: 'Select Project Folder' });
+ await browser.getByRole('button', { name: '工作区' }).click();
+ await browser.getByRole('button', { name: PICKED_WORKSPACE.display_name }).click();
+ await expect(browser.locator('code')).toHaveText(PICKED_WORKSPACE.folder_path);
+ await browser.getByRole('button', { name: 'Select' }).click();
+
+ const confirm = page.getByRole('dialog', { name: 'Open project' });
+ await expect(confirm).toContainText(PICKED_WORKSPACE.folder_path);
+ await confirm.getByRole('button', { name: 'Open project' }).click();
+
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${PICKED_WORKSPACE.folder_path}`);
+ await expect(workspaceChip(page)).toContainText(PICKED_WORKSPACE.display_name);
+}
+
+/**
+ * Types the draft, opens the non-default workspace, picks the non-default Agent,
+ * then marks the instance. Workspace before Agent because switching projects
+ * deliberately drops a stale Agent pick so the new project's default applies —
+ * doing it the other way round would be testing that rule, not the round trip.
+ */
+async function primeHome(page: Page) {
+ await composer(page).fill(DRAFT);
+ // The home resolves the most recent project on its own; the open below is
+ // what makes a preserved reading distinguishable from a re-derived one.
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${RECENT_WORKSPACE.folder_path}`);
+ await openPickedWorkspace(page);
+ await pickClaude(page);
+ await markInstance(page);
+}
+
+/**
+ * Leaves the home by the ordinary Inbox tab, and waits for the departure to
+ * have actually happened. React Router writes history synchronously but commits
+ * the new route inside a transition, so the URL reads `/inbox` while the home is
+ * still the mounted tree; turning round inside that window supersedes the
+ * pending transition and the home is never torn down at all. The control is
+ * about what a real teardown costs, so it waits for the destination to be on
+ * screen and the home's composer to be gone before going Back.
+ */
+async function leaveByInboxTab(page: Page) {
+ await inboxTab(page).click();
+ await expect(page).toHaveURL(/\/inbox$/);
+ await expect(page.getByRole('heading', { level: 1, name: 'Inbox' })).toBeVisible();
+ await expect(composer(page)).toHaveCount(0);
+}
+
+async function expectHomeIntact(page: Page, creates: unknown[]) {
+ await expect(composer(page)).toHaveValue(DRAFT);
+ await expect(agentTrigger(page)).toHaveText(/claude/);
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${PICKED_WORKSPACE.folder_path}`);
+ expect(await instanceSurvived(page)).toBe(true);
+ // Coming back must not re-run the open: the same home is still there, so the
+ // one create the user made is the only one the server ever sees.
+ expect(creates).toEqual([{ folder_path: PICKED_WORKSPACE.folder_path }]);
+}
+
+test.describe('Workbench continuations on a phone', () => {
+ test.use({ viewport: NARROW });
+
+ test('carries the composer through Settings and back on the phone continuation', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const creates = await withWorkspaceApi(page);
+ await open(page, '/');
+ await primeHome(page);
+
+ await page.getByRole('link', { name: 'Continue on your phone' }).click();
+ await expect(page).toHaveURL(/\/settings\/remote-access$/);
+
+ // Full-screen: below md the Settings surface is the whole viewport, with no
+ // sidebar offset and no shell chrome peeking out from under it.
+ await expect(settingsSurface(page)).toBeVisible();
+ expect(await settingsSurface(page).boundingBox()).toMatchObject({ x: 0, y: 0, width: NARROW.width });
+
+ // Settings-internal navigation, including the page that absorbed the retired
+ // Appearance section: the theme controls are now part of General.
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await expect(page).toHaveURL(/\/settings$/);
+ await page.getByRole('link', { name: 'General' }).click();
+ await expect(page).toHaveURL(/\/settings\/general$/);
+ await expect(page.getByRole('radiogroup', { name: 'Appearance' })).toBeVisible();
+ await expect(page.getByRole('radio', { name: 'Dark' })).toBeVisible();
+
+ // Out the way the phone offers: section list, then the Workbench.
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await backToWorkbench(page).click();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+
+ await expectHomeIntact(page, creates);
+ expect(denied).toEqual([]);
+ });
+
+ test('carries the composer through the chat-apps continuation and browser Back', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const creates = await withWorkspaceApi(page);
+ await open(page, '/');
+ await primeHome(page);
+
+ await page.locator('main a[href="/settings/platforms"]').click();
+ await expect(page).toHaveURL(/\/settings\/platforms$/);
+ await expect(settingsSurface(page)).toBeVisible();
+
+ // The OS/browser Back button, not an in-page control.
+ await page.goBack();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ await expect(settingsSurface(page)).toHaveCount(0);
+
+ await expectHomeIntact(page, creates);
+ expect(denied).toEqual([]);
+ });
+
+ test('leaves no Settings entry behind when the phone returns to the Workbench', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const creates = await withWorkspaceApi(page);
+
+ // A genuine page before the home, so "where Back goes afterwards" has an
+ // answer that is not the document load itself.
+ await open(page, '/inbox');
+ await expect(page.getByRole('heading', { level: 1, name: 'Inbox' })).toBeVisible();
+ await brandHome(page).click();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ const homeIndex = await historyIndex(page);
+ expect(homeIndex).toBe(1);
+
+ await primeHome(page);
+
+ // Everything the phone can stack in front of the home: a continuation, the
+ // section list, a section, the list again.
+ await page.getByRole('link', { name: 'Continue on your phone' }).click();
+ await expect(page).toHaveURL(/\/settings\/remote-access$/);
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await expect(page).toHaveURL(/\/settings$/);
+ await page.getByRole('link', { name: 'General' }).click();
+ await expect(page).toHaveURL(/\/settings\/general$/);
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await expect(page).toHaveURL(/\/settings$/);
+ expect(await historyIndex(page)).toBeGreaterThan(homeIndex!);
+
+ // The real exit control, not a scripted history call.
+ await backToWorkbench(page).click();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ await expect(settingsSurface(page)).toHaveCount(0);
+ // The home the user left, at the entry they left it from: everything opened
+ // over it is gone from the stack rather than sitting one Back away.
+ expect(await historyIndex(page)).toBe(homeIndex);
+ await expectHomeIntact(page, creates);
+
+ // The other continuation, out through the same control. The chevron inside
+ // Settings still steps up the rail — the origin rides along with it — and
+ // only the root action closes.
+ await page.locator('main a[href="/settings/platforms"]').click();
+ await expect(page).toHaveURL(/\/settings\/platforms$/);
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await expect(page).toHaveURL(/\/settings$/);
+ await backToWorkbench(page).click();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ expect(await historyIndex(page)).toBe(homeIndex);
+ await expectHomeIntact(page, creates);
+
+ // And Back from there is the page before the home, not Settings again.
+ await page.goBack();
+ await expect(page).toHaveURL(/\/inbox$/);
+ await expect(page.getByRole('heading', { level: 1, name: 'Inbox' })).toBeVisible();
+ await expect(settingsSurface(page)).toHaveCount(0);
+ expect(denied).toEqual([]);
+ });
+
+ test('starts a fresh home when the phone leaves by an ordinary route', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const creates = await withWorkspaceApi(page);
+ await open(page, '/');
+ await primeHome(page);
+
+ // The control for the two tests above: same phone, same fixture, same
+ // browser Back as the chat-apps case — only the departure differs. An
+ // ordinary tab is not a continuation, so the home is torn down and what
+ // comes back is a new one that resolves the most recent project again.
+ await leaveByInboxTab(page);
+ await page.goBack();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+
+ await expect(composer(page)).toHaveValue('');
+ await expect(agentTrigger(page)).toHaveText(/codex/);
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${RECENT_WORKSPACE.folder_path}`);
+ expect(await instanceSurvived(page)).toBe(false);
+ expect(creates).toEqual([{ folder_path: PICKED_WORKSPACE.folder_path }]);
+ expect(denied).toEqual([]);
+ });
+
+ test('keeps a picked workspace exactly as long as the home that holds it', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const creates = await withWorkspaceApi(page);
+ await asEditor(page);
+ await open(page, '/');
+
+ // The other branch of the same chip: someone who cannot open folders picks
+ // among the projects they already have, with no create call at all.
+ await composer(page).fill(DRAFT);
+ await pickClaude(page);
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${RECENT_WORKSPACE.folder_path}`);
+ await workspaceChip(page).click();
+ await popover(page).getByRole('button', { name: PICKED_WORKSPACE.display_name }).click();
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${PICKED_WORKSPACE.folder_path}`);
+ await expect(workspaceChip(page)).toContainText(PICKED_WORKSPACE.display_name);
+
+ // No continuation to offer: both destinations sit behind `can_manage_instance`,
+ // which this role does not have — so neither the links nor the sentence that
+ // only exists to introduce them is drawn, and chat is untouched.
+ await expect(page.getByText('Continue on your phone')).toHaveCount(0);
+ await expect(page.getByText('Connect chat apps in')).toHaveCount(0);
+ await expect(page.locator('main a[href^="/settings"]')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Send' })).toBeEnabled();
+
+ // The pick is component state of the same class as the draft: a home that is
+ // torn down comes back on the most recent project, not the chosen one. That
+ // is what a continuation has to preserve, and what a refetch cannot restore.
+ await leaveByInboxTab(page);
+ await page.goBack();
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ await expect(composer(page)).toHaveValue('');
+ await expect(workspaceChip(page)).toHaveAccessibleName(`Workspace: ${RECENT_WORKSPACE.folder_path}`);
+
+ expect(creates).toEqual([]);
+ expect(denied).toEqual([]);
+ });
+
+ test('lands a retired Settings link on the page that took its content over', async ({ page }) => {
+ const denied = await serveProduct(page);
+
+ // A stale bookmark is the only way into the alias — nothing in the product
+ // links to it any more — so this is a document load, not an in-app hop.
+ await open(page, '/settings/appearance');
+ await expect(page).toHaveURL(/\/settings\/general$/);
+ await expect(page.getByRole('radiogroup', { name: 'Appearance' })).toBeVisible();
+ // Landed directly: there is no covered surface to retain, so Settings is the
+ // primary route rather than an overlay over a home that was never rendered.
+ await expect(settingsSurface(page)).toHaveCount(0);
+ await page.getByRole('link', { name: 'All settings' }).click();
+ await expect(page).toHaveURL(/\/settings$/);
+
+ // Account did not move: it is still part of the Replies page.
+ await open(page, '/settings/account');
+ await expect(page).toHaveURL(/\/settings\/replies$/);
+ await expect(settingsSurface(page)).toHaveCount(0);
+
+ expect(denied).toEqual([]);
+ });
+});
diff --git a/ui/e2e/workbench-general/setup-handoff.spec.ts b/ui/e2e/workbench-general/setup-handoff.spec.ts
new file mode 100644
index 000000000..928ae554a
--- /dev/null
+++ b/ui/e2e/workbench-general/setup-handoff.spec.ts
@@ -0,0 +1,274 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+
+import { DESKTOP, config, open, serveProduct } from './support';
+
+/**
+ * The handoff the wizard makes to the home, driven end to end through the real
+ * product: the setup screen's own Enter, the real router, the real
+ * `ApiProvider`, and the home's own readiness read.
+ *
+ * What is under test is a claim about the running system. The wizard says setup
+ * finished; only the backend can say it is ready; and the banner may only speak
+ * once BOTH have, about the backend this home would actually run. So the
+ * fixture holds the home's read open — a state no unit test can stage, because
+ * the pending window only exists between a real navigation and a real response —
+ * and the banner must not appear until that read answers.
+ *
+ * The other half of the claim is that the banner is only a banner. The user is
+ * already working while it arrives, so the route they picked — Agent, and the
+ * MODEL on it, which is the field a re-seeded default would quietly overwrite —
+ * has to read the same before it appears, after it appears, and after it is
+ * waved off.
+ *
+ * Hermetic like the rest of the suite: every request is answered or refused by
+ * `serveProduct`, nothing reaches a running service, and the one write the flow
+ * makes (setup completion) is answered from the same fixture instance the reads
+ * come from. Each test asserts nothing was refused.
+ */
+
+const COMPOSER = 'Describe a task or ask a question...';
+const DRAFT = '整理一下这周的发布说明';
+
+/**
+ * One installed, connected assistant and two that are neither. The home's
+ * default Agent runs on Codex, so Codex is the only backend that can
+ * corroborate anything here — and a fixture where all three were ready could
+ * not tell "asked about the right one" from "asked about any of them".
+ */
+const CONNECTIONS: Record<string, Record<string, unknown>> = {
+ codex: { installed: true, enabled: true, auth: 'api_key', application: 'applied', ready: true, entry_eligible: true },
+ claude: { installed: false, enabled: false, auth: 'none', application: 'stopped', ready: false, entry_eligible: false },
+ opencode: { installed: false, enabled: false, auth: 'none', application: 'stopped', ready: false, entry_eligible: false },
+};
+
+/**
+ * The default Agent's own model, and the other model its backend offers.
+ *
+ * `PICKED_MODEL` is deliberately NOT the default: a route still showing the
+ * Agent's default after the banner arrives proves nothing, because that is also
+ * what a route reset back to defaults would show. Only a model the user chose
+ * can tell "the pick survived" from "the default was re-applied".
+ */
+const AGENT_MODEL = 'gpt-5';
+const PICKED_MODEL = 'gpt-5-codex';
+
+const backendOf = (url: string) => new URL(url).pathname.split('/').at(-2) ?? '';
+
+/**
+ * The endpoints the setup flow needs, on top of the shared harness.
+ *
+ * Connection reads answer at once until setup is persisted; every read AFTER
+ * that is the home's own — the wizard is gone by then — and is held until the
+ * test lets it answer. That boundary is the product's, not the harness's: the
+ * completion write is exactly what separates the two.
+ */
+const withSetupApi = async (page: Page) => {
+ const homeReads: string[] = [];
+ const writes: unknown[] = [];
+ let completed = false;
+ let release = () => {};
+ const held = new Promise<void>((resolve) => { release = resolve; });
+
+ await page.route('**/api/backend/*/connection', async (route) => {
+ const backend = backendOf(route.request().url());
+ if (completed) {
+ homeReads.push(backend);
+ await held;
+ }
+ await route.fulfill({ json: { ok: true, backend, ...CONNECTIONS[backend] } });
+ });
+ await page.route('**/api/backend/*/runtime', (route) => {
+ const backend = backendOf(route.request().url());
+ return route.fulfill({
+ json: {
+ ok: true,
+ name: backend,
+ enabled: Boolean(CONNECTIONS[backend]?.enabled),
+ cli_path: backend,
+ resolved_path: `/fixture/bin/${backend}`,
+ installed: Boolean(CONNECTIONS[backend]?.installed),
+ current_version: '1.0.0',
+ latest_version: '1.0.0',
+ has_update: false,
+ supports_restart: true,
+ process_status: CONNECTIONS[backend]?.ready ? 'running' : 'stopped',
+ },
+ });
+ });
+ await page.route('**/api/opencode/permission-status', (route) => route.fulfill({ json: { ok: true, permission_allowed: true } }));
+ // The Agent catalog with a model on the default Agent, and the model list its
+ // backend answers with — the product's own two reads for this, not a new
+ // contract. Stated here rather than in the shared harness: the capture specs
+ // assert against that fixture, and this is the one test about the model field.
+ await page.route('**/api/agents**', (route) => route.fulfill({
+ json: {
+ ok: true,
+ agents: [
+ { id: 'agent-codex', name: 'codex', backend: 'codex', enabled: true, model: AGENT_MODEL },
+ { id: 'agent-claude', name: 'claude', backend: 'claude', enabled: true },
+ ],
+ default_agent_name: 'codex',
+ },
+ }));
+ await page.route('**/api/codex/models', (route) => route.fulfill({
+ json: { ok: true, models: [AGENT_MODEL, PICKED_MODEL] },
+ }));
+ await page.route('**/api/cli/detect**', (route) => {
+ const binary = new URL(route.request().url()).searchParams.get('binary') ?? '';
+ const name = binary.split('/').pop() ?? '';
+ return route.fulfill({
+ json: CONNECTIONS[name]?.installed ? { found: true, path: `/fixture/bin/${name}` } : { found: false },
+ });
+ });
+ // The ONE write this flow makes. Answering it here rather than letting the
+ // harness refuse it is what makes the completion real — and what it answers
+ // with is the same instance every read comes from.
+ await page.route('**/api/config', async (route) => {
+ const request = route.request();
+ if (request.method() !== 'POST') return route.fallback();
+ writes.push(request.postDataJSON());
+ completed = true;
+ return route.fulfill({ json: { ...config('en'), setup_completed: true } });
+ });
+
+ return { homeReads, writes, release: () => release() };
+};
+
+const composer = (page: Page) => page.getByPlaceholder(COMPOSER);
+const agentTrigger = (page: Page) => page.getByRole('button', { name: /codex|claude/ }).first();
+const workspaceChip = (page: Page) => page.getByRole('button', { name: /^Workspace: / });
+const banner = (page: Page) => page.getByText('Codex is ready to go');
+const heroTitle = (page: Page) => page.getByRole('heading', { name: 'What would you like to do?' });
+
+/** `gpt-5` is a prefix of `gpt-5-codex`, so "the trigger shows the Agent's own
+ * default model" has to include the picked one being absent from it. */
+const expectDefaultModel = async (page: Page) => {
+ await expect(agentTrigger(page)).toContainText(AGENT_MODEL);
+ await expect(agentTrigger(page)).not.toContainText(PICKED_MODEL);
+};
+
+/** Walks the real wizard to the point where entering is the user's to do. */
+async function reachEntry(page: Page) {
+ await open(page, '/setup');
+ await page.getByRole('button', { name: 'Get started' }).click();
+ await expect(page.getByRole('heading', { name: 'Connect AI. Get to work' })).toBeVisible();
+ const enter = page.getByRole('button', { name: 'Enter workspace' });
+ await expect(enter).toBeEnabled();
+ return enter;
+}
+
+test.describe('Setup handoff to the Workbench home', () => {
+ test.use({ viewport: DESKTOP });
+
+ test('announces the backend only once it has answered for itself', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const setup = await withSetupApi(page);
+
+ const enter = await reachEntry(page);
+ await enter.click();
+
+ // The home, reached by the wizard's own navigation.
+ await expect(page).toHaveURL(/127\.0\.0\.1:5213\/$/);
+ await expect(heroTitle(page)).toBeVisible();
+ expect(setup.writes).toEqual([{ setup_completed: true }]);
+
+ // The home asked the backend its Agent route actually runs — and nothing
+ // else. While that read is open there is nothing corroborated, so the
+ // wizard's word alone draws no banner.
+ await expect.poll(() => setup.homeReads).toEqual(['codex']);
+ await expect(banner(page)).toHaveCount(0);
+
+ // The user starts working before anything is announced, and picks a model
+ // through the composer's own picker — the route owner the home already has,
+ // no second store and no write of its own.
+ await expectDefaultModel(page);
+ await agentTrigger(page).click();
+ await page.getByRole('button', { name: PICKED_MODEL, exact: true }).click();
+ await page.keyboard.press('Escape');
+ await expect(agentTrigger(page)).toContainText(PICKED_MODEL);
+ // Choosing a model is not choosing a backend, so there is nothing new to
+ // corroborate and the home asks nothing again.
+ expect(setup.homeReads).toEqual(['codex']);
+ await expect(banner(page)).toHaveCount(0);
+
+ setup.release();
+ await expect(banner(page)).toBeVisible();
+
+ // The Agent the setup left selected is the one the home offers, the model
+ // the user picked is untouched by the announcement arriving over it, and
+ // setup completion did not rewrite either: the completion write is still
+ // the only one this flow has made.
+ await expect(agentTrigger(page)).toHaveText(/codex/);
+ await expect(agentTrigger(page)).toContainText(PICKED_MODEL);
+ await expect(workspaceChip(page)).toContainText('中文项目');
+ expect(setup.writes).toEqual([{ setup_completed: true }]);
+
+ // Dismissing is about the banner and nothing else: the home the user has
+ // already started using is untouched.
+ await composer(page).fill(DRAFT);
+ await page.getByRole('button', { name: 'Dismiss' }).click();
+ await expect(banner(page)).toHaveCount(0);
+ await expect(composer(page)).toHaveValue(DRAFT);
+ await expect(agentTrigger(page)).toHaveText(/codex/);
+ await expect(agentTrigger(page)).toContainText(PICKED_MODEL);
+ await expect(workspaceChip(page)).toContainText('中文项目');
+
+ // The completion was consumed, not read: reloading restores the entry as it
+ // now stands, which no longer claims a setup just finished. So the home says
+ // nothing about one — and does not even ask, which is why the read count is
+ // the assertion rather than the banner alone. (A read here would hang on the
+ // still-held fixture; it never happens.)
+ const readsBeforeReload = setup.homeReads.length;
+ await page.reload();
+ await expect(heroTitle(page)).toBeVisible();
+ await expect(banner(page)).toHaveCount(0);
+ expect(setup.homeReads).toHaveLength(readsBeforeReload);
+ // And the model pick was a pick for this composer, never a write: the new
+ // page inherits the Agent's own default again, which is the same reason the
+ // completion write is still the only request this flow has sent.
+ await expectDefaultModel(page);
+ expect(setup.writes).toEqual([{ setup_completed: true }]);
+
+ expect(denied).toEqual([]);
+ });
+
+ /**
+ * The announcement is about the visit the wizard handed off to, so leaving
+ * that visit ends it — and only the route can say a departure happened. The
+ * home is also unmounted and remounted in place by the setup route guard
+ * re-validating, which is NOT a departure and must still be able to announce;
+ * a lifetime read from the component's own cleanup cannot tell the two apart.
+ *
+ * Driven through the shell's own navigation rather than a harness router, so
+ * what is observed is the real one: real links, real guard, real surface.
+ */
+ test('forgets the announcement once the user leaves the home', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const setup = await withSetupApi(page);
+
+ const enter = await reachEntry(page);
+ await enter.click();
+ await expect(heroTitle(page)).toBeVisible();
+ setup.release();
+ await expect(banner(page)).toBeVisible();
+
+ // Away, through the shell's own nav — and really away: the home's composer
+ // is gone, not covered.
+ await page.getByRole('link', { name: 'Agents' }).click();
+ await expect(page).toHaveURL(/\/agents$/);
+ await expect(composer(page)).toHaveCount(0);
+
+ // Back to the home as any other visit: nothing is owed, so nothing is
+ // announced — and nothing is asked either, which is the assertion that
+ // separates "said nothing" from "said nothing yet".
+ const readsBeforeReturn = setup.homeReads.length;
+ await page.getByRole('link', { name: 'New chat' }).click();
+ await expect(heroTitle(page)).toBeVisible();
+ await expect(composer(page)).toBeVisible();
+ await expect(banner(page)).toHaveCount(0);
+ expect(setup.homeReads).toHaveLength(readsBeforeReturn);
+
+ expect(denied).toEqual([]);
+ });
+});
diff --git a/ui/e2e/workbench-general/support.ts b/ui/e2e/workbench-general/support.ts
new file mode 100644
index 000000000..aa1f3716c
--- /dev/null
+++ b/ui/e2e/workbench-general/support.ts
@@ -0,0 +1,156 @@
+import type { Page, Route } from '@playwright/test';
+
+export const ORIGIN = 'http://127.0.0.1:5213';
+
+/**
+ * 1200 is the width the design was staged at; the others are what prove the
+ * claim the packet actually makes — sidebar 248 and settings rail 196 are the
+ * only fixed measurements, and everything to their right is fluid. A capture at
+ * the staging width alone cannot tell a fluid column from a 856-wide one.
+ */
+export const DESKTOP = { width: 1200, height: 900 };
+export const WIDE = { width: 1600, height: 900 };
+export const NARROW = { width: 390, height: 844 };
+
+export type Lang = 'en' | 'zh';
+
+const SESSION = {
+ remote: false,
+ authenticated: true,
+ authorization_state: 'current',
+ instance_kind: 'personal',
+ instance_role: 'owner',
+};
+
+/** The instance as this harness's server holds it — exported so a spec that
+ * answers a WRITE to `/api/config` can answer with the same instance it reads,
+ * rather than describing a second one. */
+export const config = (language: Lang) => ({
+ mode: 'local',
+ setup_state: { needs_setup: false },
+ platforms: { enabled: [] },
+ agents: {
+ codex: { enabled: true, cli_path: 'codex' },
+ claude: { enabled: true, cli_path: 'claude' },
+ opencode: { enabled: true, cli_path: 'opencode' },
+ },
+ agent: { default_cwd: '/fixture/work' },
+ language,
+});
+
+// A first-task home with one workspace, which is the state the source board
+// draws: a workspace chip with a name in it and no sessions yet. The name and
+// the path are deliberately non-ASCII — truncation, measurement and the chip's
+// own width are exactly where a Latin-only fixture would flatter the render.
+const PROJECTS = {
+ projects: [{
+ id: 'proj-1',
+ scope_id: 'scope-1',
+ display_name: '中文项目',
+ folder_path: '/Users/max/工作区/中文项目',
+ created_at: '2026-01-01T00:00:00Z',
+ last_active_at: null,
+ archived: false,
+ capabilities: { can_chat: true, has_folder: true },
+ }],
+ sessions: {},
+};
+
+const AGENTS = {
+ ok: true,
+ agents: [
+ { name: 'codex', backend: 'codex', enabled: true },
+ { name: 'claude', backend: 'claude', enabled: true },
+ ],
+ default_agent_name: 'codex',
+};
+
+// Web fonts are a read from a public CDN and are what the product actually
+// draws with; blocking them would make every capture compare the design against
+// fallback metrics. Nothing else off this origin is allowed.
+const FONT_HOSTS = ['https://fonts.googleapis.com/', 'https://fonts.gstatic.com/'];
+
+/**
+ * Answers the product's reads locally and refuses everything else. The guard is
+ * registered LAST so Playwright consults it FIRST: anything that is not a
+ * same-origin GET — every write verb, and anything addressed off this origin
+ * other than the font CDN — is aborted and recorded, so a capture can prove it
+ * never touched a running service or any real user state. Same-origin reads
+ * fall through to the answers below, and no `/api` request is ever left to
+ * reach the (dead) backend port.
+ */
+export async function serveProduct(page: Page, lang: Lang = 'en') {
+ const denied: string[] = [];
+
+ await page.route('**/api/**', (route) => route.fulfill({ json: {} }));
+
+ await page.route('**/api/session', (route) => route.fulfill({ json: SESSION }));
+ // The instance language is server-side state, so a capture that only seeded
+ // the browser detector would still render whatever this says.
+ await page.route('**/api/config', (route) => route.fulfill({ json: config(lang) }));
+ await page.route('**/api/csrf-token', (route) => route.fulfill({ json: { csrf_token: 'fixture' } }));
+ await page.route('**/api/projects**', (route) => route.fulfill({ json: PROJECTS }));
+ await page.route('**/api/workbench/projects-bootstrap**', (route) => route.fulfill({ json: PROJECTS }));
+ await page.route('**/api/sessions**', (route) => route.fulfill({ json: { sessions: [] } }));
+ await page.route('**/api/agents**', (route) => route.fulfill({ json: AGENTS }));
+ await page.route('**/api/inbox**', (route) => route.fulfill({ json: { sessions: [], unread: {} } }));
+ // The service badge polls the bare `/status`, not an `/api` path.
+ await page.route('**/status', (route) => route.fulfill({ json: { state: 'running' } }));
+ await page.route('**/api/version**', (route) => route.fulfill({
+ json: { current: '2.4.0', latest: '2.4.0', has_update: false, build: { kind: 'package' } },
+ }));
+ await page.route('**/api/memory/settings**', (route) => route.fulfill({ json: { status: 'ok', enabled: false } }));
+ // The live stream: answered as an open, silent stream. Fulfilling it as JSON
+ // would make EventSource reconnect in a loop and repaint mid-capture.
+ await page.route('**/api/events**', (route) => route.fulfill({
+ status: 200,
+ headers: { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' },
+ body: ': idle\n\n',
+ }));
+
+ await page.route('**/*', async (route: Route) => {
+ const request = route.request();
+ const method = request.method();
+ const url = request.url();
+ const isRead = method === 'GET' || method === 'HEAD';
+
+ if (url.startsWith(ORIGIN) && isRead) {
+ // Dev-only detail: Vite proxies `/settings` (and a few other prefixes) to
+ // the backend, so a deep link would fetch from the dead port instead of
+ // the app. Serving index.html for a document request is what the shipped
+ // server does for any unknown path, so this restores the product's own
+ // behaviour rather than inventing one for the harness.
+ if (request.resourceType() === 'document' && url !== `${ORIGIN}/`) {
+ const index = await route.fetch({ url: `${ORIGIN}/` });
+ return route.fulfill({ response: index, headers: { 'content-type': 'text/html' } });
+ }
+ return route.fallback();
+ }
+ if (isRead && FONT_HOSTS.some((host) => url.startsWith(host))) return route.fallback();
+
+ denied.push(`${method} ${url}`);
+ return route.abort();
+ });
+
+ return denied;
+}
+
+/**
+ * Opens a real product route. Theme rides the same `?theme=` the app's own
+ * ThemeProvider reads, and language is seeded into the key the app's detector
+ * reads — neither is restated here, so a capture shows the shipped behaviour.
+ */
+export async function open(
+ page: Page,
+ path: string,
+ options: { lang?: Lang; theme?: 'light' | 'dark' | 'system' } = {},
+) {
+ const lang = options.lang ?? 'en';
+ await page.addInitScript((value) => {
+ window.localStorage.setItem('i18nextLng', value);
+ }, lang);
+ const query = options.theme ? `?theme=${options.theme}` : '';
+ await page.goto(`${path}${query}`);
+}
+
+export const box = (page: Page, selector: string) => page.locator(selector).first().boundingBox();
diff --git a/ui/e2e/workbench-general/tsconfig.json b/ui/e2e/workbench-general/tsconfig.json
new file mode 100644
index 000000000..269da4217
--- /dev/null
+++ b/ui/e2e/workbench-general/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.app.json",
+ "compilerOptions": { "types": ["vite/client", "node"] },
+ "include": ["*.ts", "*.tsx", "../../playwright.workbench-general.config.ts", "../../agentation.d.ts"],
+ "exclude": []
+}
diff --git a/ui/package.json b/ui/package.json
index 6ce973e21..8bfe55530 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -26,6 +26,8 @@
"test:model-catalog": "tsc -p e2e/model-catalog/tsconfig.json --noEmit && playwright test --config playwright.model-catalog.config.ts",
"test:model-provider": "tsc -p e2e/model-provider/tsconfig.json --noEmit && playwright test --config playwright.model-provider.config.ts",
"test:onboarding-fidelity": "tsc -p e2e/onboarding-fidelity/tsconfig.json --noEmit && playwright test --config playwright.onboarding-fidelity.config.ts",
+ "test:workbench-general": "tsc -p e2e/workbench-general/tsconfig.json --noEmit && playwright test --config playwright.workbench-general.config.ts",
+ "test:workbench-general-build": "tsc -p e2e/workbench-general/tsconfig.json --noEmit && playwright test --config playwright.workbench-general-build.config.ts",
"validate:catalog": "node scripts/validate-scenario-catalog.mjs",
"validate:theme": "node scripts/validate-theme.mjs"
},
diff --git a/ui/playwright.workbench-general-build.config.ts b/ui/playwright.workbench-general-build.config.ts
new file mode 100644
index 000000000..38f1cbf58
--- /dev/null
+++ b/ui/playwright.workbench-general-build.config.ts
@@ -0,0 +1,40 @@
+import { defineConfig, devices } from '@playwright/test';
+
+/**
+ * The same hermetic harness as `playwright.workbench-general.config.ts`, against
+ * the built app instead of the dev server.
+ *
+ * `setup-handoff.spec.ts` is here because what it grades is a lifecycle: the
+ * home reads the backend once per question asked, and StrictMode's development
+ * double-mount asks it twice — a bundle-only claim about request count cannot be
+ * made against a server that deliberately runs every effect twice.
+ *
+ * `mobile-continuation.spec.ts` drives the workspace chip's manager branch, and
+ * the directory browser inside it cannot be driven on the dev server: React's
+ * StrictMode mounts, cleans up and re-mounts every component in development, and
+ * `DirectoryBrowser`'s `mountedRef` is only ever set to `false` by that cleanup —
+ * never back to `true` — so the browse response is discarded and the picker sits
+ * in a permanent loading state. That is a development-only trap in a shared
+ * primitive this PR does not touch (StrictMode is inert in a production build),
+ * so the spec runs against the bundle users actually get rather than working
+ * around it here or changing that component.
+ *
+ * The build runs as part of the server command so the spec can never grade a
+ * stale `dist/`. Port and origin match the dev config because the spec's request
+ * guard is written against that one origin.
+ */
+export default defineConfig({
+ testDir: './e2e/workbench-general',
+ testMatch: ['**/mobile-continuation.spec.ts', '**/setup-handoff.spec.ts'],
+ outputDir: './e2e/.artifacts/workbench-general/run',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5213', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run build && npx vite preview --host 127.0.0.1 --port 5213 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5213/',
+ timeout: 180_000,
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+});
diff --git a/ui/playwright.workbench-general.config.ts b/ui/playwright.workbench-general.config.ts
new file mode 100644
index 000000000..51589bf85
--- /dev/null
+++ b/ui/playwright.workbench-general.config.ts
@@ -0,0 +1,24 @@
+import { defineConfig, devices } from '@playwright/test';
+
+// Hermetic: the dev server is bound to loopback and points at a dead backend port,
+// and every request the page makes is answered or refused by the spec's own routes,
+// so nothing here reaches a running Avibe service or writes to user state.
+export default defineConfig({
+ testDir: './e2e/workbench-general',
+ // Run against the built app instead — see playwright.workbench-general-build.config.ts.
+ testIgnore: ['**/mobile-continuation.spec.ts', '**/setup-handoff.spec.ts'],
+ // Playwright empties `outputDir` at the start of every run, including a filtered
+ // one, so the captures must NOT live inside it: a `-g` re-run of two shots would
+ // otherwise delete the other sixteen. Traces get their own subdirectory and the
+ // shots keep a stable path of their own.
+ outputDir: './e2e/.artifacts/workbench-general/run',
+ workers: 1,
+ retries: 0,
+ use: { baseURL: 'http://127.0.0.1:5213', trace: 'retain-on-failure' },
+ webServer: {
+ command: 'npm run dev -- --host 127.0.0.1 --port 5213 --strictPort',
+ env: { VIBE_UI_BACKEND: 'http://127.0.0.1:9' },
+ url: 'http://127.0.0.1:5213/',
+ },
+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+});
diff --git a/ui/scripts/glowScale.test.mjs b/ui/scripts/glowScale.test.mjs
index c92f8e87a..74da2a4b9 100644
--- a/ui/scripts/glowScale.test.mjs
+++ b/ui/scripts/glowScale.test.mjs
@@ -89,6 +89,17 @@ const OFF_RULE = {
light: /^0 0 \d+px -4px color-mix\(in srgb, var\(--[a-z]+\) 44%, transparent\)$/,
},
},
+ // The sidebar's selected nav row keeps the general rule's geometry and alpha --
+ // spread = -blur/4 and 0.44 -- and departs on one field only: the design table
+ // gives it #10B98170 in Light beside #5BFFA070 in Dark, so its hue is mixed from
+ // the live accent instead of spelled out. `holds` therefore pins the two fields
+ // the general rule would have pinned, in the one spelling that can carry them
+ // through a palette; only the hue is excused, and its blur is asserted from
+ // ROLE_BLUR like every other role's.
+ nav: {
+ why: 'the approved sidebar selection halo: the scale\'s own 16/-4 and 0.44, themed through var(--mint) for #10B98170 in light and #5BFFA070 in dark',
+ holds: /^0 0 \d+px -4px color-mix\(in srgb, var\(--[a-z]+\) 44%, transparent\)$/,
+ },
};
// What each role's blur IS, rather than which blurs the scale happens to
@@ -104,7 +115,7 @@ const OFF_RULE = {
// excused entirely: "themed" was being read as "unasserted", so the owner's two
// numbers were the only blurs in this file that nothing checked.
const ROLE_BLUR = {
- dot: 8, wire: 4, xs: 12, sm: 16, md: 24, lg: 32, xl: 48,
+ dot: 8, wire: 4, xs: 12, sm: 16, md: 24, lg: 32, xl: 48, nav: 16,
cta: { dark: 16, light: 20 },
onboarding: { dark: 28, light: 16 },
};
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index f1785d0d2..6eaf8bcb2 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -34,6 +34,7 @@ import { SettingsLogsPage } from './components/settings/SettingsLogsPage';
import { SettingsMessagingPage } from './components/settings/SettingsMessagingPage';
import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPage';
import { SettingsServicePage } from './components/settings/SettingsServicePage';
+import { SettingsGeneralPage } from './components/settings/SettingsGeneralPage';
import { SettingsShortcutsPage } from './components/settings/SettingsShortcutsPage';
import { SettingsLayout } from './components/settings/SettingsLayout';
import { SettingsOverlayRouteSurface } from './components/settings/SettingsOverlayRouteSurface';
@@ -670,7 +671,10 @@ const PwaRouteMemory = () => {
const settingsRoute = () => (
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={null} />
- <Route path="appearance" element={<Navigate to="/settings/replies" replace />} />
+ <Route path="general" element={<SettingsGeneralPage />} />
+ {/* Appearance was the theme page; General now owns the theme controls, so the
+ alias follows them. Account keeps pointing at Replies, which still owns it. */}
+ <Route path="appearance" element={<Navigate to="/settings/general" replace />} />
<Route path="account" element={<Navigate to="/settings/replies" replace />} />
<Route path="shortcuts" element={<SettingsShortcutsPage />} />
<Route path="service" element={<SettingsServicePage />} />
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index 796f12952..06be42c62 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -12,6 +12,7 @@ import {
holdMobileProjectsListForChatReturn,
readMobileProjectsListSnapshot,
} from '../lib/mobileProjectsListMemory';
+import { selectLanguage } from '../lib/useLanguageSelection';
import { AppShell } from './AppShell';
const viewport = vi.hoisted(() => {
@@ -39,11 +40,31 @@ const api = vi.hoisted(() => ({
}));
const status = vi.hoisted(() => ({ state: 'ready' as const }));
const inbox = vi.hoisted(() => ({ totalUnread: 0 }));
-const i18n = vi.hoisted(() => ({
- language: 'en',
- options: { resources: { en: {}, zh: {} } },
- changeLanguage: vi.fn(),
-}));
+/** One per test, not one per file: a language operation belongs to the i18n
+ * instance and outlives any render root, so a pick made in one test would
+ * follow a shared instance into the next. */
+const makeI18n = () => {
+ const instance = {
+ language: 'en',
+ options: { resources: { en: {}, zh: {} } },
+ changeLanguage: vi.fn(async (code: string) => {
+ instance.language = code;
+ }),
+ };
+ return instance;
+};
+
+/** What `useTranslation` actually hands a component: not the instance but a copy
+ * of it, made fresh on every language change, keeping the instance itself as
+ * `__original`. The shell holds one of these, which is why a language change is
+ * what sends it back to read the config again. */
+const copyOf = (instance: ReturnType<typeof makeI18n>) => Object.assign(
+ Object.create(Object.getPrototypeOf(instance)),
+ instance,
+ { __original: instance },
+);
+
+let i18n = makeI18n();
const instanceAuth = vi.hoisted(() => ({
remote: true,
instanceKind: null as 'personal' | 'organization' | null,
@@ -116,8 +137,7 @@ beforeEach(() => {
instanceAuth.capabilities.can_manage_instance = true;
instanceAuth.capabilities.can_chat = true;
instanceAuth.capabilities.can_use_show_pages = true;
- i18n.language = 'en';
- i18n.changeLanguage.mockResolvedValue(undefined);
+ i18n = makeI18n();
api.getConfig.mockResolvedValue({ platforms: { enabled: [] } });
api.getMemorySettings.mockResolvedValue({
status: 'failed',
@@ -288,6 +308,67 @@ describe('AppShell persistent Workbench chrome', () => {
await waitFor(() => expect(i18n.changeLanguage).toHaveBeenCalledWith('zh'));
});
+ it('keeps a language the user picked while the instance config was still being read', async () => {
+ viewport.isDesktop = true;
+ const instance = i18n;
+ let answer: (config: unknown) => void = () => {};
+ api.getConfig.mockReturnValue(new Promise((resolve) => { answer = resolve; }));
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>,
+ );
+ expect(await screen.findByTestId('workbench')).toBeTruthy();
+
+ // They pick before the read answers, from a control the shell never sees.
+ await act(async () => { await selectLanguage(instance, 'zh'); });
+ await act(async () => { answer({ language: 'en', platforms: { enabled: [] } }); });
+
+ // A read that started before the pick cannot be the answer to it.
+ expect(instance.changeLanguage.mock.calls.map(([code]) => code)).toEqual(['zh']);
+ expect(instance.language).toBe('zh');
+ });
+
+ it('does not undo that pick when the language change itself starts the read again', async () => {
+ viewport.isDesktop = true;
+ const instance = i18n;
+ // The instance config as it was before the pick — what a reader that cached
+ // it, or one racing the save, still has to hand back.
+ api.getConfig.mockResolvedValue({ language: 'en', platforms: { enabled: [] } });
+
+ // A function, not one element: React skips a re-render handed back the very
+ // element it already rendered, and the shell re-rendering is the point here.
+ const tree = () => (
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route element={<AppShell />}>
+ <Route index element={<div data-testid="workbench" />} />
+ </Route>
+ </Routes>
+ </MemoryRouter>
+ );
+ const view = render(tree());
+ expect(await screen.findByTestId('workbench')).toBeTruthy();
+ await waitFor(() => expect(api.getConfig).toHaveBeenCalledTimes(1));
+
+ await act(async () => { await selectLanguage(instance, 'zh'); });
+
+ // The language change replaces the object every consumer holds, which is
+ // what sends the shell back for a second read of the older config.
+ i18n = copyOf(instance);
+ await act(async () => { view.rerender(tree()); });
+
+ await waitFor(() => expect(api.getConfig).toHaveBeenCalledTimes(2));
+ await act(async () => {});
+ expect(instance.changeLanguage.mock.calls.map(([code]) => code)).toEqual(['zh']);
+ expect(instance.language).toBe('zh');
+ });
+
it.each([
'personal',
null,
@@ -308,7 +389,7 @@ describe('AppShell persistent Workbench chrome', () => {
expect(await screen.findByTestId('workbench')).toBeTruthy();
expect(screen.getByRole('link', { name: 'appShell.openControlPanel' }).getAttribute('href')).toBe(
- '/settings/replies',
+ '/settings/general',
);
expect(screen.queryByTestId('language-switcher')).toBeNull();
expect(screen.queryByTestId('theme-toggle')).toBeNull();
@@ -325,7 +406,7 @@ describe('AppShell persistent Workbench chrome', () => {
<Route element={<AppShell />}>
<Route index element={<div data-testid="workbench" />} />
<Route path="chat/:sessionId" element={<div data-testid="chat" />} />
- <Route path="settings/replies" element={<div data-testid="settings" />} />
+ <Route path="settings/general" element={<div data-testid="settings" />} />
</Route>
</Routes>
</MemoryRouter>,
@@ -333,7 +414,7 @@ describe('AppShell persistent Workbench chrome', () => {
expect(await screen.findByTestId('chat')).toBeTruthy();
let settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });
- expect(settingsToggle.getAttribute('href')).toBe('/settings/replies');
+ expect(settingsToggle.getAttribute('href')).toBe('/settings/general');
await user.click(settingsToggle);
expect(await screen.findByTestId('settings')).toBeTruthy();
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 4057e45b2..92a8d4ca1 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -27,9 +27,10 @@ import logoImg from '../assets/logo.png';
import { useViewportHeightVar } from '../lib/useViewportHeightVar';
import { APP_SHELL_SCROLL_ID, forgetMobileProjectsListUnlessPreserved } from '../lib/mobileProjectsListMemory';
import { useIsDesktop } from '../lib/useIsDesktop';
+import { adoptPersistedLanguage } from '../lib/useLanguageSelection';
import {
isOwnerOnlyPath,
- settingsLandingPath,
+ SETTINGS_LANDING_PATH,
} from '../lib/adminNavigation';
import {
closeSettingsOverlay,
@@ -101,7 +102,7 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
return (
<nav className="fixed inset-x-0 bottom-0 z-40 border-t border-border bg-surface/96 px-2 pt-2 pb-[calc(0.5rem+env(safe-area-inset-bottom))] backdrop-blur md:hidden">
<div className="flex items-end justify-between gap-1">
- {left.map((item) => <MobileNavLink key={item.to} item={item} />)}
+ {left.map((item) => <MobileNavLink key={item.to ?? item.label} item={item} />)}
<div className="flex flex-1 justify-center">
{center.onClick ? (
<Button
@@ -125,7 +126,7 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
</Button>
)}
</div>
- {right.map((item) => <MobileNavLink key={item.to} item={item} />)}
+ {right.map((item) => <MobileNavLink key={item.to ?? item.label} item={item} />)}
</div>
</nav>
);
@@ -177,6 +178,11 @@ export const AppShell: React.FC = () => {
const navigate = useNavigate();
const settingsOverlayOrigin = useSettingsOverlayOrigin(location);
const settingsOpen = isSettingsRoutePath(location.pathname);
+ // An origin can now exist on a phone too (the Workbench home retains its
+ // composer behind Settings), but only the desktop overlay is a layer *over*
+ // this shell. Below md the Settings surface covers the shell outright, so the
+ // chrome keeps reading the foreground route and stays full-screen — the
+ // retained origin changes what survives behind it, not what is drawn.
const settingsOverlayOpen = isDesktop
&& isSettingsEntryPath(location.pathname)
&& settingsOverlayOrigin !== null;
@@ -208,9 +214,10 @@ export const AppShell: React.FC = () => {
if (!capabilities.can_manage_instance) return;
api.getConfig().then((c: any) => {
setConfig(c);
- if (c.language && c.language !== i18n.language) {
- void i18n.changeLanguage(c.language);
- }
+ // Through the language operation, not straight at i18n: a language change
+ // gives this effect a new `api` and so a second read, which must not undo
+ // the pick that caused it — nor may a first read that answers late.
+ adoptPersistedLanguage(i18n, c.language);
}).catch(() => {});
}, [api, capabilities.can_manage_instance, i18n]);
@@ -319,6 +326,10 @@ export const AppShell: React.FC = () => {
const isShowPageApp = surfaceLocation.pathname.startsWith('/apps/show/');
const isBuiltinApp = isStandaloneAppRoutePath(surfaceLocation.pathname);
const isFullScreenMobile = isChat || isSearch || isSettings || isShowPageApp || isBuiltinApp;
+ // `/` is the Workbench canvas root and the only route board 04 draws. It reads
+ // the surface location, so Settings opened over the home keeps the home's own
+ // background behind the overlay.
+ const isWorkbenchHome = surfaceLocation.pathname === '/';
const showBottomNav = !isFullScreenMobile && !chromeless && location.pathname !== '/setup';
@@ -347,88 +358,61 @@ export const AppShell: React.FC = () => {
<ConfigRecoveryNotice config={config} />
{/* Windows cover the sidebar (z-10 < z-20). AppsLauncher portals its button and Dock
above the window layer so app switching remains reachable even when maximized. */}
+ {/* Sidebar Y1TiVV — 248 wide, 20/16 padding, top group and bottom cluster
+ pushed apart. The brand row, navigation and projects are one unit inside
+ WorkbenchSidebar; this frame owns only the column and the bottom. */}
{!chromeless && (
- <aside className="fixed inset-y-0 left-0 z-10 hidden w-[240px] flex-col border-r border-border bg-surface md:flex">
- <div className="flex h-full flex-col">
- {/* Brand band — flush to the top edge, sharing the chat header's
- px-4 py-2.5 row height so the logo centerline lines up with the
- chat title bar. No bottom border (it read as out of place under
- the logo). Logo is size-8 to match the header's row height. */}
- <Link
- to="/"
- className="group flex shrink-0 items-center gap-2.5 px-4 py-2.5 transition-colors hover:bg-foreground/[0.03] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-mint/60"
- >
- <img
- src={logoImg}
- alt="avibe logo"
- className="size-8 rounded-lg border border-mint/35 bg-mint/[0.08] object-cover shadow-glow-sm-mint transition-shadow group-hover:shadow-glow-md-mint"
- />
- <div className="min-w-0 leading-tight">
- <div className="truncate text-[13px] font-semibold text-foreground">{t('appShell.title')}</div>
- <div className="truncate text-[11px] text-muted">{t('appShell.subtitle')}</div>
- </div>
- </Link>
-
- <div className="flex min-h-0 flex-1 flex-col gap-3 px-4 pt-3">
- {isDesktop && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}
- </div>
-
- {/* Bottom (design.pen NbPMq): Apps + Settings, then run state + version.
- Preferences now live with the rest of Settings. AppsLauncher keeps its layout slot
- here while its interactive surface floats above app windows. The
- outer container no longer owns padding (the brand band is flush to
- the top edge), so this cluster carries its own px-4 + bottom pad. */}
- <div className="relative flex flex-col gap-3 px-4 pb-4">
- <div className="flex items-stretch gap-2">
- {canUseApps && <AppsLauncher />}
- {settingsOpen ? (
- <button
- type="button"
- data-settings-toggle="true"
- onClick={() => {
- if (settingsOverlayOrigin) closeSettingsOverlay(navigate, settingsOverlayOrigin);
- else navigate('/');
- }}
- title={t('appShell.openControlPanel')}
- aria-label={t('appShell.openControlPanel')}
- className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-mint/40 bg-mint/[0.08] text-foreground transition-colors"
- >
- <Settings className="size-[18px] text-mint-ink" />
- </button>
- ) : (
- <Link
- data-settings-toggle="true"
- to={isDesktop
- ? settingsLandingPath(capabilities.can_manage_instance)
- : '/settings'}
- title={t('appShell.openControlPanel')}
- aria-label={t('appShell.openControlPanel')}
- className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-border-strong text-foreground transition-colors hover:bg-foreground/[0.04]"
- >
- <Settings className="size-[18px] text-muted group-hover:text-foreground" />
- </Link>
- )}
- </div>
+ <aside className="fixed inset-y-0 left-0 z-10 hidden w-[248px] flex-col justify-between gap-6 border-r border-border bg-[var(--sidebar-background)] px-4 py-5 md:flex">
+ <div className="flex min-h-0 flex-1 flex-col">
+ {isDesktop && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}
+ </div>
- {config?.runtime?.hostname && (
- <div className="truncate font-mono text-[10px] text-muted">
- {config.runtime.hostname}
- </div>
+ {/* Bottom cluster (design VDs23): Apps + Settings as two equal buttons,
+ then version on the left and the live service status on the right.
+ AppsLauncher keeps its layout slot here while its interactive surface
+ floats above app windows. */}
+ <div className="relative flex shrink-0 flex-col gap-2.5">
+ <div className="flex h-[39px] items-stretch gap-2">
+ {canUseApps && <AppsLauncher />}
+ {settingsOpen ? (
+ <button
+ type="button"
+ data-settings-toggle="true"
+ onClick={() => {
+ if (settingsOverlayOrigin) closeSettingsOverlay(navigate, settingsOverlayOrigin);
+ else navigate('/');
+ }}
+ title={t('appShell.openControlPanel')}
+ className="group flex flex-1 items-center justify-center gap-2 rounded-[10px] border border-mint/40 bg-mint/[0.08] text-[13px] font-semibold text-foreground transition-colors"
+ >
+ <Settings className="size-4 shrink-0 text-mint-ink" />
+ <span className="truncate">{t('appShell.openControlPanel')}</span>
+ </button>
+ ) : (
+ <Link
+ data-settings-toggle="true"
+ to={SETTINGS_LANDING_PATH}
+ title={t('appShell.openControlPanel')}
+ className="group flex flex-1 items-center justify-center gap-2 rounded-[10px] border border-border-strong bg-foreground/[0.03] text-[13px] text-muted transition-colors hover:bg-foreground/[0.06] hover:text-foreground"
+ >
+ <Settings className="size-4 shrink-0" />
+ <span className="truncate">{t('appShell.openControlPanel')}</span>
+ </Link>
)}
+ </div>
- {/* Row 2 (design bVke5) — run-state dot + label on the LEFT, version on the RIGHT. */}
- <div className="flex items-center justify-between gap-2">
- <span className="flex items-center gap-1.5 text-[11px] font-medium text-muted">
- <span
- className={clsx(
- 'size-2 shrink-0 rounded-full',
- isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
- )}
- />
- {isRunning ? t('common.running') : t('common.stopped')}
- </span>
- {capabilities.can_manage_instance && <VersionBadge openUpward />}
- </div>
+ {/* Version row AYIIj — version on the LEFT, run state on the RIGHT. */}
+ <div className="flex items-center justify-between gap-2 px-1 py-0.5">
+ {capabilities.can_manage_instance ? <VersionBadge openUpward /> : <span />}
+ <span className="flex items-center gap-1.5 text-[10px] text-muted">
+ {isRunning ? t('common.running') : t('common.stopped')}
+ <span
+ className={clsx(
+ 'size-[9px] shrink-0 rounded-full',
+ isRunning ? 'bg-mint shadow-glow-dot-mint' : 'bg-muted'
+ )}
+ />
+ </span>
</div>
</div>
</aside>
@@ -471,10 +455,20 @@ export const AppShell: React.FC = () => {
// is the only thing in the viewport and sizes itself to this box (h-full).
? 'min-h-0 flex-1 overflow-hidden'
: isFullScreenMobile
- ? 'min-h-0 flex-1 overflow-hidden md:ml-[240px] md:min-h-screen md:flex-none md:overflow-visible md:pb-0'
- : 'flex-1 min-h-0 overflow-y-auto md:ml-[240px] md:min-h-screen md:flex-none md:overflow-visible md:pb-0',
- !chromeless && (showBottomNav ? 'pb-[calc(5.5rem+env(safe-area-inset-bottom))]' : 'pb-0'),
- !chromeless && (isSettings ? 'page-glow-settings' : 'page-glow-console')
+ ? 'min-h-0 flex-1 overflow-hidden md:ml-[248px] md:min-h-screen md:flex-none md:overflow-visible md:pb-0'
+ : 'flex-1 min-h-0 overflow-y-auto md:ml-[248px] md:min-h-screen md:flex-none md:overflow-visible md:pb-0',
+ !chromeless && (showBottomNav ? 'pb-[var(--mobile-nav-clearance)]' : 'pb-0'),
+ // Board 04 draws the Workbench home on flat $--background. The console
+ // aurora stays with the rest of its page family (Agents, Skills,
+ // Harness, Vaults, Inbox, chat), so this is scoped to `/` alone and
+ // repaints nothing else. `bg-background` rather than no class at all:
+ // the flatness is the decision, and a computed `background-image: none`
+ // is what a test can hold it to.
+ !chromeless && (
+ isSettings ? 'page-glow-settings'
+ : isWorkbenchHome ? 'bg-background'
+ : 'page-glow-console'
+ )
)}
>
<div className={clsx(
diff --git a/ui/src/components/LanguageSwitcher.test.tsx b/ui/src/components/LanguageSwitcher.test.tsx
index b083b3a84..f6cba3218 100644
--- a/ui/src/components/LanguageSwitcher.test.tsx
+++ b/ui/src/components/LanguageSwitcher.test.tsx
@@ -4,6 +4,7 @@ import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { ToastProvider } from '../context/ToastProvider';
import { LanguageSwitcher } from './LanguageSwitcher';
const api = vi.hoisted(() => ({ getConfig: vi.fn(), mutateConfig: vi.fn() }));
@@ -24,6 +25,15 @@ vi.mock('react-i18next', () => ({
useTranslation: () => ({ t: (key: string) => key, i18n }),
}));
+// The real provider, not a stub: a failed instance save is reported through it,
+// and every surface that mounts this switcher sits inside one (App nests
+// ToastProvider above the router, which covers the wizard chrome too).
+const renderSwitcher = () => render(
+ <ToastProvider>
+ <LanguageSwitcher />
+ </ToastProvider>,
+);
+
beforeEach(() => {
authorization.capabilities.can_manage_instance = true;
i18n.language = 'en';
@@ -41,7 +51,7 @@ describe('LanguageSwitcher role-aware persistence', () => {
it('keeps a member browser preference without reading or writing the instance default', async () => {
authorization.capabilities.can_manage_instance = false;
const user = userEvent.setup();
- render(<LanguageSwitcher />);
+ renderSwitcher();
await user.click(screen.getByRole('button', { name: 'language.en' }));
await user.click(screen.getByRole('option', { name: 'language.zh' }));
@@ -53,7 +63,7 @@ describe('LanguageSwitcher role-aware persistence', () => {
it('persists an owner language change to the instance config', async () => {
const user = userEvent.setup();
- render(<LanguageSwitcher />);
+ renderSwitcher();
await user.click(screen.getByRole('button', { name: 'language.en' }));
await user.click(screen.getByRole('option', { name: 'language.zh' }));
diff --git a/ui/src/components/LanguageSwitcher.tsx b/ui/src/components/LanguageSwitcher.tsx
index 84c184e1a..e7777a292 100644
--- a/ui/src/components/LanguageSwitcher.tsx
+++ b/ui/src/components/LanguageSwitcher.tsx
@@ -1,15 +1,10 @@
import React, { useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
import { Check } from 'lucide-react';
import clsx from 'clsx';
-import { useApi } from '../context/ApiContext';
-import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
-import { setConfigField } from '../lib/configMutations';
+import { useLanguageSelection } from '../lib/useLanguageSelection';
export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpward = false }) => {
- const { i18n, t } = useTranslation();
- const { mutateConfig } = useApi();
- const { capabilities } = useInstanceAuthorization();
+ const { languages, current: currentLang, select } = useLanguageSelection();
const [isOpen, setIsOpen] = useState(false);
const wrapRef = useRef<HTMLDivElement>(null);
@@ -25,14 +20,6 @@ export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpwar
return () => document.removeEventListener('mousedown', handleClickOutside);
}, [isOpen]);
- const languageCodes = Object.keys(i18n.options.resources ?? {});
- const availableLanguages = languageCodes.length ? languageCodes : ['en'];
- const languages = availableLanguages.map((code) => ({
- code,
- label: t(`language.${code}`, { defaultValue: code }),
- }));
- const currentLang = languages.find((l) => l.code === i18n.language) || languages[0];
-
const shortLabel = (code: string) => {
if (code === 'zh') return '中';
return code.slice(0, 2).toUpperCase();
@@ -40,14 +27,7 @@ export const LanguageSwitcher: React.FC<{ openUpward?: boolean }> = ({ openUpwar
const handleSelect = async (code: string) => {
setIsOpen(false);
- if (code === i18n.language) return;
- i18n.changeLanguage(code);
- if (!capabilities.can_manage_instance) return;
- try {
- await mutateConfig([setConfigField(['language'], code)]);
- } catch {
- // Ignore save errors - language change already applied locally
- }
+ await select(code);
};
return (
diff --git a/ui/src/components/Workbench.test.tsx b/ui/src/components/Workbench.test.tsx
new file mode 100644
index 000000000..5c7874402
--- /dev/null
+++ b/ui/src/components/Workbench.test.tsx
@@ -0,0 +1,484 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter, Route, useLocation, useNavigate } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const newSession = vi.hoisted(() => ({
+ projects: [] as { id: string; display_name: string; folder_path: string }[],
+ target: undefined as { id: string; display_name: string; folder_path: string } | undefined,
+ setSelected: vi.fn(),
+ sending: false,
+ agents: [{ name: 'codex', backend: 'codex' }],
+ agentRoute: { agent_name: 'codex', agent_backend: 'codex' } as Record<string, unknown>,
+ setAgentRoute: vi.fn(),
+ effectiveDefaultAgentName: 'codex',
+ needsProject: false,
+ error: null as string | null,
+ upsertSelectProject: vi.fn(),
+ send: vi.fn(),
+}));
+const authorization = vi.hoisted(() => ({
+ capabilities: {
+ can_chat: true,
+ can_manage_projects: true,
+ can_manage_instance: true,
+ },
+}));
+vi.hoisted(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() }),
+ });
+});
+
+vi.mock('../lib/useNewSession', () => ({ useNewSession: () => newSession }));
+vi.mock('../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => authorization,
+}));
+vi.mock('../lib/sessionInfo', () => ({
+ canCreateLocalProject: (caps: { can_manage_projects?: boolean }) => Boolean(caps.can_manage_projects),
+}));
+// The real dialog opens the directory browser as its own first phase; here we
+// only need to see that the chip reaches it and that closing it changes nothing.
+vi.mock('./workbench/NewProjectDialog', () => ({
+ NewProjectDialog: ({ onClose }: { onClose: () => void }) => (
+ <div role="dialog" aria-label="directory-browser">
+ <button type="button" onClick={onClose}>cancel-folder</button>
+ </div>
+ ),
+}));
+vi.mock('./workbench/AgentRoutePicker', () => ({
+ AgentRoutePicker: ({ onChange }: { onChange: (patch: Record<string, unknown>) => void }) => (
+ <button type="button" onClick={() => onChange({ agent_name: 'claude', agent_backend: 'claude' })}>
+ agent-picker
+ </button>
+ ),
+}));
+vi.mock('../lib/apiFetch', () => ({ apiFetch: vi.fn() }));
+// Only the producer seam is stubbed; the predicate and the banner stay real, so
+// these tests exercise the lifecycle the home actually runs.
+const readiness = vi.hoisted(() => ({
+ value: null as { backend: 'claude' | 'codex' | 'opencode'; ready: boolean } | null,
+ /** What the home asked about, in order — the reader's own tests own the answering. */
+ questions: [] as Array<{ backend: string | null; asked: boolean }>,
+}));
+vi.mock('./workbench/backendReadiness', async (importOriginal) => ({
+ ...await importOriginal<typeof import('./workbench/backendReadiness')>(),
+ useBackendReadiness: (backend: string | null, asked: boolean) => {
+ readiness.questions.push({ backend, asked });
+ return readiness.value;
+ },
+}));
+
+import { ToastProvider } from '../context/ToastProvider';
+import { SettingsOverlayRouteSurface } from './settings/SettingsOverlayRouteSurface';
+import { settingsOverlayNavigationState } from '../lib/settingsOverlay';
+import { forgetSetupHandoff } from './workbench/backendReadiness';
+import en from '../i18n/en.json';
+import { Workbench } from './Workbench';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const 项目 = { id: 'p1', display_name: '中文项目', folder_path: '/Users/max/工作区/中文项目' };
+
+/** Reads back what the history entry actually holds after the home has run. */
+const LocationState: React.FC = () => (
+ <div data-testid="location-state">{JSON.stringify(useLocation().state ?? null)}</div>
+);
+
+/**
+ * The ways out of the home, as buttons so they add no links for the
+ * continuation-row cases to count: an ordinary departure and return, and
+ * Settings opened over the home carrying the same origin the shell's navigation
+ * boundary stamps on it.
+ */
+const WaysOut: React.FC = () => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ return (
+ <>
+ <button type="button" onClick={() => void navigate('/projects')}>leave-home</button>
+ <button type="button" onClick={() => void navigate('/')}>return-home</button>
+ <button type="button" onClick={() => void navigate(-1)}>go-back</button>
+ <button
+ type="button"
+ onClick={() => void navigate('/settings/general', {
+ state: settingsOverlayNavigationState({
+ destinationPathname: '/settings/general',
+ desktop: true,
+ source: location,
+ targetState: undefined,
+ }),
+ })}
+ >
+ open-settings
+ </button>
+ </>
+ );
+};
+
+const homeTree = (state?: unknown) => (
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>
+ <MemoryRouter initialEntries={[{ pathname: '/', state }]}>
+ <WaysOut />
+ {/* The real route surface, because how long the setup handoff lives is a
+ fact about the route: it has to outlive the guard remounting this home
+ in place and end when the user actually leaves, and this is the
+ component that knows which route is being shown. */}
+ <SettingsOverlayRouteSurface fallbackElement={<div>no-such-route</div>}>
+ <Route path="/" element={<><Workbench /><LocationState /></>} />
+ <Route path="/projects" element={<div>projects-page</div>} />
+ <Route path="/chat/:sessionId" element={<div>chat-page</div>} />
+ <Route path="/settings/general" element={<div>settings-page</div>} />
+ </SettingsOverlayRouteSurface>
+ </MemoryRouter>
+ </ToastProvider>
+ </I18nextProvider>
+);
+
+const renderHome = (state?: unknown) => render(homeTree(state));
+
+const locationState = () => JSON.parse(screen.getByTestId('location-state').textContent || 'null');
+const banner = () => screen.queryByText(/is ready to go/);
+
+const input = () => screen.getByPlaceholderText(en.workbench.home.inputPlaceholder) as HTMLTextAreaElement;
+
+beforeEach(() => {
+ window.localStorage.clear();
+ newSession.projects = [项目];
+ newSession.target = 项目;
+ newSession.sending = false;
+ newSession.needsProject = false;
+ newSession.error = null;
+ newSession.agentRoute = { agent_name: 'codex', agent_backend: 'codex' };
+ newSession.send.mockResolvedValue({ sessionId: 'ses_1', initialMessage: 'x' });
+ authorization.capabilities.can_chat = true;
+ authorization.capabilities.can_manage_projects = true;
+ authorization.capabilities.can_manage_instance = true;
+ readiness.value = null;
+ readiness.questions.length = 0;
+ // Each case is its own page load; the handoff a page holds is not shared.
+ forgetSetupHandoff();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('Workbench first-task home', () => {
+ it('seeds a starting task into the draft and focuses it, without sending', async () => {
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.click(screen.getByText(en.workbench.home.suggestions.researchTitle));
+
+ await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.researchDraft));
+ expect(document.activeElement).toBe(input());
+ expect(input().selectionStart).toBe(en.workbench.home.suggestions.researchDraft.length);
+ expect(newSession.send).not.toHaveBeenCalled();
+ });
+
+ it('lets the seeded task be edited before it is sent', async () => {
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.click(screen.getByText(en.workbench.home.suggestions.planTitle));
+ await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.planDraft));
+ await user.type(input(), ':先做中文文档');
+ await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
+
+ expect(newSession.send).toHaveBeenCalledWith(`${en.workbench.home.suggestions.planDraft}:先做中文文档`);
+ expect(await screen.findByText('chat-page')).toBeTruthy();
+ });
+
+ it('replaces the draft when a second starting point is picked', async () => {
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.click(screen.getByText(en.workbench.home.suggestions.exploreTitle));
+ await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.exploreDraft));
+ await user.click(screen.getByText(en.workbench.home.suggestions.planTitle));
+ await waitFor(() => expect(input().value).toBe(en.workbench.home.suggestions.planDraft));
+ expect(newSession.send).not.toHaveBeenCalled();
+ });
+
+ it('opens the folder picker straight from the workspace chip and keeps the draft when it is cancelled', async () => {
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.type(input(), '帮我看看这个仓库');
+ const chip = screen.getByRole('button', { name: `Workspace: ${项目.folder_path}` });
+ expect(chip.getAttribute('title')).toBe(项目.folder_path);
+ expect(chip.textContent).toContain(项目.display_name);
+
+ await user.click(chip);
+ // No menu in between: the chip reaches the folder picker itself.
+ expect(screen.getByRole('dialog', { name: 'directory-browser' })).toBeTruthy();
+
+ await user.click(screen.getByText('cancel-folder'));
+ expect(screen.queryByRole('dialog', { name: 'directory-browser' })).toBeNull();
+ expect(input().value).toBe('帮我看看这个仓库');
+ expect(newSession.setSelected).not.toHaveBeenCalled();
+ expect(newSession.upsertSelectProject).not.toHaveBeenCalled();
+ });
+
+ it('keeps the draft when the Agent route changes', async () => {
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.type(input(), '写一份中文周报');
+ await user.click(screen.getByText('agent-picker'));
+
+ expect(newSession.setAgentRoute).toHaveBeenCalledWith({ agent_name: 'claude', agent_backend: 'claude' });
+ expect(input().value).toBe('写一份中文周报');
+ expect(newSession.send).not.toHaveBeenCalled();
+ });
+
+ it('offers to add a workspace instead of sending into nowhere', async () => {
+ newSession.needsProject = true;
+ newSession.send.mockResolvedValue(null);
+ const user = userEvent.setup();
+ renderHome();
+
+ await user.type(input(), '开始一个新项目');
+ await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
+
+ expect(await screen.findByRole('dialog', { name: 'directory-browser' })).toBeTruthy();
+ // The prompt survives the detour — the user retries it, not retypes it.
+ expect(input().value).toBe('开始一个新项目');
+ });
+
+ it('shows no readiness banner on the wizard claim alone', () => {
+ renderHome({ onboardingCompleted: true });
+
+ // The backend has not corroborated anything yet, so there is nothing true
+ // to say about it — the claim is what makes the question worth asking, not
+ // an answer in itself.
+ expect(screen.queryByText(/is ready to go/)).toBeNull();
+ expect(screen.queryByRole('button', { name: en.workbench.home.readyDismiss })).toBeNull();
+ });
+
+ it('spells the chat-app continuation as one sentence with a real link', () => {
+ renderHome();
+
+ expect(screen.getByRole('link', { name: en.workbench.home.continueOnPhone }).getAttribute('href'))
+ .toBe('/settings/remote-access');
+ const settingsLink = screen.getByRole('link', { name: 'Settings' });
+ expect(settingsLink.getAttribute('href')).toBe('/settings/platforms');
+ // Guards the source board's missing space: "…apps inSettings".
+ expect(settingsLink.parentElement?.textContent).toBe('Connect chat apps in Settings');
+ });
+
+ it('sends someone who cannot chat to their projects instead of an unusable box', () => {
+ authorization.capabilities.can_chat = false;
+ renderHome();
+
+ expect(screen.getByText('projects-page')).toBeTruthy();
+ });
+});
+
+describe('Workbench onboarding-completion event', () => {
+ const ready = { backend: 'codex', ready: true };
+ const wizardArrival = { onboardingCompleted: true, settingsBackgroundLocation: { pathname: '/chat/会话' } };
+
+ it('takes the completion out of history and leaves the rest of the entry alone', async () => {
+ readiness.value = ready;
+ renderHome(wizardArrival);
+
+ expect(await screen.findByText('Codex is ready to go')).toBeTruthy();
+ // Consumed, not read: the key is gone from the entry, and the overlay origin
+ // the wizard was also carrying is still there for whoever needs it next.
+ await waitFor(() => expect(locationState()).toEqual({ settingsBackgroundLocation: { pathname: '/chat/会话' } }));
+ });
+
+ it('clears the entry entirely when the completion was all it carried', async () => {
+ readiness.value = ready;
+ renderHome({ onboardingCompleted: true });
+
+ await waitFor(() => expect(locationState()).toBeNull());
+ expect(banner()).toBeTruthy();
+ });
+
+ it('still announces a readiness answer that arrives after the entry was rewritten', async () => {
+ const view = renderHome({ onboardingCompleted: true });
+
+ // Nothing corroborated yet, and the history entry has already been rewritten.
+ await waitFor(() => expect(locationState()).toBeNull());
+ expect(banner()).toBeNull();
+
+ readiness.value = ready;
+ view.rerender(homeTree({ onboardingCompleted: true }));
+
+ // The event is latched for the visit, so the late answer is not wasted.
+ expect(await screen.findByText('Codex is ready to go')).toBeTruthy();
+ });
+
+ it('stays dismissed for the rest of the visit', async () => {
+ readiness.value = ready;
+ const user = userEvent.setup();
+ const view = renderHome({ onboardingCompleted: true });
+
+ await user.click(await screen.findByRole('button', { name: en.workbench.home.readyDismiss }));
+ expect(banner()).toBeNull();
+
+ view.rerender(homeTree({ onboardingCompleted: true }));
+ expect(banner()).toBeNull();
+ });
+
+ it('asks the backend nothing on a visit where no completion can be announced', () => {
+ readiness.value = ready;
+ renderHome();
+
+ // Not a claim about the banner — the home never even asks. A visit that
+ // could not announce anything costs the backend no read.
+ expect(readiness.questions.length).toBeGreaterThan(0);
+ expect(readiness.questions.some((question) => question.asked)).toBe(false);
+ expect(banner()).toBeNull();
+ });
+
+ it('stops asking about the backend once the banner is dismissed', async () => {
+ readiness.value = ready;
+ const user = userEvent.setup();
+ renderHome({ onboardingCompleted: true });
+
+ await user.click(await screen.findByRole('button', { name: en.workbench.home.readyDismiss }));
+
+ expect(readiness.questions.some((question) => question.asked)).toBe(true);
+ expect(readiness.questions.at(-1)).toEqual({ backend: 'codex', asked: false });
+ });
+
+ it('still announces after the route guard remounts the home mid-handoff', async () => {
+ readiness.value = ready;
+ const first = renderHome({ onboardingCompleted: true });
+ await waitFor(() => expect(locationState()).toBeNull());
+ first.unmount();
+
+ // Crossing the setup boundary is exactly what makes the route guard
+ // re-validate, and the home is unmounted and remounted underneath while it
+ // does — by which time the entry has already been consumed. Same page, same
+ // announcement still owed: losing it here is losing it for good.
+ renderHome(null);
+
+ expect(await screen.findByText('Codex is ready to go')).toBeTruthy();
+ });
+
+ it('does not come back when that remount happens after a dismissal', async () => {
+ readiness.value = ready;
+ const user = userEvent.setup();
+ const first = renderHome({ onboardingCompleted: true });
+
+ await user.click(await screen.findByRole('button', { name: en.workbench.home.readyDismiss }));
+ first.unmount();
+ renderHome(null);
+
+ await waitFor(() => expect(screen.getByTestId('location-state')).toBeTruthy());
+ expect(banner()).toBeNull();
+ expect(readiness.questions.at(-1)).toEqual({ backend: 'codex', asked: false });
+ });
+
+ it('does not announce the consumed setup again after leaving the home and coming back', async () => {
+ readiness.value = ready;
+ const user = userEvent.setup();
+ renderHome(wizardArrival);
+ expect(await screen.findByText('Codex is ready to go')).toBeTruthy();
+ await waitFor(() => expect(locationState()).toEqual({ settingsBackgroundLocation: { pathname: '/chat/会话' } }));
+
+ // A real departure, unlike the guard's remount above: the home is gone
+ // because the user went somewhere else, and the visit the wizard handed off
+ // to is over with it.
+ await user.click(screen.getByText('leave-home'));
+ await waitFor(() => expect(screen.getByText('projects-page')).toBeTruthy());
+ expect(screen.queryByPlaceholderText(en.workbench.home.inputPlaceholder)).toBeNull();
+
+ await user.click(screen.getByText('return-home'));
+ await waitFor(() => expect(screen.getByPlaceholderText(en.workbench.home.inputPlaceholder)).toBeTruthy());
+ expect(banner()).toBeNull();
+ // Nothing left to announce, so the backend is not asked again either.
+ expect(readiness.questions.at(-1)).toEqual({ backend: 'codex', asked: false });
+ });
+
+ it('keeps the announcement through Settings opened over the home', async () => {
+ readiness.value = ready;
+ const user = userEvent.setup();
+ renderHome({ onboardingCompleted: true });
+ expect(await screen.findByText('Codex is ready to go')).toBeTruthy();
+
+ // Settings keeps this home mounted behind it — on a phone as much as on a
+ // desktop — so the user has not left, and the banner they have not answered
+ // yet is still theirs to answer when they come back out.
+ await user.click(screen.getByText('open-settings'));
+ expect(await screen.findByText('settings-page')).toBeTruthy();
+ expect(screen.getByPlaceholderText(en.workbench.home.inputPlaceholder)).toBeTruthy();
+
+ await user.click(screen.getByText('go-back'));
+ await waitFor(() => expect(screen.queryByText('settings-page')).toBeNull());
+ expect(banner()).toBeTruthy();
+ });
+
+ it('does not re-announce the same setup on a reload or a return visit', async () => {
+ readiness.value = ready;
+ const first = renderHome(wizardArrival);
+ await waitFor(() => expect(locationState()).toEqual({ settingsBackgroundLocation: { pathname: '/chat/会话' } }));
+ const afterConsuming = locationState();
+ first.unmount();
+ // A reload is a new page, which is what tells it apart from the remount
+ // above: nothing carries over but the history entry itself.
+ forgetSetupHandoff();
+
+ // And that entry, as it now stands, no longer claims a setup just finished,
+ // so the home says nothing about one.
+ renderHome(afterConsuming);
+ await waitFor(() => expect(screen.getByTestId('location-state')).toBeTruthy());
+ expect(banner()).toBeNull();
+ });
+});
+
+// Both continuations point at OWNER_ONLY_ROUTES, so these cases are written as
+// the capability the route guard itself reads rather than as role labels the
+// test invents. The server projects `can_manage_instance` from member upward
+// and `can_chat` from editor upward (vibe/authorization.py), so the two states
+// below are the only ones this row can be in: an instance manager (owner or
+// member) sees it, an editor does not, and a viewer never reaches this page at
+// all — that redirect is covered above.
+describe('Workbench continuation row', () => {
+ const ownerOnlyLinks = () => screen
+ .queryAllByRole('link')
+ .map((link) => link.getAttribute('href') ?? '')
+ .filter((href) => href.startsWith('/settings/'));
+
+ it('offers both continuations to someone who can manage the instance', () => {
+ renderHome();
+
+ expect(screen.getByText(en.workbench.home.continueOnPhone)).toBeTruthy();
+ expect(screen.getByText('Connect chat apps in', { exact: false })).toBeTruthy();
+ expect(ownerOnlyLinks().sort()).toEqual(['/settings/platforms', '/settings/remote-access']);
+ });
+
+ it('hides the whole row from someone who cannot, while chat stays usable', async () => {
+ authorization.capabilities.can_manage_instance = false;
+ const user = userEvent.setup();
+ renderHome();
+
+ // No dead CTA: neither the links nor the sentence that only exists to
+ // introduce them survives.
+ expect(screen.queryByText(en.workbench.home.continueOnPhone)).toBeNull();
+ expect(screen.queryByText('Connect chat apps in', { exact: false })).toBeNull();
+ expect(ownerOnlyLinks()).toEqual([]);
+
+ await user.type(input(), '继续用聊天');
+ await user.click(screen.getByRole('button', { name: en.chat.compose.send }));
+ expect(newSession.send).toHaveBeenCalledWith('继续用聊天');
+ });
+});
diff --git a/ui/src/components/Workbench.tsx b/ui/src/components/Workbench.tsx
index 303e5389a..ee5b05e92 100644
--- a/ui/src/components/Workbench.tsx
+++ b/ui/src/components/Workbench.tsx
@@ -1,29 +1,67 @@
-import { useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Navigate, useNavigate } from 'react-router-dom';
-import { Activity, Bot, FolderPlus, Sparkles } from 'lucide-react';
+import { useEffect, useRef, useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+import { Link, Navigate, useLocation, useNavigate } from 'react-router-dom';
+import { ChevronDown, FolderOpen, ListChecks, Search, Smartphone } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
import { useNewSession } from '../lib/useNewSession';
import { NewProjectDialog } from './workbench/NewProjectDialog';
-import { Composer } from './workbench/Composer';
+import { Composer, type ComposerHandle } from './workbench/Composer';
import { ProjectPicker } from './workbench/ProjectPicker';
import { AgentRoutePicker } from './workbench/AgentRoutePicker';
+import { ReadyBanner } from './workbench/ReadyBanner';
+import { shouldShowReadyBanner, useBackendReadiness, useSetupHandoff } from './workbench/backendReadiness';
+import { Popover, PopoverContent, PopoverTrigger } from './ui/popover';
import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
import { canCreateLocalProject } from '../lib/sessionInfo';
+import logoImg from '../assets/logo.png';
+import type { TranslationKey } from '../i18n/types';
-// Mirrors design.pen DnkGJ "Workbench" canvas: a centered hero panel +
-// suggestion chips with the shared chat Composer below it. The Composer is
-// wired to create a new session under the most-recently-active project using
-// the default Agent, then routes to /chat/<id> with the typed message
-// pre-seeded. No project? The send surfaces the NewProjectDialog so the user
-// gets unstuck without bouncing pages. The create flow lives in the shared
-// useNewSession hook — one source of truth with the mobile NewSessionSheet.
+// The three starting points the home offers (design LDlvV). Each one seeds the
+// draft and focuses the input — it never sends, so the user edits a concrete
+// sentence instead of staring at an empty box.
+const SUGGESTIONS: {
+ key: string;
+ icon: LucideIcon;
+ titleKey: TranslationKey;
+ bodyKey: TranslationKey;
+ draftKey: TranslationKey;
+}[] = [
+ {
+ key: 'explore',
+ icon: FolderOpen,
+ titleKey: 'workbench.home.suggestions.exploreTitle',
+ bodyKey: 'workbench.home.suggestions.exploreBody',
+ draftKey: 'workbench.home.suggestions.exploreDraft',
+ },
+ {
+ key: 'research',
+ icon: Search,
+ titleKey: 'workbench.home.suggestions.researchTitle',
+ bodyKey: 'workbench.home.suggestions.researchBody',
+ draftKey: 'workbench.home.suggestions.researchDraft',
+ },
+ {
+ key: 'plan',
+ icon: ListChecks,
+ titleKey: 'workbench.home.suggestions.planTitle',
+ bodyKey: 'workbench.home.suggestions.planBody',
+ draftKey: 'workbench.home.suggestions.planDraft',
+ },
+];
+
+// The first-task home (design SfdNo + TfqkD + CRERw): one question, three
+// starting points, and the shared chat Composer carrying the Agent and workspace
+// pickers on its own action row. Sending creates a session under the selected
+// workspace with the selected Agent and routes to /chat/<id> with the typed
+// message pre-seeded; no workspace surfaces the project dialog so the user gets
+// unstuck in place. The create flow lives in the shared useNewSession hook — one
+// source of truth with the mobile NewSessionSheet.
export const Workbench: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const {
- capabilities,
- } = useInstanceAuthorization();
+ const location = useLocation();
+ const { capabilities } = useInstanceAuthorization();
const canCreateProject = canCreateLocalProject(capabilities);
const ns = useNewSession({
active: capabilities.can_chat,
@@ -31,6 +69,45 @@ export const Workbench: React.FC = () => {
createFailedText: t('newSession.createFailed'),
});
const [newProjectOpen, setNewProjectOpen] = useState(false);
+ const [workspaceMenuOpen, setWorkspaceMenuOpen] = useState(false);
+ const composerRef = useRef<ComposerHandle>(null);
+
+ // The wizard hands `{ onboardingCompleted: true }` to this route. That is an
+ // event, not a property of the location — history state survives a reload, so
+ // leaving the key in place would re-announce the same setup every time the
+ // user came back here. Take it out of the entry, keeping the REST of the state
+ // so the overlay origin and anything else travelling with it stays intact, and
+ // hold the event for the page (see useSetupHandoff: this home is remounted
+ // mid-handoff, and a readiness answer can still arrive after that).
+ // The backend itself must still confirm it is ready, so holding it alone shows
+ // nothing: it only makes the question worth asking.
+ const wizardState = location.state as Record<string, unknown> | null;
+ const wizardJustFinished = Boolean(wizardState?.onboardingCompleted);
+ const {
+ completed: onboardingCompleted,
+ dismissed: bannerDismissed,
+ dismiss: dismissReadyBanner,
+ } = useSetupHandoff(wizardJustFinished);
+ useEffect(() => {
+ if (!wizardState?.onboardingCompleted) return;
+ const { onboardingCompleted: _consumed, ...rest } = wizardState;
+ navigate(`${location.pathname}${location.search}${location.hash}`, {
+ replace: true,
+ state: Object.keys(rest).length > 0 ? rest : null,
+ });
+ }, [location.hash, location.pathname, location.search, wizardState, navigate]);
+ const currentBackend = ns.agentRoute.agent_backend
+ ?? ns.agents.find((agent) => agent.name === ns.agentRoute.agent_name)?.backend
+ ?? null;
+ // Asked only while there is a completion left to announce: an ordinary visit,
+ // and every visit after the user has dismissed the banner, reads nothing.
+ const readiness = useBackendReadiness(currentBackend, onboardingCompleted && !bannerDismissed);
+ const showReadyBanner = shouldShowReadyBanner({
+ onboardingCompleted,
+ readiness,
+ currentBackend,
+ dismissed: bannerDismissed,
+ });
// Returns whether the send actually started, so the Composer only clears the
// box on a real start — a no-project nudge or a transient create error keeps
@@ -47,94 +124,176 @@ export const Workbench: React.FC = () => {
return false;
};
- // Quick chips under the hero — three of the most common first moves.
- const suggestions = [
- ...(canCreateProject
- ? [{ key: 'newProject' as const, icon: FolderPlus, onClick: () => setNewProjectOpen(true) }]
- : []),
- ...(capabilities.can_manage_agents
- ? [{ key: 'openAgents' as const, icon: Bot, onClick: () => navigate('/agents') }]
- : []),
- ...(capabilities.can_manage_instance
- ? [{ key: 'openHarness' as const, icon: Activity, onClick: () => navigate('/harness') }]
- : []),
- ];
-
if (!capabilities.can_chat) return <Navigate to="/projects" replace />;
+ const workspaceLabel = ns.target?.display_name ?? t('workbench.home.chooseWorkspace');
+ const workspaceChipClass = 'flex h-7 min-w-0 max-w-[220px] items-center gap-1.5 rounded-md px-2 text-[12px] text-muted transition-colors hover:bg-foreground/[0.06] hover:text-foreground disabled:pointer-events-none disabled:opacity-50';
+ const workspaceChipBody = (
+ <>
+ <span className="min-w-0 truncate">{workspaceLabel}</span>
+ <ChevronDown className="size-3 shrink-0" />
+ </>
+ );
+ // One affordance, two contents by capability. Opening folders is how a
+ // workspace is chosen (design: the chip opens the directory browser directly,
+ // with no menu in between); someone who cannot open folders still has to be
+ // able to pick among the projects they already have, so the same chip lists
+ // them instead of becoming a control that does nothing.
+ const workspaceChip = canCreateProject ? (
+ <button
+ type="button"
+ onClick={() => setNewProjectOpen(true)}
+ disabled={ns.sending}
+ title={ns.target?.folder_path}
+ aria-label={ns.target ? t('workbench.home.workspaceAria', { path: ns.target.folder_path }) : t('workbench.home.chooseWorkspace')}
+ className={workspaceChipClass}
+ >
+ {workspaceChipBody}
+ </button>
+ ) : (
+ <Popover open={workspaceMenuOpen} onOpenChange={setWorkspaceMenuOpen}>
+ <PopoverTrigger asChild>
+ <button
+ type="button"
+ disabled={ns.sending || ns.projects.length === 0}
+ title={ns.target?.folder_path}
+ aria-label={ns.target ? t('workbench.home.workspaceAria', { path: ns.target.folder_path }) : t('workbench.home.chooseWorkspace')}
+ className={workspaceChipClass}
+ >
+ {workspaceChipBody}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent align="start" className="w-[320px] p-2">
+ <ProjectPicker
+ projects={ns.projects}
+ targetId={ns.target?.id}
+ onSelect={(id) => {
+ ns.setSelected(id);
+ setWorkspaceMenuOpen(false);
+ }}
+ onNewProject={() => setNewProjectOpen(true)}
+ disabled={ns.sending}
+ />
+ </PopoverContent>
+ </Popover>
+ );
+
return (
- // Desktop centers the hero + Composer as a group (min-h + justify-center). On
- // mobile we DON'T center or force a tall min-height: a tall centered container
- // fights the iOS keyboard (focusing the composer leaves a big gap / pushes it
- // off-screen). Top-aligned normal flow lets iOS scroll the focused composer
- // into view above the keyboard the way it does for ordinary in-flow inputs.
- <div className="flex flex-col items-center gap-5 md:min-h-[calc(100dvh-7rem)] md:justify-center">
- {/* Hero panel — a centered card, not a full-bleed fill. */}
- <div className="flex w-full max-w-[640px] flex-col items-center gap-6 rounded-2xl border border-border bg-surface-2 px-6 py-10">
- <div className="flex size-14 items-center justify-center rounded-2xl border border-mint/40 bg-mint-soft text-mint-ink shadow-glow-md-mint">
- <Sparkles className="size-6" />
- </div>
- <div className="flex max-w-[520px] flex-col items-center gap-3 text-center">
- <h1 className="text-[22px] font-semibold text-foreground">{t('workbench.canvas.heroTitle')}</h1>
- <p className="text-[13px] leading-[1.55] text-muted">{t('workbench.canvas.heroBody')}</p>
+ // Desktop: the discovery block is centred in whatever height is left and the
+ // composer sits at the bottom (design rhythm — not a fixed block plus a fixed
+ // gap). Mobile DOESN'T get the tall centred column: it fights the iOS
+ // keyboard. There the block flows from the top and the composer pins itself
+ // to the bottom of the scroll area instead (see below).
+ //
+ // The column is fluid. 856 in the source is what a 1200 staging window minus
+ // the 248 sidebar and its padding happens to leave — no max width is
+ // expressed anywhere in the design, so none is imposed here.
+ <div className="flex w-full flex-col gap-6 md:min-h-[calc(100dvh-4rem)]">
+ {showReadyBanner && currentBackend && (
+ <ReadyBanner backend={currentBackend} onDismiss={dismissReadyBanner} />
+ )}
+
+ <div className="flex flex-col items-center justify-center gap-6 py-6 md:flex-1 md:py-0">
+ <div className="flex flex-col items-center gap-4 text-center">
+ <img src={logoImg} alt="" aria-hidden="true" className="h-12 w-16 object-contain" />
+ <h1 className="text-[clamp(22px,4vw,30px)] font-semibold text-foreground">{t('workbench.home.heroTitle')}</h1>
+ <p className="max-w-[520px] text-[14px] leading-[1.5] text-muted">{t('workbench.home.heroBody')}</p>
</div>
- <div className="flex flex-wrap items-center justify-center gap-2">
- {suggestions.map(({ key, icon: Icon, onClick }) => (
+
+ {/* Three starting points (design LDlvV): equal columns on desktop, stacked
+ on a phone where 277-wide cards would be unreadable. */}
+ <div className="grid w-full grid-cols-1 gap-3 sm:grid-cols-3">
+ {SUGGESTIONS.map(({ key, icon: Icon, titleKey, bodyKey, draftKey }) => (
<button
key={key}
type="button"
- onClick={onClick}
- className="group flex items-center gap-2 rounded-full border border-border-strong bg-surface px-3 py-2 text-[12px] text-foreground transition hover:border-mint/40 hover:bg-mint-soft hover:text-mint-ink"
+ onClick={() => composerRef.current?.setDraft(t(draftKey))}
+ className="flex flex-col items-start gap-3 rounded-xl border border-border bg-surface-2 p-[18px] text-left transition-colors hover:border-border-strong hover:bg-foreground/[0.03]"
>
- <Icon className="size-3.5 text-muted group-hover:text-mint-ink" />
- <span>{t(`workbench.canvas.suggestions.${key}`)}</span>
+ <Icon className="size-[19px] shrink-0 text-mint-ink" />
+ <span className="flex flex-col gap-1">
+ <span className="text-[13px] font-semibold text-foreground">{t(titleKey)}</span>
+ <span className="text-[12px] leading-[1.5] text-muted">{t(bodyKey)}</span>
+ </span>
</button>
))}
</div>
</div>
- {/* Input — project + agent pickers above the shared chat Composer so the
- user can see/choose where the session lands and which agent runs it. */}
- <div className="flex w-full max-w-[640px] flex-col gap-3">
- {ns.projects.length > 0 && (
- <ProjectPicker
- projects={ns.projects}
- targetId={ns.target?.id}
- onSelect={ns.setSelected}
- onNewProject={() => setNewProjectOpen(true)}
- disabled={ns.sending}
- />
- )}
- <div className="flex min-w-0 flex-col gap-2">
- <div className="font-mono text-[11px] font-bold uppercase tracking-[0.08em] text-muted">{t('newSession.agent')}</div>
- <AgentRoutePicker
- value={ns.agentRoute}
- agents={ns.agents}
- onChange={ns.setAgentRoute}
- defaultLabel={ns.effectiveDefaultAgentName ? t('newSession.defaultAgentNamed', { name: ns.effectiveDefaultAgentName }) : t('newSession.defaultAgent')}
- disabled={ns.sending}
- align="start"
- // Fill the column on mobile (≈ full screen); on desktop hug content
- // and cap at 62% so it reads like the compact Chat-header picker
- // instead of a full-width 640px bar. self-start defeats the flex-col
- // stretch that would otherwise force the trigger to the column width.
- triggerClassName="max-w-full sm:max-w-[62%] sm:self-start"
- />
- </div>
+ {/* On a phone the page is taller than the screen (hero + three stacked
+ cards + this block), so at rest its last ~80px sit under the fixed tab
+ bar — and that is exactly where the composer's Agent, workspace and
+ Send controls are: measured at 390x844, Send's centre hit-tests to the
+ nav, so the button is dead until the user happens to scroll. Pinning
+ this block to the bottom of the scroll area, one nav clearance above
+ the bar, keeps the primary control reachable at any viewport height
+ instead of trimming the rhythm above it to fit one phone. It stays a
+ sticky child of the scrolling column rather than a fixed bar, so iOS
+ keyboard panning still moves it with the page. Desktop is untouched:
+ the column already fills the viewport and nothing overlaps it. */}
+ <div className="flex flex-col gap-4 pb-2 max-md:sticky max-md:bottom-[var(--mobile-nav-clearance)] max-md:z-10 max-md:bg-background max-md:pt-3">
+ {/* A card that scrolls behind an opaque block reads as cut in half. The
+ short fade above it says "passing behind", which is what happens. */}
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 -top-4 h-4 bg-gradient-to-t from-background to-transparent md:hidden"
+ />
<Composer
+ ref={composerRef}
onSend={send}
- placeholder={t('workbench.canvas.inputPlaceholder')}
+ placeholder={t('workbench.home.inputPlaceholder')}
disabled={ns.sending}
- className="max-w-[640px]"
+ actions={
+ <>
+ <AgentRoutePicker
+ value={ns.agentRoute}
+ agents={ns.agents}
+ onChange={ns.setAgentRoute}
+ defaultLabel={ns.effectiveDefaultAgentName
+ ? t('newSession.defaultAgentNamed', { name: ns.effectiveDefaultAgentName })
+ : t('newSession.defaultAgent')}
+ disabled={ns.sending}
+ align="start"
+ triggerClassName="h-7 max-w-[240px] rounded-md px-2 py-0"
+ />
+ {workspaceChip}
+ </>
+ }
/>
{ns.needsProject && (
- <div className="px-2 text-[10.5px] text-gold-ink">{t('workbench.canvas.noProjectForChat')}</div>
+ <div className="px-2 text-[10.5px] text-gold-ink">{t('workbench.home.noProjectForChat')}</div>
)}
{ns.error && (
- <div className="mt-1 rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">
+ <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-3 py-2 text-[12px] text-destructive-ink">
{ns.error}
</div>
)}
+
+ {/* Continuation row (design CRERw) — where this conversation can carry on
+ when the user leaves the desk. Both destinations are OWNER_ONLY_ROUTES,
+ so anyone without `can_manage_instance` who followed either would be
+ bounced straight back here; the whole row goes rather than the links
+ alone, because the sentence around them only exists to introduce a
+ destination they cannot reach. */}
+ {capabilities.can_manage_instance && (
+ <div className="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
+ <Link
+ to="/settings/remote-access"
+ className="flex items-center gap-1.5 text-[12px] font-semibold text-mint-ink transition-opacity hover:opacity-80"
+ >
+ <Smartphone className="size-[15px] shrink-0" />
+ <span>{t('workbench.home.continueOnPhone')}</span>
+ </Link>
+ <span className="text-[11px] text-muted">
+ <Trans
+ i18nKey="workbench.home.connectChatApps"
+ components={{
+ settings: <Link to="/settings/platforms" className="font-bold text-cyan-ink hover:underline" />,
+ }}
+ />
+ </span>
+ </div>
+ )}
</div>
{newProjectOpen && canCreateProject && (
diff --git a/ui/src/components/apps/MobileDockDrawer.test.tsx b/ui/src/components/apps/MobileDockDrawer.test.tsx
new file mode 100644
index 000000000..bf920a903
--- /dev/null
+++ b/ui/src/components/apps/MobileDockDrawer.test.tsx
@@ -0,0 +1,56 @@
+/* @vitest-environment jsdom */
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { MemoryRouter, Route, Routes } from 'react-router-dom';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({ t: (key: string) => key }),
+}));
+vi.mock('../../context/DockContext', () => ({
+ useDock: () => ({ order: [], pins: [], undock: vi.fn(), unpin: vi.fn() }),
+}));
+vi.mock('../../lib/useAuthAccount', () => ({ useAuthAccount: () => ({ email: null }) }));
+vi.mock('../useShowPages', () => ({ useShowPageInventory: () => ({ pages: [] }) }));
+vi.mock('../workbench/MorePage', () => ({
+ MoreAccountSection: () => null,
+ MoreAppearanceSection: () => null,
+ MoreConnectionSection: () => null,
+}));
+
+import { MobileDockDrawer } from './MobileDockDrawer';
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('MobileDockDrawer settings entry', () => {
+ it('opens Settings on General, the same place a desktop entry lands', async () => {
+ const user = userEvent.setup();
+ const onClose = vi.fn();
+
+ render(
+ <MemoryRouter initialEntries={['/']}>
+ <Routes>
+ <Route path="/" element={<MobileDockDrawer open onClose={onClose} />} />
+ <Route path="/settings" element={<div>section-list</div>} />
+ <Route path="/settings/general" element={<div>general-page</div>} />
+ </Routes>
+ </MemoryRouter>,
+ );
+
+ const chip = screen.getByRole('link', { name: 'more.controlPanel' });
+ expect(chip.getAttribute('href')).toBe('/settings/general');
+
+ await user.click(chip);
+
+ // A phone's ordinary way into Settings is a destination, not a menu: the
+ // section list stays reachable from General's back row, but it is not what
+ // tapping 设置 hands the user.
+ expect(await screen.findByText('general-page')).toBeTruthy();
+ expect(screen.queryByText('section-list')).toBeNull();
+ expect(onClose).toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/apps/MobileDockDrawer.tsx b/ui/src/components/apps/MobileDockDrawer.tsx
index 7c2c75525..8d8983978 100644
--- a/ui/src/components/apps/MobileDockDrawer.tsx
+++ b/ui/src/components/apps/MobileDockDrawer.tsx
@@ -8,6 +8,7 @@ import { showPageAvatar, showPageIconUrl } from '../../apps/showPageAvatar';
import { ShowPageAvatarContent } from '../../apps/showPageAvatarTile';
import { useDock } from '../../context/DockContext';
import { dockIdToSession } from '../../context/dockDoc';
+import { SETTINGS_LANDING_PATH } from '../../lib/adminNavigation';
import { useAuthAccount } from '../../lib/useAuthAccount';
import { useShowPageInventory } from '../useShowPages';
import { MoreAccountSection, MoreAppearanceSection, MoreConnectionSection } from '../workbench/MorePage';
@@ -225,7 +226,7 @@ export const MobileDockDrawer: React.FC<{ open: boolean; onClose: () => void }>
and 更多 open a small overflow sheet. Appearance lives inside 更多 so
the three English labels fit without truncation. */}
<div className="mt-4 flex items-stretch gap-2 border-t border-border pt-3">
- <Link to="/settings" onClick={onClose} className={chipClass}>
+ <Link to={SETTINGS_LANDING_PATH} onClick={onClose} className={chipClass}>
<Settings className="size-4 shrink-0" />
<span className="truncate">{t('more.controlPanel')}</span>
</Link>
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index e24ff6408..2579e480c 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -65,7 +65,7 @@ const ShowPageWindow: React.FC<{
};
// The portal layer that hosts app windows. Covers the workbench main area (right
-// of the 240px sidebar on desktop). The layer itself is pointer-events-none so
+// of the 248px sidebar on desktop). The layer itself is pointer-events-none so
// empty space passes clicks through to the workbench underneath; each AppWindow
// re-enables pointer events on itself (minimized windows stay mounted but inert,
// so their terminal/editor state survives a minimize). Desktop-only — mobile opens
diff --git a/ui/src/components/settings/SettingsGeneralPage.provider.test.tsx b/ui/src/components/settings/SettingsGeneralPage.provider.test.tsx
new file mode 100644
index 000000000..4548378b6
--- /dev/null
+++ b/ui/src/components/settings/SettingsGeneralPage.provider.test.tsx
@@ -0,0 +1,184 @@
+/* @vitest-environment jsdom */
+
+import { useEffect } from 'react';
+import type { ReactNode } from 'react';
+import { createInstance, type i18n as I18n } from 'i18next';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+// The wire is the only stand-in in this file. Everything above it is the app's
+// own code — the provider that memoizes its value on `t`, react-i18next's
+// instance copying, the real page — which is what separates this from the
+// sibling file's mocked api: there the identity rule is reproduced, here it is
+// the one the product actually has.
+vi.mock('../../lib/apiFetch', () => ({ apiFetch }));
+
+const authorization = vi.hoisted(() => ({ capabilities: { can_manage_instance: true } }));
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => authorization,
+}));
+
+vi.hoisted(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) => ({
+ media: query,
+ matches: false,
+ addEventListener: () => {},
+ removeEventListener: () => {},
+ }),
+ });
+});
+
+import { ApiProvider, useApi } from '../../context/ApiContext';
+import { ThemeProvider } from '../../context/ThemeProvider';
+import { ToastProvider } from '../../context/ToastProvider';
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import { SettingsGeneralPage } from './SettingsGeneralPage';
+
+// One instance per test: the language operation belongs to the i18n instance and
+// outlives any render root, so a shared one would hand this test's pending save
+// to the next.
+const makeI18n = () => {
+ const instance = createInstance();
+ void instance.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+ });
+ return instance;
+};
+
+let i18n = makeI18n();
+
+const json = (payload: unknown) => new Response(JSON.stringify(payload), {
+ status: 200,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+/** A config endpoint with a memory and the test's hand on its clock: a write is
+ * applied to it when the test lets that request answer, not when the app sends
+ * it, so what the instance ends up with is decided by the order the writes land
+ * in. */
+const instanceServer = () => {
+ const stored: Record<string, unknown> = { language: 'en' };
+ const inFlight: { answer: () => void }[] = [];
+ apiFetch.mockImplementation((path: string, init?: RequestInit) => {
+ if (path !== '/api/config' || init?.method !== 'POST') {
+ // Reads answer with the instance as it stands; anything else this app asks
+ // on mount gets an empty, successful answer, because this test speaks only
+ // about config.
+ return Promise.resolve(json(path === '/api/config' ? stored : {}));
+ }
+ const payload = JSON.parse(String(init.body));
+ return new Promise<Response>((resolve) => {
+ inFlight.push({
+ answer: () => {
+ Object.assign(stored, payload);
+ resolve(json({ ...stored }));
+ },
+ });
+ });
+ });
+ return {
+ stored,
+ inFlight,
+ /** The language writes the app has actually put on the wire, in order. */
+ sent: () => apiFetch.mock.calls
+ .filter(([path, init]) => path === '/api/config' && init?.method === 'POST')
+ .map(([, init]) => JSON.parse(String(init.body)).language),
+ };
+};
+
+/** Every distinct api the provider has handed a consumer. A language change is
+ * itself what produces a new one, which is the churn this file exists to put
+ * the real provider behind. */
+const handedOut: unknown[] = [];
+const WatchApi = () => {
+ const api = useApi();
+ useEffect(() => {
+ handedOut.push(api);
+ }, [api]);
+ return null;
+};
+
+const App = ({ instance, children }: { instance: I18n; children: ReactNode }) => (
+ <I18nextProvider i18n={instance}>
+ <ThemeProvider>
+ <ToastProvider>
+ <ApiProvider>
+ <WatchApi />
+ {children}
+ </ApiProvider>
+ </ToastProvider>
+ </ThemeProvider>
+ </I18nextProvider>
+);
+
+const renderApp = () => {
+ const at = (children: ReactNode) => <App instance={i18n}>{children}</App>;
+ const view = render(at(<SettingsGeneralPage />));
+ return {
+ ...view,
+ /** Leaves Settings the way the app does: the page unmounts, the rest stays. */
+ leave: () => view.rerender(at(<div />)),
+ comeBack: () => view.rerender(at(<SettingsGeneralPage />)),
+ };
+};
+
+const languageSelect = () => screen.getByRole('combobox') as HTMLSelectElement;
+
+beforeEach(() => {
+ window.localStorage.clear();
+ document.documentElement.removeAttribute('data-theme');
+ authorization.capabilities.can_manage_instance = true;
+ apiFetch.mockReset();
+ handedOut.length = 0;
+ i18n = makeI18n();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('General settings — language through the real ApiProvider', () => {
+ it('holds one pending instance save in order across the locale, the api handed out, and a remount', async () => {
+ const server = instanceServer();
+ const user = userEvent.setup();
+ const view = renderApp();
+ const beforeAnyPick = new Set(handedOut).size;
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await waitFor(() => expect(screen.getByText(zh.settings.general.title)).toBeTruthy());
+
+ // The write is on the wire and unanswered, and the interface is already
+ // Chinese — so the provider has re-memoized and the page is holding an api
+ // it did not have when the pick was made.
+ expect(server.sent()).toEqual(['zh']);
+ expect(new Set(handedOut).size).toBeGreaterThan(beforeAnyPick);
+
+ view.leave();
+ view.comeBack();
+
+ await user.selectOptions(languageSelect(), 'en');
+ await waitFor(() => expect(screen.getByText(en.settings.general.title)).toBeTruthy());
+
+ // Queued behind the first, not sent beside it: two writes in flight would
+ // let the older one land last and leave the instance on a language the user
+ // has already moved off.
+ expect(server.sent()).toEqual(['zh']);
+
+ await act(async () => { server.inFlight[0].answer(); });
+ await waitFor(() => expect(server.sent()).toEqual(['zh', 'en']));
+ await act(async () => { server.inFlight[1].answer(); });
+
+ await waitFor(() => expect(server.stored.language).toBe('en'));
+ expect(languageSelect().value).toBe('en');
+ });
+});
diff --git a/ui/src/components/settings/SettingsGeneralPage.test.tsx b/ui/src/components/settings/SettingsGeneralPage.test.tsx
new file mode 100644
index 000000000..adf604531
--- /dev/null
+++ b/ui/src/components/settings/SettingsGeneralPage.test.tsx
@@ -0,0 +1,546 @@
+/* @vitest-environment jsdom */
+
+import { createInstance, type i18n as I18n } from 'i18next';
+import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import type { ReactNode } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const api = vi.hoisted(() => ({ mutateConfig: vi.fn() }));
+const apiHandouts = vi.hoisted(() => [] as { t: unknown; value: unknown }[]);
+const authorization = vi.hoisted(() => ({ capabilities: { can_manage_instance: true } }));
+const media = vi.hoisted(() => ({
+ prefersLight: false,
+ listeners: new Set<() => void>(),
+}));
+vi.hoisted(() => {
+ Object.defineProperty(window, 'matchMedia', {
+ configurable: true,
+ value: (query: string) => ({
+ media: query,
+ get matches() {
+ return media.prefersLight;
+ },
+ addEventListener: (_type: string, listener: () => void) => media.listeners.add(listener),
+ removeEventListener: (_type: string, listener: () => void) => media.listeners.delete(listener),
+ }),
+ });
+});
+
+// The real ApiContext memoizes its value on `t`, so a language change is itself
+// what hands every consumer a new `mutateConfig`. Reproduced here — through the
+// real `t`, not a stand-in — because that identity is the one a language queue
+// must not be keyed on: keying on it would rebuild the queue on the very
+// operation it is meant to order.
+vi.mock('../../context/ApiContext', async () => {
+ const { useMemo } = await import('react');
+ const { useTranslation } = await import('react-i18next');
+ return {
+ useApi: () => {
+ const { t } = useTranslation();
+ return useMemo(() => {
+ const value = { mutateConfig: (...args: unknown[]) => api.mutateConfig(...args) };
+ apiHandouts.push({ t, value });
+ return value;
+ }, [t]);
+ },
+ };
+});
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => authorization,
+}));
+
+import { ThemeProvider } from '../../context/ThemeProvider';
+import { ToastProvider } from '../../context/ToastProvider';
+import en from '../../i18n/en.json';
+import zh from '../../i18n/zh.json';
+import { LanguageSwitcher } from '../LanguageSwitcher';
+import { SettingsGeneralPage } from './SettingsGeneralPage';
+
+// One per test, not one per file: the language operation is owned by the i18n
+// instance and outlives any render root, so a shared instance would carry one
+// test's pending save into the next. Two instances in the same test are how the
+// isolation between interfaces gets proved.
+const makeI18n = () => {
+ const instance = createInstance();
+ void instance.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en }, zh: { translation: zh } },
+ interpolation: { escapeValue: false },
+ });
+ return instance;
+};
+
+let i18n = makeI18n();
+
+/** Everything above the page: what the app keeps mounted while the user walks
+ * in and out of Settings, so a toast and a save can outlive the page. */
+const Shell = ({ instance, children }: { instance: I18n; children: ReactNode }) => (
+ <I18nextProvider i18n={instance}>
+ <ThemeProvider>
+ <ToastProvider>{children}</ToastProvider>
+ </ThemeProvider>
+ </I18nextProvider>
+);
+
+const renderPage = (instance: I18n = i18n) => {
+ const show = () => view.rerender(<Shell instance={instance}><SettingsGeneralPage /></Shell>);
+ const view = render(<Shell instance={instance}><SettingsGeneralPage /></Shell>);
+ return {
+ ...view,
+ /** Leaves Settings the way the app does: the page unmounts, the shell stays. */
+ leave: () => view.rerender(<Shell instance={instance}><div /></Shell>),
+ comeBack: show,
+ /** The same re-render without having left: how anything above the page,
+ * a capability among them, reaches a control that is already on screen. */
+ refresh: show,
+ };
+};
+
+/** A capability change arrives at a control by re-rendering it, so these tests
+ * never flip one without the other — otherwise a control would be asked about
+ * an authority it has not been told about yet. */
+const authorityBecomes = (canManage: boolean, refresh: () => void) => {
+ authorization.capabilities.can_manage_instance = canManage;
+ refresh();
+};
+
+const themeCard = (name: string) => screen.getByRole('radio', { name: new RegExp(name) });
+// Located by role, not by label: the label is itself translated the moment the
+// pick lands, which is part of what these tests are checking.
+const languageSelect = () => screen.getByRole('combobox') as HTMLSelectElement;
+const flip = (prefersLight: boolean) => act(() => {
+ media.prefersLight = prefersLight;
+ media.listeners.forEach((listener) => listener());
+});
+
+/** The instance as the server keeps it: whatever write landed last. */
+const persisted = { language: 'en' };
+
+/** Hands back control of when each save settles, so a race can be staged. A save
+ * reaches the instance when it settles, not when it is sent, which is the whole
+ * question these races ask. */
+const deferSaves = () => {
+ const pending: { value: unknown; resolve: () => void; reject: () => void }[] = [];
+ api.mutateConfig.mockImplementation((mutations: { value: unknown }[]) => new Promise<void>((resolve, reject) => {
+ const value = mutations[0]?.value;
+ pending.push({
+ value,
+ resolve: () => { persisted.language = String(value); resolve(); },
+ reject: () => reject(new Error('offline')),
+ });
+ }));
+ return pending;
+};
+
+const saved = () => api.mutateConfig.mock.calls.map(([mutations]) => mutations[0].value);
+
+beforeEach(async () => {
+ window.localStorage.clear();
+ document.documentElement.removeAttribute('data-theme');
+ media.prefersLight = false;
+ media.listeners.clear();
+ authorization.capabilities.can_manage_instance = true;
+ api.mutateConfig.mockReset();
+ api.mutateConfig.mockResolvedValue(undefined);
+ apiHandouts.length = 0;
+ persisted.language = 'en';
+ i18n = makeI18n();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('General settings — language', () => {
+ it('applies a pick to the interface and saves it without a Save button', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+
+ await waitFor(() => expect(screen.getByText(zh.settings.general.title)).toBeTruthy());
+ expect(api.mutateConfig).toHaveBeenCalledWith([
+ expect.objectContaining({ path: ['language'], value: 'zh' }),
+ ]);
+ expect(screen.getByText(zh.settings.general.autosaved)).toBeTruthy();
+ expect(screen.queryByRole('button', { name: /save/i })).toBeNull();
+ });
+
+ it('lets a member change their own interface language without writing instance config', async () => {
+ authorization.capabilities.can_manage_instance = false;
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+
+ await waitFor(() => expect(screen.getByText(zh.settings.general.title)).toBeTruthy());
+ expect(api.mutateConfig).not.toHaveBeenCalled();
+ });
+
+ it('says so when the instance save fails, and retries the whole pick', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[0].reject(); });
+
+ // The page promises changes save themselves, so a failure cannot be silent.
+ expect(await screen.findByText(zh.settings.general.languageSaveFailed)).toBeTruthy();
+ // The local switch stands — the pick they can see is the one they made.
+ expect(languageSelect().value).toBe('zh');
+
+ await user.click(screen.getByRole('button', { name: zh.common.retry }));
+ await waitFor(() => expect(api.mutateConfig).toHaveBeenCalledTimes(2));
+ expect(api.mutateConfig.mock.calls[1][0]).toEqual([
+ expect.objectContaining({ path: ['language'], value: 'zh' }),
+ ]);
+ });
+
+ it('settles on the last pick when they come faster than the saves', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await user.selectOptions(languageSelect(), 'en');
+ // Saves run one at a time, so the second has not been sent yet.
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+
+ await act(async () => { saves[0].reject(); });
+ await waitFor(() => expect(api.mutateConfig).toHaveBeenCalledTimes(2));
+ await act(async () => { saves[1].resolve(); });
+
+ // The instance ends on what the user actually settled on, and the failure of
+ // a language they already left is not reported at them.
+ expect(api.mutateConfig.mock.calls[1][0]).toEqual([
+ expect.objectContaining({ path: ['language'], value: 'en' }),
+ ]);
+ expect(screen.queryByText(en.settings.general.languageSaveFailed)).toBeNull();
+ expect(languageSelect().value).toBe('en');
+ });
+
+ it('holds the order when the user leaves Settings and comes back mid-save', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+
+ // The control that started the save is gone before the instance answers,
+ // and the one that replaces it is a different component with a different
+ // set of refs. The save is not.
+ view.leave();
+ view.comeBack();
+ await user.selectOptions(languageSelect(), 'en');
+
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+ await act(async () => { saves[0].resolve(); });
+ await waitFor(() => expect(api.mutateConfig).toHaveBeenCalledTimes(2));
+ await act(async () => { saves[1].resolve(); });
+
+ expect(saved()).toEqual(['zh', 'en']);
+ expect(persisted.language).toBe('en');
+ expect(languageSelect().value).toBe('en');
+ });
+
+ it('holds the order between the settings selector and the compact switcher', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ render(
+ <Shell instance={i18n}>
+ <SettingsGeneralPage />
+ <LanguageSwitcher />
+ </Shell>,
+ );
+
+ await user.selectOptions(languageSelect(), 'zh');
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+
+ // Scoped to the switcher's own list: the page's selector offers the same two
+ // languages, which is the point — two controls, one language.
+ await user.click(screen.getByRole('button', { name: zh.language.zh }));
+ await user.click(within(screen.getByRole('listbox')).getByRole('option', { name: zh.language.en }));
+
+ // Two controls, one language: the second pick queues behind the first save
+ // instead of racing it.
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+ await act(async () => { saves[0].resolve(); });
+ await waitFor(() => expect(api.mutateConfig).toHaveBeenCalledTimes(2));
+ await act(async () => { saves[1].resolve(); });
+
+ expect(saved()).toEqual(['zh', 'en']);
+ expect(persisted.language).toBe('en');
+ });
+
+ it('cannot retry a failure the user has already moved past', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[0].reject(); });
+ expect(await screen.findByText(zh.settings.general.languageSaveFailed)).toBeTruthy();
+
+ // They pick something else instead of retrying, and that one saves — from
+ // another page, so the failure's own control is gone as well.
+ view.leave();
+ view.comeBack();
+ await user.selectOptions(languageSelect(), 'en');
+ await act(async () => { saves[1].resolve(); });
+
+ await user.click(screen.getByRole('button', { name: zh.common.retry }));
+ await act(async () => {});
+
+ expect(saved()).toEqual(['zh', 'en']);
+ expect(persisted.language).toBe('en');
+ expect(languageSelect().value).toBe('en');
+ expect(screen.getByText(en.settings.general.title)).toBeTruthy();
+ });
+
+ it('cannot retry a failure whose language the user has come back to by another pick', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[0].reject(); });
+ expect(await screen.findByText(zh.settings.general.languageSaveFailed)).toBeTruthy();
+
+ await user.selectOptions(languageSelect(), 'en');
+ await act(async () => { saves[1].resolve(); });
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[2].resolve(); });
+
+ // The interface is back on the language that failed, but not because of that
+ // failure: a later pick already saved it. Retrying the old one would be a
+ // fourth write on behalf of a decision that has been superseded twice.
+ await user.click(screen.getByRole('button', { name: zh.common.retry }));
+ await act(async () => {});
+
+ expect(saved()).toEqual(['zh', 'en', 'zh']);
+ expect(persisted.language).toBe('zh');
+ });
+
+ it('does not retry a failed save from a toast that outlived every control', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[0].reject(); });
+ expect(await screen.findByText(zh.settings.general.languageSaveFailed)).toBeTruthy();
+
+ // The toast lives above Settings, so it is still there — and still offering
+ // Retry — after the page that raised it is gone.
+ view.leave();
+ await user.click(screen.getByRole('button', { name: zh.common.retry }));
+ await act(async () => {});
+
+ // Nothing on screen can answer for the user now, so nothing is written on
+ // their behalf. The pick itself is untouched: it was never the save.
+ expect(saved()).toEqual(['zh']);
+ expect(persisted.language).toBe('en');
+ view.comeBack();
+ expect(languageSelect().value).toBe('zh');
+ });
+
+ it('does not spend authority on a queued pick that the user has since lost', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ // Both picks are made as a manager, so both are instance decisions and the
+ // second is genuinely waiting in the queue when the authority goes.
+ await user.selectOptions(languageSelect(), 'zh');
+ await user.selectOptions(languageSelect(), 'en');
+ expect(saved()).toEqual(['zh']);
+
+ authorityBecomes(false, view.refresh);
+ await act(async () => { saves[0].resolve(); });
+
+ // A queued write reads the authority of the moment it runs, not of the
+ // moment it was queued; the local pick still stands either way.
+ expect(saved()).toEqual(['zh']);
+ expect(persisted.language).toBe('zh');
+ expect(languageSelect().value).toBe('en');
+ });
+
+ it('never turns a local-only pick into an instance write when the authority comes back', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ expect(saved()).toEqual(['zh']);
+
+ // Made as a member, this pick is a choice about their own interface. What it
+ // is was settled when they made it.
+ authorityBecomes(false, view.refresh);
+ await user.selectOptions(languageSelect(), 'en');
+ expect(saved()).toEqual(['zh']);
+
+ // Authority returning is not a second pick. Nothing here asked for the
+ // instance to be changed, so nothing may write it.
+ authorityBecomes(true, view.refresh);
+ await act(async () => { saves[0].resolve(); });
+
+ expect(saved()).toEqual(['zh']);
+ expect(persisted.language).toBe('zh');
+ expect(languageSelect().value).toBe('en');
+ });
+
+ it('writes nothing when a Retry is pressed after the authority is gone', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const view = renderPage();
+
+ await user.selectOptions(languageSelect(), 'zh');
+ await act(async () => { saves[0].reject(); });
+ expect(await screen.findByText(zh.settings.general.languageSaveFailed)).toBeTruthy();
+
+ authorityBecomes(false, view.refresh);
+ await user.click(screen.getByRole('button', { name: zh.common.retry }));
+
+ // The offer was made while they could still act on it; pressing it now is
+ // not authority they still have.
+ await act(async () => {});
+ expect(saved()).toEqual(['zh']);
+ expect(languageSelect().value).toBe('zh');
+ });
+
+ it('keeps two interfaces out of each other\'s queue', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ const first = renderPage();
+ const second = renderPage(makeI18n());
+
+ await user.selectOptions(within(first.container).getByRole('combobox'), 'zh');
+ await user.selectOptions(within(second.container).getByRole('combobox'), 'zh');
+
+ // Ordering is owned by the interface the language belongs to, so a second,
+ // unrelated one is not made to wait behind it.
+ expect(api.mutateConfig).toHaveBeenCalledTimes(2);
+ await act(async () => { saves[0].resolve(); saves[1].resolve(); });
+ expect(saved()).toEqual(['zh', 'zh']);
+ });
+
+ it('orders saves across the api identity the language change itself replaces', async () => {
+ const saves = deferSaves();
+ const user = userEvent.setup();
+ renderPage();
+
+ // One `t` so far. The real provider memoizes its value on it, so what this
+ // asserts is that a language change is exactly what invalidates that memo.
+ expect(new Set(apiHandouts.map((handout) => handout.t)).size).toBe(1);
+ await user.selectOptions(languageSelect(), 'zh');
+ expect(new Set(apiHandouts.map((handout) => handout.t)).size).toBe(2);
+
+ await user.selectOptions(languageSelect(), 'en');
+ expect(api.mutateConfig).toHaveBeenCalledTimes(1);
+ await act(async () => { saves[0].resolve(); });
+ await waitFor(() => expect(api.mutateConfig).toHaveBeenCalledTimes(2));
+ await act(async () => { saves[1].resolve(); });
+
+ expect(persisted.language).toBe('en');
+ });
+});
+
+describe('General settings — appearance', () => {
+ it('persists an explicit theme and stops following the system once it is chosen', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ expect(themeCard(en.settings.general.appearanceSystem).getAttribute('aria-checked')).toBe('true');
+
+ await user.click(themeCard(en.settings.general.appearanceLight));
+
+ expect(themeCard(en.settings.general.appearanceLight).getAttribute('aria-checked')).toBe('true');
+ expect(themeCard(en.settings.general.appearanceSystem).getAttribute('aria-checked')).toBe('false');
+ expect(document.documentElement.getAttribute('data-theme')).toBe('light');
+ expect(window.localStorage.getItem('vibe-remote-theme')).toBe('light');
+
+ // The OS flipping underneath must not move an explicitly chosen Light.
+ flip(false);
+ expect(document.documentElement.getAttribute('data-theme')).toBe('light');
+ expect(themeCard(en.settings.general.appearanceLight).getAttribute('aria-checked')).toBe('true');
+ });
+
+ it('follows the system while System is selected, and returns to following it', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ // System writes no data-theme at all — the stylesheet's own media query
+ // resolves it, so following the OS needs nothing recorded on the document.
+ expect(document.documentElement.getAttribute('data-theme')).toBeNull();
+
+ flip(true);
+ expect(document.documentElement.getAttribute('data-theme')).toBeNull();
+ expect(themeCard(en.settings.general.appearanceSystem).getAttribute('aria-checked')).toBe('true');
+
+ await user.click(themeCard(en.settings.general.appearanceDark));
+ expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
+
+ await user.click(themeCard(en.settings.general.appearanceSystem));
+ expect(document.documentElement.getAttribute('data-theme')).toBeNull();
+ expect(window.localStorage.getItem('vibe-remote-theme')).toBe('system');
+ });
+
+ it('is one tab stop that arrows between the three choices', async () => {
+ const user = userEvent.setup();
+ renderPage();
+
+ const system = themeCard(en.settings.general.appearanceSystem);
+ expect(system.getAttribute('tabindex')).toBe('0');
+ expect(themeCard(en.settings.general.appearanceLight).getAttribute('tabindex')).toBe('-1');
+
+ system.focus();
+ await user.keyboard('{ArrowRight}');
+ expect(document.activeElement).toBe(themeCard(en.settings.general.appearanceLight));
+ expect(document.documentElement.getAttribute('data-theme')).toBe('light');
+
+ await user.keyboard('{ArrowRight}');
+ expect(document.activeElement).toBe(themeCard(en.settings.general.appearanceDark));
+ expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
+
+ // Wraps, the way a radio group does.
+ await user.keyboard('{ArrowRight}');
+ expect(document.activeElement).toBe(themeCard(en.settings.general.appearanceSystem));
+ expect(window.localStorage.getItem('vibe-remote-theme')).toBe('system');
+
+ await user.keyboard('{End}');
+ expect(document.activeElement).toBe(themeCard(en.settings.general.appearanceDark));
+ });
+
+ it('draws each theme rather than previewing the current one', async () => {
+ const user = userEvent.setup();
+ renderPage();
+ await user.click(themeCard(en.settings.general.appearanceDark));
+
+ // Source swatches (Q8zxF1): the Light card stays light while the app is
+ // dark, and System keeps both halves instead of collapsing into the
+ // resolved theme — which is what made the source's System card unreadable.
+ const lightShell = 'rgb(244, 246, 251)';
+ const darkShell = 'rgb(8, 8, 18)';
+ const light = themeCard(en.settings.general.appearanceLight);
+ const system = themeCard(en.settings.general.appearanceSystem);
+ const dark = themeCard(en.settings.general.appearanceDark);
+
+ expect(light.querySelectorAll(`[style*="${lightShell}"]`).length).toBeGreaterThan(0);
+ expect(light.querySelectorAll(`[style*="${darkShell}"]`).length).toBe(0);
+ expect(dark.querySelectorAll(`[style*="${darkShell}"]`).length).toBeGreaterThan(0);
+ expect(dark.querySelectorAll(`[style*="${lightShell}"]`).length).toBe(0);
+ expect(system.querySelectorAll(`[style*="${lightShell}"]`).length).toBeGreaterThan(0);
+ expect(system.querySelectorAll(`[style*="${darkShell}"]`).length).toBeGreaterThan(0);
+
+ // The drawings are decoration; the label is what names the control.
+ for (const card of [light, system, dark]) {
+ expect(card.querySelector('[aria-hidden="true"]')).toBeTruthy();
+ }
+ });
+});
diff --git a/ui/src/components/settings/SettingsGeneralPage.tsx b/ui/src/components/settings/SettingsGeneralPage.tsx
new file mode 100644
index 000000000..f52f58b26
--- /dev/null
+++ b/ui/src/components/settings/SettingsGeneralPage.tsx
@@ -0,0 +1,180 @@
+import { useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Check, CircleCheck, Monitor, Moon, Sun } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import clsx from 'clsx';
+
+import { SettingsPageShell } from './SettingsPageShell';
+import { SettingsPanel } from './SettingsPrimitives';
+import { Select } from '../ui/select';
+import { useTheme } from '../../context/ThemeContext';
+import type { ThemeMode } from '../../context/ThemeContext';
+import { useLanguageSelection } from '../../lib/useLanguageSelection';
+import type { TranslationKey } from '../../i18n/types';
+
+// The 88px miniature is a drawing OF a theme, not a preview rendered IN one:
+// the Light card has to look light while the app is dark. Source Q8zxF1 builds
+// these from literal hex rather than tokens, so these are those exact values.
+const PALETTE = {
+ light: { shell: '#f4f6fb', chrome: '#ffffff', bar: '#5c6079' },
+ dark: { shell: '#080812', chrome: '#11111c', bar: '#9ba3b8' },
+} as const;
+
+const MiniatureBody: React.FC<{ tone: keyof typeof PALETTE }> = ({ tone }) => {
+ const c = PALETTE[tone];
+ return (
+ <div className="absolute inset-0 flex" style={{ background: c.shell }}>
+ <div className="flex w-[38px] shrink-0 flex-col gap-[5px] p-2" style={{ background: c.chrome }}>
+ <div className="flex items-center gap-[3px]">
+ {[0, 1, 2].map((i) => (
+ <span key={i} className="size-[4px] rounded-full" style={{ background: c.bar, opacity: 0.45 }} />
+ ))}
+ </div>
+ <div className="h-[4px] w-full rounded-sm" style={{ background: c.bar, opacity: 0.45 }} />
+ <div className="h-[4px] w-[78%] rounded-sm" style={{ background: c.bar, opacity: 0.45 }} />
+ <div className="h-[4px] w-[62%] rounded-sm" style={{ background: c.bar, opacity: 0.45 }} />
+ </div>
+ <div className="flex min-w-0 flex-1 flex-col gap-[6px] p-2.5">
+ <div className="h-[6px] w-[55%] rounded-sm" style={{ background: c.bar, opacity: 0.65 }} />
+ <div className="h-[4px] w-[85%] rounded-sm" style={{ background: c.bar, opacity: 0.35 }} />
+ <div className="h-[4px] w-[70%] rounded-sm" style={{ background: c.bar, opacity: 0.35 }} />
+ <div className="mt-auto h-[16px] w-full rounded" style={{ background: c.chrome }} />
+ </div>
+ </div>
+ );
+};
+
+/**
+ * `system` is drawn as one app split diagonally rather than as whichever theme
+ * the OS currently reports. The source renders it identically to `dark` in both
+ * boards, so "follow the system" and "dark" are told apart only by their icon;
+ * binding it to the resolved theme instead would make it identical to whichever
+ * of the other two is live. Only the representation changes — both halves use
+ * the source's own Light and Dark swatches.
+ */
+const ThemeMiniature: React.FC<{ mode: ThemeMode }> = ({ mode }) => (
+ <div aria-hidden="true" className="relative h-[88px] w-full overflow-hidden rounded-sm">
+ <MiniatureBody tone={mode === 'dark' ? 'dark' : 'light'} />
+ {mode === 'system' && (
+ <div className="absolute inset-0" style={{ clipPath: 'polygon(100% 0, 100% 100%, 0 100%)' }}>
+ <MiniatureBody tone="dark" />
+ </div>
+ )}
+ </div>
+);
+
+const THEME_CHOICES: { mode: ThemeMode; icon: LucideIcon; labelKey: TranslationKey }[] = [
+ { mode: 'system', icon: Monitor, labelKey: 'settings.general.appearanceSystem' },
+ { mode: 'light', icon: Sun, labelKey: 'settings.general.appearanceLight' },
+ { mode: 'dark', icon: Moon, labelKey: 'settings.general.appearanceDark' },
+];
+
+// design r6G6P — ordinary Settings: interface language and appearance, both
+// saved the moment they are picked. Content is fluid; the 924 column in the
+// source is what 1200 minus the 196 rail happens to leave, not a max width.
+export const SettingsGeneralPage: React.FC = () => {
+ const { t } = useTranslation();
+ const { languages, current, select } = useLanguageSelection();
+ const { mode, setMode } = useTheme();
+ const cardRefs = useRef<(HTMLButtonElement | null)[]>([]);
+
+ // A radiogroup is one tab stop that arrows through its options; three
+ // separately tabbable buttons would only look like radios.
+ const moveTo = (index: number) => {
+ const next = (index + THEME_CHOICES.length) % THEME_CHOICES.length;
+ setMode(THEME_CHOICES[next].mode);
+ cardRefs.current[next]?.focus();
+ };
+
+ const onCardKeyDown = (event: React.KeyboardEvent, index: number) => {
+ if (event.key === 'ArrowRight' || event.key === 'ArrowDown') moveTo(index + 1);
+ else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') moveTo(index - 1);
+ else if (event.key === 'Home') moveTo(0);
+ else if (event.key === 'End') moveTo(THEME_CHOICES.length - 1);
+ else return;
+ event.preventDefault();
+ };
+
+ return (
+ <SettingsPageShell
+ title={t('settings.general.title')}
+ subtitle={t('settings.general.subtitle')}
+ activeTab="general"
+ titleScale="landing"
+ >
+ <div className="flex flex-col gap-6">
+ {/* Language le5QU — label and selector are one row, no divider. */}
+ <SettingsPanel
+ variant="preference"
+ title={t('settings.general.languageTitle')}
+ description={t('settings.general.languageDescription')}
+ actions={
+ <Select
+ aria-label={t('settings.general.languageTitle')}
+ value={current.code}
+ onChange={(event) => void select(event.target.value)}
+ wrapperClassName="w-[190px] max-w-full"
+ className="h-10 rounded-[9px] border-border-strong bg-surface px-3.5 pr-9 text-[13px]"
+ >
+ {languages.map((lang) => (
+ <option key={lang.code} value={lang.code}>{lang.label}</option>
+ ))}
+ </Select>
+ }
+ />
+
+ {/* Appearance Q8zxF1 — three drawn choices, selection is real state. */}
+ <SettingsPanel
+ variant="preference"
+ title={t('settings.general.appearanceTitle')}
+ description={t('settings.general.appearanceDescription')}
+ >
+ <div
+ role="radiogroup"
+ aria-label={t('settings.general.appearanceTitle')}
+ className="grid grid-cols-1 gap-3.5 sm:grid-cols-3"
+ >
+ {THEME_CHOICES.map(({ mode: choice, icon: Icon, labelKey }, index) => {
+ const selected = mode === choice;
+ return (
+ <button
+ key={choice}
+ ref={(node) => { cardRefs.current[index] = node; }}
+ type="button"
+ role="radio"
+ aria-checked={selected}
+ tabIndex={selected ? 0 : -1}
+ onClick={() => setMode(choice)}
+ onKeyDown={(event) => onCardKeyDown(event, index)}
+ className={clsx(
+ 'flex flex-col gap-2.5 rounded-xl text-left transition-colors',
+ // The selected border is 2px in the source; padding absorbs
+ // the extra pixel so picking a card never nudges the row.
+ selected
+ ? 'border-2 border-mint bg-mint-soft p-[9px]'
+ : 'border border-border-strong bg-surface p-2.5 hover:bg-foreground/[0.03]',
+ )}
+ >
+ <ThemeMiniature mode={choice} />
+ <span className="flex items-center gap-2">
+ <Icon className={clsx('size-3.5 shrink-0', selected ? 'text-mint-ink' : 'text-muted')} />
+ <span className={clsx('flex-1 text-[12px] font-medium', selected ? 'text-foreground' : 'text-muted')}>
+ {t(labelKey)}
+ </span>
+ {selected && <CircleCheck className="size-3.5 shrink-0 text-mint-ink" />}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </SettingsPanel>
+
+ {/* i3LvLl — the autosave contract, stated once for the whole page. */}
+ <div className="flex items-center gap-2 text-[12px] text-muted">
+ <Check className="size-[15px] shrink-0 text-mint-ink" />
+ <span>{t('settings.general.autosaved')}</span>
+ </div>
+ </div>
+ </SettingsPageShell>
+ );
+};
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index 847b595ad..e1d7cd51d 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -84,6 +84,7 @@ const renderLayout = (entry: SettingsTestEntry) => render(
<MemoryRouter initialEntries={[entry]}>
<Routes>
<Route path="/settings" element={<SettingsLayoutHarness />}>
+ <Route path="general" element={<div>general-body</div>} />
<Route path="backends" element={<div>backends-body</div>} />
<Route path="backends/claude" element={<div>claude-body</div>} />
<Route path="models" element={<div>models-body</div>} />
@@ -93,6 +94,7 @@ const renderLayout = (entry: SettingsTestEntry) => render(
<Route path="platforms" element={<div>platforms-body</div>} />
<Route path="platforms/users" element={<div>users-body</div>} />
<Route path="platforms/groups" element={<div>groups-body</div>} />
+ <Route path="remote-access" element={<div>remote-access-body</div>} />
</Route>
<Route path="/chat/:sessionId" element={<div>chat-body</div>} />
</Routes>
@@ -160,7 +162,12 @@ describe('SettingsLayout', () => {
expect(routePane?.className).toContain('overflow-y-auto');
expect(navigation.className).not.toContain('overflow-y-auto');
- expect(navigation.firstElementChild?.className).toContain('overflow-y-auto');
+ // The return row is pinned above the scrolling section list, so the way out
+ // of Settings never scrolls away from the top of the rail.
+ const returnRow = navigation.firstElementChild;
+ expect(returnRow?.getAttribute('aria-label')).toBe('settings.backToApp');
+ expect(returnRow?.className).not.toContain('overflow-y-auto');
+ expect(navigation.querySelector('.overflow-y-auto')).toBeTruthy();
expect(shell?.className).toContain('h-full');
expect(shell?.className).toContain('min-h-0');
expect(shell?.className).toContain('overflow-hidden');
@@ -181,6 +188,22 @@ describe('SettingsLayout', () => {
},
);
+ // The source draws General as content that simply fills whatever the rail
+ // leaves, so the shared reading column would re-introduce a fixed width the
+ // design does not have. It opts out the way Model Hub already does — without
+ // Model Hub's `min-h-full`, which is a full-height pane, not a width.
+ it.each(['/settings/general', '/settings/general/'])(
+ 'lets General fill the route pane at %s',
+ (path) => {
+ renderLayout(path);
+
+ const generalFrame = screen.getByText('general-body').parentElement;
+ expect(generalFrame?.className).not.toContain('mx-auto');
+ expect(generalFrame?.className).not.toContain('max-w-[1180px]');
+ expect(generalFrame?.className).not.toContain('min-h-full');
+ },
+ );
+
it('keeps standard settings pages constrained', () => {
renderLayout('/settings/replies');
@@ -228,8 +251,8 @@ describe('SettingsLayout', () => {
await waitFor(() => {
expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
});
- expect(screen.getByRole('link', { name: 'nav.channels' }).className).toContain('bg-mint/[0.09]');
- expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).className).not.toContain('bg-mint/[0.09]');
+ expect(screen.getByRole('link', { name: 'nav.channels' }).className).toContain('bg-mint-soft');
+ expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).className).not.toContain('bg-mint-soft');
expect(screen.getByRole('link', { name: 'settings.sections.platformConnections' }).getAttribute('aria-current')).toBeNull();
});
@@ -294,11 +317,16 @@ describe('SettingsLayout', () => {
expect(screen.getByRole('button', { name: 'nav.messagingPlatforms' }).getAttribute('aria-expanded')).toBe('true');
});
- it('keeps language, theme, and account preferences in the Settings rail', () => {
+ it('moves language and appearance into General and keeps the account menu in the rail', () => {
renderLayout('/settings/replies');
- expect(screen.getByTestId('language-switcher').getAttribute('data-open-upward')).toBe('true');
- expect(screen.getByTestId('theme-toggle')).toBeTruthy();
+ // Language and appearance are a Settings SECTION now, reachable and
+ // linkable like every other one — not two icons wedged into the rail
+ // footer where nothing else about the interface lives.
+ expect(screen.queryByTestId('language-switcher')).toBeNull();
+ expect(screen.queryByTestId('theme-toggle')).toBeNull();
+ expect(screen.getByRole('link', { name: 'settings.sections.general' }).getAttribute('href'))
+ .toBe('/settings/general');
expect(screen.getByTestId('account-menu').getAttribute('data-open-upward')).toBe('true');
});
@@ -315,16 +343,58 @@ describe('SettingsLayout', () => {
expect(api.getConfig).not.toHaveBeenCalled();
});
- it('selects the landing section when a mobile root viewport becomes desktop', async () => {
+ it('opens General from /settings even after a remembered Backends visit', async () => {
+ // Ordinary Settings is a destination, not a resume: whatever the last visit
+ // was, the landing is the section every role can read.
+ window.localStorage.setItem('avibe.settings.last-path', '/settings/backends');
+ media.matches = true;
+ renderLayout('/settings');
+
+ expect(await screen.findByText('general-body')).toBeTruthy();
+ expect(screen.queryByText('backends-body')).toBeNull();
+ });
+
+ it.each([
+ ['/settings/backends', 'backends-body'],
+ ['/settings/platforms', 'platforms-body'],
+ ['/settings/remote-access', 'remote-access-body'],
+ ])('keeps the explicit deep link %s authoritative over the landing page', (path, body) => {
+ media.matches = true;
+ window.localStorage.setItem('avibe.settings.last-path', '/settings/service');
+ renderLayout(path);
+
+ expect(screen.getByText(body)).toBeTruthy();
+ expect(screen.queryByText('general-body')).toBeNull();
+ });
+
+ it('keeps the narrow root as the explicit section list a detail page can return to', async () => {
+ const user = userEvent.setup();
+ media.matches = false;
+ renderLayout('/settings');
+
+ // This root is the phone's section-NAVIGATION screen, not its ordinary way
+ // in: the dock chip goes straight to General at every width (see
+ // MobileDockDrawer). Redirecting the root as well would leave General's back
+ // row pointing at a screen that bounces the user back to General.
+ const general = screen.getByRole('link', { name: 'settings.sections.general' });
+ expect(general.getAttribute('href')).toBe('/settings/general');
+ expect(screen.queryByText('general-body')).toBeNull();
+
+ await user.click(general);
+ expect(await screen.findByText('general-body')).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'settings.backToSections' }).getAttribute('href')).toBe('/settings');
+ });
+
+ it('selects General when a mobile root viewport becomes desktop', async () => {
renderLayout('/settings');
- expect(screen.queryByText('replies-body')).toBeNull();
+ expect(screen.queryByText('general-body')).toBeNull();
act(() => {
media.matches = true;
media.listeners.forEach((listener) => listener({ matches: true } as MediaQueryListEvent));
});
- await waitFor(() => expect(screen.getByText('replies-body')).toBeTruthy());
+ await waitFor(() => expect(screen.getByText('general-body')).toBeTruthy());
});
it('refreshes Memory visibility after its settings change', async () => {
@@ -356,6 +426,48 @@ describe('SettingsLayout', () => {
expect(back.className).toContain('size-11');
});
+ it('unwinds a retained overlay from the phone root instead of pushing a second home', async () => {
+ // A phone that opened Settings over a surface worth keeping now has the same
+ // origin the desktop controls close through, so its root back has to close
+ // rather than navigate: pushing '/' would leave the whole Settings chain one
+ // Back away from the user.
+ const user = userEvent.setup();
+ const origin: Location = {
+ pathname: '/chat/ses_7',
+ search: '?message=m1',
+ hash: '#tail',
+ state: { source: 'search' },
+ key: 'chat-origin',
+ };
+
+ renderLayout({ pathname: '/settings', state: settingsOverlayOpenState(origin) });
+
+ const back = screen.getByRole('button', { name: 'settings.backToWorkbench' });
+ expect(back.className).toContain('size-11');
+ expect(back.className).toContain('md:hidden');
+ await user.click(back);
+ expect(await screen.findByText('chat-body')).toBeTruthy();
+ });
+
+ it('keeps a retained origin on ordinary links inside settings', () => {
+ // Only the root action leaves; a section's back still steps one level up the
+ // rail, and does it as a link so the origin rides along with the push.
+ renderLayout({
+ pathname: '/settings/replies',
+ state: settingsOverlayOpenState({
+ pathname: '/chat/ses_7',
+ search: '',
+ hash: '',
+ state: null,
+ key: 'chat-origin',
+ } as Location),
+ });
+
+ const back = screen.getByRole('link', { name: 'settings.backToSections' });
+ expect(back.getAttribute('href')).toBe('/settings');
+ expect(screen.queryByRole('button', { name: 'settings.backToSections' })).toBeNull();
+ });
+
it('shows the current version with a safe-area-aware mobile popup', async () => {
const user = userEvent.setup();
renderLayout('/settings');
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index 1872d76ed..6be60af7a 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -2,7 +2,7 @@ import type { TranslationKey } from '@/i18n/types';
import React, { useEffect, useMemo, useState } from 'react';
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
- Bot,
+ ArrowLeft,
Brain,
ChevronDown,
ChevronLeft,
@@ -10,14 +10,16 @@ import {
Globe,
Hash,
Keyboard,
+ Layers,
MessageCircle,
MessageSquare,
Package,
- PlugZap,
+ Plug,
Server,
Settings,
ShieldCheck,
Stethoscope,
+ Unplug,
X,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
@@ -26,7 +28,7 @@ import clsx from 'clsx';
import { useApi } from '@/context/ApiContext';
import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';
import { memoryNavShouldBeVisible } from '@/lib/memorySettings';
-import { rememberSettingsPath, settingsLandingPath } from '@/lib/adminNavigation';
+import { SETTINGS_LANDING_PATH } from '@/lib/adminNavigation';
import { getEnabledPlatforms, platformSupportsChannels } from '@/lib/platforms';
import { useIsDesktop } from '@/lib/useIsDesktop';
import {
@@ -34,8 +36,6 @@ import {
useSettingsOverlayContext,
} from '@/lib/settingsOverlay';
import { AccountMenu } from '../AccountMenu';
-import { LanguageSwitcher } from '../LanguageSwitcher';
-import { ThemeToggle } from '../ThemeToggle';
import { VersionBadge } from '../VersionBadge';
import { modelHubEnabledFromConfig } from './models/featureFlags';
@@ -51,15 +51,21 @@ type SettingsItem = {
};
type SettingsGroup = {
- labelKey: TranslationKey;
+ /** Omitted for the landing group, which needs no header above the first row. */
+ labelKey?: TranslationKey;
items: SettingsItem[];
};
const SETTINGS_GROUPS: SettingsGroup[] = [
+ {
+ items: [
+ { path: SETTINGS_LANDING_PATH, labelKey: 'settings.sections.general', icon: Settings },
+ ],
+ },
{
labelKey: 'settings.groups.agents',
items: [
- { path: '/settings/backends', labelKey: 'settings.sections.backends', icon: Bot, ownerOnly: true },
+ { path: '/settings/backends', labelKey: 'settings.sections.backends', icon: Server, ownerOnly: true },
{ path: '/settings/models', labelKey: 'settings.sections.models', icon: Cpu, ownerOnly: true, feature: 'models' },
{ path: '/settings/memory', labelKey: 'settings.sections.memory', icon: Brain, ownerOnly: true, feature: 'memory' },
{ path: '/settings/replies', labelKey: 'settings.sections.replies', icon: MessageSquare },
@@ -71,14 +77,14 @@ const SETTINGS_GROUPS: SettingsGroup[] = [
{
path: '/settings/platforms',
labelKey: 'nav.messagingPlatforms',
- icon: PlugZap,
+ icon: Plug,
ownerOnly: true,
defaultOpen: true,
children: [
{
path: '/settings/platforms',
labelKey: 'settings.sections.platformConnections',
- icon: PlugZap,
+ icon: Unplug,
exact: true,
},
{ path: '/settings/platforms/users', labelKey: 'nav.users', icon: MessageCircle },
@@ -97,7 +103,7 @@ const SETTINGS_GROUPS: SettingsGroup[] = [
labelKey: 'settings.groups.system',
items: [
{ path: '/settings/shortcuts', labelKey: 'settings.sections.shortcuts', icon: Keyboard },
- { path: '/settings/service', labelKey: 'settings.sections.service', icon: Server, ownerOnly: true },
+ { path: '/settings/service', labelKey: 'settings.sections.service', icon: Layers, ownerOnly: true },
{ path: '/settings/dependencies', labelKey: 'settings.sections.dependencies', icon: Package, ownerOnly: true },
{ path: '/settings/diagnostics', labelKey: 'settings.sections.diagnostics', icon: Stethoscope, ownerOnly: true },
{ path: '/settings/access', labelKey: 'settings.sections.access', icon: ShieldCheck },
@@ -125,15 +131,21 @@ const SettingsNavLink: React.FC<{ item: SettingsItem }> = ({ item }) => {
end={item.exact}
title={t(item.labelKey)}
className={clsx(
- 'flex min-h-11 items-center gap-2 rounded-lg px-2 py-2 text-[12.5px] font-medium transition-colors md:min-h-0',
+ 'flex min-h-11 items-center gap-2 rounded-[9px] px-2.5 py-2 text-[12.5px] transition-colors md:min-h-[34px] md:py-0',
'md:justify-center lg:justify-start',
active
- ? 'bg-mint/[0.09] text-foreground'
- : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
+ ? 'bg-mint-soft font-semibold text-foreground'
+ : 'font-medium text-muted hover:bg-foreground/[0.04] hover:text-foreground',
)}
>
- <Icon className={clsx('size-4 shrink-0', active ? 'text-mint-ink' : 'text-muted')} />
- <span className="truncate md:hidden lg:block">{t(item.labelKey)}</span>
+ <Icon className={clsx('size-3.5 shrink-0', active ? 'text-mint-ink' : 'text-muted')} />
+ {/* The rail is a fixed 196 and a section name is not optional detail: an
+ ellipsis here hides which of two neighbouring pages a row leads to
+ ("Messaging Platforms" / "Platform Connections" both cut to "Platform…"
+ in English). Wrapping keeps every label readable in any language, and
+ two lines at this size still fit the row's min height, so nothing moves
+ for the labels that already fitted. */}
+ <span className="min-w-0 leading-[1.3] break-words md:hidden lg:block">{t(item.labelKey)}</span>
</NavLink>
);
};
@@ -155,15 +167,15 @@ const SettingsNavGroup: React.FC<{ item: SettingsItem }> = ({ item }) => {
aria-expanded={open}
onClick={() => setManualOpen(!open)}
className={clsx(
- 'flex min-h-11 w-full items-center gap-2 rounded-lg px-2 py-2 text-[12.5px] font-medium transition-colors md:min-h-0',
+ 'flex min-h-11 w-full items-center gap-2 rounded-[9px] px-2.5 py-2 text-[12.5px] font-medium transition-colors md:min-h-[34px] md:py-0',
'md:justify-center lg:justify-start',
childActive
? 'text-foreground'
: 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
)}
>
- <Icon className={clsx('size-4 shrink-0', childActive ? 'text-mint-ink' : 'text-muted')} />
- <span className="min-w-0 flex-1 truncate text-left md:hidden lg:block">{t(item.labelKey)}</span>
+ <Icon className={clsx('size-3.5 shrink-0', childActive ? 'text-mint-ink' : 'text-muted')} />
+ <span className="min-w-0 flex-1 leading-[1.3] break-words text-left md:hidden lg:block">{t(item.labelKey)}</span>
<ChevronDown
className={clsx(
'size-3.5 shrink-0 text-muted transition-transform md:hidden lg:block',
@@ -183,6 +195,38 @@ const SettingsNavGroup: React.FC<{ item: SettingsItem }> = ({ item }) => {
const SettingsNavItem: React.FC<{ item: SettingsItem }> = ({ item }) =>
item.children?.length ? <SettingsNavGroup item={item} /> : <SettingsNavLink item={item} />;
+/**
+ * Leaving Settings has one meaning regardless of the control that triggers it:
+ * an overlay returns to the surface it covered, a direct visit goes to the
+ * Workbench. Both paths keep the originating project, session and unsent draft.
+ */
+const ReturnToApp: React.FC<{
+ className?: string;
+ 'aria-label'?: string;
+ children: React.ReactNode;
+}> = ({ className, 'aria-label': ariaLabel, children }) => {
+ const navigate = useNavigate();
+ const overlayOrigin = useSettingsOverlayContext();
+
+ if (!overlayOrigin) {
+ return (
+ <NavLink to="/" aria-label={ariaLabel} className={className}>
+ {children}
+ </NavLink>
+ );
+ }
+ return (
+ <button
+ type="button"
+ aria-label={ariaLabel}
+ onClick={() => closeSettingsOverlay(navigate, overlayOrigin)}
+ className={className}
+ >
+ {children}
+ </button>
+ );
+};
+
export const SettingsLayout: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -190,12 +234,17 @@ export const SettingsLayout: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const isDesktop = useIsDesktop();
- const overlayOrigin = useSettingsOverlayContext();
const [modelHubVisible, setModelHubVisible] = useState(false);
const [memoryVisible, setMemoryVisible] = useState(false);
const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);
const atRoot = location.pathname === '/settings' || location.pathname === '/settings/';
const isModelHub = pathMatches(location.pathname, '/settings/models');
+ // The shared `max-w-[1180px]` is a reading column for pages made of prose and
+ // form rows. General is not one: its source (r6G6P) draws content that simply
+ // fills whatever the rail leaves, so capping it would re-introduce a fixed
+ // column the design does not have. Opting one route out — the way Model Hub
+ // already does — leaves every other Settings page exactly as it was.
+ const isFluidContent = isModelHub || pathMatches(location.pathname, SETTINGS_LANDING_PATH);
useEffect(() => {
if (!capabilities.can_manage_instance) return;
@@ -285,6 +334,10 @@ export const SettingsLayout: React.FC = () => {
: activeSection.path;
}, [activeTrail, atRoot, location.pathname]);
+ // One class string for both branches below, so the touch target and the
+ // chevron cannot drift apart depending on where the control points.
+ const mobileBackClassName = '-ml-2 grid size-11 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:hidden';
+
const mobileBackLabel = mobileBackTarget === '/'
? t('settings.backToWorkbench')
: mobileBackTarget === '/settings'
@@ -293,25 +346,31 @@ export const SettingsLayout: React.FC = () => {
section: t(activeTrail.at(-1)?.labelKey ?? 'nav.settings'),
});
- useEffect(() => {
- if (atRoot || !location.pathname.startsWith('/settings/')) return;
- rememberSettingsPath(location.pathname);
- }, [atRoot, location.pathname]);
-
useEffect(() => {
if (!atRoot || !isDesktop) return;
- navigate(settingsLandingPath(capabilities.can_manage_instance), { replace: true });
- }, [atRoot, capabilities.can_manage_instance, isDesktop, navigate]);
+ navigate(SETTINGS_LANDING_PATH, { replace: true });
+ }, [atRoot, isDesktop, navigate]);
return (
<div className="flex h-full min-h-0 flex-col overflow-hidden bg-background md:h-[var(--app-shell-h)]">
<header className="flex h-[calc(3.5rem+env(safe-area-inset-top))] shrink-0 items-center justify-between border-b border-border bg-surface px-4 pt-[env(safe-area-inset-top)] md:h-14 md:pt-0">
<div className="flex min-w-0 items-center gap-2 text-[13px] font-semibold text-foreground">
- {mobileBackTarget && (
+ {/* Leaving Settings for the Workbench is the same action whichever
+ control triggers it, so the phone's root back goes through
+ ReturnToApp like the desktop close and rail row do: with a retained
+ origin it unwinds the Settings entries it opened over, instead of
+ pushing a second home in front of them and leaving the whole chain
+ one Back away. Every destination inside Settings stays an ordinary
+ link, and a direct visit still gets one. */}
+ {mobileBackTarget === '/' ? (
+ <ReturnToApp aria-label={mobileBackLabel} className={mobileBackClassName}>
+ <ChevronLeft className="size-5" />
+ </ReturnToApp>
+ ) : (
<NavLink
to={mobileBackTarget}
aria-label={mobileBackLabel}
- className="-ml-2 grid size-11 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:hidden"
+ className={mobileBackClassName}
>
<ChevronLeft className="size-5" />
</NavLink>
@@ -333,24 +392,12 @@ export const SettingsLayout: React.FC = () => {
<VersionBadge />
</div>
)}
- {overlayOrigin ? (
- <button
- type="button"
- onClick={() => closeSettingsOverlay(navigate, overlayOrigin)}
- aria-label={t('settings.close')}
- className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"
- >
- <X className="size-4" />
- </button>
- ) : (
- <NavLink
- to="/"
- aria-label={t('settings.close')}
- className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"
- >
- <X className="size-4" />
- </NavLink>
- )}
+ <ReturnToApp
+ aria-label={t('settings.close')}
+ className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"
+ >
+ <X className="size-4" />
+ </ReturnToApp>
</div>
</header>
@@ -363,12 +410,22 @@ export const SettingsLayout: React.FC = () => {
atRoot ? 'flex' : 'hidden md:flex',
)}
>
+ <ReturnToApp
+ aria-label={t('settings.backToApp')}
+ className="mb-2 hidden min-h-10 shrink-0 items-center gap-2.5 rounded-[9px] px-2.5 text-[14px] text-foreground transition-colors hover:bg-foreground/[0.05] md:flex md:justify-center lg:justify-start"
+ >
+ <ArrowLeft className="size-[17px] shrink-0" />
+ <span className="truncate md:hidden lg:block">{t('settings.backToApp')}</span>
+ </ReturnToApp>
+
<div className="min-h-0 flex-1 overflow-y-auto">
{visibleGroups.map((group) => (
- <div key={group.labelKey} className="mb-2 last:mb-0">
- <div className="px-2 pb-1 pt-1 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted md:hidden lg:block">
- {t(group.labelKey)}
- </div>
+ <div key={group.labelKey ?? group.items[0]?.path} className="mb-2 last:mb-0">
+ {group.labelKey && (
+ <div className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted md:hidden lg:block">
+ {t(group.labelKey)}
+ </div>
+ )}
<div className="flex flex-col gap-0.5">
{/* A manual disclosure choice belongs to this route visit only. */}
{group.items.map((item) => (
@@ -382,9 +439,7 @@ export const SettingsLayout: React.FC = () => {
))}
</div>
- <div className="mt-3 flex shrink-0 items-center gap-2 border-t border-border px-2 pt-3 md:flex-col lg:flex-row">
- <LanguageSwitcher openUpward />
- <ThemeToggle />
+ <div className="mt-3 flex shrink-0 items-center gap-2 border-t border-border px-2 pt-3">
<AccountMenu openUpward />
</div>
</nav>
@@ -394,7 +449,8 @@ export const SettingsLayout: React.FC = () => {
key={location.pathname}
className={clsx(
'w-full px-4 pb-[calc(1.25rem+env(safe-area-inset-bottom))] pt-5 motion-safe:animate-in motion-safe:slide-in-from-right-4 motion-safe:duration-200 md:px-6 md:pb-7 md:pt-7 md:animate-none lg:px-8',
- isModelHub ? 'min-h-full' : 'mx-auto max-w-[1180px]',
+ isModelHub && 'min-h-full',
+ !isFluidContent && 'mx-auto max-w-[1180px]',
)}
>
<Outlet />
diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
index 44f791841..3d8692d94 100644
--- a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
@@ -6,6 +6,7 @@ import { useTranslation } from 'react-i18next';
import { RouteSurfaceActivityBoundary } from '@/components/RouteSurfaceActivityBoundary';
import { Dialog, DialogSurfaceContent, DialogTitle } from '@/components/ui/dialog';
+import { useSetupHandoffDeparture } from '@/components/workbench/backendReadiness';
import {
closeSettingsOverlay,
isSettingsEntryPath,
@@ -29,6 +30,14 @@ export const SettingsOverlayRouteSurface = ({
const navigate = useNavigate();
const origin = useSettingsOverlayOrigin(location);
const settingsSurfaceOpen = isSettingsEntryPath(location.pathname) && origin !== null;
+ // The route this surface renders behind any overlay — the retained origin
+ // while Settings is open, the foreground route otherwise.
+ const backgroundLocation = settingsSurfaceOpen ? origin.location : location;
+ // Which route is rendered here is also the only thing that can tell a real
+ // departure from the home apart from the route guard unmounting and remounting
+ // it in place, so the setup handoff reads it from here rather than guessing
+ // from a component's lifecycle.
+ useSetupHandoffDeparture(backgroundLocation.pathname);
const replaceBackground = useCallback<Navigator['replace']>((to, state) => {
if (!origin) return;
const path = resolvePath(to, origin.location.pathname);
@@ -57,7 +66,7 @@ export const SettingsOverlayRouteSurface = ({
active={!settingsSurfaceOpen}
inactiveReplace={replaceBackground}
>
- <Routes location={settingsSurfaceOpen ? origin.location : location}>
+ <Routes location={backgroundLocation}>
{children}
<Route path="*" element={fallbackElement} />
</Routes>
@@ -74,6 +83,18 @@ export const SettingsOverlayRouteSurface = ({
<SettingsOverlayOriginContext.Provider value={origin}>
<DialogSurfaceContent
data-settings-overlay="true"
+ // The overlay covers the work area and stops at the shell sidebar,
+ // which is what keeps the origin project/session visible behind it.
+ // This overrides the primitive's historical 240 default with
+ // AppShell's actual `w-[248px]`; it is asserted against the
+ // sidebar's measured edge rather than restated as a shared token,
+ // so the two cannot drift apart unnoticed.
+ //
+ // Below md the surface is the whole viewport, so the primitive's
+ // left border would draw a hairline down the screen edge and make
+ // Settings-from-home look different from a direct Settings link.
+ // There is no sidebar to divide from until the offset applies.
+ className="border-l-0 md:left-[248px] md:border-l"
aria-describedby={undefined}
onInteractOutside={(event) => {
const target = event.target;
diff --git a/ui/src/components/settings/SettingsPageShell.test.tsx b/ui/src/components/settings/SettingsPageShell.test.tsx
index 21fd75638..dde9d266f 100644
--- a/ui/src/components/settings/SettingsPageShell.test.tsx
+++ b/ui/src/components/settings/SettingsPageShell.test.tsx
@@ -23,4 +23,33 @@ describe('SettingsPageShell', () => {
expect(screen.getByText('Backends').parentElement?.className).toContain('hidden');
expect(screen.getByText('Backends').parentElement?.className).toContain('md:block');
});
+
+ // The landing block is opt-in precisely so the fifteen sections that never ask
+ // for it keep the heading they shipped with.
+ it('keeps the section heading for callers that do not ask for the landing block', () => {
+ render(
+ <SettingsPageShell activeTab="service" title="Service" subtitle="Run state">
+ <div>body</div>
+ </SettingsPageShell>,
+ );
+
+ const heading = screen.getByRole('heading', { name: 'Service' });
+ expect(heading.className).toContain('text-[28px]');
+ expect(heading.className).toContain('font-bold');
+ expect(screen.getByText('Run state').className).toContain('text-[14px]');
+ });
+
+ it('draws the source landing block when asked for it', () => {
+ render(
+ <SettingsPageShell activeTab="general" title="General" subtitle="Language and appearance" titleScale="landing">
+ <div>body</div>
+ </SettingsPageShell>,
+ );
+
+ // design.pen Ozmrf: 27/600 over a 13 muted line.
+ const heading = screen.getByRole('heading', { name: 'General' });
+ expect(heading.className).toContain('text-[27px]');
+ expect(heading.className).toContain('font-semibold');
+ expect(screen.getByText('Language and appearance').className).toContain('text-[13px]');
+ });
});
diff --git a/ui/src/components/settings/SettingsPageShell.tsx b/ui/src/components/settings/SettingsPageShell.tsx
index e934eadcc..de80c5ded 100644
--- a/ui/src/components/settings/SettingsPageShell.tsx
+++ b/ui/src/components/settings/SettingsPageShell.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import clsx from 'clsx';
type SettingsTab = string;
@@ -9,6 +10,13 @@ export type SettingsPageShellProps = {
breadcrumb?: React.ReactNode;
actions?: React.ReactNode;
children: React.ReactNode;
+ /**
+ * `section` (default) is the 28/700 heading every Settings section has
+ * shipped with. `landing` is the quieter block the source draws for the
+ * Settings landing (design.pen `Ozmrf`: 27/600 over a 13 `$--muted` line).
+ * Opt-in, so adding it restyles no sibling section.
+ */
+ titleScale?: 'section' | 'landing';
};
export const SettingsPageShell: React.FC<SettingsPageShellProps> = ({
@@ -18,15 +26,26 @@ export const SettingsPageShell: React.FC<SettingsPageShellProps> = ({
breadcrumb,
actions,
children,
+ titleScale = 'section',
}) => {
void activeTab;
+ const landing = titleScale === 'landing';
return (
<div className="flex flex-col gap-6">
<div className="flex flex-wrap items-end justify-between gap-4">
<div className="flex flex-col gap-1.5">
- <h1 className="text-[28px] font-bold leading-tight tracking-[-0.4px] text-foreground">{title}</h1>
- <p className="max-w-3xl text-[14px] leading-[1.55] text-muted">{subtitle}</p>
+ <h1
+ className={clsx(
+ 'leading-tight tracking-[-0.4px] text-foreground',
+ landing ? 'text-[27px] font-semibold' : 'text-[28px] font-bold',
+ )}
+ >
+ {title}
+ </h1>
+ <p className={clsx('max-w-3xl leading-[1.55] text-muted', landing ? 'text-[13px]' : 'text-[14px]')}>
+ {subtitle}
+ </p>
</div>
{actions && <div className="shrink-0">{actions}</div>}
</div>
diff --git a/ui/src/components/settings/SettingsPrimitives.tsx b/ui/src/components/settings/SettingsPrimitives.tsx
index 24a3cea81..f65c27f32 100644
--- a/ui/src/components/settings/SettingsPrimitives.tsx
+++ b/ui/src/components/settings/SettingsPrimitives.tsx
@@ -9,8 +9,15 @@ type SettingsPanelProps = {
title?: React.ReactNode;
description?: React.ReactNode;
actions?: React.ReactNode;
- children: React.ReactNode;
+ children?: React.ReactNode;
className?: string;
+ /**
+ * `panel` (default) is the machine-management section: a header ruled off from
+ * a list of rows. `preference` is the quieter single-preference card used by
+ * ordinary Settings (design.pen le5QU / Q8zxF1) — surface-2, one 22px pad, and
+ * no internal divider, because its header and its control are one statement.
+ */
+ variant?: 'panel' | 'preference';
};
// Mirrors design.pen O8BNR/B6qFRA (svcSec1 / msgSec1):
@@ -22,27 +29,56 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({
actions,
children,
className,
-}) => (
- <section
- className={clsx(
- 'flex flex-col overflow-hidden rounded-xl border border-border bg-background',
- className
- )}
- >
- {(title || description || actions) && (
- <div className="flex items-start justify-between gap-4 border-b border-border px-5 py-4">
- <div className="flex min-w-0 flex-col gap-1">
- {title && <h2 className="text-[14px] font-semibold text-foreground">{title}</h2>}
- {description && (
- <p className="max-w-2xl text-[12px] leading-relaxed text-muted">{description}</p>
- )}
- </div>
- {actions && <div className="shrink-0">{actions}</div>}
+ variant = 'panel',
+}) => {
+ const header = (title || description || actions) && (
+ <div
+ className={clsx(
+ 'flex justify-between',
+ variant === 'preference'
+ // The source has no narrow frame, so this is an implementation
+ // decision: on a phone a 190-wide control beside the description
+ // leaves the text a column barely wider than one word, so the control
+ // drops under the label instead of squeezing it.
+ ? 'flex-col items-start gap-3 sm:flex-row sm:items-center sm:gap-[18px]'
+ : 'items-start gap-4 border-b border-border px-5 py-4'
+ )}
+ >
+ <div className="flex min-w-0 flex-col gap-1">
+ {title && <h2 className="text-[14px] font-semibold text-foreground">{title}</h2>}
+ {description && (
+ <p className="max-w-2xl text-[12px] leading-relaxed text-muted">{description}</p>
+ )}
</div>
- )}
- {children}
- </section>
-);
+ {actions && <div className="shrink-0">{actions}</div>}
+ </div>
+ );
+
+ // radius 12 (`rounded-lg` here), not the 16 the `panel` variant renders:
+ // le5QU and Q8zxF1 both draw this card at 12.
+ if (variant === 'preference') {
+ return (
+ <section className={clsx('rounded-lg border border-border bg-surface-2', className)}>
+ <div className="flex flex-col gap-5 p-[22px]">
+ {header}
+ {children}
+ </div>
+ </section>
+ );
+ }
+
+ return (
+ <section
+ className={clsx(
+ 'flex flex-col overflow-hidden rounded-xl border border-border bg-background',
+ className
+ )}
+ >
+ {header}
+ {children}
+ </section>
+ );
+};
type SettingsRowProps = {
title: React.ReactNode;
diff --git a/ui/src/components/ui/dialog.tsx b/ui/src/components/ui/dialog.tsx
index 9edc70a49..3735ada9a 100644
--- a/ui/src/components/ui/dialog.tsx
+++ b/ui/src/components/ui/dialog.tsx
@@ -66,6 +66,11 @@ DialogContent.displayName = DialogPrimitive.Content.displayName;
// Route-sized modal: the transparent backdrop preserves visual context while Radix owns focus,
// outside interaction, and accessibility isolation for the foreground surface.
+//
+// The `md:left-[240px]` default is the historical offset every existing caller
+// inherits; a caller whose shell differs overrides it with its own `md:left-[…]`
+// (tailwind-merge keeps the caller's). The primitive cannot see the shell, so
+// the default is a starting point, not an authority on the sidebar's width.
export const DialogSurfaceContent = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index a97b62de6..7b6aac2e1 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -346,6 +346,11 @@ export interface ComposerProps {
disabled?: boolean;
/** Override the row container — e.g. a narrower max-width on the home canvas. */
className?: string;
+ /** Caller-owned controls (Agent + workspace pickers on the home). Supplying
+ * them moves the box to the two-row layout: input on top, then an action row
+ * carrying these on the left and Send on the right. Callers that pass nothing
+ * keep the single-row box the chat has always used. */
+ actions?: React.ReactNode;
/** When set, enables file upload + voice input scoped to this session. The
* Workbench home leaves it unset → a plain text-only composer. */
sessionId?: string;
@@ -372,6 +377,10 @@ export interface ComposerHandle {
* with a separating space when the composer is non-empty. No-op when the
* mention editor isn't active (the plain-textarea home composer). */
appendText: (text: string) => void;
+ /** Replace the whole draft from outside and focus the input with the caret at
+ * the end — the home's suggestion cards seed a starting task the user then
+ * edits. It never sends, and refuses while voice capture owns the draft. */
+ setDraft: (text: string) => void;
/** Handle the Chat page's configured voice chord. Starting may be gated by
* the page, while an active recording can always be completed. */
handleVoiceShortcut: (event: KeyboardEvent, allowStart: boolean) => boolean;
@@ -391,6 +400,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
placeholder,
disabled = false,
className,
+ actions,
sessionId,
autoFocus = false,
onSearchAgents,
@@ -418,6 +428,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
const draftAppliedRef = useRef(false);
// Blocks a same-tick double-submit before the optimistic clear re-renders.
const pendingRef = useRef(false);
+ // Set by setDraft; consumed by the layout effect that focuses after the seeded
+ // text has rendered.
+ const seedFocusRef = useRef(false);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const attachmentFilesRef = useRef(new Map<string, File>());
const [attachments, setAttachments] = useState<ComposerAttachment[]>([]);
@@ -1322,9 +1335,34 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
appendText: (text: string) => {
if (!voiceDraftLocked()) mentionRef.current?.append(text);
},
+ setDraft: (text: string) => {
+ if (voiceDraftLocked()) return;
+ valueRef.current = text;
+ setHasText(text.trim().length > 0);
+ if (useMentions) mentionRef.current?.setText(text);
+ else setValue(text);
+ onDraftChange?.(text);
+ // Focus lands in the layout effect below, once the new text is in the DOM —
+ // focusing here would put the caret at the pre-seed offset (0) instead of
+ // after the text the user is meant to edit.
+ seedFocusRef.current = true;
+ },
handleVoiceShortcut,
}));
+ useLayoutEffect(() => {
+ if (!seedFocusRef.current) return;
+ seedFocusRef.current = false;
+ if (useMentions) {
+ mentionRef.current?.focus();
+ return;
+ }
+ const el = textareaRef.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ }, [value, useMentions]);
+
useEffect(() => {
if (!busyControls) {
setStopArmed(false);
@@ -1391,70 +1429,10 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
}
};
- return (
- <div
- ref={composerRootRef}
- className={cn('mx-auto flex w-full max-w-[1080px] flex-col gap-2', className)}
- >
- {mediaEnabled && attachments.length > 0 && (
- <div className="flex flex-wrap gap-2">
- {attachments.map((att) => (
- <div
- key={att.localId}
- className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 py-1 pl-1.5 pr-1 text-[12px]"
- >
- {att.status === 'uploading' ? (
- <span className="grid size-7 place-items-center rounded text-muted">
- <Loader2 className="size-4 animate-spin" />
- </span>
- ) : att.kind === 'image' && att.url ? (
- <img src={att.url} alt="" className="size-7 rounded object-cover" />
- ) : (
- <span className="grid size-7 place-items-center rounded bg-cyan/15 text-cyan-ink">
- <Paperclip className="size-3.5" />
- </span>
- )}
- <span className={clsx('max-w-[160px] truncate', att.status === 'error' ? 'text-pink-ink' : 'text-foreground')}>
- {att.name}
- </span>
- {att.status === 'error' && att.retryable && (
- <Button
- type="button"
- variant="ghost"
- size="icon"
- disabled={disabled || voiceDraftReadOnly}
- onClick={() => retryAttachment(att.localId)}
- aria-label={t('chat.compose.retryAttachment')}
- className="size-5 shrink-0 text-muted hover:text-foreground"
- >
- <RotateCcw className="size-3.5" />
- </Button>
- )}
- <Button
- type="button"
- variant="ghost"
- size="icon"
- onClick={() => removeAttachment(att.localId)}
- aria-label={t('chat.compose.removeAttachment')}
- className="size-5 shrink-0 text-muted hover:text-foreground"
- >
- <X className="size-3.5" />
- </Button>
- </div>
- ))}
- </div>
- )}
- <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">
- {realtimeAnnouncement
- ? `${t('chat.compose.voicePreview')}: ${realtimeAnnouncement}`
- : ''}
- </div>
- <div
- className={cn(
- 'flex w-full items-end gap-1.5 rounded-2xl border border-border-strong bg-surface-2 py-2 pr-2 shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]',
- mediaEnabled ? 'pl-1.5' : 'pl-3.5',
- )}
- >
+ // The left-edge media cluster and the input itself, named so both box
+ // layouts below compose the same controls instead of duplicating them.
+ const mediaControls = (
+ <>
{/* Attach stays in the first idle slot and voice starts in the second.
Once a voice flow starts, the unrelated attachment control withdraws
and the active voice action takes the left edge. */}
@@ -1579,6 +1557,11 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
)}
</div>
)}
+ </>
+ );
+
+ const inputControl = (
+ <>
{useMentions ? (
<MentionEditor
ref={mentionRef}
@@ -1642,8 +1625,16 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
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"
/>
)}
- {/* A running agent turn keeps its Stop escape hatch even during voice
- capture. Queue/Send withdraw while capture owns the draft. */}
+ </>
+ );
+
+ // Send / Stop / Queue / Discard — one cluster, so the two-row layout can put it
+ // at the end of the action row without either box owning a second copy.
+ //
+ // A running agent turn keeps its Stop escape hatch even during voice capture.
+ // Queue/Send withdraw while capture owns the draft.
+ const sendControls = (
+ <>
{busyControls ? (
<>
{/* Sending while a turn runs is allowed — the backend enqueues it
@@ -1718,7 +1709,92 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
<Trash2 className="size-4" />
</Button>
)}
+ </>
+ );
+
+ return (
+ <div
+ ref={composerRootRef}
+ className={cn('mx-auto flex w-full max-w-[1080px] flex-col gap-2', className)}
+ >
+ {mediaEnabled && attachments.length > 0 && (
+ <div className="flex flex-wrap gap-2">
+ {attachments.map((att) => (
+ <div
+ key={att.localId}
+ className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 py-1 pl-1.5 pr-1 text-[12px]"
+ >
+ {att.status === 'uploading' ? (
+ <span className="grid size-7 place-items-center rounded text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ </span>
+ ) : att.kind === 'image' && att.url ? (
+ <img src={att.url} alt="" className="size-7 rounded object-cover" />
+ ) : (
+ <span className="grid size-7 place-items-center rounded bg-cyan/15 text-cyan-ink">
+ <Paperclip className="size-3.5" />
+ </span>
+ )}
+ <span className={clsx('max-w-[160px] truncate', att.status === 'error' ? 'text-pink-ink' : 'text-foreground')}>
+ {att.name}
+ </span>
+ {att.status === 'error' && att.retryable && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ disabled={disabled || voiceDraftReadOnly}
+ onClick={() => retryAttachment(att.localId)}
+ aria-label={t('chat.compose.retryAttachment')}
+ className="size-5 shrink-0 text-muted hover:text-foreground"
+ >
+ <RotateCcw className="size-3.5" />
+ </Button>
+ )}
+ <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ onClick={() => removeAttachment(att.localId)}
+ aria-label={t('chat.compose.removeAttachment')}
+ className="size-5 shrink-0 text-muted hover:text-foreground"
+ >
+ <X className="size-3.5" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="sr-only" role="status" aria-live="polite" aria-atomic="true">
+ {realtimeAnnouncement
+ ? `${t('chat.compose.voicePreview')}: ${realtimeAnnouncement}`
+ : ''}
</div>
+ {actions ? (
+ /* Two-row box (design TfqkD): the input on top, then an action row
+ carrying the caller's pickers on the left and Send on the right. */
+ <div className="flex w-full flex-col gap-[22px] rounded-2xl border border-border-strong bg-surface-2 p-[18px] shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]">
+ <div className="flex w-full items-end gap-1.5">
+ {mediaControls}
+ {inputControl}
+ </div>
+ <div className="flex w-full items-center justify-between gap-4">
+ <div className="flex min-w-0 items-center gap-4">{actions}</div>
+ <div className="flex shrink-0 items-center gap-1.5">{sendControls}</div>
+ </div>
+ </div>
+ ) : (
+ <div
+ className={cn(
+ 'flex w-full items-end gap-1.5 rounded-2xl border border-border-strong bg-surface-2 py-2 pr-2 shadow-[0_-4px_24px_-12px_rgba(0,0,0,0.5)]',
+ mediaEnabled ? 'pl-1.5' : 'pl-3.5',
+ )}
+ >
+ {mediaControls}
+ {inputControl}
+ {sendControls}
+ </div>
+ )}
</div>
);
});
diff --git a/ui/src/components/workbench/ReadyBanner.test.tsx b/ui/src/components/workbench/ReadyBanner.test.tsx
new file mode 100644
index 000000000..a7a235448
--- /dev/null
+++ b/ui/src/components/workbench/ReadyBanner.test.tsx
@@ -0,0 +1,62 @@
+/* @vitest-environment jsdom */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { ReadyBanner } from './ReadyBanner';
+import { shouldShowReadyBanner, type ReadyBannerInput } from './backendReadiness';
+
+vi.mock('react-i18next', () => ({
+ useTranslation: () => ({
+ t: (key: string, vars?: Record<string, unknown>) => (vars?.backend ? `${key}:${vars.backend}` : key),
+ }),
+}));
+
+afterEach(cleanup);
+
+const verified: ReadyBannerInput = {
+ onboardingCompleted: true,
+ readiness: { backend: 'codex', ready: true },
+ currentBackend: 'codex',
+ dismissed: false,
+};
+
+describe('shouldShowReadyBanner', () => {
+ it('shows only when the wizard finished AND the backend itself confirms it', () => {
+ expect(shouldShowReadyBanner(verified)).toBe(true);
+ });
+
+ it.each<[string, Partial<ReadyBannerInput>]>([
+ ['the wizard did not just finish', { onboardingCompleted: false }],
+ ['nothing has been observed yet', { readiness: null }],
+ ['the probe answered not-ready', { readiness: { backend: 'codex', ready: false } }],
+ ['a different backend answered', { readiness: { backend: 'claude', ready: true } }],
+ ['the running backend is unknown', { currentBackend: null }],
+ ['the user dismissed it', { dismissed: true }],
+ ])('stays hidden when %s', (_case, override) => {
+ expect(shouldShowReadyBanner({ ...verified, ...override })).toBe(false);
+ });
+
+ it('treats a pending probe exactly like a refused one — never as an optimistic yes', () => {
+ expect(shouldShowReadyBanner({ ...verified, readiness: null }))
+ .toBe(shouldShowReadyBanner({ ...verified, readiness: { backend: 'codex', ready: false } }));
+ });
+});
+
+describe('ReadyBanner', () => {
+ it('names the backend that confirmed and dismisses on request', async () => {
+ const user = userEvent.setup();
+ const onDismiss = vi.fn();
+ render(<ReadyBanner backend="codex" onDismiss={onDismiss} />);
+
+ expect(screen.getByText('workbench.home.ready:Codex')).toBeTruthy();
+ await user.click(screen.getByRole('button', { name: 'workbench.home.readyDismiss' }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ });
+
+ it('falls back to the raw name for a backend it has no label for', () => {
+ render(<ReadyBanner backend="future-backend" onDismiss={() => {}} />);
+ expect(screen.getByText('workbench.home.ready:future-backend')).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/workbench/ReadyBanner.tsx b/ui/src/components/workbench/ReadyBanner.tsx
new file mode 100644
index 000000000..1f4914a55
--- /dev/null
+++ b/ui/src/components/workbench/ReadyBanner.tsx
@@ -0,0 +1,32 @@
+import { useTranslation } from 'react-i18next';
+import { CircleCheck, X } from 'lucide-react';
+
+import { BACKEND_LABEL, isBackend } from '../../lib/backendAccent';
+
+// Only the banner lives here; what decides whether it may be shown, and what
+// would observe the backend, are in backendReadiness.ts.
+
+/**
+ * design gJMu4 — a single 42-tall mint line above the first-task home, dismissed
+ * with the trailing ✕.
+ */
+export const ReadyBanner: React.FC<{ backend: string; onDismiss: () => void }> = ({ backend, onDismiss }) => {
+ const { t } = useTranslation();
+ const name = isBackend(backend) ? BACKEND_LABEL[backend] : backend;
+ return (
+ <div className="flex h-[42px] w-full shrink-0 items-center gap-2.5 rounded-[10px] border border-border bg-mint-soft px-4">
+ <CircleCheck className="size-[18px] shrink-0 text-mint-ink" />
+ <span className="min-w-0 flex-1 truncate text-[12px] text-foreground">
+ {t('workbench.home.ready', { backend: name })}
+ </span>
+ <button
+ type="button"
+ onClick={onDismiss}
+ aria-label={t('workbench.home.readyDismiss')}
+ className="shrink-0 rounded text-muted transition-colors hover:text-foreground"
+ >
+ <X className="size-[15px]" />
+ </button>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx
new file mode 100644
index 000000000..907aa317a
--- /dev/null
+++ b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx
@@ -0,0 +1,111 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { cleanup, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const inbox = vi.hoisted(() => ({
+ totalUnread: 0,
+ unreadSessions: 0,
+ inboxSessions: [] as unknown[],
+ unreadBySession: {} as Record<string, number>,
+ markRead: vi.fn(),
+}));
+
+vi.mock('../../context/WorkbenchInboxContext', () => ({ useWorkbenchInbox: () => inbox }));
+vi.mock('../../context/InstanceAuthorizationContext', () => ({
+ useInstanceAuthorization: () => ({
+ capabilities: {
+ can_chat: true,
+ can_manage_projects: true,
+ can_use_agents: true,
+ can_use_skills: true,
+ can_use_vault_secrets: true,
+ },
+ }),
+}));
+vi.mock('../../context/WorkbenchProjectsContext', () => ({
+ useWorkbenchProjectsTree: () => ({
+ projects: [],
+ projectsError: null,
+ sessionsOf: () => [],
+ isExpanded: () => false,
+ toggleExpanded: vi.fn(),
+ loadMore: vi.fn(),
+ creatingSession: null,
+ createSessionForProject: vi.fn(),
+ renameProject: vi.fn(),
+ archiveProject: vi.fn(),
+ reorderProjects: vi.fn(),
+ isReorderingProjects: false,
+ }),
+ useWorkbenchProjectsActions: () => ({}),
+}));
+vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => ({ open: vi.fn() }) }));
+vi.mock('../../context/useUnsavedChangesActionGuard', () => ({
+ useUnsavedChangesActionGuard: () => (run: () => void) => run,
+}));
+
+import en from '../../i18n/en.json';
+import { WorkbenchSidebar } from './WorkbenchSidebar';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const renderSidebar = () => render(
+ <I18nextProvider i18n={i18n}>
+ <MemoryRouter initialEntries={['/']}>
+ <WorkbenchSidebar />
+ </MemoryRouter>
+ </I18nextProvider>,
+);
+
+const inboxIcon = () => screen.getByRole('link', { name: en.workbench.nav.inbox }).querySelector('svg')!;
+
+beforeEach(() => {
+ inbox.totalUnread = 0;
+ inbox.unreadSessions = 0;
+ inbox.inboxSessions = [];
+ inbox.unreadBySession = {};
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('Workbench sidebar inbox counter', () => {
+ it('says nothing at all when nothing is unread', () => {
+ renderSidebar();
+
+ const link = screen.getByRole('link', { name: en.workbench.nav.inbox });
+ // A zero badge is still a badge — an empty inbox draws no attention at all.
+ expect(link.textContent).toBe('');
+ expect(inboxIcon().getAttribute('class')).toContain('text-muted');
+ expect(inboxIcon().getAttribute('class')).not.toContain('text-cyan-ink');
+ });
+
+ it('shows the real unread count and colours the icon with it', () => {
+ inbox.totalUnread = 7;
+ inbox.unreadSessions = 3;
+ inbox.unreadBySession = { ses_a: 4, ses_b: 3 };
+ renderSidebar();
+
+ expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe('7');
+ expect(inboxIcon().getAttribute('class')).toContain('text-cyan-ink');
+ });
+
+ it('caps the badge instead of widening the icon', () => {
+ inbox.totalUnread = 150;
+ renderSidebar();
+
+ expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe('99+');
+ });
+});
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 9186f3ee6..bebb084b7 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -1,7 +1,7 @@
import type { TranslationKey } from '@/i18n/types';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { NavLink, useLocation, useNavigate } from 'react-router-dom';
+import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom';
import {
Activity,
Archive,
@@ -22,6 +22,7 @@ import {
Plus,
Search,
Settings2,
+ SquarePen,
WandSparkles,
} from 'lucide-react';
import clsx from 'clsx';
@@ -47,6 +48,7 @@ import { NewProjectDialog } from './NewProjectDialog';
import { ProjectAgentsMdDialog } from './ProjectAgentsMdDialog';
import { ProjectSettingsDialog } from './ProjectSettingsDialog';
import { SortableProjectList, type ProjectDragHandle } from './SortableProjectList';
+import logoImg from '../../assets/logo.png';
interface CapabilityNavItem {
to: string;
@@ -61,7 +63,40 @@ const CAPABILITY_NAV: CapabilityNavItem[] = [
{ to: '/vaults', i18nKey: 'workbench.nav.vaults', icon: KeyRound },
];
-const CAPS_COLLAPSED_KEY = 'vibe-remote:caps-collapsed';
+// One navigation row (design m8K59, 216 x 40). Selected / hover / default are the
+// three states the approved source draws, each on its own token so Light and Dark
+// follow the table instead of a hard-coded neon.
+const SidebarNavRow: React.FC<{
+ to: string;
+ end?: boolean;
+ icon: LucideIcon;
+ label: string;
+}> = ({ to, end, icon: Icon, label }) => (
+ <NavLink
+ to={to}
+ end={end}
+ className={({ isActive }) =>
+ clsx(
+ 'group flex h-10 items-center gap-2.5 rounded-xl border px-3 text-[13px] transition-colors',
+ isActive
+ ? 'border-[var(--nav-selected-border)] bg-[var(--nav-selected-bg)] font-semibold text-foreground shadow-[var(--shadow-glow-nav-mint)]'
+ : 'border-transparent font-medium text-muted hover:bg-[var(--nav-hover-bg)] hover:text-foreground',
+ )
+ }
+ >
+ {({ isActive }) => (
+ <>
+ <Icon
+ className={clsx(
+ 'size-[17px] shrink-0',
+ isActive ? 'text-mint-ink' : 'text-muted group-hover:text-foreground',
+ )}
+ />
+ <span className="truncate">{label}</span>
+ </>
+ )}
+ </NavLink>
+);
// 360px floating popover that opens when the user hovers the Inbox entry.
// Mirrors design.pen KmQ1L — header + a few session cards + footer "open full
@@ -696,25 +731,6 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
const [popoverOpen, setPopoverOpen] = useState(false);
const closeTimer = useRef<number | null>(null);
const [showNewProject, setShowNewProject] = useState(false);
- // Capabilities section is collapsible to free room for Projects; the choice is
- // remembered (best-effort localStorage, same convention as the other toggles).
- const [capsCollapsed, setCapsCollapsed] = useState<boolean>(() => {
- try {
- return window.localStorage.getItem(CAPS_COLLAPSED_KEY) === '1';
- } catch {
- return false;
- }
- });
- const toggleCaps = () =>
- setCapsCollapsed((prev) => {
- const next = !prev;
- try {
- window.localStorage.setItem(CAPS_COLLAPSED_KEY, next ? '1' : '0');
- } catch {
- /* best-effort */
- }
- return next;
- });
// Small open/close delays so the popover doesn't flicker as the cursor
// brushes through the inbox row on its way somewhere else, and survives
@@ -761,128 +777,114 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
}, [totalUnread]);
// Fill the sidebar column and cap its height so the project list (and only the
- // project list) scrolls; Inbox + Capabilities stay pinned. The Inbox hover
- // popover stays OUT of any overflow box below, so it is never clipped.
+ // project list) scrolls; the brand row and navigation stay pinned. The Inbox
+ // hover popover stays OUT of any overflow box below, so it is never clipped.
return (
- <div className="flex min-h-0 flex-1 flex-col gap-2.5">
- {/* Search moved to a compact icon in the Projects header (left of the add
- button) to reclaim this full row for the Projects list. ⌘K still works. */}
- {/* Inbox entry — hover opens the floating popover (portaled above the chat). */}
- <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>
- <PopoverAnchor asChild>
- <div onMouseEnter={openPopover} onMouseLeave={queueClose}>
- <NavLink
- to="/inbox"
- className={({ isActive }) =>
- clsx(
- 'group flex items-center gap-2.5 rounded-lg border px-3 py-2.5 text-[13px] font-semibold transition-colors',
- // Cyan active state per design.pen ze15A — mint is reserved
- // for sessions / projects so the two reads stay distinct.
- isActive
- ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-glow-sm-cyan'
- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',
- )
- }
+ <div className="flex min-h-0 flex-1 flex-col gap-4">
+ {/* Brand row tLDP1 — identity on the left, Search and Inbox on the right.
+ Search and Inbox are siblings of the home link, not nested inside it. */}
+ <div className="flex shrink-0 items-center gap-2.5 py-2">
+ <Link
+ to="/"
+ className="group flex min-w-0 flex-1 items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"
>
- {({ isActive }) => (
- <>
- <Inbox className={clsx('size-4', isActive ? 'text-cyan-ink' : 'text-foreground')} />
- <span className="flex-1">{t('workbench.nav.inbox')}</span>
- {badge && (
- <span className="inline-flex min-w-[1.25rem] items-center justify-center rounded-full bg-cyan px-1.5 py-0.5 font-mono text-[9px] font-bold text-accent-foreground shadow-glow-xs-cyan">
- {badge}
- </span>
- )}
- <ChevronRight className="size-3.5 text-muted opacity-0 transition-opacity group-hover:opacity-100" />
- </>
- )}
- </NavLink>
+ {/* Decorative: the link's accessible name is the localized brand text
+ beside it, so naming the image too would read the destination twice. */}
+ <img
+ src={logoImg}
+ alt=""
+ aria-hidden="true"
+ className="h-9 w-[38px] shrink-0 rounded-[7px] border border-mint/35 bg-[var(--logo-well-background)] object-cover transition-shadow group-hover:shadow-glow-sm-mint"
+ />
+ <div className="min-w-0 leading-tight">
+ <div className="truncate text-[13px] font-semibold text-foreground">{t('appShell.title')}</div>
+ {/* tLDP1 labels this row "Workbench", not the full "Agent OS ·
+ Workbench" the settings shell uses: at 248 with Search and Inbox
+ beside it, the longer line only ever renders truncated. */}
+ <div className="truncate text-[11px] text-muted">{t('workbench.eyebrow')}</div>
</div>
- </PopoverAnchor>
- <InboxHoverPopover
- sessions={inboxSessions}
- unreadBySession={unreadBySession}
- unreadSessions={unreadSessions}
- totalUnread={totalUnread}
- canMarkRead={canChat}
- onItemClick={onItemClick}
- onMarkAllRead={onMarkAllRead}
- onMouseEnter={openPopover}
- onMouseLeave={queueClose}
- />
- </Popover>
-
- {capabilityNav.length > 0 && <div className="flex flex-col gap-1.5">
- <button
+ </Link>
+ <Button
type="button"
- onClick={toggleCaps}
- aria-expanded={!capsCollapsed}
- className="group flex items-center gap-1 px-1 font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted transition-colors hover:text-foreground"
+ variant="ghost"
+ size="icon"
+ className="size-8 shrink-0 rounded-lg text-muted hover:text-foreground"
+ aria-label={t('workbench.search.entry')}
+ onClick={onOpenSearch}
>
- <span className="flex-1 text-left">{t('workbench.capabilitiesLabel')}</span>
- <ChevronDown className={clsx('size-3.5 shrink-0 transition-transform', capsCollapsed && '-rotate-90')} />
- </button>
- {!capsCollapsed && (
- <nav className="flex flex-col gap-0.5">
- {capabilityNav.map(({ to, i18nKey, icon: Icon }) => (
- <NavLink
- key={to}
- to={to}
- className={({ isActive }) =>
- clsx(
- 'group flex items-center gap-2.5 rounded-lg px-3 py-2 text-[13px] font-medium transition-colors',
- isActive
- ? 'border border-mint/30 bg-mint/[0.08] text-foreground shadow-glow-sm-mint'
- : 'border border-transparent text-muted hover:bg-foreground/[0.04] hover:text-foreground',
- )
- }
- >
- {({ isActive }) => (
- <>
- <Icon className={clsx('size-4', isActive ? 'text-mint-ink' : 'text-muted group-hover:text-foreground')} />
- <span>{t(i18nKey)}</span>
- </>
- )}
- </NavLink>
- ))}
- </nav>
+ <Search className="size-[18px]" />
+ </Button>
+ {/* Inbox entry — hover opens the floating popover (portaled above the chat).
+ At zero unread there is no badge node at all and the icon stays muted;
+ both reads come from the same real counter. */}
+ <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>
+ <PopoverAnchor asChild>
+ <div className="shrink-0" onMouseEnter={openPopover} onMouseLeave={queueClose}>
+ <NavLink
+ to="/inbox"
+ aria-label={t('workbench.nav.inbox')}
+ className="relative flex size-8 items-center justify-center rounded-lg transition-colors hover:bg-[var(--nav-hover-bg)]"
+ >
+ {({ isActive }) => (
+ <>
+ <Inbox
+ className={clsx(
+ 'size-[18px]',
+ badge ? 'text-cyan-ink' : isActive ? 'text-foreground' : 'text-muted',
+ )}
+ />
+ {badge && (
+ <span className="absolute right-0.5 top-0.5 inline-flex min-w-[14px] items-center justify-center rounded-full border border-surface bg-cyan px-[3px] font-mono text-[9px] font-bold leading-[12px] text-primary-foreground">
+ {badge}
+ </span>
+ )}
+ </>
+ )}
+ </NavLink>
+ </div>
+ </PopoverAnchor>
+ <InboxHoverPopover
+ sessions={inboxSessions}
+ unreadBySession={unreadBySession}
+ unreadSessions={unreadSessions}
+ totalUnread={totalUnread}
+ canMarkRead={canChat}
+ onItemClick={onItemClick}
+ onMarkAllRead={onMarkAllRead}
+ onMouseEnter={openPopover}
+ onMouseLeave={queueClose}
+ />
+ </Popover>
+ </div>
+
+ {/* Navigation m8K59 — one always-expanded group. "New chat" is the home
+ itself, which is where a task is described and a session is created. */}
+ <nav className="flex shrink-0 flex-col gap-0.5">
+ {canChat && (
+ <SidebarNavRow to="/" end icon={SquarePen} label={t('workbench.nav.newChat')} />
)}
- </div>}
+ {capabilityNav.map(({ to, i18nKey, icon }) => (
+ <SidebarNavRow key={to} to={to} icon={icon} label={t(i18nKey)} />
+ ))}
+ </nav>
- {/* Projects section — design.pen b8wX2. Header row carries the
- "Projects" label on the left (matching the Capabilities label
- style) and the 22x22 add button on the right. */}
+ {/* Projects section t7o96 — the label on the left and the create
+ affordance on the right; Search now lives in the brand row. */}
<div className="flex min-h-0 flex-1 flex-col gap-1.5">
<div className="flex items-center justify-between px-1">
- <span className="font-mono text-[10px] font-bold uppercase tracking-[0.18em] text-muted">
+ <span className="font-mono text-[10px] font-bold uppercase tracking-[0.16em] text-muted">
{t('workbench.projectsLabel')}
</span>
- {/* Borderless ghost icon buttons (design-system Button) — search +
- add, grouped on the right. Search moved here from a full-width
- row above to reclaim that space for the Projects list; ⌘K still
- works. Both are roomy 28px tap targets. */}
- <div className="flex items-center gap-0.5">
- {canManageProjects && <Button
- type="button"
- variant="ghost"
- size="icon"
- className="size-7 shrink-0 text-muted hover:text-foreground"
- aria-label={t('workbench.search.entry')}
- onClick={onOpenSearch}
- >
- <Search className="size-4" />
- </Button>}
- {canCreateProject && <Button
- type="button"
- variant="ghost"
- size="icon"
- className="size-7 shrink-0 text-muted hover:text-foreground"
- aria-label={t('workbench.addProject')}
- onClick={() => setShowNewProject(true)}
- >
- <FolderPlus className="size-4" />
- </Button>}
- </div>
+ {canCreateProject && <Button
+ type="button"
+ variant="ghost"
+ size="icon"
+ className="size-[22px] shrink-0 text-muted hover:text-foreground"
+ aria-label={t('workbench.addProject')}
+ onClick={() => setShowNewProject(true)}
+ >
+ <FolderPlus className="size-[15px]" />
+ </Button>}
</div>
<div className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto pr-0.5">
@@ -897,10 +899,11 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
{t('workbench.projectsLoadError')}
</div>
)}
+ {/* True empty state e5Kplg — a real row, not a centered illustration. */}
{projects !== null && projects.length === 0 && (
- <div className="flex flex-col items-center gap-1.5 rounded-md border border-dashed border-border px-3 py-4 text-center">
- <Folder className="size-4 text-muted" />
- <div className="text-[11px] text-muted">{t('workbench.projectsEmpty')}</div>
+ <div className="flex items-center gap-[7px] rounded-md px-1.5 py-[7px]">
+ <FolderPlus className="size-[14px] shrink-0 text-muted" />
+ <span className="min-w-0 truncate text-[11px] text-muted">{t('workbench.projectsEmpty')}</span>
</div>
)}
{projects !== null && <SortableProjectList
diff --git a/ui/src/components/workbench/backendReadiness.test.tsx b/ui/src/components/workbench/backendReadiness.test.tsx
new file mode 100644
index 000000000..6f5ec8f83
--- /dev/null
+++ b/ui/src/components/workbench/backendReadiness.test.tsx
@@ -0,0 +1,247 @@
+/* @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { act, cleanup, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const apiFetch = vi.hoisted(() => vi.fn());
+// The wire is the only stand-in. The api the reader consumes is the real one —
+// the provider's own `getBackendConnection`, its path, its error policy — so
+// this file pins the reader against the producer as shipped rather than against
+// a second description of it.
+vi.mock('../../lib/apiFetch', () => ({ apiFetch }));
+
+import { ApiProvider, type BackendConnectionState } from '../../context/ApiContext';
+import { ToastProvider } from '../../context/ToastProvider';
+import en from '../../i18n/en.json';
+import { useBackendReadiness } from './backendReadiness';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const json = (payload: unknown, status = 200) => new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+});
+
+/**
+ * The connection endpoint with its answers held: a read is outstanding until the
+ * test answers it, which is how a route change can be made to happen while an
+ * earlier question is still on the wire.
+ */
+const connectionServer = () => {
+ const outstanding: Array<{
+ backend: string;
+ answer: (state?: Partial<BackendConnectionState>) => void;
+ reject: (status?: number) => void;
+ }> = [];
+ apiFetch.mockImplementation((path: string) => {
+ const asked = /^\/api\/backend\/([^/]+)\/connection$/.exec(path);
+ // Anything else the provider does on mount is not what this file is about.
+ if (!asked) return Promise.resolve(json({}));
+ const backend = asked[1];
+ return new Promise<Response>((resolve) => {
+ outstanding.push({
+ backend,
+ answer: (state) => resolve(json({
+ ok: true,
+ backend,
+ installed: true,
+ enabled: true,
+ auth: 'api_key',
+ application: 'applied',
+ ready: true,
+ entry_eligible: true,
+ ...state,
+ })),
+ reject: (status = 403) => resolve(json({ error: 'fixture refusal' }, status)),
+ });
+ });
+ });
+ return {
+ outstanding,
+ /** Which backends were actually asked about, in order. */
+ asked: () => apiFetch.mock.calls
+ .map(([path]) => /^\/api\/backend\/([^/]+)\/connection$/.exec(String(path))?.[1])
+ .filter((backend): backend is string => Boolean(backend)),
+ };
+};
+
+const Probe = ({ backend, asked }: { backend: string | null; asked: boolean }) => {
+ const readiness = useBackendReadiness(backend, asked);
+ return <span data-testid="observed">{readiness ? `${readiness.backend}:${readiness.ready}` : 'nothing'}</span>;
+};
+
+const tree = (backend: string | null, asked: boolean) => (
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>
+ <ApiProvider>
+ <Probe backend={backend} asked={asked} />
+ </ApiProvider>
+ </ToastProvider>
+ </I18nextProvider>
+);
+
+const renderProbe = (backend: string | null = 'codex', asked = true) => {
+ const view = render(tree(backend, asked));
+ return { ...view, ask: (next: string | null, stillAsked = true) => view.rerender(tree(next, stillAsked)) };
+};
+
+const observed = () => screen.getByTestId('observed').textContent;
+
+beforeEach(() => {
+ apiFetch.mockReset();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe('useBackendReadiness', () => {
+ it('repeats what the backend said about itself, from the endpoint that owns it', async () => {
+ const server = connectionServer();
+ renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ // A plain read of the producer's own route — no start, no auth, no write.
+ expect(apiFetch.mock.calls.map(([path, init]) => [path, init?.method ?? 'GET']))
+ .toContainEqual(['/api/backend/codex/connection', 'GET']);
+
+ await act(async () => { server.outstanding[0].answer(); });
+
+ expect(observed()).toBe('codex:true');
+ });
+
+ it.each([
+ ['the backend does not call itself ready', { ready: false }],
+ ['the read itself did not succeed', { ok: false }],
+ ['the answer is about a different backend', { backend: 'claude' }],
+ ['the backend is waiting on a permission the user has not given', { ready: false, permission_required: true }],
+ ])('observes nothing when %s', async (_case, state) => {
+ const server = connectionServer();
+ renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ await act(async () => { server.outstanding[0].answer(state as Partial<BackendConnectionState>); });
+
+ expect(observed()).toBe('nothing');
+ });
+
+ it('observes nothing, and stays out of the way, when the read fails', async () => {
+ const server = connectionServer();
+ const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ await act(async () => { server.outstanding[0].reject(); });
+
+ // A refusal is not a report of "not ready" — it is no report, and the home
+ // goes on working. The rejection is the api's own error policy; what matters
+ // here is that the reader lets it pass instead of failing the tree with it.
+ expect(observed()).toBe('nothing');
+ logged.mockRestore();
+ });
+
+ it.each([
+ ['there is nothing left to announce', 'codex', false],
+ ['the home has no backend to ask about', null, true],
+ ['the route names a backend this build cannot ask about', 'future-backend', true],
+ ])('asks nothing at all when %s', async (_case, backend, asked) => {
+ const server = connectionServer();
+ renderProbe(backend, asked);
+
+ await act(async () => {});
+
+ expect(server.asked()).toEqual([]);
+ expect(observed()).toBe('nothing');
+ });
+
+ it('drops an answer to a question the route has moved on from', async () => {
+ const server = connectionServer();
+ const view = renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ view.ask('claude');
+ await waitFor(() => expect(server.outstanding).toHaveLength(2));
+
+ // Codex answers ready, but the home would no longer run Codex.
+ await act(async () => { server.outstanding[0].answer(); });
+ expect(observed()).toBe('nothing');
+
+ await act(async () => { server.outstanding[1].answer(); });
+ expect(observed()).toBe('claude:true');
+ });
+
+ it('does not let an old answer stand in for the same backend asked again', async () => {
+ const server = connectionServer();
+ const view = renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ view.ask('claude');
+ await waitFor(() => expect(server.outstanding).toHaveLength(2));
+ view.ask('codex');
+ await waitFor(() => expect(server.outstanding).toHaveLength(3));
+
+ // The first Codex read names the backend now in effect, and is still stale:
+ // it answers a question that was withdrawn two route changes ago.
+ await act(async () => { server.outstanding[0].answer(); });
+ expect(observed()).toBe('nothing');
+
+ await act(async () => { server.outstanding[2].answer(); });
+ expect(observed()).toBe('codex:true');
+ });
+
+ it('forgets what it observed once the question changes', async () => {
+ const server = connectionServer();
+ const view = renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ await act(async () => { server.outstanding[0].answer(); });
+ expect(observed()).toBe('codex:true');
+
+ view.ask('claude');
+ // Nothing has been observed about Claude yet, and what was true of Codex is
+ // not evidence about it.
+ expect(observed()).toBe('nothing');
+
+ view.ask('codex', false);
+ await act(async () => {});
+ expect(observed()).toBe('nothing');
+ });
+
+ it('reads once for one question, whatever else the interface does', async () => {
+ const server = connectionServer();
+ renderProbe('codex');
+
+ await waitFor(() => expect(server.asked()).toEqual(['codex']));
+ await act(async () => { server.outstanding[0].answer(); });
+
+ // The provider hands out a new api on a language change. A reader that
+ // depended on that identity would re-read the backend every time the
+ // interface language moved; this one is asking one question.
+ await act(async () => { await i18n.changeLanguage('en-GB'); });
+ await act(async () => { await i18n.changeLanguage('en'); });
+
+ expect(server.asked()).toEqual(['codex']);
+ expect(observed()).toBe('codex:true');
+ });
+
+ it('ignores an answer that arrives after the home is gone', async () => {
+ const server = connectionServer();
+ const view = renderProbe('codex');
+
+ await waitFor(() => expect(server.outstanding).toHaveLength(1));
+ view.unmount();
+
+ await act(async () => { server.outstanding[0].answer(); });
+
+ expect(screen.queryByTestId('observed')).toBeNull();
+ });
+});
diff --git a/ui/src/components/workbench/backendReadiness.ts b/ui/src/components/workbench/backendReadiness.ts
new file mode 100644
index 000000000..54bc78595
--- /dev/null
+++ b/ui/src/components/workbench/backendReadiness.ts
@@ -0,0 +1,200 @@
+import { useCallback, useEffect, useState, useSyncExternalStore } from 'react';
+import { useApi, type BackendConnectionState } from '../../context/ApiContext';
+import { isBackend } from '../../lib/backendAccent';
+import { useLatestRef } from '../../lib/useLatestRef';
+
+/**
+ * What the home knows about the backend it would actually run on, as reported by
+ * the backend itself. `null` means nothing has been observed yet — which is not
+ * the same as "not ready", and must not be rounded up or down.
+ *
+ * This is a view of the connection state the backend settings own, narrowed to
+ * the two fields a banner is allowed to speak about. It is derived from that
+ * type rather than restated, so the home cannot drift into describing a shape
+ * the endpoint does not return.
+ */
+export type BackendReadiness = Pick<BackendConnectionState, 'backend' | 'ready'>;
+
+export interface ReadyBannerInput {
+ /** The setup wizard lands on `/` with `{ onboardingCompleted: true }` in router
+ * state. History state SURVIVES a reload, so the home consumes the key once
+ * and replaces the entry without it; what arrives here is that latch, held
+ * for the visit so a slow readiness answer can still find it. */
+ onboardingCompleted: boolean;
+ /** Corroboration from the backend. */
+ readiness: BackendReadiness | null;
+ /** The backend the home's current Agent route would actually run. */
+ currentBackend: string | null;
+ dismissed: boolean;
+}
+
+/**
+ * The banner states a fact about the running system, so every part of it has to
+ * be observed: the wizard reported it finished, the backend reports itself ready,
+ * and the backend that reported is the one this home would use. A probe that is
+ * pending, failed, or answers for a different backend renders nothing — an
+ * unverified guess here is a false claim, not an optimistic one.
+ */
+export const shouldShowReadyBanner = (input: ReadyBannerInput): boolean => {
+ if (!input.onboardingCompleted || input.dismissed) return false;
+ if (!input.readiness || input.readiness.ready !== true) return false;
+ if (!input.currentBackend) return false;
+ return input.readiness.backend === input.currentBackend;
+};
+
+/** What this page still owes the user about the setup the wizard just finished:
+ * nothing, an announcement it has not made yet, or one already waved off. */
+type Handoff = 'none' | 'owed' | 'settled';
+
+/**
+ * Held for the page rather than for the component, which is not a detail.
+ *
+ * The completion arrives as router state on a navigation that crosses the setup
+ * boundary — and crossing it is exactly what makes the route guard re-validate,
+ * so the home is unmounted and remounted underneath it while that runs, after
+ * the history entry carrying the event has already been consumed. A latch in
+ * component state dies with that remount, and the completion could then never be
+ * announced at all, however quickly the backend answered.
+ *
+ * So the lifetime is not the home's own. It has to outlive a remount the home
+ * does not survive, and it has to end when the user actually leaves the visit it
+ * was made for — which is a fact about the route, not about a component, and is
+ * ended by `useSetupHandoffDeparture` below. A reload ends it as well, being a
+ * different page reading an entry that no longer claims a setup just finished.
+ */
+let handoff: Handoff = 'none';
+const watchers = new Set<() => void>();
+const subscribe = (watcher: () => void) => {
+ watchers.add(watcher);
+ return () => { watchers.delete(watcher); };
+};
+const record = (next: Handoff) => {
+ if (next === handoff) return;
+ handoff = next;
+ watchers.forEach((watcher) => watcher());
+};
+
+/** A new page, which is the only thing that forgets a handoff on its own. Tests
+ * share one module across many pages and start each one from here. */
+export const forgetSetupHandoff = () => record('none');
+
+export interface SetupHandoff {
+ /** The wizard reported a finished setup to this page. */
+ completed: boolean;
+ /** ...and the user has already waved the announcement off. */
+ dismissed: boolean;
+ dismiss: () => void;
+}
+
+/**
+ * Holds the wizard's completion for the page, and remembers a dismissal the same
+ * way: a remount mid-visit loses neither, and the page ends both.
+ *
+ * Read as what it is — state outside React that a component subscribes to — so a
+ * home mounting after the event is handed the same answer as one that was there
+ * to receive it.
+ */
+export const useSetupHandoff = (arrived: boolean): SetupHandoff => {
+ const held = useSyncExternalStore(subscribe, () => handoff);
+ // The completion can arrive at an already mounted home too, and it is only
+ // ever taken once: a dismissal is the user's answer to it, not a state to
+ // overwrite the next time this runs.
+ useEffect(() => {
+ if (arrived && handoff === 'none') record('owed');
+ }, [arrived]);
+ const dismiss = useCallback(() => record('settled'), []);
+ return { completed: held !== 'none', dismissed: held === 'settled', dismiss };
+};
+
+/** The route the handoff is about: the home the wizard hands off to. */
+const HOME_PATH = '/';
+
+/**
+ * Ends the handoff when the user actually leaves the visit it was made for.
+ *
+ * The home is unmounted for two unrelated reasons — the route guard
+ * re-validating at the setup boundary, and the user going somewhere else — and
+ * only the route tells them apart, which is the whole reason this reads the
+ * route being shown instead of the home's own lifecycle. Ending it on unmount
+ * would end it during the guard's remount too, which is the bug the page scope
+ * exists to fix.
+ *
+ * `shownPath` is what the route surface is actually RENDERING, which is why
+ * Settings opened over the home is not a departure: on either form factor the
+ * home is still there behind that surface, still holding a banner the user has
+ * not answered. It is also not the shell's own chrome location, which follows
+ * the foreground URL below md and would make a phone forget a handoff its home
+ * is still holding.
+ */
+export const useSetupHandoffDeparture = (shownPath: string) => {
+ useEffect(() => {
+ if (shownPath !== HOME_PATH) record('none');
+ }, [shownPath]);
+};
+
+/**
+ * Only a backend the connection endpoint is defined for can be asked about. An
+ * Agent route may name anything — an older route, a backend this build does not
+ * know — and asking about one of those would produce an error toast over a home
+ * the user is already using, to learn nothing. Unknown names are simply not a
+ * question, so none is asked.
+ *
+ * The banner beside this one already names its backend through the same guard,
+ * so the two agree on what a backend is by construction.
+ */
+const askable = (backend: string | null): BackendConnectionState['backend'] | null =>
+ backend !== null && isBackend(backend) ? backend : null;
+
+/**
+ * Reads, once, whether the backend this home would run reports itself ready.
+ *
+ * It is a reader and nothing more: one GET per question asked, no polling, no
+ * starting, no auth, no install, no write. Readiness is owned by the backend
+ * settings and reported by their endpoint; the home only repeats what it was
+ * told, and only about the backend it asked.
+ *
+ * `asked` is the question itself. A banner can only ever announce a completion
+ * the home is still holding, so an ordinary visit — nothing to announce, or
+ * something already announced and dismissed — asks nothing at all.
+ *
+ * Nothing observed here survives the question that produced it. When the Agent
+ * route moves to another backend, or the home unmounts, the answer still on the
+ * wire is about a question no longer being asked: it is dropped, and what was
+ * already observed is cleared. That holds for A -> B -> A too, where the first
+ * A's answer is stale despite naming the backend now in effect.
+ */
+export const useBackendReadiness = (backend: string | null, asked: boolean): BackendReadiness | null => {
+ const api = useApi();
+ // The api identity changes with the interface language, among other things.
+ // Re-reading it here keeps a locale switch from re-probing the backend.
+ const latest = useLatestRef(api);
+ const name = asked ? askable(backend) : null;
+ const [observed, setObserved] = useState<BackendReadiness | null>(null);
+ const [answering, setAnswering] = useState(name);
+ // Evidence belongs to the question that produced it, so a new question drops
+ // it here rather than a frame later, and nothing stale is ever returned.
+ const moved = answering !== name;
+ if (moved) {
+ setAnswering(name);
+ setObserved(null);
+ }
+
+ useEffect(() => {
+ if (!name) return;
+ let current = true;
+ void latest.current.getBackendConnection(name)
+ .then((state) => {
+ if (!current) return;
+ // Every part has to hold: the read succeeded, the backend calls itself
+ // ready, and the report is about the backend that was asked about.
+ if (state?.ok !== true || state.ready !== true || state.backend !== name) return;
+ setObserved({ backend: state.backend, ready: true });
+ })
+ // A refused, denied or unreachable read is not a report of "not ready" —
+ // it is no report at all. The home stays exactly as silent, and usable.
+ .catch(() => {});
+ return () => { current = false; };
+ }, [latest, name]);
+
+ return moved ? null : observed;
+};
diff --git a/ui/src/context/WindowManagerProvider.tsx b/ui/src/context/WindowManagerProvider.tsx
index b1c5e857c..da427fc4a 100644
--- a/ui/src/context/WindowManagerProvider.tsx
+++ b/ui/src/context/WindowManagerProvider.tsx
@@ -189,7 +189,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa
const id = `win-${++idSeq.current}`;
const z = ++zSeq.current;
const bounds: WindowBounds = {
- // Cascade starts clear of the 240px sidebar so a new window doesn't open over it
+ // Cascade starts clear of the 248px sidebar so a new window doesn't open over it
// (the layer now spans the full viewport); it can still be dragged/maximized over it.
x: 264 + i * CASCADE_STEP,
y: 32 + i * CASCADE_STEP,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index d40238b4d..fcd306603 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -279,6 +279,7 @@
"system": "System"
},
"sections": {
+ "general": "General",
"backends": "Backends",
"models": "Models",
"memory": "Memory",
@@ -294,9 +295,23 @@
},
"navigationLabel": "Settings sections",
"backToWorkbench": "Back to Workbench",
+ "backToApp": "Back to Avibe",
"backToSections": "All settings",
"backToSection": "Back to {{section}}",
"close": "Close Settings",
+ "general": {
+ "title": "General",
+ "subtitle": "Choose the interface language and appearance",
+ "languageTitle": "Language",
+ "languageDescription": "Display language for the Avibe interface",
+ "appearanceTitle": "Appearance",
+ "appearanceDescription": "Follow the system, or pick a light or dark theme",
+ "appearanceSystem": "System",
+ "appearanceLight": "Light",
+ "appearanceDark": "Dark",
+ "autosaved": "Changes are saved automatically",
+ "languageSaveFailed": "The language changed here, but could not be saved for this instance"
+ },
"shortcuts": {
"title": "Shortcuts",
"subtitle": "Choose the keyboard commands you use most often in Chat and Show Pages.",
@@ -2501,22 +2516,30 @@
"eyebrow": "Workbench",
"placeholderTitle": "Your AI workbench is coming together",
"placeholderBody": "Agents, Skills, Harness, and Vaults will live here. For now, jump into the control panel to configure platforms and backends.",
- "canvas": {
- "heroTitle": "What should we build today?",
- "heroBody": "Describe what you want and an agent will run it. Or start with one of the suggestions below.",
+ "home": {
+ "heroTitle": "What would you like to do?",
+ "heroBody": "Pick a starting point, or describe your own task",
"suggestions": {
- "newProject": "Open project",
- "newProjectHint": "Pick a folder; sessions default to it",
- "openAgents": "Manage agents",
- "openAgentsHint": "Add or tweak available agents",
- "openHarness": "Schedule background work",
- "openHarnessHint": "Have an agent write the cron / watch"
+ "exploreTitle": "Explore a project",
+ "exploreBody": "Get to know your project's structure",
+ "exploreDraft": "Walk me through this project and how its main parts fit together",
+ "researchTitle": "Research a topic",
+ "researchBody": "Get a clear, practical overview",
+ "researchDraft": "Research this topic and summarize what matters in a short brief",
+ "planTitle": "Make a plan",
+ "planBody": "Turn your goal into a step-by-step plan",
+ "planDraft": "Help me turn this goal into a concrete step-by-step plan"
},
- "inputPlaceholder": "Tell the agent what you want…",
- "noProjectForChat": "No projects yet — add one before starting a chat"
+ "inputPlaceholder": "Describe a task or ask a question...",
+ "chooseWorkspace": "Choose a workspace",
+ "workspaceAria": "Workspace: {{path}}",
+ "noProjectForChat": "No projects yet — add one before starting a chat",
+ "ready": "{{backend}} is ready to go",
+ "readyDismiss": "Dismiss",
+ "continueOnPhone": "Continue on your phone",
+ "connectChatApps": "Connect chat apps in <settings>Settings</settings>"
},
"openControlPanel": "Open Control Panel",
- "capabilitiesLabel": "Capabilities",
"projectsLabel": "Projects",
"addProject": "Open project",
"addSession": "New session in this project",
@@ -2553,7 +2576,7 @@
"noReclaim": "No scheduled tasks or watches are linked to this session.",
"confirm": "Archive permanently"
},
- "projectsEmpty": "No projects yet — add one to start a session.",
+ "projectsEmpty": "Add a project to get started",
"projectsLoading": "Loading projects…",
"projectsLoadError": "Couldn't load projects.",
"sessionsLoading": "Loading sessions…",
@@ -2578,6 +2601,7 @@
},
"nav": {
"inbox": "Inbox",
+ "newChat": "New chat",
"agents": "Agents",
"skills": "Skills",
"harness": "Harness",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c0fcf6c26..9a53c3599 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -279,6 +279,7 @@
"system": "系统"
},
"sections": {
+ "general": "常规",
"backends": "后端",
"models": "模型",
"memory": "记忆",
@@ -294,9 +295,23 @@
},
"navigationLabel": "设置分区",
"backToWorkbench": "返回工作台",
+ "backToApp": "返回应用",
"backToSections": "全部设置",
"backToSection": "返回{{section}}",
"close": "关闭设置",
+ "general": {
+ "title": "常规",
+ "subtitle": "选择界面语言与外观",
+ "languageTitle": "语言",
+ "languageDescription": "Avibe 界面的显示语言",
+ "appearanceTitle": "外观",
+ "appearanceDescription": "跟随系统,或选择浅色、深色主题",
+ "appearanceSystem": "跟随系统",
+ "appearanceLight": "浅色",
+ "appearanceDark": "深色",
+ "autosaved": "修改会自动保存",
+ "languageSaveFailed": "语言已在本机切换,但未能保存到此实例"
+ },
"shortcuts": {
"title": "快捷键",
"subtitle": "设置你在聊天和 Show Page 中最常用的键盘操作。",
@@ -2501,22 +2516,30 @@
"eyebrow": "工作台",
"placeholderTitle": "你的 AI 工作台正在搭建",
"placeholderBody": "Agents、Skills、Harness、Vaults 将会汇聚到这里。现在先进控制面板配置平台和 backend。",
- "canvas": {
- "heroTitle": "今天想搭点什么?",
- "heroBody": "在下面输入想做的事,Agent 会按你的描述执行。你也可以从下面的建议开始。",
+ "home": {
+ "heroTitle": "你想做什么?",
+ "heroBody": "从一个真实任务开始,助手可以规划、研究和构建",
"suggestions": {
- "newProject": "打开项目",
- "newProjectHint": "选个目录开个项目,会话默认会落在里面",
- "openAgents": "管理 Agents",
- "openAgentsHint": "添加或调整可选的 Agent",
- "openHarness": "建后台任务",
- "openHarnessHint": "让 Agent 帮你写 cron / watch"
+ "exploreTitle": "探索项目",
+ "exploreBody": "了解工作区中的文件",
+ "exploreDraft": "请帮我梳理这个项目的结构和主要模块",
+ "researchTitle": "研究一个问题",
+ "researchBody": "把一个主题整理成实用简报",
+ "researchDraft": "帮我研究这个主题,整理成一份简短实用的简报",
+ "planTitle": "制定计划",
+ "planBody": "把目标拆成可执行的下一步",
+ "planDraft": "帮我把这个目标拆成具体、可执行的步骤"
},
- "inputPlaceholder": "和 Agent 聊点什么…",
- "noProjectForChat": "还没有项目 — 先新建一个,再来这里聊"
+ "inputPlaceholder": "给你的助手安排任务…",
+ "chooseWorkspace": "选择工作区",
+ "workspaceAria": "工作区:{{path}}",
+ "noProjectForChat": "还没有项目 — 先添加一个,再开始对话",
+ "ready": "{{backend}} 已连接,可以开始工作",
+ "readyDismiss": "关闭",
+ "continueOnPhone": "在手机 APP 上继续",
+ "connectChatApps": "聊天应用可在<settings>设置</settings>中连接"
},
"openControlPanel": "进入控制面板",
- "capabilitiesLabel": "能力",
"projectsLabel": "项目",
"addProject": "打开项目",
"addSession": "在该项目新建会话",
@@ -2553,7 +2576,7 @@
"noReclaim": "此会话没有关联的定时任务或 Watch。",
"confirm": "永久归档"
},
- "projectsEmpty": "还没有项目 — 添加一个就能开始会话。",
+ "projectsEmpty": "添加项目,开始工作",
"projectsLoading": "加载项目中…",
"projectsLoadError": "项目加载失败。",
"sessionsLoading": "加载会话中…",
@@ -2578,6 +2601,7 @@
},
"nav": {
"inbox": "收件箱",
+ "newChat": "新建会话",
"agents": "Agents",
"skills": "Skills",
"harness": "Harness",
diff --git a/ui/src/index.css b/ui/src/index.css
index 96b2461e9..b1d299fce 100644
--- a/ui/src/index.css
+++ b/ui/src/index.css
@@ -25,6 +25,16 @@
}
}
+/* How much bottom room the fixed mobile tab bar needs: its own height, the
+ home-indicator inset, and a small gap. The shell's scroll area pads by it so
+ the last row can always be scrolled clear, and a control pinned to the bottom
+ of that scroll area offsets by it so it rests just above the bar. Two
+ consumers, one number — the pair drifting apart is what leaves a button under
+ the bar. */
+:root {
+ --mobile-nav-clearance: calc(5.5rem + env(safe-area-inset-bottom));
+}
+
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
@@ -213,6 +223,15 @@
--shadow-glow-cta-cyan: 0 0 var(--brand-glow-blur) -4px rgba(63, 224, 229, 0.6);
--shadow-glow-cta-violet: 0 0 var(--brand-glow-blur) -4px rgba(124, 91, 255, 0.6);
--shadow-glow-cta-gold: 0 0 var(--brand-glow-blur) -4px rgba(255, 200, 87, 0.6);
+
+ /* The approved Workbench sidebar draws its selected nav row with a halo at the
+ sized scale's own `sm` geometry and alpha -- 16/-4 at 0.44 -- but the design
+ table gives it #10B98170 in Light beside #5BFFA070 in Dark, so the hue has to
+ follow the palette. A written-out RGB cannot: the sized rungs stay on the dark
+ neon precisely because their channels are spelled out. Mixing the live accent
+ is what `wire` already does for the same reason, which is why this is a role
+ named for its use rather than a fifth rung on the scale. */
+ --shadow-glow-nav-mint: 0 0 16px -4px color-mix(in srgb, var(--mint) 44%, transparent);
}
:root,
@@ -264,6 +283,26 @@
--input: rgba(255, 255, 255, 0.10);
--ring: rgba(91, 255, 160, 0.6);
+ /* Workbench shell surfaces from the approved design table, written as the exact
+ 8-digit hex the table states so no alpha is lost to a rounded decimal. The
+ sidebar fill and the nav row states are their own tokens rather than reuses
+ because two of them are not the value the nearest existing token holds: in
+ Light the sidebar is #FCFCFE against a #ffffff --surface, and --nav-selected-bg
+ is #10B98114 against --mint-soft's #10B98124. They happen to coincide in Dark,
+ which is exactly why collapsing them there would look correct and render wrong
+ in the other theme. */
+ --sidebar-background: #0e0e18;
+ --nav-selected-bg: #5bffa029;
+ --nav-selected-border: #5bffa059;
+ --nav-hover-bg: #1a1a26;
+ /* The well behind the brand mark, and the hairline around the decorative theme
+ preview artwork in General Settings. --desktop-overlay-shadow is the shared
+ shadow colour for surfaces that float above the shell (the settings/connection
+ dialogs); it is a colour token, not a geometry one. */
+ --logo-well-background: #ffffff04;
+ --illustration-card-border: #ffffff1c;
+ --desktop-overlay-shadow: #00000088;
+
--mint: #5bffa0;
--route-manual: #8bb4ff;
--mint-soft: rgba(91, 255, 160, 0.16);
@@ -404,6 +443,16 @@
surface those values read 2.2-4.2:1, under WCAG AA (4.5:1), and stay
there by the owner decision of 2026-08-14 above. The washes below mix
from the fill, which is why they carry the fill's hex. */
+ /* Mirrors the dark block's note: the sidebar fill and the selected nav wash
+ are the two that genuinely differ from --surface and --mint-soft here. */
+ --sidebar-background: #fcfcfe;
+ --nav-selected-bg: #10b98114;
+ --nav-selected-border: #10b98160;
+ --nav-hover-bg: #f5f5f6;
+ --logo-well-background: #eef1f780;
+ --illustration-card-border: #08081212;
+ --desktop-overlay-shadow: #0a0a1424;
+
--mint: #10b981;
--route-manual: #245bcd;
--mint-soft: rgba(16, 185, 129, 0.14);
@@ -517,6 +566,15 @@
/* Mirrors the @media light block above; see the note there. */
--ring: rgba(16, 185, 129, 0.5);
+ /* Mirrors the @media light block above; see the note in the dark block. */
+ --sidebar-background: #fcfcfe;
+ --nav-selected-bg: #10b98114;
+ --nav-selected-border: #10b98160;
+ --nav-hover-bg: #f5f5f6;
+ --logo-well-background: #eef1f780;
+ --illustration-card-border: #08081212;
+ --desktop-overlay-shadow: #0a0a1424;
+
--mint: #10b981;
--route-manual: #245bcd;
--mint-soft: rgba(16, 185, 129, 0.14);
diff --git a/ui/src/lib/adminNavigation.test.ts b/ui/src/lib/adminNavigation.test.ts
index 17c9127b7..cc12d1acc 100644
--- a/ui/src/lib/adminNavigation.test.ts
+++ b/ui/src/lib/adminNavigation.test.ts
@@ -6,9 +6,7 @@ import {
isLocalOnlyMessagingField,
isMemorySettingsPath,
isOwnerOnlyPath,
- rememberSettingsPath,
- SETTINGS_LAST_PATH_KEY,
- settingsLandingPath,
+ SETTINGS_LANDING_PATH,
} from './adminNavigation';
beforeEach(() => {
@@ -43,27 +41,12 @@ describe('isOwnerOnlyPath', () => {
});
});
-describe('settings landing memory', () => {
- it('remembers the most recent canonical section or detail', () => {
- rememberSettingsPath('/settings/backends/claude');
- expect(window.localStorage.getItem(SETTINGS_LAST_PATH_KEY)).toBe('/settings/backends/claude');
- expect(settingsLandingPath(true)).toBe('/settings/backends/claude');
+describe('settings landing', () => {
+ it('opens General, which every role can read', () => {
+ expect(SETTINGS_LANDING_PATH).toBe('/settings/general');
+ expect(isOwnerOnlyPath(SETTINGS_LANDING_PATH)).toBe(false);
});
- it('falls back to Replies for members when an owner-only section was remembered', () => {
- window.localStorage.setItem(SETTINGS_LAST_PATH_KEY, '/settings/service');
- expect(settingsLandingPath(false)).toBe('/settings/replies');
- });
-
- it('does not remember transitional platform scope pages as the Settings landing page', () => {
- rememberSettingsPath('/settings/platforms/groups');
- expect(settingsLandingPath(true)).toBe('/settings/replies');
- });
-
- it.each(['/settings/appearance', '/settings/account'])('retires a remembered preference destination: %s', (path) => {
- window.localStorage.setItem(SETTINGS_LAST_PATH_KEY, path);
- expect(settingsLandingPath(true)).toBe('/settings/replies');
- });
});
describe('isLocalOnlyMessagingField', () => {
diff --git a/ui/src/lib/adminNavigation.ts b/ui/src/lib/adminNavigation.ts
index 634ab6a37..4df85e781 100644
--- a/ui/src/lib/adminNavigation.ts
+++ b/ui/src/lib/adminNavigation.ts
@@ -4,7 +4,12 @@ const matchesRoute = (pathname: string, route: string): boolean =>
export const isMemorySettingsPath = (pathname: string): boolean =>
matchesRoute(pathname, '/settings/memory');
-export const SETTINGS_LAST_PATH_KEY = 'avibe.settings.last-path';
+/**
+ * Ordinary Settings always opens General, irrespective of the last visited
+ * subsection. General is readable by every role, so the landing page needs no
+ * capability fallback; explicit deep links stay authoritative on their own.
+ */
+export const SETTINGS_LANDING_PATH = '/settings/general';
/**
* Destinations that require Instance Owner management capability.
@@ -45,33 +50,3 @@ export const isOwnerOnlyPath = (pathname: string): boolean =>
export const isLocalOnlyMessagingField = (field: string): boolean =>
LOCAL_ONLY_MESSAGING_FIELDS.has(field);
-
-const isValidSettingsPath = (pathname: string): boolean =>
- pathname.startsWith('/settings/') &&
- pathname !== '/settings/appearance' &&
- pathname !== '/settings/account' &&
- !pathname.startsWith('/settings/platforms/groups') &&
- !pathname.startsWith('/settings/platforms/users');
-
-export const rememberSettingsPath = (pathname: string): void => {
- if (typeof window === 'undefined' || !isValidSettingsPath(pathname)) return;
- try {
- window.localStorage.setItem(SETTINGS_LAST_PATH_KEY, pathname);
- } catch {
- // Storage is an optional convenience; routing keeps a deterministic fallback.
- }
-};
-
-export const settingsLandingPath = (canManageInstance: boolean): string => {
- let remembered: string | null = null;
- if (typeof window !== 'undefined') {
- try {
- remembered = window.localStorage.getItem(SETTINGS_LAST_PATH_KEY);
- } catch {
- // Ignore unavailable storage.
- }
- }
- if (!remembered || !isValidSettingsPath(remembered)) return '/settings/replies';
- if (!canManageInstance && isOwnerOnlyPath(remembered)) return '/settings/replies';
- return remembered;
-};
diff --git a/ui/src/lib/applicationRoutes.test.ts b/ui/src/lib/applicationRoutes.test.ts
index e878e38f4..ccd4e3d29 100644
--- a/ui/src/lib/applicationRoutes.test.ts
+++ b/ui/src/lib/applicationRoutes.test.ts
@@ -13,13 +13,29 @@ import { LEGACY_SETTINGS_REDIRECTS } from './settingsRoutes';
function routePath(element: ts.JsxOpeningLikeElement): string | null {
if (element.tagName.getText() !== 'Route') return null;
- const path = element.attributes.properties.find(
+ const path = jsxAttribute(element, 'path')?.initializer;
+ return path && ts.isStringLiteral(path) ? path.text : null;
+}
+
+function jsxAttribute(
+ element: ts.JsxOpeningLikeElement,
+ name: string,
+): ts.JsxAttribute | undefined {
+ return element.attributes.properties.find(
(property): property is ts.JsxAttribute =>
- ts.isJsxAttribute(property) && property.name.getText() === 'path',
+ ts.isJsxAttribute(property) && property.name.getText() === name,
);
- return path?.initializer && ts.isStringLiteral(path.initializer)
- ? path.initializer.text
- : null;
+}
+
+/** The `to` of a `<Route element={<Navigate to="…" />} />`, or null for a page route. */
+function redirectTarget(element: ts.JsxOpeningLikeElement): string | null {
+ const initializer = jsxAttribute(element, 'element')?.initializer;
+ if (!initializer || !ts.isJsxExpression(initializer)) return null;
+ const rendered = initializer.expression;
+ if (!rendered || !ts.isJsxSelfClosingElement(rendered)) return null;
+ if (rendered.tagName.getText() !== 'Navigate') return null;
+ const to = jsxAttribute(rendered, 'to')?.initializer;
+ return to && ts.isStringLiteral(to) ? to.text : null;
}
function resolveRoutePath(path: string, parentPath: string | null): string {
@@ -27,7 +43,13 @@ function resolveRoutePath(path: string, parentPath: string | null): string {
return parentPath ? `${parentPath.replace(/\/$/, '')}/${path}` : path;
}
-function declaredRoutePaths(sourceText: string): string[] {
+type DeclaredRoutes = {
+ paths: string[];
+ /** Resolved route path -> the path its `<Navigate>` element sends callers to. */
+ redirects: Record<string, string>;
+};
+
+function declaredRoutes(sourceText: string): DeclaredRoutes {
const source = ts.createSourceFile(
'App.tsx',
sourceText,
@@ -35,33 +57,42 @@ function declaredRoutePaths(sourceText: string): string[] {
true,
ts.ScriptKind.TSX,
);
- const declared: string[] = [];
+ const paths: string[] = [];
+ const redirects: Record<string, string> = {};
+
+ const record = (element: ts.JsxOpeningLikeElement, resolvedPath: string) => {
+ paths.push(resolvedPath);
+ const target = redirectTarget(element);
+ if (target !== null) redirects[resolvedPath] = target;
+ };
const visit = (node: ts.Node, parentPath: string | null) => {
if (ts.isJsxElement(node)) {
const path = routePath(node.openingElement);
const resolvedPath = path === null ? parentPath : resolveRoutePath(path, parentPath);
- if (path !== null) declared.push(resolvedPath as string);
+ if (path !== null) record(node.openingElement, resolvedPath as string);
node.children.forEach((child) => visit(child, resolvedPath));
return;
}
if (ts.isJsxSelfClosingElement(node)) {
const path = routePath(node);
- if (path !== null) declared.push(resolveRoutePath(path, parentPath));
+ if (path !== null) record(node, resolveRoutePath(path, parentPath));
return;
}
ts.forEachChild(node, (child) => visit(child, parentPath));
};
visit(source, null);
- return declared;
+ return { paths, redirects };
}
+const appRoutes = () =>
+ declaredRoutes(readFileSync(new URL('../App.tsx', import.meta.url), 'utf8'));
+
describe('AppShell route policy', () => {
it('matches every page and generated legacy redirect declared by App.tsx', () => {
- const appSource = readFileSync(new URL('../App.tsx', import.meta.url), 'utf8');
const declared = [
- ...declaredRoutePaths(appSource),
+ ...appRoutes().paths,
...LEGACY_SETTINGS_REDIRECTS.map((redirect) => redirect.from),
];
const catalog = [...APPLICATION_ROUTE_PATHS, ...APPLICATION_DYNAMIC_ROUTE_PATHS];
@@ -69,6 +100,17 @@ describe('AppShell route policy', () => {
expect([...declared].sort()).toEqual([...catalog].sort());
});
+ it('sends each retired Settings alias to the page that took its content over', () => {
+ // Read off App.tsx itself: an alias that still points at the page it was
+ // moved away from is a live wrong destination, not a stale constant.
+ const { redirects } = appRoutes();
+
+ // Theme controls moved to General; the rest of Appearance did not survive.
+ expect(redirects['/settings/appearance']).toBe('/settings/general');
+ // Account remains part of the Replies page, so its alias is unchanged.
+ expect(redirects['/settings/account']).toBe('/settings/replies');
+ });
+
it('recognizes exact and dynamic routes without reserving their namespaces', () => {
for (const path of APPLICATION_ROUTE_PATHS) {
expect(isApplicationRouteHref(path), path).toBe(true);
diff --git a/ui/src/lib/applicationRoutes.ts b/ui/src/lib/applicationRoutes.ts
index 17aecbf22..bf544b26a 100644
--- a/ui/src/lib/applicationRoutes.ts
+++ b/ui/src/lib/applicationRoutes.ts
@@ -44,6 +44,7 @@ export const APPLICATION_ROUTE_PATHS = [
'/users',
'/logs',
'/settings',
+ '/settings/general',
'/settings/appearance',
'/settings/account',
'/settings/shortcuts',
diff --git a/ui/src/lib/pwaRouteMemory.test.ts b/ui/src/lib/pwaRouteMemory.test.ts
index ed51a42b8..3bfd3cb5e 100644
--- a/ui/src/lib/pwaRouteMemory.test.ts
+++ b/ui/src/lib/pwaRouteMemory.test.ts
@@ -51,6 +51,31 @@ describe('PWA route memory', () => {
expect(setItem).toHaveBeenCalledWith('avibe.pwa.last-route.v1', '/chat/session-456');
});
+ it('cold-launches an installed PWA back onto General through the whole chain', () => {
+ // One test-owned store carries the actual write -> read -> resolve path, so
+ // the allowlist entry is exercised where the product uses it rather than
+ // only where it is declared.
+ const store = new Map<string, string>();
+ const storage = {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => { store.set(key, value); },
+ };
+
+ writeLastPwaPath('/settings/general?tab=theme#appearance', storage);
+ expect(store.get('avibe.pwa.last-route.v1')).toBe('/settings/general');
+
+ const remembered = readLastPwaPath(storage);
+ expect(remembered).toBe('/settings/general');
+ expect(resolvePwaLaunchPath(true, { pathname: '/', search: '', hash: '' }, remembered))
+ .toBe('/settings/general');
+
+ // The allowlist is still a list, not a prefix rule: an unknown sub-path is
+ // rejected at the write, leaving the last restorable route intact.
+ expect(normalizeRestorablePwaPath('/settings/general/theme')).toBeNull();
+ writeLastPwaPath('/settings/general/theme', storage);
+ expect(readLastPwaPath(storage)).toBe('/settings/general');
+ });
+
it('tolerates unavailable browser storage', () => {
expect(
readLastPwaPath({
diff --git a/ui/src/lib/pwaRouteMemory.ts b/ui/src/lib/pwaRouteMemory.ts
index b17a0a1af..54f8ef0d3 100644
--- a/ui/src/lib/pwaRouteMemory.ts
+++ b/ui/src/lib/pwaRouteMemory.ts
@@ -17,6 +17,7 @@ const RESTORABLE_EXACT_PATHS = new Set([
'/apps/editor',
'/apps/library',
'/settings',
+ '/settings/general',
'/settings/appearance',
'/settings/account',
'/settings/shortcuts',
diff --git a/ui/src/lib/settingsOverlay.test.ts b/ui/src/lib/settingsOverlay.test.ts
index a45fef48f..74efe0d79 100644
--- a/ui/src/lib/settingsOverlay.test.ts
+++ b/ui/src/lib/settingsOverlay.test.ts
@@ -87,7 +87,7 @@ describe('Settings overlay navigation ownership', () => {
expect(settingsOverlayOriginFromState(directRedirectState)).toBeNull();
});
- it('leaves mobile Settings ingress as a primary route', () => {
+ it('leaves mobile Settings ingress from an ordinary route as a primary route', () => {
const state = settingsOverlayNavigationState({
destinationPathname: '/settings/replies',
desktop: false,
@@ -97,6 +97,66 @@ describe('Settings overlay navigation ownership', () => {
expect(settingsOverlayOriginFromState(state)).toBeNull();
});
+ it('retains the Workbench home behind mobile Settings and carries it onward', () => {
+ const home = location('/');
+ const state = settingsOverlayNavigationState({
+ destinationPathname: '/settings/remote-access',
+ desktop: false,
+ historyState: { idx: 4 },
+ source: home,
+ targetState: undefined,
+ });
+
+ const retained = settingsOverlayOriginFromState(state);
+ expect(retained).toEqual({ historyIndex: 4, location: home });
+
+ // Settings-internal navigation keeps the same origin rather than minting a
+ // second one, so Back still unwinds to the composer the user left.
+ const onward = settingsOverlayNavigationState({
+ destinationPathname: '/settings/general',
+ desktop: false,
+ historyState: { idx: 5 },
+ source: location('/settings/remote-access', state),
+ targetState: undefined,
+ });
+ expect(settingsOverlayOriginFromState(onward)).toEqual({ historyIndex: 4, location: home });
+
+ // Closing from anywhere in that chain unwinds every entry back to home.
+ const navigate = vi.fn();
+ closeSettingsOverlay(navigate, settingsOverlayOriginFromState(onward)!, { idx: 6 });
+ expect(navigate).toHaveBeenCalledWith(-2);
+ });
+
+ it('keeps the origin across a retired-alias redirect', () => {
+ const opened = settingsOverlayNavigationState({
+ destinationPathname: '/settings/appearance',
+ desktop: true,
+ historyState: { idx: 2 },
+ source: origin().location,
+ targetState: undefined,
+ });
+ // `<Navigate to="/settings/general" replace />` runs through the same
+ // boundary, so the page the alias lands on still knows what it covered.
+ const redirected = settingsOverlayNavigationState({
+ destinationPathname: '/settings/general',
+ desktop: true,
+ historyState: { idx: 3 },
+ source: location('/settings/appearance', opened),
+ targetState: undefined,
+ });
+ expect(settingsOverlayOriginFromState(redirected)).toEqual(origin());
+ });
+
+ it('invents no origin for a mobile Settings deep link', () => {
+ const state = settingsOverlayNavigationState({
+ destinationPathname: '/settings/general',
+ desktop: false,
+ source: location('/settings'),
+ targetState: undefined,
+ });
+ expect(settingsOverlayOriginFromState(state)).toBeNull();
+ });
+
it('identifies only an ingress that preserves the current route', () => {
const current = origin().location;
const overlayState = settingsOverlayNavigationState({
diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.ts
index e15596b65..04cffa22e 100644
--- a/ui/src/lib/settingsOverlay.ts
+++ b/ui/src/lib/settingsOverlay.ts
@@ -87,6 +87,18 @@ export const settingsOverlayStateForOrigin = (
...overlayStateForOrigin(origin),
});
+/**
+ * The Workbench home's Settings continuations lead away from an unsent draft
+ * plus the Agent and workspace it is aimed at, none of which is persisted
+ * anywhere. They therefore record an origin on mobile too, which keeps that one
+ * Workbench instance mounted behind the full-screen mobile Settings surface so
+ * Back returns to the composition the user left instead of a new home. This
+ * retains that one route's local state and nothing else: every other mobile
+ * route keeps its ordinary unmount-on-navigate lifecycle, and a direct Settings
+ * link still invents no origin.
+ */
+const retainsOriginOnMobile = (pathname: string): boolean => pathname === '/';
+
export const settingsOverlayNavigationState = ({
destinationPathname,
desktop,
@@ -104,8 +116,9 @@ export const settingsOverlayNavigationState = ({
if (settingsOverlayOriginFromState(targetState)) return targetState;
const retainedOrigin = settingsOverlayOriginFromState(source.state);
+ const retains = desktop || retainsOriginOnMobile(source.pathname);
const origin = retainedOrigin
- ?? (desktop && !isSettingsEntryPath(source.pathname)
+ ?? (retains && !isSettingsEntryPath(source.pathname)
? originFromLocation(source, historyState)
: null);
if (!origin) return targetState;
diff --git a/ui/src/lib/useLanguageSelection.ts b/ui/src/lib/useLanguageSelection.ts
new file mode 100644
index 000000000..b53b24427
--- /dev/null
+++ b/ui/src/lib/useLanguageSelection.ts
@@ -0,0 +1,241 @@
+import { useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useApi } from '../context/ApiContext';
+import { useInstanceAuthorization } from '../context/InstanceAuthorizationContext';
+import { useToast } from '../context/ToastContext';
+import { setConfigField } from './configMutations';
+import { useLatestRef } from './useLatestRef';
+
+export interface LanguageOption {
+ code: string;
+ label: string;
+}
+
+export interface LanguageSelection {
+ languages: LanguageOption[];
+ current: LanguageOption;
+ /** Apply the pick to this browser immediately, then persist it as the instance
+ * language when the caller may manage the instance. There is no Save button,
+ * so a failed save is reported where the user can act on it instead of being
+ * swallowed under a page that claims changes save themselves. The local
+ * change still stands: the pick they can see is the one they made. */
+ select: (code: string) => Promise<void>;
+}
+
+/** The interface a language belongs to. Structural on purpose: the key is the
+ * i18n instance itself, the one thing in this stack that lasts as long as the
+ * interface it names. */
+type LanguageHost = {
+ language: string;
+ changeLanguage: (code: string) => unknown;
+};
+
+/** What a mounted control lends the operation. Every field is read when a write
+ * actually runs, never captured when it is queued: `ApiContext` memoizes its
+ * value on `t`, so changing the language is itself what hands out a new
+ * `mutateConfig`, and the user's authority can change while a save waits. */
+type LanguageConsumer = {
+ /** Asked twice on purpose: once as the pick is made, which decides whether it
+ * is an instance decision at all, and again when its write actually runs, so
+ * authority taken away in between is never spent. Neither answer stands in
+ * for the other. */
+ canPersist: () => boolean;
+ persist: (code: string) => Promise<unknown>;
+ reportFailure: (retry: () => void) => void;
+};
+
+type LanguageOperation = {
+ /** The controls on screen now. Any of them can serve the queue — they read the
+ * same providers — which is the point: the operation belongs to the language,
+ * not to whichever control the user happened to have open. */
+ serving: Set<LanguageConsumer>;
+ /** The last one to have served, kept after it unmounts so a save already under
+ * way still has an api to finish through. */
+ last: LanguageConsumer | null;
+ tail: Promise<void>;
+ /** Generations, not language codes: A -> B -> A has to stay three decisions,
+ * and a failure has to name the pick that caused it. */
+ picks: number;
+ latest: number;
+ failed: number | null;
+};
+
+// MODULE scope on purpose, the way `useCoalescedWrite` owns a chat's writes: the
+// language is one instance-wide value and a save outlives the control that
+// started it. Settings unmounts the moment the user leaves it, so a queue owned
+// by the component let the next control fire a second POST beside the first and
+// let the older one commit last. Keyed by the i18n instance rather than by the
+// api, because ApiContext's value is memoized on `t` and is therefore replaced by
+// the very language change being ordered; a WeakMap rather than a singleton so
+// two independent interfaces cannot serialize each other's writes.
+const operations = new WeakMap<LanguageHost, LanguageOperation>();
+
+/** The instance behind what a component is holding. `useTranslation` does not
+ * hand out the i18n instance: on every language change it returns a fresh copy
+ * of it — same prototype, same own properties, the instance kept as
+ * `__original` — so the object a control holds is replaced by the very
+ * operation being ordered, exactly like `ApiContext`'s value. Resolved at the
+ * boundary so everything below this line means the instance; a copy is what an
+ * interface looks like from inside a render, not what it is. If a future
+ * react-i18next stops copying, the object already is the instance and this is a
+ * no-op — and the consumer tests fail loudly if neither holds. */
+const instanceOf = (held: LanguageHost): LanguageHost =>
+ (held as { __original?: LanguageHost }).__original ?? held;
+
+const operationFor = (host: LanguageHost): LanguageOperation => {
+ const existing = operations.get(host);
+ if (existing) return existing;
+ const created: LanguageOperation = {
+ serving: new Set<LanguageConsumer>(),
+ last: null,
+ tail: Promise.resolve(),
+ picks: 0,
+ latest: 0,
+ failed: null,
+ };
+ operations.set(host, created);
+ return created;
+};
+
+/** Lends a mounted control to its interface's language operation for as long as
+ * it is on screen. Returns the release, for an effect cleanup. */
+export const serveLanguageOperation = (
+ held: LanguageHost,
+ consumer: LanguageConsumer,
+): (() => void) => {
+ const operation = operationFor(instanceOf(held));
+ operation.serving.add(consumer);
+ operation.last = consumer;
+ return () => {
+ operation.serving.delete(consumer);
+ };
+};
+
+const activeConsumer = (operation: LanguageOperation): LanguageConsumer | null => {
+ let active: LanguageConsumer | null = null;
+ for (const consumer of operation.serving) active = consumer;
+ return active;
+};
+
+const enqueue = (operation: LanguageOperation, code: string, pick: number): Promise<void> => {
+ const run = async () => {
+ // A pick the user has already moved past is not worth a request.
+ if (operation.latest !== pick) return;
+ // The control that started this may be gone; the interface still has to
+ // finish the save, so fall back to the last one that served. Its authority
+ // is read now rather than remembered from when the pick was queued — a
+ // write must not outlive the permission behind it. An already-sent request
+ // is not recalled; this is about what is still ours to send.
+ const consumer = activeConsumer(operation) ?? operation.last;
+ if (!consumer || !consumer.canPersist()) return;
+ try {
+ await consumer.persist(code);
+ operation.failed = null;
+ } catch {
+ if (operation.latest !== pick) return;
+ operation.failed = pick;
+ consumer.reportFailure(() => retryLanguageSave(operation, code, pick));
+ }
+ };
+ // Both arms run the next save: one refusal must not strand everything queued
+ // behind it.
+ operation.tail = operation.tail.then(run, run);
+ return operation.tail;
+};
+
+const retryLanguageSave = (operation: LanguageOperation, code: string, pick: number): void => {
+ // Inert unless this is still both the current choice and the current failure:
+ // after a newer pick — the same code picked again included — the toast is a
+ // record of something that no longer describes the interface.
+ if (operation.latest !== pick || operation.failed !== pick) return;
+ // Nothing is on screen to own a retry. The pick itself still stands locally;
+ // it is the save that is not re-attempted on the authority of a control that
+ // is no longer there.
+ if (!activeConsumer(operation)) return;
+ void enqueue(operation, code, pick);
+};
+
+/**
+ * Records a user's language pick for one interface: local first, then persisted
+ * once, in order, however the controls come and go.
+ */
+export const selectLanguage = (held: LanguageHost, code: string): Promise<void> => {
+ const host = instanceOf(held);
+ const operation = operationFor(host);
+ operation.picks += 1;
+ const pick = operation.picks;
+ operation.latest = pick;
+ // The pick they can see is the one they made, whatever the save does next —
+ // and it retires any older failure, including for a user who persists nothing.
+ void host.changeLanguage(code);
+ // Whether this pick is an instance decision at all is settled here, by the
+ // authority the user held while making it, and never revisited: a member
+ // changing their own interface is choosing something local, so authority
+ // arriving later — a promotion, a re-read, a second tab — must not turn that
+ // into a write they never asked for. Only a control on screen can answer for
+ // them; a pick made with none is nobody's authority to spend.
+ const chooser = activeConsumer(operation);
+ if (!chooser || !chooser.canPersist()) return Promise.resolve();
+ return enqueue(operation, code, pick);
+};
+
+/**
+ * Adopts the persisted instance language on load. A config read can answer late
+ * — and the shell starts another one whenever `api` changes identity, which a
+ * language change does — so it may only ever speak before the user has: once
+ * this interface has a pick of its own, that pick is the answer.
+ */
+export const adoptPersistedLanguage = (held: LanguageHost, code: unknown): void => {
+ if (typeof code !== 'string' || !code) return;
+ const host = instanceOf(held);
+ const operation = operationFor(host);
+ if (operation.picks > 0) return;
+ if (code === host.language) return;
+ void host.changeLanguage(code);
+};
+
+/**
+ * One owner for "which language is this, and what happens when you pick another"
+ * — shared by the compact header switcher and the General settings selector, so
+ * the two cannot drift on persistence or on which codes exist.
+ */
+export const useLanguageSelection = (): LanguageSelection => {
+ const { i18n, t } = useTranslation();
+ const { mutateConfig } = useApi();
+ const { capabilities } = useInstanceAuthorization();
+ const { showToast } = useToast();
+
+ const latest = useLatestRef({
+ i18n,
+ mutateConfig,
+ showToast,
+ canManage: capabilities.can_manage_instance,
+ });
+ useEffect(() => serveLanguageOperation(i18n, {
+ canPersist: () => latest.current.canManage,
+ persist: (code) => latest.current.mutateConfig([setConfigField(['language'], code)]),
+ reportFailure: (retry) => {
+ const { showToast: toast, i18n: active } = latest.current;
+ // Translated when it is shown, not when the save was started: by now the
+ // interface is already in the language that failed to save.
+ toast(active.t('settings.general.languageSaveFailed'), 'error', {
+ label: active.t('common.retry'),
+ onClick: retry,
+ });
+ },
+ }), [i18n, latest]);
+
+ const codes = Object.keys(i18n.options.resources ?? {});
+ const languages = (codes.length ? codes : ['en']).map((code) => ({
+ code,
+ label: t(`language.${code}`, { defaultValue: code }),
+ }));
+ const current = languages.find((lang) => lang.code === i18n.language) || languages[0];
+
+ const select = (code: string): Promise<void> => (
+ code === i18n.language ? Promise.resolve() : selectLanguage(i18n, code)
+ );
+
+ return { languages, current, select };
+};