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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(ui): settings menu placement, unified cards, one left column (#2068)
Maxb45fbc604b09
diff --git a/docs/plans/2026-09-20-settings-general-polish.md b/docs/plans/2026-09-20-settings-general-polish.mdnew file mode 100644index 000000000..68db6882c--- /dev/null+++ b/docs/plans/2026-09-20-settings-general-polish.md@@ -0,0 +1,269 @@+# Settings: unified cards, a menu-placement choice, and one left column++## Background++Three things about the Settings surface were inconsistent enough to notice.++1. **The General page's cards are the only filled ones.** `SettingsPanel`'s+ `preference` variant rendered `bg-surface-2`, so Appearance sat on a lighter+ board while every other settings page draws its cards as an outline on the+ page background. The design source (`design.pen`, frames `le5QU` / `Q8zxF1`)+ does specify surface-2 there, but it specifies one page in isolation; the+ product reads them as a set.++2. **Settings has exactly one layout and no way to ask for the other.** Since+ PR #2051 Settings is *standalone*: it takes the whole window and its rail+ replaces the app sidebar. The older *inline* layout — Settings opening beside+ a sidebar that stays visible and live — is a real preference, and the shell+ still has all the machinery for it.++3. **The two left columns are different widths.** The app sidebar is 248px+ (draggable, published as `--app-sidebar-w`); the Settings rail was a literal+ 196px. Because standalone Settings replaces the sidebar, opening Settings+ moved the left column 52px and moved it back on close.++## Goal++- General's cards look like every other settings page's cards.+- The owner can choose whether Settings takes over the window or opens beside+ the app sidebar, from a control drawn like the theme selector next to it.+- Opening standalone Settings never shifts the left column.++## Where the preference lives: localStorage, not the database++Chosen: `localStorage`, key `avibe.settings.menu-placement.v1`.++- It is a per-person, per-device *view* preference, the same tier as theme —+ which already lives in `localStorage` under `vibe-remote-theme`.+- There is no per-user preference store on the server. `UiConfig` is+ instance-wide; `language` lives there precisely *because* it is owner-managed.+ Copying that path would let one member re-lay out every other member's window.+- A preferences table plus an API, a role projection and cache invalidation is a+ whole new concept to carry one binary choice — and `config/v2_config.py` is a+ shipped on-disk surface, so the schema would be permanent.+- The house pattern already exists (`actionShortcuts.ts`, `agentsViewMemory.ts`):+ `useSyncExternalStore` + a versioned key + a custom event + an injectable+ `Storage` for tests.++Accepted cost: no cross-device sync, and clearing browser data resets it —+identical to theme, and reversible later if a real preference store ever exists.++## Solution++### One derived question, answered once++Three trees need the same answer and would otherwise each re-derive it.+`ui/src/lib/settingsMenuPlacement.ts` exports the store *and*+`useStandaloneSettingsMenu()`, which owns the whole derivation.++`inline` is a claim about something *else* being on screen, so the stored+preference only means anything where an app sidebar is actually there to sit+beside. Two things take that away, and the hook folds in both:++- **The viewport.** Below `md` there is no room for two rails, so Settings+ covers the shell.+- **The shell.** Some shells draw no sidebar at all, so there is nothing to open+ beside and the answer is standalone on a full desktop window too. Without this,+ inline would offset Settings past an empty strip and narrow its rail for a+ neighbour that does not exist.++Either way the answer is standalone, and neither one forgets what the owner+picked for the windows that do have a sidebar.++*Which* shells those are is the shell's own business, so `AppShell` **publishes**+the answer through `ShellSidebarContext` rather than letting each Settings surface+recognise them by pathname. Two shells draw no sidebar and they disagree on what+the answer even depends on: the setup wizard is a matter of the route, while a+single-app tab (`?standalone=1`) turns on a document flag frozen at mount and+deliberately *not* re-read from the URL the shell rewrites underneath it. No+pathname predicate can recover that second one, and the route a Settings surface+lands on says nothing about the shell it opened over anyway — the config-recovery+banner's Diagnostics link opens Settings from a single-app tab onto an ordinary+settings route. So the shell states `shellDrawsSidebar = !chromeless && !setupShell`+beside the two conditions that actually decide whether an `<aside>` renders, and+both consumers read it.++`isStandaloneSettingsMenu(placement, isDesktop, shellHasSidebar)` is the pure rule+and takes no defaultable parameter — a forgotten optional boolean is+indistinguishable from "there is a sidebar" and fails silently. Everything inside+the shell calls the zero-argument `useStandaloneSettingsMenu()`; `AppShell`, being+the publisher, feeds the rule directly.++> Scope note: this publication model replaced a first attempt that re-derived the+> question from `isChromelessShellPath(pathname)` at each call site. Two review+> heads produced findings of one root-cause class — the derivation could only ever+> cover the cases someone remembered to enumerate — which tripped the review-loop+> circuit breaker. The diagnosis was that `AppShell` already owned a concept for+> this (`chromeless`) and the pathname predicate was a second, parallel one+> answering the same question; making the existing owner publish it is the smallest+> complete fix, and it is reversible and contract-preserving.+>+> A fourth head then produced a finding of the *other* class already seen on+> `b1c5c330d6` — "which interactions belong to the live sidebar", answered by DOM+> ancestry, missing everything portaled out of it. Same escalation: rather than+> name one more surface, inline stopped dismissing on outside interaction at all,+> which is what the reachable-surface inventory above says it should never have+> done. Standalone's shipped behaviour is untouched.+>+> A fifth head put that class on three heads, now claiming a transparent+> `z-20` backdrop swallows every sidebar interaction. That one is not true:+> Radix returns `null` from `DialogOverlay` unless the dialog is modal, and the+> surface's only caller is non-modal, so the backdrop never reached the DOM. The+> class's real root cause is what makes three reviewers keep finding new+> mechanisms for one violation: *"inline leaves the shell live"* was stated only+> as prose and class names, and the primitive carried dead markup that reads+> exactly like the violation. So the contract is now stated where covering is a+> real concept — a browser hit test — and the dead backdrop is deleted rather+> than explained.+>+> The same head carried a *fourth* instance of the class that is true, and it+> corrects the rule rather than the code: `WindowLayer` really is `fixed inset-0`+> at `z-20`, above the sidebar's `z-10`, deliberately, so a window can be dragged+> over the sidebar and maximize can fill the screen. Under inline Settings that+> layer stays live behind an opaque `z-30` surface, so an open window shows as a+> strip over the one column inline exists to keep, with its title bar, controls+> and content all hidden. So the rule is not "inline leaves the shell live" but+> **inline keeps the sidebar column live; whatever the opaque surface covers+> retires in both placements** — which is two consumers, not a growing list:+> `WindowLayer` and the `AppsLauncher` that opens into it. Everything else is+> either inside the sidebar column or floats above the surface, so it keeps+> `settingsCoversSidebar`.++### What each consumer does with it++- **`AppShell`** previously used one flag, `settingsOpen`, for two different+ questions. It now distinguishes *Settings is the foreground route* (the+ sidebar toggle's label, still `settingsOpen`) from *Settings took over the+ shell* (`settingsCoversSidebar`). Everything in or above the sidebar column+ reads the latter: the `aside`'s `inert`/`aria-hidden`/visibility, the+ `WorkbenchSidebar` route-surface boundary, the content column's left offset,+ the mobile dock, `NewSessionSheet`, `SearchPalette` and the ⌘K guard. Inline+ Settings therefore leaves a live, navigable sidebar — which is exactly what+ shipped before #2051 (verified against `66fc91db^`).++ The two exceptions read `settingsOpen`, and they are the reason both flags+ exist: `WindowLayer` spans the whole viewport *above* the sidebar so windows+ can be dragged over it, so inline's opaque surface would leave it+ live-but-invisible rather than live; and `AppsLauncher`, whose every result+ appears in that layer, goes with it. Both retire under either placement, and+ both come back when Settings closes.+- **`SettingsOverlayRouteSurface`** picks its own left edge: standalone starts at+ the screen edge with no left border; inline takes the primitive's+ `--app-sidebar-w` offset and a border, so the two edges stay together while the+ sidebar is dragged. It publishes `data-settings-menu-placement` for tests.++ It also decides what an interaction *outside* the surface means, and inline+ turns out not to have an outside in the sense that handler assumes. Inline+ covers everything right of the sidebar, so what stays reachable is the sidebar+ column (z-10, left of the surface) and whatever the shell floats above the+ z-30 surface: the Apps launcher and its Dock at z-40, menus and floating+ details at z-50. Every one of those belongs to the live shell and already owns+ what it does — there is no neutral background left to click at. So **inline+ does not dismiss on outside interaction at all**, and is left by Escape, by the+ Settings toggle, or by navigating.++ That is deletion rather than exemption, and deliberately so. The resize edge+ moves this surface's own left edge, so grabbing it must not close what the drag+ is laying out; a sidebar link already navigates, and that navigation *is* the+ way out — letting dismissal fire too would race two navigations+ (`closeSettingsOverlay` traverses history asynchronously while the link pushes+ synchronously) and could land on the retained origin instead of the route that+ was clicked. Naming the exempt surfaces cannot express this, because+ `AppsLauncher` portals itself to `document.body` to clear the route panel's+ stacking context: it belongs to the sidebar without descending from it, and so+ do the menus and details beside it. Any DOM-ancestry test covers only the+ portals someone remembered.++ Standalone keeps the dismissal that shipped, including its single+ `data-settings-toggle` exemption — it does own the whole viewport, so "outside"+ there means what it always did.+- **`SettingsLayout`**'s rail is `var(--app-sidebar-w)` when standalone (so it+ tracks even a dragged sidebar) and stays 196px inline, where spending a second+ full-width column on a secondary nav would cost 496px of left chrome.++### Incidental fixes++The first two are in `DialogSurfaceContent`, and are the same shape: markup that+looked authoritative and was in fact dead.++- The default offset was a literal `md:left-[240px]` — dead (its only caller+ overrode it) and wrong (the sidebar has been 248/variable for a while). It is+ now `md:left-[var(--app-sidebar-w)]`, which is what lets the inline caller+ need no override at all.+- It also declared a transparent full-viewport backdrop at `z-20`, above the+ app sidebar's `z-10`, with a comment crediting it for focus and accessibility+ isolation. None of that was happening: Radix's `DialogOverlay` returns `null`+ unless the dialog is modal, and this surface's one caller is deliberately+ non-modal precisely so the shell behind stays live. The element never+ existed at runtime — but on the page it reads as a layer over a live sidebar,+ which is how it produced a P2. Deleted; a caller that wants a real backdrop+ wants `DialogContent`.++The third is the sidebar's own maximum width, and it predates this PR:+`MAX_SIDEBAR_WIDTH = 496` is viewport-blind, so a full drag in a 768px window+already leaves a 272px workbench today. Inline Settings spends 196 of that on+its rail, which is what made it visible. The fix belongs to the sidebar, not to+its consumers — each of them would otherwise re-derive the same budget, and+capping only while Settings is open would move the column the moment Settings+opened. So the maximum now reserves `MIN_WIDTH_BESIDE_SIDEBAR` (768 − 248 = 520,+exactly what a default sidebar already leaves at `md`, so no shipped+configuration changes), and follows the viewport as well as the gesture:+narrowing the window after a wide drag reaches the same starved layout, just+later. An untouched shell still publishes no inline width at all.++### The card++`ChoiceCards<T extends string>` was extracted from the existing appearance+radiogroup rather than copied: same DOM, same roles, same keyboard handling, now+serving both the theme miniatures and the two placement miniatures (a 2-column+sketch for standalone, a 3-column one for inline). The placement card is hidden+below `md` — a control that changes nothing on the viewport you are holding is+not a choice.++## Deliberate divergence++`design.pen` `le5QU` / `Q8zxF1` fill the preference card with `--surface-2`.+The card now carries `--background`. Consistency with every neighbouring+settings page was judged worth more than fidelity to one frame; radius (12),+padding (22) and gap (20) still follow the source exactly, which is why+`preference` remains its own variant. Recorded here and in the PR rather than+edited into `design.pen`.++## Validation++- `settingsMenuPlacement.test.tsx` — default, persistence, refused storage,+ same-tab propagation across React trees, cross-tab `storage` events, and both+ fold-ins: the viewport, and a shell that draws no sidebar.+- `SettingsGeneralPage.test.tsx` — the placement radiogroup is its own group,+ arrowed and drawn like the theme one beside it, and does not touch the theme key.+- `AppShell.test.tsx` — the shell retires only where Settings replaces it, covers+ the shell below `md` even when inline is stored, and publishes a sidebar-free+ shell to the Settings surfaces above it in a single-app tab. Plus the two+ exceptions: the window layer and its launcher retire under *either* placement+ and come back when Settings closes. The `AppsLauncher` stub now honours its+ route-surface boundary the way the real one does, so it cannot report a live+ Apps button in a state the shell retires it.+- `SidebarResizer.test.tsx` — the width budget as a pure function across five+ viewports, a drag and an `End` press both stopping at the affordable maximum+ rather than the constant one, a window narrowed *after* a wide drag giving the+ width back, and an untouched shell still publishing no inline width when the+ budget moves. Verified non-vacuous: disabling the re-clamp fails the narrowing+ test (it also caught a real bug while being written — the first re-clamp read+ an already-clamped width, so it could never see one that no longer fit).+- `SettingsLayout.test.tsx` — rail width per placement, including standalone where+ the shell draws no sidebar while `inline` is stored.+- `SettingsOverlayRouteSurface.test.tsx` — the surface's left edge and border per+ placement, standalone where the shell draws no sidebar, and what an outside+ interaction means: inline dismisses on none of them — the resize edge, the+ sidebar's quiet space, a control *portaled* out of the sidebar, or the rest of+ the shell — while Escape and a sidebar link each still leave, in exactly one+ navigation. Standalone still dismisses on the same portaled control, which is+ the shipped behaviour. The portal case is the one an ancestry test cannot pass.+- `e2e/workbench-general/geometry.spec.ts` — measured in a browser: the 248 rail,+ the card's background matching a neighbouring page's card, and inline actually+ putting a live sidebar beside Settings at the sidebar's own width. It also+ asks the browser what is under the pointer over that sidebar's Settings+ toggle, which is the only place "nothing covers the live shell" can be+ settled — a class name, a bounding box and jsdom all miss a transparent+ layer. Verified non-vacuous: injecting a real `fixed inset-0 z-20` div into+ the surface fails it.diff --git a/ui/e2e/workbench-general/capture.spec.ts b/ui/e2e/workbench-general/capture.spec.tsindex 469fd5e16..b51df9361 100644--- a/ui/e2e/workbench-general/capture.spec.ts+++ b/ui/e2e/workbench-general/capture.spec.ts@@ -54,7 +54,7 @@ for (const osTheme of ['light', 'dark'] as const) {await serveProduct(page);await page.setViewportSize(DESKTOP);await open(page, '/settings/general', { theme: 'system' });- await page.locator('[role="radiogroup"]').waitFor({ state: 'visible' });+ await page.locator('[role="radiogroup"]').first().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.tsindex e69f3f8d5..30001f9aa 100644--- a/ui/e2e/workbench-general/geometry.spec.ts+++ b/ui/e2e/workbench-general/geometry.spec.ts@@ -5,8 +5,9 @@ import { DESKTOP, NARROW, ORIGIN, WIDE, config, open, serveProduct } from './sup/*** The packet's geometry claims, measured in a browser rather than inferred from* class names. Workbench keeps its adjustable 248px default/sidebar offset;- * standalone Settings has a 196px rail and a 944px outer content frame with- * 880px of common content at the desktop reference width.+ * standalone Settings stands in for that sidebar, so its rail is the same 248px+ * and the left column cannot jump when Settings opens. The 944px outer content+ * frame still carries 880px of common content at the desktop reference width.*/const SIDEBAR = 'aside.fixed';@@ -15,7 +16,10 @@ 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"])';+// General now has two preference cards drawn the same way, so name the one the+// geometry claims are about by the selector it owns.+const APPEARANCE_CARD = 'section.bg-background:has([role="radiogroup"][aria-label="Appearance"])';+const PLACEMENT_CARD = 'section.bg-background:has([role="radiogroup"][aria-label="Settings menu"])';// The home's own project row, not the sidebar tree row: it is the selection the// overlay has to hand back, and the fixture names it in non-ASCII on purpose.const PROJECT_CHIP = '中文项目';@@ -348,14 +352,14 @@ test.describe('page background family', () => {});test.describe('general settings geometry', () => {- test('keeps the rail at 196 and the common content at 880px', async ({ page }) => {+ test('keeps the standalone rail on the sidebar width and the common content at 880px', 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);+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(248);const cardAtStaging = await widthOf(page, APPEARANCE_CARD);// The desktop Settings frame is 944px wide with 32px horizontal padding,@@ -363,7 +367,7 @@ test.describe('general settings geometry', () => {await page.setViewportSize(ULTRA);await page.waitForFunction(() => window.innerWidth === 1920);- expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(248);const cardAtUltra = await widthOf(page, APPEARANCE_CARD);expect(cardAtStaging).toBe(880);expect(cardAtUltra).toBe(880);@@ -402,15 +406,15 @@ test.describe('general settings geometry', () => {});// 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.+ // two neighbours that both ended in "Platform…" when the rail was narrower.+ // The rail width is the sidebar's, so the labels wrap rather than widen it.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);+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(248);// Measured, not eyeballed: a wrapped label's scrollWidth equals its// clientWidth; a clipped one exceeds it.@@ -501,13 +505,13 @@ test.describe('general settings geometry', () => {await open(page, path);await settleSettingsFrame(page);const frame = await frameGeometry(page);- expect(frame.width).toBe(viewport.width >= 944 + 196 ? 944 : viewport.width);- expect(frame.paddingLeft).toBe(viewport.width >= 944 + 196 ? 32 : 16);+ expect(frame.width).toBe(viewport.width >= 944 + 248 ? 944 : viewport.width);+ expect(frame.paddingLeft).toBe(viewport.width >= 944 + 248 ? 32 : 16);expect(frame.paddingRight).toBe(frame.paddingLeft);- expect(frame.contentWidth).toBe(viewport.width >= 944 + 196 ? 880 : viewport.width - 32);+ expect(frame.contentWidth).toBe(viewport.width >= 944 + 248 ? 880 : viewport.width - 32);const pane = await page.locator(SETTINGS_PAGE).boundingBox();expect(pane).not.toBeNull();- if (viewport.width >= 944 + 196) {+ if (viewport.width >= 944 + 248) {expect(Math.abs(frame.x - pane!.x - (pane!.width - frame.width) / 2)).toBeLessThanOrEqual(0.5);await expect(page.locator(SETTINGS_RAIL)).toBeVisible();} else {@@ -546,15 +550,25 @@ test.describe('general settings geometry', () => {expect(cardStyle.pad).toBe('22px');expect(cardStyle.gap).toBe('20px');- const surface2 = await page.evaluate(() => {+ // Every other settings page draws its cards as an outline on the page, and+ // General is not a different kind of page. The source fills this card with+ // surface-2; matching its neighbours is worth more than matching that fill,+ // so the card carries the page background and keeps its border.+ const background = await page.evaluate(() => {const probe = document.createElement('div');- probe.style.backgroundColor = 'var(--surface-2)';+ probe.style.backgroundColor = 'var(--background)';document.body.appendChild(probe);const value = getComputedStyle(probe).backgroundColor;probe.remove();return value;});- expect(cardStyle.bg).toBe(surface2);+ expect(cardStyle.bg).toBe(background);+ // …and "the same as its neighbours" is the claim, so read a neighbour.+ await open(page, '/settings/shortcuts', { theme: 'dark' });+ const neighbour = page.locator(`${SETTINGS_PAGE} section.border`).first();+ await expect(neighbour).toBeVisible();+ expect(await neighbour.evaluate((node) => getComputedStyle(node).backgroundColor)).toBe(background);+ await open(page, '/settings/general', { theme: 'dark' });const select = page.getByLabel('Language', { exact: true });const selectBox = await select.boundingBox();@@ -582,18 +596,84 @@ test.describe('general settings geometry', () => {// 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) =>+ const appearance = page.getByRole('radiogroup', { name: 'Appearance' });+ const boxes = await appearance.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');+ expect(await appearance.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');++ // The menu-placement card is the same kind of control drawn the same way,+ // which is the point of the shared choice-card component.+ const placement = page.getByRole('radiogroup', { name: 'Settings menu' });+ expect(await widthOf(page, PLACEMENT_CARD)).toBe(await widthOf(page, APPEARANCE_CARD));+ const placementPreview = await placement.getByRole('radio').first()+ .locator('[aria-hidden="true"]').first()+ .evaluate((node) => node.getBoundingClientRect().height);+ expect(placementPreview).toBe(preview.height);+ });++ // Inline puts Settings beside a sidebar that stays live, so both columns are+ // on screen at once. That is a layout claim a class name cannot settle.+ test('opens Settings beside a live sidebar once inline is picked', async ({ page }) => {+ const denied = await serveProduct(page);+ await page.setViewportSize(ULTRA);+ await open(page, '/');+ await page.locator(`${SIDEBAR} [data-settings-toggle="true"]`).click();++ const overlay = page.locator('[data-settings-overlay="true"]');+ await expect(overlay).toHaveAttribute('data-settings-menu-placement', 'standalone');+ await expect(page.locator(SIDEBAR)).toBeHidden();+ expect(await overlay.boundingBox()).toMatchObject({ x: 0, width: ULTRA.width });+ const standaloneRail = await widthOf(page, SETTINGS_RAIL);++ await page.getByRole('radio', { name: 'Inline' }).click();+ await expect(overlay).toHaveAttribute('data-settings-menu-placement', 'inline');++ // The app sidebar is back, and Settings starts exactly where it ends.+ const sidebar = await page.locator(SIDEBAR).boundingBox();+ expect(sidebar).toMatchObject({ x: 0, width: standaloneRail });+ expect(await overlay.boundingBox()).toMatchObject({ x: standaloneRail, width: ULTRA.width - standaloneRail });+ // A secondary nav beside the real one does not deserve a second full column.+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);++ // Live, not a picture of a sidebar. `toBeEnabled` only reads the element;+ // whether anything is stacked over it is a hit test, and a hit test is the+ // one thing a class name, a bounding box and jsdom all cannot settle. So+ // ask the browser what is actually under the pointer there — a transparent+ // full-viewport layer would answer here and nowhere else.+ const toggle = page.locator(`${SIDEBAR} [data-settings-toggle="true"]`);+ await expect(toggle).toBeEnabled();+ const toggleBox = (await toggle.boundingBox())!;+ expect(await page.evaluate(([x, y]) => {+ const hit = document.elementFromPoint(x, y);+ return {+ sidebar: Boolean(hit?.closest('[data-settings-toggle="true"]')),+ covered: Boolean(hit?.closest('[data-settings-overlay="true"]')),+ };+ }, [toggleBox.x + toggleBox.width / 2, toggleBox.y + toggleBox.height / 2])).toEqual({+ sidebar: true,+ covered: false,+ });++ // The preference outlives the surface that set it.+ await toggle.click();+ await expect(overlay).toHaveCount(0);+ await open(page, '/settings/general');+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);++ await page.getByRole('radio', { name: 'Standalone' }).click();+ await expect(page.locator(SIDEBAR)).toBeHidden();+ expect(await widthOf(page, SETTINGS_RAIL)).toBe(standaloneRail);+ expect(denied).toEqual([]);});});diff --git a/ui/e2e/workbench-general/standalone-settings.spec.ts b/ui/e2e/workbench-general/standalone-settings.spec.tsindex e75a1aa61..d39a82acb 100644--- a/ui/e2e/workbench-general/standalone-settings.spec.ts+++ b/ui/e2e/workbench-general/standalone-settings.spec.ts@@ -59,8 +59,7 @@ for (const width of [1200, 1366, 1920]) {const denied = await serveProduct(page);await page.setViewportSize({ width, height: 768 });await open(page, '/');- await page.getByRole('separator').focus();- await page.keyboard.press('End');+ const sidebarWidth = (await page.locator('aside.fixed').boundingBox())!.width;await textarea(page).fill(draft);await toggle(page).click();await expect(settings(page)).toBeVisible();@@ -70,7 +69,9 @@ for (const width of [1200, 1366, 1920]) {await expect(textarea(page)).toBeHidden();expect(await textarea(page).evaluate((node) => Boolean(node.closest('[inert][aria-hidden="true"]')))).toBe(true);const retained = await frame(page);- expect(retained.rail?.width).toBe(196);+ // Standalone Settings stands in for the sidebar, so its rail is that+ // sidebar's width: the left column cannot move when Settings opens.+ expect(retained.rail?.width).toBe(sidebarWidth);expect(retained.content?.width).toBe(944);// Keyboard focus may only visit foreground controls; Ctrl+K may not awaken// the Workbench palette behind Settings or change its state for the return.@@ -82,12 +83,26 @@ for (const width of [1200, 1366, 1920]) {await settings(page).getByRole('button', { name: 'Close Settings' }).click();await expect(textarea(page)).toHaveValue(draft);await expect(toggle(page)).toBeFocused();- await expect(page.getByRole('separator')).toHaveAttribute('aria-valuenow', '496');await open(page, '/settings/general');await expect(rail(page)).toBeVisible();expect(await frame(page)).toEqual(retained);expect(await page.locator('main#app-shell-scroll').boundingBox()).toMatchObject({ x: 0, width });await expect(page.locator('aside.fixed')).toBeHidden();++ // A width the owner dragged the sidebar to is still the width Settings has+ // to stand in at — a default-only match would jump for everyone who resized+ // — and the divider's own value has to survive Settings taking the column.+ await open(page, '/');+ await page.getByRole('separator').focus();+ await page.keyboard.press('End');+ await expect(page.getByRole('separator')).toHaveAttribute('aria-valuenow', '496');+ const dragged = (await page.locator('aside.fixed').boundingBox())!.width;+ expect(dragged).toBe(496);+ await toggle(page).click();+ await expect(settings(page)).toBeVisible();+ expect((await frame(page)).rail?.width).toBe(dragged);+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();+ await expect(page.getByRole('separator')).toHaveAttribute('aria-valuenow', '496');expect(denied).toEqual([]);});}@@ -135,14 +150,14 @@ for (const width of [320, 375, 390]) {await page.setViewportSize({ width, height: 568 });await open(page, '/settings/appearance');await expect(page).toHaveURL(/\/settings\/general$/);- await expect(page.getByRole('radiogroup')).toBeVisible();+ await expect(page.getByRole('radiogroup', { name: 'Appearance' })).toBeVisible();await expect(page.locator('aside.fixed')).toBeHidden();expect(await page.locator('main#app-shell-scroll').boundingBox()).toMatchObject({ x: 0, width });expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(width);await page.getByRole('link', { name: 'All settings' }).click();await expect(rail(page)).toBeVisible();await rail(page).getByRole('link', { name: 'General', exact: true }).click();- await expect(page.getByRole('radiogroup')).toBeVisible();+ await expect(page.getByRole('radiogroup', { name: 'Appearance' })).toBeVisible();await page.getByRole('link', { name: 'All settings' }).click();await page.getByRole('link', { name: 'Back to Workbench' }).click();await expect(textarea(page)).toBeVisible();diff --git a/ui/e2e/workbench-general/support.ts b/ui/e2e/workbench-general/support.tsindex aa1f3716c..999cd3d6f 100644--- a/ui/e2e/workbench-general/support.ts+++ b/ui/e2e/workbench-general/support.ts@@ -4,9 +4,10 @@ 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.+ * claim the packet actually makes — the 248 left column (the sidebar, or the+ * standalone Settings rail standing in for it) is the only fixed measurement,+ * and everything to its 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 };diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsxindex 30f7f4084..e8c8b543e 100644--- a/ui/src/components/AppShell.test.tsx+++ b/ui/src/components/AppShell.test.tsx@@ -15,6 +15,10 @@ import {readMobileProjectsListSnapshot,} from '../lib/mobileProjectsListMemory';import { selectLanguage } from '../lib/useLanguageSelection';+import {+ SETTINGS_MENU_PLACEMENT_STORAGE_KEY,+ useStandaloneSettingsMenu,+} from '../lib/settingsMenuPlacement';import { AppShell } from './AppShell';const viewport = vi.hoisted(() => {@@ -106,7 +110,15 @@ vi.mock('../context/WindowManagerProvider', () => ({vi.mock('../context/ShowPageDragProvider', () => ({ShowPageDragProvider: ({ children }: { children: ReactNode }) => <>{children}</>,}));-vi.mock('./AppsLauncher', () => ({ AppsLauncher: () => <div data-testid="apps-launcher" /> }));+// Stands down when its boundary suspends it, exactly as the real launcher does+// (`useRouteSurfaceActive() ? … : null`) — a stub that always rendered would+// report a live Apps button in every state the shell retires it.+vi.mock('./AppsLauncher', async () => {+ const { useRouteSurfaceActive } = await import('../lib/routeSurfaceActivity');+ return {+ AppsLauncher: () => (useRouteSurfaceActive() ? <div data-testid="apps-launcher" /> : null),+ };+});vi.mock('./AccountMenu', () => ({ AccountMenu: () => <div data-testid="account-menu" /> }));vi.mock('./LanguageSwitcher', () => ({ LanguageSwitcher: () => <div data-testid="language-switcher" /> }));vi.mock('./ThemeToggle', () => ({ ThemeToggle: () => <div data-testid="theme-toggle" /> }));@@ -114,7 +126,11 @@ vi.mock('./VersionBadge', () => ({ VersionBadge: () => null }));vi.mock('./apps/MobileDockDrawer', () => ({MobileDockDrawer: () => <div data-testid="mobile-dock-drawer" />,}));-vi.mock('./apps/WindowLayer', () => ({ WindowLayer: () => <div data-testid="window-layer" /> }));+vi.mock('./apps/WindowLayer', () => ({+ WindowLayer: ({ active }: { active: boolean }) => (+ <div data-testid="window-layer" data-active={String(active)} />+ ),+}));vi.mock('./workbench/NewSessionSheet', () => ({NewSessionSheet: () => null,}));@@ -140,8 +156,15 @@ const SettingsExit = ({ testId }: { testId: string }) => {</div>;};+// Stands in for the Settings surfaces, which read this and nothing else to+// decide whether their menu replaces the app sidebar or opens beside it.+const StandaloneMenuProbe = () => (+ <span data-testid="standalone-menu">{String(useStandaloneSettingsMenu())}</span>+);+beforeEach(() => {viewport.isDesktop = false;+ window.localStorage.clear();clearMobileProjectsListSnapshot();instanceAuth.remote = true;instanceAuth.instanceKind = null;@@ -334,6 +357,84 @@ describe('AppShell sidebar width', () => {.toHaveLength(expected);});+ // Standalone Settings stands IN FOR this column, so the two have to agree on+ // one width or the left edge jumps as Settings opens. Inline Settings opens+ // beside the column, which therefore has to stay live — navigable, keyboard+ // reachable, and able to raise the palettes, which float above the surface.+ it.each([+ ['standalone', true],+ ['inline', false],+ ] as const)('retires the sidebar only where Settings replaces it (%s)', async (+ placement,+ covered,+ ) => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ renderShell('/settings/general');+ await screen.findByTestId('surface');++ const aside = document.querySelector('aside');+ expect(aside?.hasAttribute('inert')).toBe(covered);+ expect(aside?.className.includes('invisible')).toBe(covered);+ expect(document.getElementById(APP_SHELL_SCROLL_ID)?.className+ .includes('md:ml-[var(--app-sidebar-w)]')).toBe(!covered);++ // ⌘K belongs to whichever surface owns the shell.+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', {+ key: 'k',+ metaKey: true,+ bubbles: true,+ cancelable: true,+ })));+ expect(screen.getByTestId('search-palette').getAttribute('data-open')).toBe(String(!covered));+ });++ // The exception to the rule above, and the reason the two flags exist at all.+ // The window layer spans the whole viewport at z-20 so a window can be dragged+ // over the sidebar; inline Settings is opaque from the sidebar's trailing edge+ // at z-30. Left live, a window would show as a strip over the very column+ // inline exists to keep, with everything that makes it a window — title bar,+ // controls, content — behind Settings. Live-but-invisible is worse than+ // retired, so this one retires in both placements. Its launcher goes with it:+ // a control whose every result is hidden is not a live control.+ it.each(['standalone', 'inline'] as const)(+ 'retires the window layer and its launcher under %s Settings',+ async (placement) => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ renderShell('/settings/general');+ await screen.findByTestId('surface');++ expect(screen.getByTestId('window-layer').parentElement?.hasAttribute('hidden')).toBe(true);+ expect(screen.getByTestId('window-layer').getAttribute('data-active')).toBe('false');+ expect(screen.queryByTestId('apps-launcher')).toBeNull();+ },+ );++ // ...and comes back, so retiring it is not a way of losing it.+ it('restores the window layer and its launcher once Settings closes', async () => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ renderShell('/');+ await screen.findByTestId('surface');++ expect(screen.getByTestId('window-layer').parentElement?.hasAttribute('hidden')).toBe(false);+ expect(screen.getByTestId('window-layer').getAttribute('data-active')).toBe('true');+ expect(screen.getByTestId('apps-launcher')).toBeTruthy();+ });++ it('covers the shell below md even when inline is the stored preference', async () => {+ viewport.isDesktop = false;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ renderShell('/settings/general');+ await screen.findByTestId('surface');++ // A phone has no room for two rails, so the preference is not in force.+ expect(document.querySelector('aside')?.hasAttribute('inert')).toBe(true);+ expect(document.getElementById(APP_SHELL_SCROLL_ID)?.className)+ .not.toContain('md:ml-[var(--app-sidebar-w)]');+ });+it('leaves a standalone app tab without a sidebar to resize', async () => {viewport.isDesktop = true;// The shell reads standalone mode from the document URL, once, at mount.@@ -348,6 +449,35 @@ describe('AppShell sidebar width', () => {window.history.replaceState({}, '', '/');}});++ // The same tab, asked the question Settings actually asks. `inline` is a claim+ // about the app sidebar being on screen to open beside; here there is none, so+ // Settings has to come up standalone however the owner set the preference for+ // the windows that do have one. The shell states that, because only the shell+ // can: standalone mode comes from a document flag frozen at mount, which no+ // pathname predicate can recover — and the route Settings lands on says+ // nothing about the shell it opened over anyway, as with the config-recovery+ // banner's Diagnostics link in a single-app tab.+ it('publishes a sidebar-free shell to the Settings surfaces above it', async () => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ window.history.replaceState({}, '', `/apps/editor?${APP_TAB_PARAM}=1`);+ try {+ render(+ <MemoryRouter initialEntries={['/apps/editor']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="*" element={<StandaloneMenuProbe />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ expect((await screen.findByTestId('standalone-menu')).textContent).toBe('true');+ } finally {+ window.history.replaceState({}, '', '/');+ }+ });});describe('AppShell persistent Workbench chrome', () => {diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 9e11f9a22..8817aaee0 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -5,6 +5,7 @@ import { useTranslation } from 'react-i18next';import clsx from 'clsx';import { APP_TAB_PARAM, isStandaloneAppRoutePath, isStandaloneAppTab } from '../apps/appLaunch';+import { ShellSidebarContext } from '../context/ShellSidebarContext';import { StandaloneAppTabContext } from '../context/StandaloneAppTabContext';import { useApi } from '../context/ApiContext';import { useStatus } from '../context/StatusContext';@@ -36,9 +37,11 @@ import {} from '../lib/adminNavigation';import {closeSettingsOverlay,+ isChromelessShellPath,isSettingsEntryPath,useSettingsOverlayOrigin,} from '../lib/settingsOverlay';+import { isStandaloneSettingsMenu, useSettingsMenuPlacement } from '../lib/settingsMenuPlacement';import { SettingsOverlayNavigationBoundary } from './settings/SettingsOverlayNavigationBoundary';type ShellNavItem = {@@ -191,6 +194,57 @@ export const AppShell: React.FC = () => {&& isSettingsEntryPath(location.pathname)&& settingsOverlayOrigin !== null;const surfaceLocation = settingsOverlayOpen ? settingsOverlayOrigin.location : location;+ // Whether THIS document was opened as a single-app tab (⌘/Ctrl-click on an app icon,+ // §7.1m). Frozen at mount from the landing URL rather than tracked off `location`, so+ // navigating deeper inside the tab can't suddenly restore the workbench window layout+ // this tab exists to stay out of — nor re-enable the save that would clobber it.+ const [standaloneAppTab] = useState(() =>+ typeof window === 'undefined' ? false : isStandaloneAppTab(window.location.search),+ );+ // A single-app tab sitting on the app's own route (⌘/Ctrl-clicked Terminal / Files /+ // Editor, or that URL bookmarked): the tab exists to show ONE app, so it drops EVERY+ // piece of shell chrome — sidebar, mobile brand header, bottom tab bar, page padding —+ // and hands the whole viewport to the app. Both halves matter: the flag alone would+ // strip the chrome off any page such a tab later navigates to, and the route alone+ // would strip it inside the normal workbench.+ //+ // Route-scoped, and therefore LOCAL to the layout: what `StandaloneAppTabContext`+ // publishes is the mount-frozen document flag instead, because the window controls+ // that read it must stay decided for the tab's whole life (see the context doc). The+ // app pages read the same context and mount only on these routes, so for them the two+ // agree anyway.+ const chromeless = standaloneAppTab && isStandaloneAppRoutePath(surfaceLocation.pathname);+ // The setup wizard owns the whole window — the shell hands it the outlet and+ // draws nothing else. True for a retained setup origin too, so that Settings+ // opened from the wizard is measured against the wizard, not the route the+ // overlay happens to be on.+ const setupShell = isChromelessShellPath(location.pathname)+ || (settingsOverlayOrigin !== null && isChromelessShellPath(settingsOverlayOrigin.location.pathname));+ // The one fact the Settings surfaces cannot work out for themselves, so the+ // shell states it here, next to the two conditions that actually decide+ // whether an `<aside>` is rendered at all, and publishes it below.+ const shellDrawsSidebar = !chromeless && !setupShell;+ // Two different questions wear the same name if you let them. `settingsOpen`+ // asks whether Settings is the foreground route — that is what the toggle in+ // the sidebar reads, so it stays on that. This asks whether Settings has TAKEN+ // OVER the shell, and it is the one everything BEHIND Settings must read:+ // standalone Settings stands in for the sidebar, so the shell retires; inline+ // Settings opens beside a live sidebar, so that column stays awake and+ // navigable, and so do the palettes, which float above the surface.+ //+ // "Beside", not "behind": inline's surface is opaque from the sidebar's+ // trailing edge rightwards, so anything it covers is live-but-invisible,+ // which is worse than retired. The window layer is the one such thing, and+ // it reads `settingsOpen` instead.+ //+ // The rule, not the hook: the shell is what publishes `ShellSidebarContext`,+ // so it cannot read its own broadcast and feeds the same function directly.+ const standaloneSettingsMenu = isStandaloneSettingsMenu(+ useSettingsMenuPlacement(),+ isDesktop,+ shellDrawsSidebar,+ );+ const settingsCoversSidebar = settingsOpen && standaloneSettingsMenu;useEffect(() => {forgetMobileProjectsListUnlessPreserved(location.pathname);}, [location.pathname]);@@ -200,13 +254,6 @@ export const AppShell: React.FC = () => {// The mobile Dock drawer (opened from the workbench Apps tab). Like the admin// sheet it closes on any route change — tapping a tile navigates + dismisses.const [appsDrawerOpen, setAppsDrawerOpen] = useState(false);- // Whether this DOCUMENT was opened as a single-app tab (⌘/Ctrl-click on an app icon,- // §7.1m). Frozen at mount from the landing URL rather than tracked off `location`, so- // navigating deeper inside the tab can't suddenly restore the workbench window layout- // this tab exists to stay out of — nor re-enable the save that would clobber it.- const [standaloneAppTab] = useState(() =>- typeof window === 'undefined' ? false : isStandaloneAppTab(window.location.search),- );// Mirror the iOS visual-viewport height into --app-vvh. The MOBILE shell is a// static locked column that does NOT read it (resizing the shell mid-focus// fought iOS's scroll-into-view and flung the input off-screen); only the md+@@ -229,7 +276,7 @@ export const AppShell: React.FC = () => {// consume the same user-configured chord first; otherwise search owns it.useEffect(() => {const onKeyDown = (e: KeyboardEvent) => {- if (e.defaultPrevented || settingsOpen) return;+ if (e.defaultPrevented || settingsCoversSidebar) return;if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {e.preventDefault();setSearchOpen((prev) => !prev);@@ -237,27 +284,13 @@ export const AppShell: React.FC = () => {};window.addEventListener('keydown', onKeyDown);return () => window.removeEventListener('keydown', onKeyDown);- }, [settingsOpen]);+ }, [settingsCoversSidebar]);// Close the mobile Dock drawer on navigation.useEffect(() => {setAppsDrawerOpen(false);}, [location.pathname]);- // A single-app tab sitting on the app's own route (⌘/Ctrl-clicked Terminal / Files /- // Editor, or that URL bookmarked): the tab exists to show ONE app, so it drops EVERY- // piece of shell chrome — sidebar, mobile brand header, bottom tab bar, page padding —- // and hands the whole viewport to the app. Both halves matter: the flag alone would- // strip the chrome off any page such a tab later navigates to, and the route alone- // would strip it inside the normal workbench.- //- // Route-scoped, and therefore LOCAL to the layout: what `StandaloneAppTabContext`- // publishes is the mount-frozen document flag instead, because the window controls- // that read it must stay decided for the tab's whole life (see the context doc). The- // app pages read the same context and mount only on these routes, so for them the two- // agree anyway.- const chromeless = standaloneAppTab && isStandaloneAppRoutePath(surfaceLocation.pathname);-// Keep the visible URL honest about standalone mode. An in-tab app-to-app navigation// (Files → "Open in Editor" / "Open Terminal Here") lands on `/apps/editor` WITHOUT the// marker, while the document is still the single-app tab — `standaloneAppTab` is frozen@@ -295,14 +328,14 @@ export const AppShell: React.FC = () => {return <Navigate to="/" replace />;}- if (location.pathname === '/setup' || settingsOverlayOrigin?.location.pathname === '/setup') {+ if (setupShell) {return (- <>+ <ShellSidebarContext.Provider value={shellDrawsSidebar}><ConfigRecoveryNotice config={config} /><SettingsOverlayNavigationBoundary desktop={isDesktop}><Outlet /></SettingsOverlayNavigationBoundary>- </>+ </ShellSidebarContext.Provider>);}@@ -353,6 +386,7 @@ export const AppShell: React.FC = () => {// fought iOS's own scroll-into-view and threw the input off-screen. iOS instead// pans the locked page to lift the focused composer above the keyboard.// Desktop: normal document flow.+ <ShellSidebarContext.Provider value={shellDrawsSidebar}><SettingsOverlayNavigationBoundary desktop={isDesktop}><WindowManagerProvider standalone={standaloneAppTab}><StandaloneAppTabContext.Provider value={standaloneAppTab}>@@ -374,19 +408,21 @@ export const AppShell: React.FC = () => {cluster pushed apart. The brand row, navigation and projects are one unitinside WorkbenchSidebar; this frame owns only the column and the bottom.The width is SidebarResizer's --app-sidebar-w, shared with Workbench- content. Settings owns the viewport and never reads this offset. */}+ content — and, when Settings stands in for this column, with the+ Settings rail, so the two never swap at different widths. Standalone+ Settings retires this whole aside; inline Settings leaves it live. */}{!chromeless && (<aside- aria-hidden={settingsOpen || undefined}- inert={settingsOpen || undefined}+ aria-hidden={settingsCoversSidebar || undefined}+ inert={settingsCoversSidebar || undefined}className={clsx('fixed inset-y-0 left-0 z-10 hidden w-[var(--app-sidebar-w)] flex-col justify-between gap-6 border-r border-border bg-[var(--sidebar-background)] px-4 pt-2.5 pb-4 md:flex',- settingsOpen && 'invisible pointer-events-none',+ settingsCoversSidebar && 'invisible pointer-events-none',)}><div className="flex min-h-0 flex-1 flex-col">{isDesktop && (- <RouteSurfaceActivityBoundary active={!settingsOpen}>+ <RouteSurfaceActivityBoundary active={!settingsCoversSidebar}><WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} /></RouteSurfaceActivityBoundary>)}@@ -398,6 +434,12 @@ export const AppShell: React.FC = () => {floats above app windows. */}<div className="relative flex shrink-0 flex-col gap-2"><div className="flex h-[39px] items-stretch gap-2">+ {/* `settingsOpen`, not `settingsCoversSidebar`: this control lives in+ the sidebar column, but what it produces lives in the window+ layer, which Settings covers in BOTH placements (see below). A+ launcher whose every result is invisible is not a live control,+ so it retires with the windows it opens rather than with the+ column it sits in. Its Dock goes with it — same component. */}{canUseApps && (<RouteSurfaceActivityBoundary active={!settingsOpen}><AppsLauncher />@@ -489,7 +531,7 @@ export const AppShell: React.FC = () => {// Single-app tab: no sidebar offset, no scroll, no page glow — the app body// is the only thing in the viewport and sizes itself to this box (h-full).? 'min-h-0 flex-1 overflow-hidden'- : settingsOpen+ : settingsCoversSidebar? 'min-h-0 flex-1 overflow-hidden md:min-h-screen md:flex-none md:overflow-visible md:pb-0': isFullScreenMobile? 'min-h-0 flex-1 overflow-hidden md:ml-[var(--app-sidebar-w)] md:min-h-screen md:flex-none md:overflow-visible md:pb-0'@@ -539,12 +581,12 @@ export const AppShell: React.FC = () => {{/* Mobile Dock drawer — the workbench Apps tab summons it (§7.1b). Mobile-only(md:hidden internally); mounted inside DockProvider so it reads the samedocked tiles + order as the desktop Dock. */}- {!settingsOpen && canUseApps && (+ {!settingsCoversSidebar && canUseApps && (<MobileDockDrawer open={appsDrawerOpen} onClose={() => setAppsDrawerOpen(false)} />)}{capabilities.can_chat && (- <RouteSurfaceActivityBoundary active={!settingsOpen}>+ <RouteSurfaceActivityBoundary active={!settingsCoversSidebar}><NewSessionSheetopen={newSessionOpen}onClose={() => setNewSessionOpen(false)}@@ -555,14 +597,29 @@ export const AppShell: React.FC = () => {{/* ⌘K message-search palette. Mounted shell-wide; the sidebar field is theWorkbench entry point. */}- <RouteSurfaceActivityBoundary active={!settingsOpen}>+ <RouteSurfaceActivityBoundary active={!settingsCoversSidebar}><SearchPalette open={searchOpen} onClose={() => setSearchOpen(false)} /></RouteSurfaceActivityBoundary>{/* App windows float over the workbench main area (desktop). The Dock (P2)- and the AppsLauncher bridge open windows via the WindowManager. */}+ and the AppsLauncher bridge open windows via the WindowManager.++ `settingsOpen`, not `settingsCoversSidebar` — the one thing behind+ Settings that retires in BOTH placements. This layer deliberately+ spans the whole viewport at z-20, above the sidebar's z-10, so a+ window can be dragged over the sidebar and maximize can fill the+ screen. Inline Settings is opaque from the sidebar's trailing edge+ rightwards at z-30, so leaving the layer live there shows a window as+ a strip over the sidebar with its title bar, controls and content all+ hidden behind Settings: visible, unusable, and covering the one column+ inline exists to keep. Inline keeps the sidebar column live, not+ everything its surface covers. */}{canUseApps && (- <div hidden={settingsOpen} inert={settingsOpen || undefined} aria-hidden={settingsOpen || undefined}>+ <div+ hidden={settingsOpen}+ inert={settingsOpen || undefined}+ aria-hidden={settingsOpen || undefined}+ ><WindowLayer active={!settingsOpen} /></div>)}@@ -572,5 +629,6 @@ export const AppShell: React.FC = () => {</StandaloneAppTabContext.Provider></WindowManagerProvider></SettingsOverlayNavigationBoundary>+ </ShellSidebarContext.Provider>);};diff --git a/ui/src/components/SidebarResizer.test.tsx b/ui/src/components/SidebarResizer.test.tsxindex 6ff714f32..18ded495f 100644--- a/ui/src/components/SidebarResizer.test.tsx+++ b/ui/src/components/SidebarResizer.test.tsx@@ -1,9 +1,17 @@/* @vitest-environment jsdom */import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { cleanup, fireEvent, render, screen } from '@testing-library/react';--import { MAX_SIDEBAR_WIDTH, MIN_SIDEBAR_WIDTH, SIDEBAR_WIDTH_VAR, SidebarResizer } from './SidebarResizer';+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';++import {+ MAX_SIDEBAR_WIDTH,+ MIN_SIDEBAR_WIDTH,+ MIN_WIDTH_BESIDE_SIDEBAR,+ SIDEBAR_WIDTH_VAR,+ maxSidebarWidth,+} from '../lib/sidebarWidth';+import { DESKTOP_MIN_WIDTH } from '../lib/useIsDesktop';+import { SidebarResizer } from './SidebarResizer';vi.mock('react-i18next', () => ({useTranslation: () => ({ t: (key: string) => key }),@@ -220,3 +228,74 @@ describe('SidebarResizer keyboard', () => {expect(handle.tabIndex).toBe(0);});});++// `MAX_SIDEBAR_WIDTH` is a constant, so on its own it lets the sidebar take a+// share of a narrow window that leaves nothing workable beside it: at 768 a full+// drag leaves 272px, and inline Settings spends 196 of that on its rail before+// the page gets any. The cap is the sidebar's own business — every consumer+// would otherwise re-derive the same budget — and it is expressed as the width+// the shell keeps free, not as a second magic number.+describe('SidebarResizer viewport budget', () => {+ const setViewport = (width: number) => Object.defineProperty(window, 'innerWidth', {+ configurable: true,+ writable: true,+ value: width,+ });++ afterEach(() => setViewport(1024));++ it.each([+ // [viewport, widest allowed, why]+ [1920, MAX_SIDEBAR_WIDTH, 'room to spare: the plain maximum'],+ [1016, MAX_SIDEBAR_WIDTH, 'exactly enough for the maximum and the reserve'],+ [900, 380, 'the reserve wins, so the sidebar stops early'],+ [DESKTOP_MIN_WIDTH, MIN_SIDEBAR_WIDTH, 'the narrowest desktop affords no growth'],+ [600, MIN_SIDEBAR_WIDTH, 'below md nothing is rendered, so nothing to constrain'],+ ])('caps the sidebar at %ipx viewport (%s)', (viewport, widest) => {+ expect(maxSidebarWidth(viewport)).toBe(widest);+ expect(viewport - maxSidebarWidth(viewport)).toBeGreaterThanOrEqual(+ Math.min(MIN_WIDTH_BESIDE_SIDEBAR, viewport - MIN_SIDEBAR_WIDTH),+ );+ });++ it('stops the drag at the cap and says so', () => {+ setViewport(900);+ render(<SidebarResizer />);++ expect(separator().getAttribute('aria-valuemax')).toBe('380');+ drag(900);+ expect(reportedWidth()).toBe(380);+ // `End` asks for the constant maximum and lands on the affordable one.+ fireEvent.keyDown(separator(), { key: 'End' });+ expect(reportedWidth()).toBe(380);+ });++ // Dragging wide and then narrowing the window reaches the same starved layout+ // the cap exists to prevent, so the cap follows the viewport too.+ it('gives width back when the window narrows under it', async () => {+ render(<SidebarResizer />);+ drag(900);+ expect(reportedWidth()).toBe(MAX_SIDEBAR_WIDTH);++ setViewport(900);+ fireEvent(window, new Event('resize'));+ await waitFor(() => expect(reportedWidth()).toBe(380));+ expect(publishedWidth()).toBe('380px');+ expect(separator().getAttribute('aria-valuemax')).toBe('380');+ });++ // An untouched shell needs no JS to lay itself out, and a resize must not+ // quietly take that over just because the budget moved.+ it('leaves the stylesheet in charge while nothing has been dragged', async () => {+ setViewport(900);+ render(<SidebarResizer />);+ expect(separator().getAttribute('aria-valuemax')).toBe('380');+ expect(publishedWidth()).toBe('');++ setViewport(1400);+ fireEvent(window, new Event('resize'));+ await waitFor(() => expect(separator().getAttribute('aria-valuemax'))+ .toBe(String(MAX_SIDEBAR_WIDTH)));+ expect(publishedWidth()).toBe('');+ });+});diff --git a/ui/src/components/SidebarResizer.tsx b/ui/src/components/SidebarResizer.tsxindex cd2e482de..e006856b4 100644--- a/ui/src/components/SidebarResizer.tsx+++ b/ui/src/components/SidebarResizer.tsx@@ -2,29 +2,30 @@ import React, { useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';-/** The one width the sidebar, every desktop content offset and the Settings- * overlay edge read. Declared in `index.css` at MIN_SIDEBAR_WIDTH so the- * default shell needs no JS; this component overrides it inline while it is- * mounted, which is also how the value reaches the overlay's portal. */-export const SIDEBAR_WIDTH_VAR = '--app-sidebar-w';-/** The shipped width is the minimum, so the default shell is unchanged. */-export const MIN_SIDEBAR_WIDTH = 248;-export const MAX_SIDEBAR_WIDTH = 496;-const KEYBOARD_STEP = 16;+import {+ MAX_SIDEBAR_WIDTH,+ MIN_SIDEBAR_WIDTH,+ SIDEBAR_WIDTH_VAR,+ clampSidebarWidth as clampWidth,+ currentViewportWidth,+ maxSidebarWidth,+} from '../lib/sidebarWidth';-const clampWidth = (width: number) => (- Math.min(MAX_SIDEBAR_WIDTH, Math.max(MIN_SIDEBAR_WIDTH, Math.round(width)))-);+const KEYBOARD_STEP = 16;// This component is the only writer, so the inline value is either a width it// set or nothing at all — no need to resolve the stylesheet's own default.-const readWidth = () => {+// Unclamped on purpose: it is what the DOM currently shows, which is the only+// thing a viewport change can find too wide.+const readPublishedWidth = () => {const inline = Number.parseFloat(document.documentElement.style.getPropertyValue(SIDEBAR_WIDTH_VAR),);- return Number.isFinite(inline) ? clampWidth(inline) : MIN_SIDEBAR_WIDTH;+ return Number.isFinite(inline) ? inline : null;};+const readWidth = () => clampWidth(readPublishedWidth() ?? MIN_SIDEBAR_WIDTH);+type Gesture = {pointerId: number;startX: number;@@ -44,6 +45,7 @@ type Gesture = {export const SidebarResizer = () => {const { t } = useTranslation();const [width, setWidth] = useState(readWidth);+ const [maxWidth, setMaxWidth] = useState(() => maxSidebarWidth(currentViewportWidth()));const [dragging, setDragging] = useState(false);const gesture = useRef<Gesture | null>(null);@@ -66,6 +68,21 @@ export const SidebarResizer = () => {document.body.style.userSelect = active.bodyUserSelect;}, []);+ // Narrowing the window after a wide drag reaches the same starved layout the+ // cap exists to prevent — the drag is simply earlier in time — so the cap has+ // to follow the viewport, not just the gesture. Re-clamp only when the width+ // no longer fits, so an untouched shell keeps needing no JS at all.+ useEffect(() => {+ const sync = () => {+ const max = maxSidebarWidth(window.innerWidth);+ setMaxWidth(max);+ const published = readPublishedWidth();+ if (published !== null && published > max) apply(max);+ };+ window.addEventListener('resize', sync);+ return () => window.removeEventListener('resize', sync);+ }, [apply]);+// Unmount is also how a gesture ends when the viewport leaves desktop layout:// give the borrowed styling back, and the width back to the stylesheet, so one// mount's drag cannot leak into a later mount or a standalone app tab.@@ -121,7 +138,7 @@ export const SidebarResizer = () => {aria-label={t('appShell.resizeSidebar')}aria-valuenow={width}aria-valuemin={MIN_SIDEBAR_WIDTH}- aria-valuemax={MAX_SIDEBAR_WIDTH}+ aria-valuemax={maxWidth}tabIndex={0}// Read by the Settings overlay, which is dismissed by an interaction// outside itself and would otherwise close the moment this edge — whichdiff --git a/ui/src/components/settings/SettingsGeneralPage.test.tsx b/ui/src/components/settings/SettingsGeneralPage.test.tsxindex adf604531..8f8a6f594 100644--- a/ui/src/components/settings/SettingsGeneralPage.test.tsx+++ b/ui/src/components/settings/SettingsGeneralPage.test.tsx@@ -56,6 +56,7 @@ import { ToastProvider } from '../../context/ToastProvider';import en from '../../i18n/en.json';import zh from '../../i18n/zh.json';import { LanguageSwitcher } from '../LanguageSwitcher';+import { SETTINGS_MENU_PLACEMENT_STORAGE_KEY } from '../../lib/settingsMenuPlacement';import { SettingsGeneralPage } from './SettingsGeneralPage';// One per test, not one per file: the language operation is owned by the i18n@@ -108,6 +109,7 @@ const authorityBecomes = (canManage: boolean, refresh: () => void) => {};const themeCard = (name: string) => screen.getByRole('radio', { name: new RegExp(name) });+const placementCard = (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;@@ -544,3 +546,69 @@ describe('General settings — appearance', () => {}});});++describe('General settings — menu placement', () => {+ it('opens on Standalone and records a pick where the shell reads it', async () => {+ const user = userEvent.setup();+ renderPage();++ // Nothing stored yet still selects a choice: the shipped layout.+ expect(placementCard(en.settings.general.menuPlacementStandalone).getAttribute('aria-checked'))+ .toBe('true');+ expect(window.localStorage.getItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY)).toBeNull();++ await user.click(placementCard(en.settings.general.menuPlacementInline));++ expect(window.localStorage.getItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY)).toBe('inline');+ expect(placementCard(en.settings.general.menuPlacementInline).getAttribute('aria-checked'))+ .toBe('true');+ expect(placementCard(en.settings.general.menuPlacementStandalone).getAttribute('aria-checked'))+ .toBe('false');+ });++ it('shows the stored choice on a later visit, and falls back on an unknown one', () => {+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ const { leave, comeBack } = renderPage();+ expect(placementCard(en.settings.general.menuPlacementInline).getAttribute('aria-checked'))+ .toBe('true');++ // A value this build does not know (an older build, a hand edit) selects+ // the default rather than leaving the group with nothing checked.+ leave();+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'floating');+ comeBack();+ expect(placementCard(en.settings.general.menuPlacementStandalone).getAttribute('aria-checked'))+ .toBe('true');+ expect(placementCard(en.settings.general.menuPlacementInline).getAttribute('aria-checked'))+ .toBe('false');+ });++ it('is its own radiogroup, arrowed and drawn like the theme one beside it', async () => {+ const user = userEvent.setup();+ renderPage();++ const groups = screen.getAllByRole('radiogroup');+ expect(groups.map((group) => group.getAttribute('aria-label'))).toEqual([+ en.settings.general.appearanceTitle,+ en.settings.general.menuPlacementTitle,+ ]);++ const standalone = placementCard(en.settings.general.menuPlacementStandalone);+ expect(standalone.getAttribute('tabindex')).toBe('0');+ standalone.focus();+ await user.keyboard('{ArrowRight}');++ expect(document.activeElement)+ .toBe(placementCard(en.settings.general.menuPlacementInline));+ expect(window.localStorage.getItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY)).toBe('inline');+ // The theme pick is a separate group and this must not have moved it.+ expect(window.localStorage.getItem('vibe-remote-theme')).toBeNull();++ // Each card draws its own layout; only the inline one has the app sidebar+ // standing beside the Settings rail, which is the whole difference.+ const columns = (card: HTMLElement) =>+ card.querySelector('[aria-hidden="true"]')?.childElementCount;+ expect(columns(placementCard(en.settings.general.menuPlacementStandalone))).toBe(2);+ expect(columns(placementCard(en.settings.general.menuPlacementInline))).toBe(3);+ });+});diff --git a/ui/src/components/settings/SettingsGeneralPage.tsx b/ui/src/components/settings/SettingsGeneralPage.tsxindex ff7bdb72a..8e259c4da 100644--- a/ui/src/components/settings/SettingsGeneralPage.tsx+++ b/ui/src/components/settings/SettingsGeneralPage.tsx@@ -1,6 +1,6 @@import { useRef } from 'react';import { useTranslation } from 'react-i18next';-import { Check, CircleCheck, Monitor, Moon, Sun } from 'lucide-react';+import { Check, CircleCheck, Columns3, Monitor, Moon, PanelLeft, Sun } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';@@ -10,6 +10,11 @@ import { Select } from '../ui/select';import { useTheme } from '../../context/ThemeContext';import type { ThemeMode } from '../../context/ThemeContext';import { useLanguageSelection } from '../../lib/useLanguageSelection';+import {+ useSettingsMenuPlacement,+ writeSettingsMenuPlacement,+} from '../../lib/settingsMenuPlacement';+import type { SettingsMenuPlacement } from '../../lib/settingsMenuPlacement';import type { TranslationKey } from '../../i18n/types';// The 88px miniature is a drawing OF a theme, not a preview rendered IN one:@@ -63,26 +68,77 @@ const ThemeMiniature: React.FC<{ mode: ThemeMode }> = ({ mode }) => (</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' },-];+/**+ * Where the Settings menu sits, drawn from live tokens rather than the literal+ * palette above: this miniature is about layout, so unlike the theme cards it+ * SHOULD repaint with the active theme. Mint marks the Settings menu itself, so+ * the eye can follow that one column between the two cards — the neutral column+ * that appears before it in `inline` is the app sidebar the choice preserves.+ */+const PlacementMiniature: React.FC<{ placement: SettingsMenuPlacement }> = ({ placement }) => (+ <div+ aria-hidden="true"+ className="flex h-[88px] w-full overflow-hidden rounded-sm border border-border bg-background"+ >+ {placement === 'inline' && (+ <div className="flex w-[26px] shrink-0 flex-col gap-[5px] border-r border-border bg-[var(--sidebar-background)] p-1.5">+ <div className="h-[4px] w-full rounded-sm bg-muted/40" />+ <div className="h-[4px] w-[70%] rounded-sm bg-muted/40" />+ <div className="h-[4px] w-[85%] rounded-sm bg-muted/40" />+ </div>+ )}+ <div+ className={clsx(+ 'flex shrink-0 flex-col gap-[5px] border-r border-mint/30 bg-mint-soft p-1.5',+ placement === 'inline' ? 'w-[30px]' : 'w-[38px]',+ )}+ >+ <div className="h-[4px] w-[80%] rounded-sm bg-mint-ink/50" />+ <div className="h-[4px] w-full rounded-sm bg-mint-ink/25" />+ <div className="h-[4px] w-[65%] rounded-sm bg-mint-ink/25" />+ <div className="h-[4px] w-[75%] rounded-sm bg-mint-ink/25" />+ </div>+ <div className="flex min-w-0 flex-1 flex-col gap-[6px] p-2.5">+ <div className="h-[6px] w-[55%] rounded-sm bg-muted/60" />+ <div className="h-[13px] w-full rounded border border-border" />+ <div className="h-[13px] w-full rounded border border-border" />+ </div>+ </div>+);-// design r6G6P — ordinary Settings: interface language and appearance, both-// saved the moment they are picked. The standalone frame owns an 880px content-// column inside a 944px outer frame at the desktop reference width.-export const SettingsGeneralPage: React.FC = () => {+type ChoiceCard<T extends string> = {+ value: T;+ icon: LucideIcon;+ labelKey: TranslationKey;+ miniature: React.ReactNode;+};++type ChoiceCardsProps<T extends string> = {+ label: string;+ choices: readonly ChoiceCard<T>[];+ value: T;+ onChange: (value: T) => void;+ className?: string;+};++/**+ * The drawn-choice control the page uses twice. A radiogroup is one tab stop+ * that arrows through its options; separately tabbable buttons would only look+ * like radios.+ */+function ChoiceCards<T extends string>({+ label,+ choices,+ value,+ onChange,+ className,+}: ChoiceCardsProps<T>) {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);+ const next = (index + choices.length) % choices.length;+ onChange(choices[next].value);cardRefs.current[next]?.focus();};@@ -90,11 +146,94 @@ export const SettingsGeneralPage: React.FC = () => {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 if (event.key === 'End') moveTo(choices.length - 1);else return;event.preventDefault();};+ return (+ <div role="radiogroup" aria-label={label} className={clsx('grid gap-3.5', className)}>+ {choices.map(({ value: choice, icon: Icon, labelKey, miniature }, index) => {+ const selected = value === choice;+ return (+ <button+ key={choice}+ ref={(node) => { cardRefs.current[index] = node; }}+ type="button"+ role="radio"+ aria-checked={selected}+ tabIndex={selected ? 0 : -1}+ onClick={() => onChange(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]',+ )}+ >+ {miniature}+ <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>+ );+}++const THEME_CHOICES: readonly ChoiceCard<ThemeMode>[] = [+ {+ value: 'system',+ icon: Monitor,+ labelKey: 'settings.general.appearanceSystem',+ miniature: <ThemeMiniature mode="system" />,+ },+ {+ value: 'light',+ icon: Sun,+ labelKey: 'settings.general.appearanceLight',+ miniature: <ThemeMiniature mode="light" />,+ },+ {+ value: 'dark',+ icon: Moon,+ labelKey: 'settings.general.appearanceDark',+ miniature: <ThemeMiniature mode="dark" />,+ },+];++const PLACEMENT_CHOICES: readonly ChoiceCard<SettingsMenuPlacement>[] = [+ {+ value: 'standalone',+ icon: PanelLeft,+ labelKey: 'settings.general.menuPlacementStandalone',+ miniature: <PlacementMiniature placement="standalone" />,+ },+ {+ value: 'inline',+ icon: Columns3,+ labelKey: 'settings.general.menuPlacementInline',+ miniature: <PlacementMiniature placement="inline" />,+ },+];++// design r6G6P — ordinary Settings: interface language and appearance, both+// saved the moment they are picked. The standalone frame owns an 880px content+// column inside a 944px outer frame at the desktop reference width.+export const SettingsGeneralPage: React.FC = () => {+ const { t } = useTranslation();+ const { languages, current, select } = useLanguageSelection();+ const { mode, setMode } = useTheme();+ const placement = useSettingsMenuPlacement();+return (<SettingsPageShelltitle={t('settings.general.title')}@@ -129,44 +268,31 @@ export const SettingsGeneralPage: React.FC = () => {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>+ <ChoiceCards+ label={t('settings.general.appearanceTitle')}+ choices={THEME_CHOICES}+ value={mode}+ onChange={setMode}+ className="grid-cols-1 sm:grid-cols-3"+ />+ </SettingsPanel>++ {/* Settings menu placement. Hidden below md: the Settings surface is+ full-screen on a phone whatever this says, and a control that+ changes nothing on the viewport you are holding is not a choice. */}+ <SettingsPanel+ variant="preference"+ className="hidden md:block"+ title={t('settings.general.menuPlacementTitle')}+ description={t('settings.general.menuPlacementDescription')}+ >+ <ChoiceCards+ label={t('settings.general.menuPlacementTitle')}+ choices={PLACEMENT_CHOICES}+ value={placement}+ onChange={writeSettingsMenuPlacement}+ className="grid-cols-1 sm:grid-cols-2"+ /></SettingsPanel>{/* i3LvLl — the autosave contract, stated once for the whole page. */}diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsxindex 743492dac..c354e58ff 100644--- a/ui/src/components/settings/SettingsLayout.test.tsx+++ b/ui/src/components/settings/SettingsLayout.test.tsx@@ -11,6 +11,8 @@ import {settingsOverlayOpenState,useSettingsOverlayOrigin,} from '@/lib/settingsOverlay';+import { ShellSidebarContext } from '@/context/ShellSidebarContext';+import { SETTINGS_MENU_PLACEMENT_STORAGE_KEY } from '@/lib/settingsMenuPlacement';import { SettingsLayout } from './SettingsLayout';const api = vi.hoisted(() => {@@ -80,8 +82,15 @@ type SettingsTestEntry = string | {state?: unknown;};-const renderLayout = (entry: SettingsTestEntry) => render(+// `shellHasSidebar` stands in for what AppShell publishes around this layout.+// It defaults to the context's own default — an ordinary shell route, which is+// what every case but the sidebar-less one below is about.+const renderLayout = (+ entry: SettingsTestEntry,+ { shellHasSidebar = true }: { shellHasSidebar?: boolean } = {},+) => render(<MemoryRouter initialEntries={[entry]}>+ <ShellSidebarContext.Provider value={shellHasSidebar}><Routes><Route path="/settings" element={<SettingsLayoutHarness />}><Route path="general" element={<div>general-body</div>} />@@ -98,6 +107,7 @@ const renderLayout = (entry: SettingsTestEntry) => render(</Route><Route path="/chat/:sessionId" element={<div>chat-body</div>} /></Routes>+ </ShellSidebarContext.Provider></MemoryRouter>,);@@ -176,6 +186,39 @@ describe('SettingsLayout', () => {expect(shell?.className).not.toContain('min-h-full');});+ // Opening standalone Settings swaps this rail IN FOR the app sidebar, so it+ // has to be the width that sidebar was — a width the owner dragged it to+ // included — or the left column jumps as Settings opens. Inline Settings sits+ // beside that sidebar, where matching it would spend a second full-width+ // column on a secondary nav, so it stays 196.+ it.each([+ ['standalone', 'md:w-[var(--app-sidebar-w)]', 'md:w-[196px]'],+ ['inline', 'md:w-[196px]', 'md:w-[var(--app-sidebar-w)]'],+ ] as const)('sizes the rail for a %s menu', (placement, expected, rejected) => {+ media.matches = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ renderLayout('/settings/general');++ const navigation = screen.getByRole('navigation', { name: 'settings.navigationLabel' });+ expect(navigation.className).toContain(expected);+ expect(navigation.className).not.toContain(rejected);+ });++ // The inline rail is 196px because it sits beside a 248px sidebar. Where the+ // shell draws none — the setup wizard, a single-app tab — that rail would be+ // narrowed for a neighbour that is not there, so the stored preference is not+ // in force, and is not forgotten for the windows that do have one.+ it('sizes the rail standalone where the shell draws no sidebar, even when inline is stored', () => {+ media.matches = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');++ renderLayout('/settings/models', { shellHasSidebar: false });++ const navigation = screen.getByRole('navigation', { name: 'settings.navigationLabel' });+ expect(navigation.className).toContain('md:w-[var(--app-sidebar-w)]');+ expect(navigation.className).not.toContain('md:w-[196px]');+ });+it.each(['/settings/models', '/settings/models/'])('lets Model Hub fill the route pane at %s',(path) => {diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsxindex 17d1e1b3d..f048b3fb0 100644--- a/ui/src/components/settings/SettingsLayout.tsx+++ b/ui/src/components/settings/SettingsLayout.tsx@@ -33,8 +33,10 @@ import { getEnabledPlatforms, platformSupportsChannels } from '@/lib/platforms';import { useIsDesktop } from '@/lib/useIsDesktop';import {closeSettingsOverlay,+ isChromelessShellPath,useSettingsOverlayContext,} from '@/lib/settingsOverlay';+import { useStandaloneSettingsMenu } from '@/lib/settingsMenuPlacement';import { AccountMenu } from '../AccountMenu';import { VersionBadge } from '../VersionBadge';import { modelHubEnabledFromConfig } from './models/featureFlags';@@ -139,12 +141,13 @@ const SettingsNavLink: React.FC<{ item: SettingsItem }> = ({ item }) => {)}><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. */}+ {/* The rail's width is the layout's to decide 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 at the inline width). Wrapping keeps every+ label readable in any language and at either width, 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">{t(item.labelKey)}</span></NavLink>);@@ -234,7 +237,13 @@ export const SettingsLayout: React.FC = () => {const location = useLocation();const navigate = useNavigate();const isDesktop = useIsDesktop();- const setupOrigin = useSettingsOverlayContext()?.location.pathname === '/setup';+ // Specifically the setup wizard, and only for the mobile back affordance+ // below: coming from the wizard makes Back mean Back. That is a different+ // question from whether a sidebar is on screen, which the rail reads from the+ // shell instead.+ const setupOriginPath = useSettingsOverlayContext()?.location.pathname;+ const setupOrigin = setupOriginPath !== undefined && isChromelessShellPath(setupOriginPath);+ const standaloneMenu = useStandaloneSettingsMenu();const [modelHubVisible, setModelHubVisible] = useState(false);const [memoryVisible, setMemoryVisible] = useState(false);const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);@@ -401,11 +410,17 @@ export const SettingsLayout: React.FC = () => {</header><div className="flex min-h-0 flex-1">+ {/* Standalone Settings replaces the app sidebar, so this rail has to be+ the same width the sidebar was — including a width the owner dragged+ it to — or the left column jumps the moment Settings opens. Inline+ Settings sits BESIDE that sidebar, where matching it would spend a+ second full-width column on a secondary nav, so it keeps 196. */}<navaria-label={t('settings.navigationLabel')}className={clsx('min-h-0 shrink-0 border-r border-border bg-surface/70 px-2 pb-[calc(0.75rem+env(safe-area-inset-bottom))] pt-3 md:pb-3',- 'w-full flex-col md:w-[196px]',+ 'w-full flex-col',+ standaloneMenu ? 'md:w-[var(--app-sidebar-w)]' : 'md:w-[196px]',atRoot ? 'flex' : 'hidden md:flex',)}>diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsxindex d297b070c..495303db1 100644--- a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx@@ -4,6 +4,7 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/reimport userEvent from '@testing-library/user-event';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useEffect, useRef, useState } from 'react';+import { createPortal } from 'react-dom';import {Link,MemoryRouter,@@ -23,6 +24,8 @@ import {useSettingsOverlayContext,} from '@/lib/settingsOverlay';import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';+import { ShellSidebarContext } from '@/context/ShellSidebarContext';+import { SETTINGS_MENU_PLACEMENT_STORAGE_KEY } from '@/lib/settingsMenuPlacement';import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';import { SettingsOverlayNavigationBoundary } from './SettingsOverlayNavigationBoundary';import { SettingsOverlayRouteSurface } from './SettingsOverlayRouteSurface';@@ -172,6 +175,11 @@ const ChatProbe = () => {const SetupProbe = () => <Link to="/settings/models">open-model-hub</Link>;+const PortaledShellControl = () => createPortal(+ <button type="button">sidebar-portaled</button>,+ document.body,+);+const SettingsFrame = () => {const location = useLocation();const navigate = useNavigate();@@ -227,6 +235,19 @@ const SettingsToggle = () => {const Harness = ({ desktop }: { desktop: boolean }) => (<SettingsOverlayNavigationBoundary desktop={desktop}><SettingsToggle />+ {/* Shell chrome that lives OUTSIDE the overlay. Inline, the app sidebar is+ still on screen beside Settings and still live, so what an outside+ interaction means stops being hypothetical. */}+ <aside>+ <button type="button" data-sidebar-resizer="true">shell-resizer</button>+ <button type="button">sidebar-idle</button>+ <Link to="/chat/ses_2">sidebar-chat-link</Link>+ </aside>+ {/* The launcher and its Dock keep a layout slot in that column but portal+ themselves to `document.body` to clear the route panel's stacking+ context, so they belong to the sidebar without descending from it. */}+ <PortaledShellControl />+ <button type="button">shell-elsewhere</button><SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}><Route path="/setup" element={<SetupProbe />} /><Route path="/chat/:sessionId" element={<ChatProbe />} />@@ -258,6 +279,7 @@ const settleDeferredFocus = async () => {beforeEach(() => {chatMounts = 0;chatUnmounts = 0;+ window.localStorage.clear();vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({matches: true,addEventListener: vi.fn(),@@ -523,13 +545,152 @@ describe('SettingsOverlayRouteSurface', () => {await user.click(screen.getByRole('link', { name: 'shell-settings' }));expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();expect(document.body.style.pointerEvents).not.toBe('none');- expect(document.querySelector('[data-dialog-surface-backdrop="true"]')).toBeNull();await user.click(screen.getByRole('button', { name: 'shell-settings' }));await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');});+ // Standalone Settings replaces the app sidebar, so it starts at the screen+ // edge with nothing on that side to divide from. Inline Settings opens beside+ // a sidebar that is still there, so it takes the primitive's own+ // `--app-sidebar-w` offset — the same variable the sidebar sizes itself with,+ // which is what keeps the two edges together while it is dragged.+ it.each([+ ['standalone', 'md:left-0', 'md:left-[var(--app-sidebar-w)]', false],+ ['inline', 'md:left-[var(--app-sidebar-w)]', 'md:left-0', true],+ ] as const)('starts the %s surface at the right edge', async (+ placement,+ offset,+ rejected,+ dividedFromSidebar,+ ) => {+ const user = userEvent.setup();+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ const surface = document.querySelector('[data-settings-overlay="true"]') as HTMLElement;++ expect(surface.getAttribute('data-settings-menu-placement')).toBe(placement);+ // Exact class tokens: `md:border-l-0` would satisfy a substring match for+ // `md:border-l` and quietly invert what this asserts.+ expect(surface.classList.contains(offset)).toBe(true);+ expect(surface.classList.contains(rejected)).toBe(false);+ expect(surface.classList.contains('md:border-l')).toBe(dividedFromSidebar);+ });++ it('never dismisses inline on an outside interaction, and still lets the user leave', async () => {+ const user = userEvent.setup();+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ const open = async () => {+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();+ // Inline's whole premise is that the shell behind stays reachable, so+ // this dialog must never go modal: Radix's modal path inerts the page+ // behind it. Whether a layer *covers* the sidebar is a hit test, which+ // only a browser can run — `geometry.spec.ts` settles that half.+ expect(document.body.style.pointerEvents).not.toBe('none');+ };+ const stillOpen = () => expect(+ document.querySelector('[data-settings-overlay="true"]'),+ ).toBeTruthy();++ await open();++ // Grabbing the divider moves this surface's OWN left edge. Dismissing on it+ // would close the thing the drag is laying out.+ await user.click(screen.getByRole('button', { name: 'shell-resizer' }));+ stillOpen();++ // Nor is the sidebar's own quiet space a dismissal: inline puts these two+ // surfaces side by side, so the sidebar is a neighbour, not "outside".+ await user.click(screen.getByRole('button', { name: 'sidebar-idle' }));+ stillOpen();++ // The launcher and Dock belong to that column but portal above this layer,+ // so they are not descendants of it. Anything deciding this by DOM ancestry+ // passes the two cases above and fails here — which is the whole point of+ // not deciding it that way.+ await user.click(screen.getByRole('button', { name: 'sidebar-portaled' }));+ stillOpen();++ // Not even the rest of the shell: inline covers everything right of the+ // sidebar, so there is no neutral background left to click at.+ await user.click(screen.getByRole('button', { name: 'shell-elsewhere' }));+ stillOpen();++ // Leaving is never in doubt, though. Escape still closes to the retained+ // origin...+ await user.keyboard('{Escape}');+ await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');++ // ...and a sidebar link takes the user out by its own navigation, which is+ // exactly ONE navigation. Were dismissal to fire too, `closeSettingsOverlay`+ // would traverse history asynchronously and race this synchronous push back+ // to the retained origin.+ await open();+ await user.click(screen.getByRole('link', { name: 'sidebar-chat-link' }));+ await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_2');+ });++ it('keeps the shipped outside dismissal for the standalone surface', async () => {+ const user = userEvent.setup();+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ // Standalone really does own the viewport — anything that floats above it is+ // outside in the ordinary sense, and closes it back to the retained origin.+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'sidebar-portaled' }));+ await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');+ });++ // Some shells draw no app sidebar at all — the setup wizard, a single-app tab.+ // Inline over one of those would offset Settings past an empty strip and give+ // it a rail narrowed for a neighbour that does not exist, so the stored+ // preference is simply not in force there. Which shells those are is the+ // shell's own business: this surface reads the answer it publishes rather+ // than trying to recognise them by pathname.+ it('opens standalone where the shell draws no sidebar, even when inline is stored', async () => {+ const user = userEvent.setup();+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <ShellSidebarContext.Provider value={false}>+ <RoutedHarness />+ </ShellSidebarContext.Provider>+ </MemoryRouter>,+ );++ // An ordinary workbench route, so nothing about the path suggests the+ // answer: only the shell's own claim does.+ await user.click(screen.getByRole('link', { name: 'open-settings' }));+ const surface = document.querySelector('[data-settings-overlay="true"]') as HTMLElement;++ expect(surface.getAttribute('data-settings-menu-placement')).toBe('standalone');+ expect(surface.classList.contains('md:left-0')).toBe(true);+ expect(surface.classList.contains('md:left-[var(--app-sidebar-w)]')).toBe(false);+ expect(surface.classList.contains('md:border-l')).toBe(false);+ });+it('keeps legacy redirects out of origins while preserving real ingress origins', async () => {const user = userEvent.setup();const view = render(diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.tsxindex 07238d9ef..425c3410f 100644--- a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx@@ -15,6 +15,7 @@ import {settingsOverlayStateForOrigin,useSettingsOverlayOrigin,} from '@/lib/settingsOverlay';+import { useStandaloneSettingsMenu } from '@/lib/settingsMenuPlacement';type SettingsOverlayRouteSurfaceProps = {children: ReactNode;@@ -47,6 +48,7 @@ export const SettingsOverlayRouteSurface = ({const location = useLocation();const navigate = useNavigate();const origin = useSettingsOverlayOrigin(location);+ const standaloneMenu = useStandaloneSettingsMenu();const settingsSurfaceOpen = isSettingsEntryPath(location.pathname) && origin !== null;const lastFocusRef = useRef<HTMLElement | null>(null);const returnFocusRef = useRef<HTMLElement | null>(null);@@ -123,17 +125,51 @@ export const SettingsOverlayRouteSurface = ({<SettingsOverlayOriginContext.Provider value={origin}><DialogSurfaceContentdata-settings-overlay="true"- // Settings owns the whole viewport. The retained Workbench origin- // remains mounted behind this portal for drafts and return state,- // but its sidebar is not part of the Settings surface at any width.- className="left-0 border-l-0 md:left-0 md:border-l-0"+ data-settings-menu-placement={standaloneMenu ? 'standalone' : 'inline'}+ // Standalone: Settings owns the whole viewport, so it starts at the+ // screen edge and draws no left border — there is nothing on that+ // side to divide from. The retained Workbench origin stays mounted+ // behind this portal for drafts and return state, but its sidebar+ // is not part of the surface at any width.+ //+ // Inline: the app sidebar is still there and still live, so the+ // surface starts at its trailing edge and takes the primitive's+ // own `--app-sidebar-w` offset — the same variable the sidebar+ // sizes itself with, which is what keeps the two edges together+ // while that sidebar is being dragged. Below md there is no+ // sidebar to divide from, so the border only applies from md up.+ className={standaloneMenu+ ? 'left-0 border-l-0 md:left-0 md:border-l-0'+ : 'left-0 border-l-0 md:border-l'}aria-describedby={undefined}onInteractOutside={(event) => {+ // Inline has no outside in the sense this handler assumes. It is+ // a pane beside a live shell, not a popup over an inert one, and+ // everything still reachable belongs to that shell: the sidebar+ // column left of this surface, plus the launcher, Dock, menus and+ // floating details it portals to `document.body` above this+ // layer. Each of those already owns what it does. The resize edge+ // moves this surface's own left edge, so grabbing it must not+ // close what the drag is laying out; a sidebar link navigates,+ // and that navigation IS the way out — were dismissal to fire+ // too, `closeSettingsOverlay`'s asynchronous history traversal+ // would race the link's synchronous push and could land on the+ // retained origin instead of the route that was clicked.+ //+ // Naming those surfaces is what a portal defeats: they are not+ // DOM descendants of the column they belong to, so any ancestry+ // test can only cover the ones someone remembered. Inline is left+ // by Escape, by the Settings toggle, or by navigating — never by+ // clicking its neighbour — so it simply does not dismiss.+ if (!standaloneMenu) {+ event.preventDefault();+ return;+ }+ // Standalone does own the whole viewport, and keeps the dismissal+ // that shipped with it. Only the toggle is exempt there, because+ // it closes this surface itself and must not do it twice.const target = event.target;- if (- target instanceof Element- && target.closest('[data-settings-toggle="true"]')- ) {+ if (target instanceof Element && target.closest('[data-settings-toggle="true"]')) {event.preventDefault();}}}diff --git a/ui/src/components/settings/SettingsPrimitives.tsx b/ui/src/components/settings/SettingsPrimitives.tsxindex f65c27f32..f7ccee1c5 100644--- a/ui/src/components/settings/SettingsPrimitives.tsx+++ b/ui/src/components/settings/SettingsPrimitives.tsx@@ -14,8 +14,8 @@ type SettingsPanelProps = {/*** `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.+ * ordinary Settings (design.pen le5QU / Q8zxF1) — one 22px pad and no internal+ * divider, because its header and its control are one statement.*/variant?: 'panel' | 'preference';};@@ -56,9 +56,16 @@ export const SettingsPanel: React.FC<SettingsPanelProps> = ({// radius 12 (`rounded-lg` here), not the 16 the `panel` variant renders:// le5QU and Q8zxF1 both draw this card at 12.+ //+ // The fill is `bg-background`, not the surface-2 those two boards draw. A card+ // is one concept across Settings, and every other page (Backends,+ // Dependencies, Service) renders it as border-only on the page fill; a white+ // card on General alone read as a different kind of object rather than as the+ // same card holding a quieter control. Deliberate divergence from the boards,+ // recorded in the PR rather than silently reconciled here.if (variant === 'preference') {return (- <section className={clsx('rounded-lg border border-border bg-surface-2', className)}>+ <section className={clsx('rounded-lg border border-border bg-background', className)}><div className="flex flex-col gap-5 p-[22px]">{header}{children}diff --git a/ui/src/components/ui/dialog.tsx b/ui/src/components/ui/dialog.tsxindex bfbade9cf..21e2ae805 100644--- a/ui/src/components/ui/dialog.tsx+++ b/ui/src/components/ui/dialog.tsx@@ -77,26 +77,31 @@ export const DialogContent = React.forwardRef<});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.+// Route-sized surface: a panel the size of a route rather than a centered box,+// with Radix owning focus and outside interaction for it.//-// 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.+// It deliberately renders no backdrop. This surface declared one — transparent,+// `inset-0`, `z-20` — which never reached the DOM: Radix's `DialogOverlay`+// returns null unless the dialog is modal, and this surface exists for the+// non-modal case, where the shell behind stays live and reachable. Dead markup+// that reads as a full-viewport layer over a live sidebar is worse than none,+// so it is gone. A caller that wants a real backdrop wants `DialogContent`.+//+// The left default clears the app sidebar by reading the same `--app-sidebar-w`+// the shell lays itself out with, so a dragged sidebar and this surface cannot+// drift apart. It was a literal `240px` — a number the sidebar had not used+// since it became a variable — which was only invisible because the one caller+// overrode it. A caller that owns the whole viewport still overrides with+// `md:left-0` (tailwind-merge keeps the caller's).export const DialogSurfaceContent = React.forwardRef<React.ComponentRef<typeof DialogPrimitive.Content>,React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>>(({ className, ...props }, ref) => (<DialogPortal>- <DialogOverlay- data-dialog-surface-backdrop="true"- className="z-20 bg-transparent backdrop-blur-none"- /><DialogPrimitive.Contentref={ref}className={cn(- 'fixed inset-y-0 left-0 right-0 z-30 overflow-hidden border-l border-border bg-background shadow-2xl focus:outline-none md:left-[240px]',+ 'fixed inset-y-0 left-0 right-0 z-30 overflow-hidden border-l border-border bg-background shadow-2xl focus:outline-none md:left-[var(--app-sidebar-w)]',className,)}{...props}diff --git a/ui/src/context/ShellSidebarContext.ts b/ui/src/context/ShellSidebarContext.tsnew file mode 100644index 000000000..71300f8de--- /dev/null+++ b/ui/src/context/ShellSidebarContext.ts@@ -0,0 +1,28 @@+import { createContext, useContext } from 'react';++/**+ * Whether the shell behind the current surface draws the app sidebar at all.+ *+ * Published rather than re-derived, because only the shell can answer it. Two+ * shells draw no sidebar, and they disagree on what the answer depends on: the+ * setup wizard is a matter of the route, while a single-app tab turns on a+ * document flag frozen at mount — deliberately NOT re-read from the URL, which+ * the shell rewrites underneath it. Any surface trying to work this out from a+ * pathname could only ever cover the cases someone remembered to enumerate, and+ * would silently regress the next time a shell learns to drop its chrome.+ *+ * "At all" is the whole claim: the sidebar is hidden below `md`, and that is a+ * separate question, answered separately by whoever cares about the viewport.+ *+ * Read by the Settings menu placement, where `inline` is a claim about this+ * sidebar being on screen to sit beside — with no sidebar there is no inline+ * layout to have, whatever the owner picked for the windows that do have one.+ *+ * Defaults to true: an ordinary shell route draws a sidebar, and so does a+ * surface mounted outside the shell entirely in a test harness.+ */+export const ShellSidebarContext = createContext(true);++export function useShellHasSidebar(): boolean {+ return useContext(ShellSidebarContext);+}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 511a525c8..f4b474091 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -311,6 +311,10 @@"appearanceSystem": "System","appearanceLight": "Light","appearanceDark": "Dark",+ "menuPlacementTitle": "Settings menu",+ "menuPlacementDescription": "Let Settings take over the window, or open it beside the app sidebar. Saved in this browser.",+ "menuPlacementStandalone": "Standalone",+ "menuPlacementInline": "Inline","autosaved": "Changes are saved automatically","languageSaveFailed": "The language changed here, but could not be saved for this instance"},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 8bca87c7c..b5947ec98 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -311,6 +311,10 @@"appearanceSystem": "跟随系统","appearanceLight": "浅色","appearanceDark": "深色",+ "menuPlacementTitle": "设置菜单",+ "menuPlacementDescription": "让设置占满窗口,或者展开在应用侧栏旁边。保存在当前浏览器。",+ "menuPlacementStandalone": "独立",+ "menuPlacementInline": "内联","autosaved": "修改会自动保存","languageSaveFailed": "语言已在本机切换,但未能保存到此实例"},diff --git a/ui/src/lib/settingsMenuPlacement.test.tsx b/ui/src/lib/settingsMenuPlacement.test.tsxnew file mode 100644index 000000000..74f159b3f--- /dev/null+++ b/ui/src/lib/settingsMenuPlacement.test.tsx@@ -0,0 +1,153 @@+/* @vitest-environment jsdom */++import { act, cleanup, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { ShellSidebarContext } from '../context/ShellSidebarContext';+import {+ DEFAULT_SETTINGS_MENU_PLACEMENT,+ readSettingsMenuPlacement,+ SETTINGS_MENU_PLACEMENT_STORAGE_KEY,+ useSettingsMenuPlacement,+ useStandaloneSettingsMenu,+ writeSettingsMenuPlacement,+} from './settingsMenuPlacement';+import { DESKTOP_MEDIA_QUERY } from './useIsDesktop';++const desktop = { matches: true, listeners: new Set<() => void>() };++const installMatchMedia = () => {+ Object.defineProperty(window, 'matchMedia', {+ configurable: true,+ value: (query: string) => ({+ media: query,+ get matches() {+ return query === DESKTOP_MEDIA_QUERY ? desktop.matches : false;+ },+ addEventListener: (_type: string, listener: () => void) => desktop.listeners.add(listener),+ removeEventListener: (_type: string, listener: () => void) => desktop.listeners.delete(listener),+ }),+ });+};++const resizeTo = (isDesktop: boolean) => act(() => {+ desktop.matches = isDesktop;+ desktop.listeners.forEach((listener) => listener());+});++const Placement = () => <span data-testid="placement">{useSettingsMenuPlacement()}</span>;+const Standalone = () => (+ <span data-testid="standalone">{String(useStandaloneSettingsMenu())}</span>+);+// What the shell publishes. Absent a provider the context defaults to true,+// which is what the ordinary cases below render against.+const InShell = ({ hasSidebar }: { hasSidebar: boolean }) => (+ <ShellSidebarContext.Provider value={hasSidebar}>+ <Standalone />+ </ShellSidebarContext.Provider>+);++const shown = (testId: string) => screen.getByTestId(testId).textContent;++beforeEach(() => {+ window.localStorage.clear();+ desktop.matches = true;+ desktop.listeners.clear();+ installMatchMedia();+});++afterEach(cleanup);++describe('settings menu placement store', () => {+ it('opens on the shipped layout and keeps a pick across readers', () => {+ expect(readSettingsMenuPlacement()).toBe(DEFAULT_SETTINGS_MENU_PLACEMENT);++ writeSettingsMenuPlacement('inline');+ expect(window.localStorage.getItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY)).toBe('inline');+ expect(readSettingsMenuPlacement()).toBe('inline');+ });++ it('degrades to the default instead of throwing when storage is refused', () => {+ // Private-browsing and locked-down storage contexts throw on access. A view+ // preference is not worth a blank screen, so both halves swallow it.+ const refused = {+ getItem: () => { throw new DOMException('denied', 'SecurityError'); },+ setItem: () => { throw new DOMException('denied', 'SecurityError'); },+ };+ expect(readSettingsMenuPlacement(refused)).toBe(DEFAULT_SETTINGS_MENU_PLACEMENT);+ expect(() => writeSettingsMenuPlacement('inline', refused)).not.toThrow();+ });++ it('reaches a reader in another React tree on the same tab', () => {+ // The Settings rail renders in a portal outside the shell's subtree, so a+ // write from the General page has to announce itself rather than rely on a+ // shared provider — and `storage` events only fire in OTHER tabs.+ render(<Placement />);+ expect(shown('placement')).toBe('standalone');++ act(() => writeSettingsMenuPlacement('inline'));+ expect(shown('placement')).toBe('inline');+ });++ it('follows the same preference changed in another tab', () => {+ render(<Placement />);++ act(() => {+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ window.dispatchEvent(new StorageEvent('storage', {+ key: SETTINGS_MENU_PLACEMENT_STORAGE_KEY,+ newValue: 'inline',+ }));+ });+ expect(shown('placement')).toBe('inline');++ // Another key's tab-to-tab write is not this preference changing.+ act(() => {+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'standalone');+ window.dispatchEvent(new StorageEvent('storage', { key: 'vibe-remote-theme' }));+ });+ expect(shown('placement')).toBe('inline');+ });+});++describe('useStandaloneSettingsMenu', () => {+ it('answers the preference on a desktop window', () => {+ render(<Standalone />);+ expect(shown('standalone')).toBe('true');++ act(() => writeSettingsMenuPlacement('inline'));+ expect(shown('standalone')).toBe('false');+ });++ it('is true below md whatever the preference says', () => {+ writeSettingsMenuPlacement('inline');+ render(<Standalone />);+ expect(shown('standalone')).toBe('false');++ // There is no room for two rails on a phone, so Settings covers the shell+ // and the preference is simply not in force — without being forgotten.+ resizeTo(false);+ expect(shown('standalone')).toBe('true');+ expect(readSettingsMenuPlacement()).toBe('inline');++ resizeTo(true);+ expect(shown('standalone')).toBe('false');+ });++ it('is true where the shell draws no sidebar, whatever the preference says', () => {+ writeSettingsMenuPlacement('inline');++ // `inline` is a claim about something else being on screen. A shell that+ // renders no app sidebar — the setup wizard, a single-app tab — leaves it+ // nothing to sit beside, so the answer is standalone on a full desktop+ // window too. Which shells those are is the shell's business, not this+ // rule's: it reads the answer rather than re-deriving it from a pathname.+ render(<InShell hasSidebar={false} />);+ expect(shown('standalone')).toBe('true');+ expect(readSettingsMenuPlacement()).toBe('inline');++ cleanup();+ render(<InShell hasSidebar />);+ expect(shown('standalone')).toBe('false');+ });+});diff --git a/ui/src/lib/settingsMenuPlacement.ts b/ui/src/lib/settingsMenuPlacement.tsnew file mode 100644index 000000000..b8461f5de--- /dev/null+++ b/ui/src/lib/settingsMenuPlacement.ts@@ -0,0 +1,128 @@+import { useSyncExternalStore } from 'react';++import { useShellHasSidebar } from '../context/ShellSidebarContext';+import { useIsDesktop } from './useIsDesktop';++/**+ * Where the Settings menu sits on a desktop viewport.+ *+ * `standalone` (the shipped default) gives Settings the whole window: its rail+ * stands in for the app sidebar, which is hidden for as long as Settings is+ * open. `inline` keeps the app sidebar live and opens Settings beside it, so+ * the project tree stays reachable while a setting is being changed.+ *+ * This is a per-person, per-device view preference — the same tier as the theme+ * — so it lives in localStorage rather than in instance config, where one+ * member's choice would re-lay out every other member's window. Storage+ * conventions mirror agentsViewMemory: versioned `avibe.*` key, injectable+ * storage for tests, best-effort try/catch so blocked storage degrades to the+ * default instead of throwing.+ */+export type SettingsMenuPlacement = 'standalone' | 'inline';++export const SETTINGS_MENU_PLACEMENTS: readonly SettingsMenuPlacement[] = ['standalone', 'inline'];+export const DEFAULT_SETTINGS_MENU_PLACEMENT: SettingsMenuPlacement = 'standalone';++export const SETTINGS_MENU_PLACEMENT_STORAGE_KEY = 'avibe.settings.menu-placement.v1';+export const SETTINGS_MENU_PLACEMENT_CHANGED_EVENT = 'avibe:settings-menu-placement-changed';++type PlacementStorage = Pick<Storage, 'getItem' | 'setItem'>;++function browserStorage(storage?: PlacementStorage): PlacementStorage | undefined {+ return storage ?? (typeof window !== 'undefined' ? window.localStorage : undefined);+}++export function readSettingsMenuPlacement(storage?: PlacementStorage): SettingsMenuPlacement {+ try {+ const raw = browserStorage(storage)?.getItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY);+ // An unknown value (older build, hand-edited storage) opens the default+ // rather than selecting neither choice.+ return (SETTINGS_MENU_PLACEMENTS as readonly string[]).includes(raw ?? '')+ ? (raw as SettingsMenuPlacement)+ : DEFAULT_SETTINGS_MENU_PLACEMENT;+ } catch {+ return DEFAULT_SETTINGS_MENU_PLACEMENT;+ }+}++export function writeSettingsMenuPlacement(+ placement: SettingsMenuPlacement,+ storage?: PlacementStorage,+): void {+ try {+ browserStorage(storage)?.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ } catch {+ // View memory is best-effort in private browsing and restricted storage contexts.+ }+ // The shell, the overlay frame and the Settings rail read this from three+ // different React trees — one of them a portal outside the shell's subtree —+ // so the write has to announce itself rather than ride a shared provider.+ // `storage` events only reach *other* tabs, which is the half this covers.+ if (typeof window !== 'undefined') {+ window.dispatchEvent(new Event(SETTINGS_MENU_PLACEMENT_CHANGED_EVENT));+ }+}++function subscribeToSettingsMenuPlacement(listener: () => void): () => void {+ if (typeof window === 'undefined') return () => undefined;+ const onStorage = (event: StorageEvent) => {+ if (event.key === SETTINGS_MENU_PLACEMENT_STORAGE_KEY) listener();+ };+ window.addEventListener('storage', onStorage);+ window.addEventListener(SETTINGS_MENU_PLACEMENT_CHANGED_EVENT, listener);+ return () => {+ window.removeEventListener('storage', onStorage);+ window.removeEventListener(SETTINGS_MENU_PLACEMENT_CHANGED_EVENT, listener);+ };+}++export function useSettingsMenuPlacement(): SettingsMenuPlacement {+ // The snapshot is a plain string, so identity comparison is value comparison+ // and no caching layer is needed between reads.+ return useSyncExternalStore(+ subscribeToSettingsMenuPlacement,+ () => readSettingsMenuPlacement(),+ () => DEFAULT_SETTINGS_MENU_PLACEMENT,+ );+}++/**+ * Whether the Settings menu stands IN FOR the app sidebar rather than opening+ * beside it — the one question the shell, the overlay frame and the Settings+ * rail each have to answer, so it is answered once, here, for all three.+ *+ * `inline` is a claim about something else being on screen: it only means+ * anything where an app sidebar is there to sit beside. Two things take that+ * away, and both make the answer standalone without forgetting what the owner+ * picked for the windows that do have a sidebar.+ *+ * - The viewport: below `md` there is no room for two rails.+ * - The shell: some shells draw no sidebar at all, and inline over one of those+ * would offset Settings past an empty strip and narrow its rail for a+ * neighbour that does not exist.+ *+ * Kept as a plain function of three facts, with no defaultable parameter: the+ * shell fact is not something a call site may forget to supply, because a+ * missing answer here is indistinguishable from "there is a sidebar" and fails+ * silently. Every consumer inside the shell should call the hook below instead.+ */+export function isStandaloneSettingsMenu(+ placement: SettingsMenuPlacement,+ isDesktop: boolean,+ shellHasSidebar: boolean,+): boolean {+ return !shellHasSidebar || placement === 'standalone' || !isDesktop;+}++/**+ * The rule above, fed from the three sources that own its inputs. This is what+ * every surface *inside* the shell calls — the shell itself publishes+ * `ShellSidebarContext` and so has to feed `isStandaloneSettingsMenu` directly.+ */+export function useStandaloneSettingsMenu(): boolean {+ return isStandaloneSettingsMenu(+ useSettingsMenuPlacement(),+ useIsDesktop(),+ useShellHasSidebar(),+ );+}diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.tsindex 2fa8a5a32..5d3c9d1cc 100644--- a/ui/src/lib/settingsOverlay.ts+++ b/ui/src/lib/settingsOverlay.ts@@ -26,6 +26,15 @@ export const isSettingsRoutePath = (pathname: string): boolean =>export const isSettingsEntryPath = (pathname: string): boolean =>isSettingsRoutePath(pathname) || isLegacySettingsEntryPath(pathname);+/**+ * The setup wizard owns the whole window: AppShell renders its outlet alone,+ * with no sidebar, header or bottom nav around it. Stated once here because+ * three separate decisions turn on it — whether the shell draws its chrome at+ * all, and, for a Settings surface opened from there, whether the Settings menu+ * has an app sidebar to sit beside.+ */+export const isChromelessShellPath = (pathname: string): boolean => pathname === '/setup';+export const settingsOverlayOriginFromState = (state: unknown): SettingsOverlayOrigin | null => {if (!state || typeof state !== 'object') return null;const candidate = (state as SettingsOverlayState)[SETTINGS_BACKGROUND_KEY];diff --git a/ui/src/lib/sidebarWidth.ts b/ui/src/lib/sidebarWidth.tsnew file mode 100644index 000000000..36961b51c--- /dev/null+++ b/ui/src/lib/sidebarWidth.ts@@ -0,0 +1,46 @@+import { DESKTOP_MIN_WIDTH } from './useIsDesktop';++/** The one width the sidebar, every desktop content offset and the Settings+ * overlay edge read. Declared in `index.css` at MIN_SIDEBAR_WIDTH so the+ * default shell needs no JS; `SidebarResizer` overrides it inline while it is+ * mounted, which is also how the value reaches the overlay's portal. */+export const SIDEBAR_WIDTH_VAR = '--app-sidebar-w';+/** The shipped width is the minimum, so the default shell is unchanged. */+export const MIN_SIDEBAR_WIDTH = 248;+export const MAX_SIDEBAR_WIDTH = 496;++/**+ * What the shell keeps for whatever sits beside the sidebar — the workbench+ * content, or inline Settings, which is a 196px rail plus a pane inside this+ * same remainder. It is the narrowest desktop the shell supports minus the+ * sidebar's own shipped width, i.e. exactly what a default sidebar already+ * leaves at the `md` breakpoint, so no configuration the shell ships today+ * changes.+ *+ * `MAX_SIDEBAR_WIDTH` alone is viewport-blind: dragging to 496 in a 768px+ * window leaves 272px, which is a cramped workbench and an unusable inline+ * Settings (196 of that 272 is the rail). The maximum is the only place to say+ * this — capping the consumers instead would have each of them re-derive the+ * same budget, and capping the sidebar only while Settings is open would move+ * the column the moment Settings opened.+ */+export const MIN_WIDTH_BESIDE_SIDEBAR = DESKTOP_MIN_WIDTH - MIN_SIDEBAR_WIDTH;++/** Never below the minimum: under `md` no sidebar is rendered at all, so a+ * viewport that cannot afford even the default has none to constrain. */+export const maxSidebarWidth = (viewportWidth: number) => Math.max(+ MIN_SIDEBAR_WIDTH,+ Math.min(MAX_SIDEBAR_WIDTH, viewportWidth - MIN_WIDTH_BESIDE_SIDEBAR),+);++export const currentViewportWidth = () => (+ typeof window === 'undefined' ? Number.POSITIVE_INFINITY : window.innerWidth+);++export const clampSidebarWidth = (+ width: number,+ viewportWidth = currentViewportWidth(),+) => Math.min(+ maxSidebarWidth(viewportWidth),+ Math.max(MIN_SIDEBAR_WIDTH, Math.round(width)),+);diff --git a/ui/src/lib/useIsDesktop.ts b/ui/src/lib/useIsDesktop.tsindex ff5900d9e..c05ef8d4f 100644--- a/ui/src/lib/useIsDesktop.ts+++ b/ui/src/lib/useIsDesktop.ts@@ -1,6 +1,9 @@import { useEffect, useState } from 'react';-export const DESKTOP_MEDIA_QUERY = '(min-width: 768px)';+/** The shell's `md` breakpoint. Exported as a number too, because layout+ * budgeting has to do arithmetic with it and a second literal would drift. */+export const DESKTOP_MIN_WIDTH = 768;+export const DESKTOP_MEDIA_QUERY = `(min-width: ${DESKTOP_MIN_WIDTH}px)`;type MatchMediaOwner = Pick<Window, 'matchMedia'>;