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
fix(ui): keep the Apps launcher under inline Settings (#2072)
Maxa07acee02380
diff --git a/docs/plans/2026-09-20-settings-general-polish.md b/docs/plans/2026-09-20-settings-general-polish.mdindex 68db6882c..ed401afb8 100644--- a/docs/plans/2026-09-20-settings-general-polish.md+++ b/docs/plans/2026-09-20-settings-general-polish.md@@ -124,10 +124,14 @@ the publisher, feeds the rule directly.> 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+> retires in both placements** — one consumer, `WindowLayer`. Everything else is> either inside the sidebar column or floats above the surface, so it keeps> `settingsCoversSidebar`.+>+> (As merged this also took the `AppsLauncher` with the layer, on the grounds+> that a control whose every result is hidden is not a live control. That was+> wrong in the user-visible direction — see *Follow-up: the launcher is a sidebar+> control* at the end.)### What each consumer does with it@@ -141,12 +145,11 @@ the publisher, feeds the rule directly.Settings therefore leaves a live, navigable sidebar — which is exactly whatshipped 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.+ The one exception reads `settingsOpen`, and it is 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. It retires under either placement and comes back when+ Settings closes. `AppsLauncher` does *not* go with it — see the follow-up.- **`SettingsOverlayRouteSurface`** picks its own left edge: standalone starts atthe 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@@ -239,10 +242,10 @@ edited into `design.pen`.- `AppShell.test.tsx` — the shell retires only where Settings replaces it, coversthe shell below `md` even when inline is stored, and publishes a sidebar-freeshell 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.+ exception: the window layer retires under *either* placement and comes back+ when Settings closes, while the launcher retires only under standalone. The+ `AppsLauncher` stub 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 fiveviewports, a drag and an `End` press both stopping at the affordable maximumrather than the constant one, a window narrowed *after* a wide drag giving the@@ -267,3 +270,322 @@ edited into `design.pen`.settled — a class name, a bounding box and jsdom all miss a transparentlayer. Verified non-vacuous: injecting a real `fixed inset-0 z-20` div intothe surface fails it.++## Follow-up: the launcher is a sidebar control++Reported after merge: *switching to the inline menu makes the Apps button at the+bottom of the sidebar disappear.* It does, and the cause is the paragraph above —+the launcher was retired together with the window layer it opens into.++The reasoning behind that ("a control whose every result is hidden is not a live+control") is sound about the *layer* and wrong about the *control*. Apps is a+sidebar control, sitting in the same bottom row as the Settings toggle and the+service status, and inline's whole claim is that the sidebar column stays live.+A column that keeps every button except one has no rule the user can see; it just+looks like something broke. So the launcher goes back to `settingsCoversSidebar`,+like every other control in that column.++What made retiring it look necessary is real, though: the window layer is hidden+while Settings is open, so a window opened from there would arrive invisible.+That is answered the way the sidebar already answers it for its links — **bringing+a window forward is a way out of Settings**. Clicking Inbox leaves Settings by+going to Inbox; opening Files leaves Settings by opening Files. The Settings+toggle beside it uses the same exit.++Where to put that is the only real design question. Not in `AppsLauncher`: the+Dock, a deep link, a restored window and a window focusing itself all reach the+same layer, and each would have to ask what happens to be covering it. So+`WindowManagerProvider` takes an `onWindowForeground` callback and calls it from+the only two places a window can reach the top — `focus` and `openApp`, with+`restore` funnelling through `focus` — and `AppShell` supplies the exit. The+callback is held in a `useLatestRef` so `focus`/`openApp` keep their identity;+they are part of the context value every window consumes.++The second report — *clicking blank space in the app sidebar while the inline+menu is open also dismisses it* — does **not** reproduce on `b45fbc604`. Swept in+a browser with `document.elementFromPoint` at two x positions across sixteen y+positions of the sidebar: every point that closed Settings had a real link under+it (the brand row's `a[href="/"]`, the tree's `a[href="/inbox"]`) and navigated+there, which is the designed exit; every genuinely blank point — the aside+itself, the tree's scroll container, the bottom row, the whole right-hand column —+kept it open. The brand link is content-sized (measured 159.5px wide against a+248px rail), so the apparent blank to its right is not part of it. Most likely a+build predating `4f2e34ab1`, where inline still dismissed on any outside+interaction; that build would also show the missing Apps button.++### Validation++- `WindowManagerProvider.test.tsx` — every way a window reaches the top announces+ itself (`openApp`, `focus`, and `restore` through `focus`), the ways down do not+ (`focusCanvas`, `minimize`, `close`), and a provider with no listener still+ works.+- `AppShell.test.tsx` — the launcher retires under standalone and stays under+ inline; a foreground announcement while Settings is open returns to the origin+ route and brings the window layer back; one outside Settings changes nothing.+ Verified non-vacuous: restoring the old boundary fails the first, dropping the+ prop fails the second, dropping the `settingsOpen` guard fails the third.+- `e2e/workbench-general/geometry.spec.ts` — in a browser: Apps is gone under+ standalone, back under inline, and the pointer actually lands on it rather than+ on the surface above it; opening a Dock tile from there closes Settings and+ shows the window.++### Review round: three consequences of the new exit++Codex review of `9bf337e2` found three, all real, all the same shape — a+foreground announcement crossing from the window manager into a surface that+does not own it. One announcement per window meets one exit per gesture; a+close meets a focus decision; and a lazily-loaded route meets a surface that has+already been retired. Keeping the announcement at the manager stays right — the+Dock, ⌘K search, a deep link and a restored window all reach the same layer, and+none of them should have to ask what is covering it — so each consequence is+answered where it lands.++**One gesture, one exit.** The Dock's "Show all windows" restores every+minimized window in a loop, so N announcements arrive in one synchronous batch,+before React can re-render with Settings closed. Announcing stays per window and+truthful; *leaving* becomes per gesture. `AppShell` holds a latch cleared after+every commit, so it covers exactly the batch it is for. Without it the exit's+history traversal runs N times and lands N-1 entries before the origin — on a+route the user never asked to see.++**The window keeps the focus it took.** Settings hands focus back to the control+that opened it. Not on this exit: the window that caused it has already claimed+DOM focus, and the window chords (⌘W / ⌘M) resolve their target from+`document.activeElement`, so restoring the sidebar toggle would leave that window+on screen and deaf, with ⌘W falling through to the browser's close-tab. Only the+shell knows the close had a cause and only the surface owns the focus decision,+so the shell publishes a one-shot `SettingsFocusHandoffContext` ref and the+surface spends it in Radix's deferred close callback. A ref, not state: nothing+renders differently for it, and the callback runs after the render that closed+the surface. The shell clears it on any commit that still shows Settings — every+commit except the one this exit produces — so a flag raised for a close that then+did not happen cannot eat the next, ordinary close's return focus.++**A retired route does not launch.** `RouteSurfaceActivityBoundary` scopes+navigation, not the window manager, so `/apps/show/:sessionId` resolving its lazy+chunk after Settings took the foreground would bring a window forward behind an+opaque overlay — and half-handle itself, since the boundary refuses the redirect+while the route's once-only latch is already spent. Both halves of that handoff+are foreground gestures, so the whole effect waits on `useRouteSurfaceActive()`+and runs whole when the surface is live again.++### Validation (review round)++- `AppShell.test.tsx` — three announcements in one batch land on the origin, not+ two entries past it; the window exit raises the handoff flag and the next+ visit's ordinary close does not see it. Non-vacuous: dropping the latch lands+ on `session-1`, dropping the raise reads `false`, dropping the clear reads+ `true` on the second close.+- `SettingsOverlayRouteSurface.test.tsx` — a retained app window keeps DOM focus+ when it is what closed Settings, against the neighbouring rule that the same+ window loses it on an ordinary close. Non-vacuous: dropping the early return+ moves focus to the toggle.+- `ShowPageRoute.test.tsx` — a retired surface neither opens the window nor+ redirects, and still owes both once it is live. Non-vacuous: dropping the gate+ opens the window while retired.+- `e2e/workbench-general/geometry.spec.ts` — in a browser, opening a Dock tile+ beside inline Settings leaves focus inside the window. Non-vacuous: dropping+ the early return fails it.++## Review round 2: the exit cannot be refused++The round-2 finding asked the window-foreground exit to carry an authorization+verdict: a dirty `/apps/editor` retained behind Settings would put the+router-wide unsaved-changes blocker in front of `closeSettingsOverlay()`, and+cancelling that prompt would leave the window appended and focused behind a+Settings surface that never closed — half of an action the user declined.++The premise does not hold, and the reason is the same boundary that answered the+round-1 `ShowPageRoute` finding. `useUnsavedChanges` reads+`useRouteSurfaceActive()` and registers `null` while its surface is inactive, so+the route retained behind Settings withdraws its registration for the whole+visit. `shouldBlock` then sees an empty registry and lets the close through:+there is no prompt, no verdict to propagate, and no half-applied state to guard+against.++That is the right answer rather than a lucky one. Closing the overlay returns to+the very route the overlay was opened over, which stayed mounted the entire time+with its draft intact — nothing is discarded, so a "Discard unsaved changes?"+prompt would be false in both of its branches. Adding `authorizeRouteAction()`+here would be a no-op today (it reads the same empty registry) and a lie the day+the withdrawal changed.++Both round-1 and round-2 findings therefore share one class — what an inactive+route surface may still do — and that class already has a single owner in+`RouteSurfaceActivityBoundary`. Round 1 brought `ShowPageRoute` under it; the+unsaved-changes registry was already there.++`UnsavedChangesProvider.test.tsx` pins the guarantee at the level of the+behaviour rather than the mechanism: leaving the overlay while a dirty route is+retained prompts nothing and closes Settings, and the same harness still prompts+when a navigation really does leave that route. Non-vacuous both ways —+dropping the `routeSurfaceActive` gate reproduces exactly the prompt the finding+described.++### Out of scope, found while diagnosing++Navigating from an open Settings surface to a *different* route unmounts the+retained dirty route without prompting, because its registration is withdrawn+for the duration of the visit. That is pre-existing behaviour in the+unsaved-changes feature, independent of the Settings menu placement work, and it+wants its own change: the withdrawal should cover transitions that return to the+origin, not every transition made while the overlay is open.++## Review round 3: the announcement belongs to the caller++Round 3 found two more launch paths with the shape round 1 fixed in+`ShowPageRoute`: `ShowPageLaunchControl.openWindow` awaits `prepare()` before+`openApp`, and `ChatPage.openLocalFile` awaits `fileMeta`. Both components stay+mounted behind the Settings overlay, so a user who opens Settings mid-await gets+Settings thrown away by a launch they had already moved on from. Both premises+check out.++Three findings-bearing heads, all one class, so the circuit breaker applies and+the diagnosis moves up a level. The class is mine: `onWindowForeground` is new+in this PR, and the mistake was where it was wired. Putting the announcement+inside the provider's `focus` and `openApp` gave every caller an obligation none+of them knows about — "clear whatever covers the window layer" — and left each+one to discover for itself that the obligation has a condition. Patching two+more call sites would have bought the same bug a fourth head.++The announcement is the one thing the window manager does on someone else's+behalf, so it is the one thing that depends on who is asking. It moves to+`useWindowManager`, the single consumer boundary, where `useRouteSurfaceActive()`+already answers "is this caller still what the user is looking at". The provider+exposes `announceForeground` and calls it from nothing; the hook calls it ahead+of `openApp`, `focus`, `restore` and `toggleMaximize`. Every present and future+caller inherits the gate, and none of them has to know it exists.++The gate reads its answer when the method is *called*, not when the closure was+made — through `useLatestRef`, not the memo's dependencies. That is the whole+point for the suspended launches above: their closure was created while the+surface was live and only the call is late, so a render-time check would still+let the stale continuation announce.++Rejected: gating each awaited call site (the shape that already needed three+rounds to enumerate), moving the exit up to shell chrome (it would stop the Dock+from working in inline mode, which is the bug this PR opened with), and teaching+`RouteSurfaceActivityBoundary` about windows (it would couple routing to the+window manager to serve one caller).++`LibraryRoute` gets the `surfaceActive` gate that `ShowPageRoute` got in round+1 — same latch, same half-done handoff, and it was simply missed.+`toggleMaximize` reaches the top through `focus`, so it announced before this+refactor; it is wrapped too, rather than silently losing the behaviour.++`WindowManagerProvider.test.tsx` pins both halves: a retired caller still gets+its window opened and focused but announces nothing, and a reference captured+while the surface was live announces by whether the surface is live at the call.+Non-vacuous — removing the gate fails both.++### Correction to this PR's own validation++`npx tsc --noEmit` in `ui/` checks nothing: `ui/tsconfig.json` is a solution file+with `"files": []` and only project references. The real typecheck is `tsc -b`,+which is what `npm run build` runs — and it caught a nullability error in the+first version of the hook that the vacuous command had reported clean.++## Review round 4: a command route is not a place++Fourth findings-bearing head, same class, so the breaker applies again and the+diagnosis goes up another level. This time it reaches something I wrote in+round 1 and then reasoned from three times.++Round 1 claimed that `RouteSurfaceActivityBoundary` "already refuses the+redirect" from a retired surface, and deferred `ShowPageRoute`'s whole handoff+on that basis. The boundary does no such thing. It swallows `go` and `push`,+but `replace` is *diverted* to `inactiveReplace`, and+`SettingsOverlayRouteSurface` always supplies one. The claim came from the+round-1 test itself, which rendered the boundary without that prop and so+manufactured the premise it went on to verify. The round-3 note repeated it and+extended the same gate to `LibraryRoute`.++With the real boundary in view, the deferral is the defect Codex reported: a+command that waits is a command that fires later, once the user has moved on.+Both gates are removed. `ShowPageRoute` and `LibraryRoute` run when they are+asked, retired or not, and neither half reaches over the foreground — the+window manager withholds the announcement (round 3) and the boundary routes the+redirect to the surface. `LibraryRoute` is not lazily loaded, so its gate was+unreachable on top of being wrong.++Removing the deferral is necessary and not sufficient. The exit had the same+bug by a second road:++`replaceBackground` rewrote the retained origin's *location* and kept its+recorded `historyIndex`. That index names the history entry the origin was read+from, and that entry still holds the pre-rewrite url. `closeSettingsOverlay`+prefers a history pop whenever the index is usable, so leaving Settings landed+back on the command url, mounted the command a second time, and raised its+window over the app the user had just picked from the launcher — Codex's+scenario exactly, reproduced with the deferral already gone. The rewrite now+clears the index, so the exit replaces forward onto where the origin actually+is.++Unconditional, including a rewrite that only carries new state. Two rules would+have let the same surface answer differently for a url change and a state+change, and the state case is not benign either: the existing+"maintains only the retained origin" test asserts the rewrite survives the+exit, which was true in jsdom only because a memory router leaves+`history.state` null. One rule makes that assertion true in a browser too.++Rejected: Codex's proposed "a window-caused Settings exit supersedes pending+handoffs", which adds a concept to carry the deferral rather than removing it;+and abandoning a handoff that cannot run, which silently drops a navigation the+user asked for.++Evidence. `ShowPageRoute.test.tsx`'s handoff describe is rewritten around a real+`inactiveReplace` — the prop whose absence caused this. Two surface tests pin+the exit against a seeded `history.state.idx`, and both fail without the index+fix. `C-SETTINGS-10` plays the reported gesture end to end in a browser, where+the history stack is real: hold the lazy chunk, open inline Settings, release+it, pick Files from the launcher, and require Files to stay in front. It fails+against either half of the fix reverted on its own.++## Review round 5: who put the entry there++Round 4 traded one misfire for a quieter one, and Codex caught the trade. With+the index cleared, the exit replaces the Settings entry going forward, so the+entry the command was pushed into survives underneath. Press Back and the+command url mounts again and raises its window.++Verified in a browser rather than argued: after the launcher exit the stack is+`[/apps/show/ses-show, /]` at index 1, and Back lands on index 0, focuses the+existing Show Page window — two windows, not three — and replaces to `/`.++No API erases a history entry you are not standing on, and every way of+standing on this one runs the command to get there. So the question is not how+to erase it but whether it should be erased, and that turns on who put it+there. On desktop nothing in the product navigates to `/apps/show/:id`: the+Dock calls `wm.openApp` directly, the App Library and app search both branch to+the window on a desktop viewport, and the only caller that routes is the mobile+Dock drawer — a surface with neither this Settings placement nor this launcher.+A desktop session holds that entry only because the user opened that url.++Back returning them to the page that url names, raising its window, is what the+url means; a fresh visit to it does the same. The alternative Codex asks for —+removing the spent command from history — would send Back out of the app+instead. The two halves are one rule: an exit the user did not aim at the Show+Page must not raise it, and a Back they did aim there must. `C-SETTINGS-10`+now carries both, which is the coverage gap the finding named.++## Review round 6: the gate already reaches window bodies++Codex read the announcement gate as covering retained routes only, on the+premise that `WindowLayer` sits outside any `RouteSurfaceActivityBoundary`. It+does not: the layer renders one around its windows, fed by the same `active`+prop the shell hides it with, and `useWindowManager` reads it from there. So a+window body is retired exactly when the layer is, and the awaited+`AppsPreviewPage.openInEditor` and `AppsFileBrowserPage` content-hit paths it+named are already covered — the suspended-closure case is the one the gate was+written for.++The premise was reachable, though, because nothing pinned the wiring end to+end. The gate's tests drive `RouteSurfaceActiveContext` directly, and the+layer's boundary has no test at all, so both halves read as plausible while+neither states that window bodies inherit the answer.++`windowLayerForeground.test.tsx` now renders the real layer under the real+provider, captures the manager from a window body the way an await holds it,+retires the layer, and requires the late `openApp` to open its window without+announcing — then to announce again once the layer is live. Both fail if the+layer stops passing `active` into its boundary.diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex 30001f9aa..90e8f7135 100644--- a/ui/e2e/workbench-general/geometry.spec.ts+++ b/ui/e2e/workbench-general/geometry.spec.ts@@ -676,4 +676,52 @@ test.describe('general settings geometry', () => {expect(await widthOf(page, SETTINGS_RAIL)).toBe(standaloneRail);expect(denied).toEqual([]);});++ // Keeping that column live means keeping its controls. Apps is one of them,+ // and the one a boundary can quietly take away: it portals its button and Dock+ // to `document.body`, so nothing in the sidebar's markup shows it missing.+ test('keeps the Apps launcher usable beside inline Settings', async ({ page }) => {+ const denied = await serveProduct(page);+ await page.setViewportSize(ULTRA);+ await open(page, '/');+ const apps = page.getByRole('button', { name: 'Apps', exact: true });+ await expect(apps).toBeVisible();++ const overlay = page.locator('[data-settings-overlay="true"]');+ await page.locator(`${SIDEBAR} [data-settings-toggle="true"]`).click();+ // Standalone stands in for the sidebar, so the sidebar's controls go with it.+ await expect(overlay).toHaveAttribute('data-settings-menu-placement', 'standalone');+ await expect(apps).toHaveCount(0);++ await page.getByRole('radio', { name: 'Inline' }).click();+ await expect(overlay).toHaveAttribute('data-settings-menu-placement', 'inline');+ await expect(apps).toBeVisible();++ // Reachable, not merely rendered: it floats at z-40 over a surface at z-30,+ // and which of the two the pointer lands on is a hit test.+ const box = (await apps.boundingBox())!;+ expect(await page.evaluate(([x, y]) => Boolean(+ document.elementFromPoint(x, y)?.closest('button[aria-haspopup="menu"]'),+ ), [box.x + box.width / 2, box.y + box.height / 2])).toBe(true);++ // And it still opens what it is for. The window layer stays hidden for as+ // long as Settings is open, so bringing a window forward leaves Settings+ // first — otherwise the window would arrive behind an opaque surface.+ await apps.click();+ const dock = page.getByRole('menu', { name: 'Apps', exact: true });+ await expect(dock).toBeVisible();+ await dock.getByRole('button', { name: 'Files', exact: true }).click();+ await expect(overlay).toHaveCount(0);+ await expect(page.locator('[data-window-id]').first()).toBeVisible();++ // And the window keeps the focus it just took. The window chords resolve+ // their target from DOM focus, so Settings restoring focus to the toggle it+ // was opened from — its ordinary way out — would leave this window on+ // screen and deaf, with ⌘W falling through to the browser's close-tab.+ // Polled: the restore Settings would attempt is deferred a frame.+ await expect+ .poll(() => page.evaluate(() => Boolean(document.activeElement?.closest('[data-window-id]'))))+ .toBe(true);+ expect(denied).toEqual([]);+ });});diff --git a/ui/e2e/workbench-general/standalone-settings.spec.ts b/ui/e2e/workbench-general/standalone-settings.spec.tsindex d39a82acb..c27fd0189 100644--- a/ui/e2e/workbench-general/standalone-settings.spec.ts+++ b/ui/e2e/workbench-general/standalone-settings.spec.ts@@ -547,3 +547,95 @@ test('C-SETTINGS-09: a held sidebar create cannot navigate through foreground Seexpect(denied).toEqual([]);expect(pageErrors).toEqual([]);});++// A command route is a route only in the url bar: /apps/show/:id opens its+// window and replaces itself with the canvas. It is lazily loaded, so the user+// can open Settings before its chunk lands, and the window it then opens has to+// wait behind Settings instead of evicting it. The half that outlived two+// attempts at this is the way OUT. The exit prefers a history pop back to the+// entry the origin was read from — that entry still holds the command url — so+// leaving Settings mounts the command a second time and raises its window over+// whatever the user actually asked for. Only a browser has the history stack+// that decision turns on, which is why it is settled here and not in jsdom.+test('C-SETTINGS-10: a command route finished under Settings does not re-run over the app the user picks', async ({ page }) => {+ const denied = await serveProduct(page);+ const pageErrors: string[] = [];+ page.on('pageerror', (error) => pageErrors.push(error.message));+ await page.route('**/api/show-pages', (route) => route.fulfill({ json: { pages: [] } }));+ await page.route('**/api/sessions/ses-show**', (route) => route.fulfill({ json: {+ id: 'ses-show', title: 'Pinned page', status: 'active', scope_id: 'scope-1', project_id: 'proj-1',+ } }));++ // Hold the chunk the way a cold load does, then let it land while Settings is+ // in front — the one ordering this is about.+ let release!: () => void;+ const held = new Promise<void>((resolve) => { release = resolve; });+ let chunkRequests = 0;+ await page.route('**/ShowPageRoute.tsx*', async (route) => {+ chunkRequests += 1;+ if (chunkRequests === 1) await held;+ return route.fallback();+ });++ // Inline, because that is where this is reachable: it is the placement that+ // keeps the Apps launcher beside Settings, so picking another app is the+ // ordinary way out rather than a second gesture.+ await page.addInitScript(() => {+ window.localStorage.setItem('avibe.settings.menu-placement.v1', 'inline');+ });+ await page.setViewportSize({ width: 1600, height: 900 });+ await open(page, '/apps/show/ses-show');+ await expect(toggle(page)).toBeVisible();++ await toggle(page).click();+ await expect(settings(page)).toHaveAttribute('data-settings-menu-placement', 'inline');+ const originIndex = await page.evaluate(() => history.state.idx);+ release();++ // The command runs while retired: its window opens behind Settings, which+ // does not move, and the origin it will return to becomes the canvas.+ const windows = page.locator('[data-window-id]');+ await expect(windows).toHaveCount(1);+ await expect(settings(page)).toBeVisible();+ await expect(page).toHaveURL(/\/settings\/general$/);++ // Now the reported gesture: a different app, chosen from the launcher that+ // inline keeps on screen. It opens its window and that is what closes+ // Settings.+ await page.getByRole('button', { name: 'Apps', exact: true }).click();+ await page.getByRole('menu', { name: 'Apps', exact: true })+ .getByRole('button', { name: 'Files', exact: true }).click();+ await expect(settings(page)).toHaveCount(0);+ await expect(windows).toHaveCount(2);++ // The window the user just picked is the one in front, and stays there: a+ // re-run of the command would focus the Show Page window over it.+ const topWindow = () => page.evaluate(() => Array.from(+ document.querySelectorAll<HTMLElement>('[data-window-id]'),+ ).sort((a, b) => Number(a.style.zIndex || 0) - Number(b.style.zIndex || 0))+ .at(-1)?.getAttribute('aria-label') ?? null);+ await expect(page).toHaveURL(`${origin}/`);+ await page.waitForTimeout(400);+ expect(await topWindow()).toBe('Files');+ await expect(page).toHaveURL(`${origin}/`);+ // Left forward, not popped back onto the entry the command already spent.+ expect(await page.evaluate(() => history.state.idx)).toBe(originIndex);++ // Back still reaches that entry, and should: leaving Settings forward cannot+ // erase a history entry it is not standing on, and no browser API can. What+ // saves it is who put the entry there. On desktop nothing in the product+ // navigates to this url — the Dock, the App Library and app search all open+ // the window directly, and only mobile, which has neither this Settings+ // placement nor this launcher, routes to it. So a desktop session holds this+ // entry only because the user opened that url themselves, and Back returning+ // them to the page they opened, raising its window, is what that url means.+ // Both halves are the same rule read twice: an exit the user did not aim at+ // the Show Page must not raise it, and a Back they did aim there must.+ await page.goBack();+ await expect(page).toHaveURL(`${origin}/`);+ await expect(windows).toHaveCount(2); // raised, not duplicated+ await page.waitForTimeout(400);+ expect(await topWindow()).toBe('Show Page');+ expect(denied).toEqual([]);+ expect(pageErrors).toEqual([]);+});diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 64bc3abc3..435b764f5 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -571,6 +571,11 @@ const LibraryRoute = () => {// opens on the Show Pages inventory the bookmark asked for, not the Apps tab.const initialTab = new URLSearchParams(location.search).get('view') === 'pages' ? ('showpages' as const) : undefined;+ // Runs whether or not this surface is the live one — same handoff, and the same+ // reason, as ShowPageRoute: a command route runs when it is asked, not when it+ // is convenient. The manager withholds the foreground announcement from a+ // retired surface and the boundary diverts the redirect to it, so nothing here+ // reaches over the top of what the user is looking at.useEffect(() => {if (!isDesktop || handledRef.current) return;handledRef.current = true;diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsxindex e8c8b543e..d46a0d5f3 100644--- a/ui/src/components/AppShell.test.tsx+++ b/ui/src/components/AppShell.test.tsx@@ -3,9 +3,15 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';-import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom';+import { MemoryRouter, Route, Routes, useLocation, useNavigate, useParams } from 'react-router-dom';+import { useEffect } from 'react';import type { ReactNode } from 'react';-import { closeSettingsOverlay, useSettingsOverlayOrigin } from '../lib/settingsOverlay';+import {+ closeSettingsOverlay,+ settingsOverlayStateForOrigin,+ useSettingsFocusHandoff,+ useSettingsOverlayOrigin,+} from '../lib/settingsOverlay';import { APP_TAB_PARAM } from '../apps/appLaunch';import {@@ -104,8 +110,18 @@ vi.mock('../context/DockProvider', () => ({<div data-testid="dock-provider" data-enabled={String(enabled)}>{children}</div>),}));+// Captures the one prop the shell hands the manager: what to do when a window is+// about to come forward. The real manager calls it from `focus`/`openApp`; here+// the test calls it directly, which is the same event from the shell's side.+const windowManager = vi.hoisted(() => ({ foreground: null as (() => void) | null }));vi.mock('../context/WindowManagerProvider', () => ({- WindowManagerProvider: ({ children }: { children: ReactNode }) => <>{children}</>,+ WindowManagerProvider: ({ children, onWindowForeground }: {+ children: ReactNode;+ onWindowForeground?: () => void;+ }) => {+ windowManager.foreground = onWindowForeground ?? null;+ return <>{children}</>;+ },}));vi.mock('../context/ShowPageDragProvider', () => ({ShowPageDragProvider: ({ children }: { children: ReactNode }) => <>{children}</>,@@ -156,6 +172,21 @@ const SettingsExit = ({ testId }: { testId: string }) => {</div>;};+// Stands in for a background route the shell can land back on, and for the one+// thing the real Settings surface reads from the shell on its way out: whether+// this close is handing focus to a window (`SettingsFocusHandoffContext`).+const chatProbe = { handoff: null as boolean | null };+const ChatProbe = () => {+ const { sessionId } = useParams();+ const handoffRef = useSettingsFocusHandoff();+ // Child effects run before the shell's own, so this reads the flag as the+ // Settings surface's deferred close callback would find it on this commit.+ useEffect(() => {+ chatProbe.handoff = handoffRef?.current ?? null;+ });+ return <div data-testid="chat">{sessionId}</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 = () => (@@ -164,6 +195,8 @@ const StandaloneMenuProbe = () => (beforeEach(() => {viewport.isDesktop = false;+ windowManager.foreground = null;+ chatProbe.handoff = null;window.localStorage.clear();clearMobileProjectsListSnapshot();instanceAuth.remote = true;@@ -395,10 +428,9 @@ describe('AppShell sidebar width', () => {// 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.+ // retired, so this one retires in both placements.it.each(['standalone', 'inline'] as const)(- 'retires the window layer and its launcher under %s Settings',+ 'retires the window layer under %s Settings',async (placement) => {viewport.isDesktop = true;window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);@@ -407,12 +439,11 @@ describe('AppShell sidebar width', () => {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 () => {+ it('restores the window layer once Settings closes', async () => {viewport.isDesktop = true;window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');renderShell('/');@@ -423,6 +454,170 @@ describe('AppShell sidebar width', () => {expect(screen.getByTestId('apps-launcher')).toBeTruthy();});+ // The launcher does NOT go with the layer. It is a sidebar control, and it+ // retires with the column it sits in like every other control there: gone+ // under standalone, which stands in for that column, present under inline,+ // which keeps it. Taking Apps away under inline is the sidebar losing a button+ // that is on screen the rest of the time, for no reason the user can see.+ it.each([+ ['standalone', false],+ ['inline', true],+ ] as const)('keeps the Apps launcher wherever the sidebar stays live (%s)', async (+ placement,+ live,+ ) => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ renderShell('/settings/general');+ await screen.findByTestId('surface');++ expect(Boolean(screen.queryByTestId('apps-launcher'))).toBe(live);+ });++ // What makes keeping it safe: the layer a window arrives in is hidden while+ // Settings is open, so coming forward has to leave Settings first — the same+ // exit a sidebar link takes by navigating, and the toggle beside it by closing.+ // The shell says it once, to the manager, rather than each caller working out+ // what is covering the layer.+ it('leaves Settings when a window comes forward', async () => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ const user = userEvent.setup();++ render(+ <MemoryRouter initialEntries={['/chat/session-1']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="chat/:sessionId" element={<div data-testid="chat" />} />+ <Route path="settings/general" element={<SettingsExit testId="settings" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ expect(await screen.findByTestId('chat')).toBeTruthy();+ await user.click(screen.getByRole('link', { name: 'appShell.openControlPanel' }));+ expect(await screen.findByTestId('settings')).toBeTruthy();+ expect(screen.getByTestId('window-layer').parentElement?.hasAttribute('hidden')).toBe(true);++ act(() => windowManager.foreground?.());++ expect(await screen.findByTestId('chat')).toBeTruthy();+ expect(screen.getByTestId('window-layer').parentElement?.hasAttribute('hidden')).toBe(false);+ });++ // Coming forward is announced per window, and one gesture can raise many: the+ // Dock's "Show all windows" restores every minimized window in a loop, so the+ // announcements all land before React can re-render with Settings closed.+ // Leaving is not per window — it is per gesture. Answering each would run the+ // exit's history traversal once per window and land that many entries before+ // the origin, on a route the user never asked to see.+ it('leaves Settings once however many windows come forward', async () => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ // The exit walks history back to the origin when it can tell where that is,+ // which is the path a repeat overshoots; the fallback replace is idempotent+ // and would hide the defect.+ const origin = {+ historyIndex: 1,+ location: {+ pathname: '/chat/session-2', search: '', hash: '', state: null, key: 'origin',+ },+ };+ window.history.replaceState({ idx: 2 }, '');+ try {+ render(+ <MemoryRouter+ initialEntries={[+ '/chat/session-1',+ '/chat/session-2',+ { pathname: '/settings/general', state: settingsOverlayStateForOrigin(origin, null) },+ ]}+ initialIndex={2}+ >+ <Routes>+ <Route element={<AppShell />}>+ <Route path="chat/:sessionId" element={<ChatProbe />} />+ <Route path="settings/general" element={<SettingsExit testId="settings" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByTestId('settings')).toBeTruthy();++ // One gesture, three windows: the same synchronous batch the Dock produces.+ act(() => {+ windowManager.foreground?.();+ windowManager.foreground?.();+ windowManager.foreground?.();+ });++ // The origin, not two entries further back.+ expect((await screen.findByTestId('chat')).textContent).toBe('session-2');+ } finally {+ window.history.replaceState(null, '', '/');+ }+ });++ // Who holds DOM focus after this exit is not the Settings surface's usual+ // answer. The window that caused it has already taken focus, and the window+ // chords read their target from focus, so handing it back to the control that+ // opened Settings would put a window on screen that ⌘W no longer closes. Only+ // the shell knows this close had a cause, so the shell is what says so.+ it('marks the window exit as a focus handoff, and spends it only there', async () => {+ viewport.isDesktop = true;+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, 'inline');+ const user = userEvent.setup();+ render(+ <MemoryRouter initialEntries={['/chat/session-1']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="chat/:sessionId" element={<ChatProbe />} />+ <Route path="settings/general" element={<SettingsExit testId="settings" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ expect(await screen.findByTestId('chat')).toBeTruthy();+ await user.click(screen.getByRole('link', { name: 'appShell.openControlPanel' }));+ expect(await screen.findByTestId('settings')).toBeTruthy();++ act(() => windowManager.foreground?.());+ expect(await screen.findByTestId('chat')).toBeTruthy();+ expect(chatProbe.handoff).toBe(true);++ // The same flag, one visit later. Nothing about the toggle's own close hands+ // focus anywhere, so a flag still standing from the previous exit would take+ // the return focus away from the control that asked for it.+ await user.click(screen.getByRole('link', { name: 'appShell.openControlPanel' }));+ await user.click(await screen.findByRole('button', { name: 'settings.close' }));+ expect(await screen.findByTestId('chat')).toBeTruthy();+ expect(chatProbe.handoff).toBe(false);+ });++ // The window it opens is the foreground, not a reason to leave one route for+ // another: with Settings closed there is nothing to clear out of the way.+ it('stays put when a window comes forward outside Settings', async () => {+ viewport.isDesktop = true;+ render(+ <MemoryRouter initialEntries={['/chat/session-1']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route index element={<div data-testid="workbench" />} />+ <Route path="chat/:sessionId" element={<div data-testid="chat" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );+ expect(await screen.findByTestId('chat')).toBeTruthy();++ act(() => windowManager.foreground?.());++ expect(screen.getByTestId('chat')).toBeTruthy();+ expect(screen.queryByTestId('workbench')).toBeNull();+ });+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');diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 8817aaee0..b1c4c18c5 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState } from 'react';+import React, { useCallback, useEffect, useRef, useState } from 'react';import { Link, Navigate, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';import { AlertTriangle, FolderTree, Grid2x2, Inbox, LayoutGrid, Plus, Settings } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -39,6 +39,7 @@ import {closeSettingsOverlay,isChromelessShellPath,isSettingsEntryPath,+ SettingsFocusHandoffContext,useSettingsOverlayOrigin,} from '../lib/settingsOverlay';import { isStandaloneSettingsMenu, useSettingsMenuPlacement } from '../lib/settingsMenuPlacement';@@ -235,7 +236,9 @@ export const AppShell: React.FC = () => {// "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.+ // it reads `settingsOpen` instead. Its launcher does NOT go with it — it is+ // a sidebar control, and a live sidebar keeps its controls; bringing a window+ // forward is simply a way out of Settings, exactly like the links above it.//// The rule, not the hook: the shell is what publishes `ShellSidebarContext`,// so it cannot read its own broadcast and feeds the same function directly.@@ -309,6 +312,45 @@ export const AppShell: React.FC = () => {window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);}, [chromeless, location.pathname, location.search]);+ // One gesture, one exit. Announcements are per window: the Dock's "Show all+ // windows" restores every minimized window in a single loop and each restore+ // comes forward, so N of them arrive before React can re-render with Settings+ // closed. Answering each would run `closeSettingsOverlay`'s history delta N+ // times over and land well past the origin. Cleared after every commit, so+ // the latch covers exactly the synchronous batch it is for and cannot outlive+ // a navigation that never happened.+ const leavingSettingsRef = useRef(false);+ useEffect(() => { leavingSettingsRef.current = false; });+ // Read by the Settings surface below the outlet, on the close this exit+ // causes. See `SettingsFocusHandoffContext`.+ //+ // Cleared on any commit that still shows Settings, which is every commit+ // except the one this exit produces: a flag raised for a close that then did+ // not happen — or one the surface never came back to spend — would otherwise+ // sit here and eat the return focus of the next, ordinary close. Radix defers+ // its close callback past this effect, so the successful exit still finds it.+ const settingsFocusHandoffRef = useRef(false);+ useEffect(() => {+ if (settingsOpen) settingsFocusHandoffRef.current = false;+ });++ // A window coming forward is a way out of Settings, and has to be: the window+ // layer is hidden for as long as Settings is open, so a window opened or+ // focused from behind it would arrive invisible. The sidebar's links already+ // work this way -- clicking Inbox leaves Settings by going to Inbox -- and the+ // Apps launcher is one more sidebar control, so it leaves the same way instead+ // of being taken away. Same exit the Settings toggle beside it uses.+ //+ // Above the access redirects below, because it is a hook and they are returns.+ const leaveSettingsForWindow = useCallback(() => {+ if (!settingsOpen || leavingSettingsRef.current) return;+ leavingSettingsRef.current = true;+ // The window that caused this exit owns the focus that comes with it.+ settingsFocusHandoffRef.current = true;+ if (settingsOverlayOrigin) closeSettingsOverlay(navigate, settingsOverlayOrigin);+ else navigate('/');+ }, [navigate, settingsOpen, settingsOverlayOrigin]);+const isRunning = status.state === 'running';const canUseApps = capabilities.can_chat;const canUseShowPageApp =@@ -388,7 +430,8 @@ export const AppShell: React.FC = () => {// Desktop: normal document flow.<ShellSidebarContext.Provider value={shellDrawsSidebar}><SettingsOverlayNavigationBoundary desktop={isDesktop}>- <WindowManagerProvider standalone={standaloneAppTab}>+ <SettingsFocusHandoffContext.Provider value={settingsFocusHandoffRef}>+ <WindowManagerProvider standalone={standaloneAppTab} onWindowForeground={leaveSettingsForWindow}><StandaloneAppTabContext.Provider value={standaloneAppTab}><DockProvider enabled={canUseApps}><ShowPageDragProvider>@@ -434,14 +477,15 @@ 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. */}+ {/* Retires with the column it sits in, like every other control here:+ a live sidebar keeps its controls. The window layer it opens into+ IS hidden under inline Settings (see below), but that makes+ bringing a window forward a way OUT of Settings, not a reason to+ take the control away — `onWindowForeground` below leaves first so+ the window arrives visible, exactly as clicking Inbox leaves for+ Inbox. Its Dock goes with it — same component. */}{canUseApps && (- <RouteSurfaceActivityBoundary active={!settingsOpen}>+ <RouteSurfaceActivityBoundary active={!settingsCoversSidebar}><AppsLauncher /></RouteSurfaceActivityBoundary>)}@@ -613,7 +657,13 @@ export const AppShell: React.FC = () => {a strip over the sidebar with its title bar, controls and content allhidden behind Settings: visible, unusable, and covering the one columninline exists to keep. Inline keeps the sidebar column live, not- everything its surface covers. */}+ everything its surface covers.++ The launcher that opens into this layer does NOT retire with it:+ `onWindowForeground` leaves Settings first, so by the time a window is+ on top this layer is back. That holds for every way a window can come+ forward, not just the launcher — the manager announces it, rather than+ each caller checking what happens to be covering the layer. */}{canUseApps && (<divhidden={settingsOpen}@@ -628,6 +678,7 @@ export const AppShell: React.FC = () => {</DockProvider></StandaloneAppTabContext.Provider></WindowManagerProvider>+ </SettingsFocusHandoffContext.Provider></SettingsOverlayNavigationBoundary></ShellSidebarContext.Provider>);diff --git a/ui/src/components/apps/ShowPageRoute.test.tsx b/ui/src/components/apps/ShowPageRoute.test.tsxindex 2c9a56ced..726e81650 100644--- a/ui/src/components/apps/ShowPageRoute.test.tsx+++ b/ui/src/components/apps/ShowPageRoute.test.tsx@@ -1,9 +1,11 @@/* @vitest-environment jsdom */import { cleanup, fireEvent, render, screen } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom';+import type { Navigator } from 'react-router-dom';+import { RouteSurfaceActivityBoundary } from '../RouteSurfaceActivityBoundary';import { ShowPageRoute } from './ShowPageRoute';const api = vi.hoisted(() => ({@@ -12,19 +14,24 @@ const api = vi.hoisted(() => ({connectWorkbenchEvents: vi.fn(),}));const shareControl = vi.hoisted(() => ({ canManageInstance: undefined as boolean | undefined }));+const viewport = vi.hoisted(() => ({ isDesktop: false }));+const wm = vi.hoisted(() => ({+ windows: [] as unknown[],+ openApp: vi.fn(),+ focus: vi.fn(),+ restore: vi.fn(),+}));vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));vi.mock('../../context/DockContext', () => ({ useDock: () => ({ unpin: vi.fn() }) }));vi.mock('../../context/InstanceAuthorizationContext', () => ({useInstanceAuthorization: () => ({ capabilities: { can_manage_instance: true } }),}));-vi.mock('../../context/WindowManagerContext', () => ({- useWindowManager: () => ({ windows: [], openApp: vi.fn(), focus: vi.fn(), restore: vi.fn() }),-}));+vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => wm }));vi.mock('../../context/showPageDrag', () => ({useShowPageDrag: () => ({ active: false, begin: vi.fn(), end: vi.fn(), dropToDock: vi.fn() }),}));-vi.mock('../../lib/useIsDesktop', () => ({ useIsDesktop: () => false }));+vi.mock('../../lib/useIsDesktop', () => ({ useIsDesktop: () => viewport.isDesktop }));vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));vi.mock('../workbench/ShowPageShareControl', () => ({ShowPageShareControl: ({ canManageInstance }: { canManageInstance?: boolean }) => {@@ -38,6 +45,11 @@ const LocationProbe = () => {return <output data-testid="location">{location.pathname}{location.search}</output>;};+beforeEach(() => {+ viewport.isDesktop = false;+ wm.windows = [];+});+afterEach(() => {cleanup();vi.clearAllMocks();@@ -102,3 +114,45 @@ describe('mobile Show Page app route', () => {expect(screen.queryByRole('button', { name: 'chat.showPage.share' })).toBeNull();});});++// Desktop turns this route into a handoff: open the window, then get out of the+// way. It is a command, not a place — and because it is lazily loaded, Settings+// can take the foreground before its chunk arrives. It runs anyway, both halves,+// because a command held back is a command that fires later, once the user has+// asked for something else. Neither half reaches over the top of Settings: the+// window manager withholds the foreground announcement from a retired surface,+// and the surface takes the redirect through its own replacement.+describe('desktop Show Page window handoff', () => {+ const renderRoute = (active: boolean, inactiveReplace?: Navigator['replace']) => render(+ <MemoryRouter initialEntries={['/apps/show/session-1']}>+ <RouteSurfaceActivityBoundary active={active} inactiveReplace={inactiveReplace}>+ <Routes>+ <Route path="/apps/show/:sessionId" element={<ShowPageRoute />} />+ <Route path="/" element={<div data-testid="canvas" />} />+ </Routes>+ </RouteSurfaceActivityBoundary>+ <LocationProbe />+ </MemoryRouter>,+ );++ it('runs whole while the surface is retired, handing the redirect to it', () => {+ viewport.isDesktop = true;+ const inactiveReplace = vi.fn();+ renderRoute(false, inactiveReplace);++ expect(wm.openApp).toHaveBeenCalledWith('showpage', { params: { sessionId: 'session-1' } });+ // The retired surface decides where its own origin goes — here it just+ // records the ask — so the foreground url is untouched while Settings owns it.+ expect(inactiveReplace).toHaveBeenCalledTimes(1);+ expect(inactiveReplace.mock.calls[0][0]).toMatchObject({ pathname: '/' });+ expect(screen.getByTestId('location').textContent).toBe('/apps/show/session-1');+ });++ it('opens the window and hands back to the canvas on the live surface', () => {+ viewport.isDesktop = true;+ renderRoute(true);++ expect(wm.openApp).toHaveBeenCalledWith('showpage', { params: { sessionId: 'session-1' } });+ expect(screen.getByTestId('location').textContent).toBe('/');+ });+});diff --git a/ui/src/components/apps/ShowPageRoute.tsx b/ui/src/components/apps/ShowPageRoute.tsxindex 33b3f3cec..6c33e5c6e 100644--- a/ui/src/components/apps/ShowPageRoute.tsx+++ b/ui/src/components/apps/ShowPageRoute.tsx@@ -33,6 +33,16 @@ export const ShowPageRoute: React.FC = () => {// Desktop: open (or focus) the Show Page window for this session and hand back// to the canvas. Guarded so the effect runs once even as window state ticks.+ //+ // This runs whether or not the surface is the live one, and it has to. This+ // route is a command, not a place: it is lazily loaded, so Settings can take+ // the foreground before its chunk arrives, and a command held back is a+ // command that fires later — after the user has asked for something else.+ // Running it now is safe in both halves. `useWindowManager` withholds the+ // foreground announcement from a retired surface, so the window opens and+ // waits behind Settings instead of evicting it, and the redirect is diverted+ // to that surface's `inactiveReplace`, which moves the retained origin here+ // so leaving Settings lands on the canvas rather than back on this command.useEffect(() => {if (!isDesktop || handledRef.current || !sessionId) return;handledRef.current = true;diff --git a/ui/src/components/apps/windowLayerForeground.test.tsx b/ui/src/components/apps/windowLayerForeground.test.tsxnew file mode 100644index 000000000..ff59e8a21--- /dev/null+++ b/ui/src/components/apps/windowLayerForeground.test.tsx@@ -0,0 +1,158 @@+/** @vitest-environment jsdom */++// A window body is a retained surface too. It keeps running while Settings+// covers the layer — `AppsPreviewPage` awaits `fileMeta()` before opening the+// editor, `AppsFileBrowserPage` awaits a content hit the same way — so an await+// begun before the overlay resolves after it, and the `openApp` that follows+// would take Settings down on behalf of a user who has moved on.+//+// Nothing in the body knows that. What makes it safe is where the body is+// rendered: this layer wraps its windows in the same activity boundary a+// retained route gets, fed by the same `active` the shell hides the layer with.+// `useWindowManager` reads that boundary, so the body inherits the answer+// without asking. This pins the wiring end to end — the layer's own prop+// through the boundary into the announcement — because reading either half+// alone invites the conclusion that window bodies are ungated.++import { createInstance } from 'i18next';+import { act, cleanup, render } from '@testing-library/react';+import { useEffect } from 'react';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { MemoryRouter } from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import en from '../../i18n/en.json';+import { useWindowManager, type WindowManagerValue } from '../../context/WindowManagerContext';+import { WindowManagerProvider } from '../../context/WindowManagerProvider';+import { WindowLayer } from './WindowLayer';++const dockState = { order: [] as string[], pins: [] as unknown[] };+const api = vi.hoisted(() => ({+ getShowPages: vi.fn(),+ getSessionResult: vi.fn(),+ connectWorkbenchEvents: vi.fn(),+}));++vi.mock('../../context/DockContext', () => ({ useDock: () => dockState }));+vi.mock('../../context/StandaloneAppTabContext', () => ({ useStandaloneAppTab: () => false }));+vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));+vi.mock('../useShowPages', () => ({ useShowPageInventory: () => ({ pages: [] }) }));+vi.mock('../workbench/ShowPageAnnotationHost', () => ({+ ShowPageAnnotationHost: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++// Stands in for a real app body — the only thing that matters here is that it+// takes the manager the way one does and hands the reference back out, which is+// what an awaited continuation holds on to.+const body = { manager: null as WindowManagerValue | null };+vi.mock('./AppWindow', () => ({+ AppWindow: () => {+ const value = useWindowManager();+ useEffect(() => {+ body.manager = value;+ }, [value]);+ return <div data-window-id="win_1" />;+ },+}));++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++describe('window bodies inherit the layer retirement', () => {+ beforeEach(() => {+ vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+ });+ dockState.order = [];+ dockState.pins = [];+ api.getShowPages.mockReset().mockResolvedValue([]);+ api.getSessionResult.mockReset().mockResolvedValue({ status: null, session: null });+ api.connectWorkbenchEvents.mockReset().mockReturnValue(vi.fn());+ body.manager = null;+ });++ afterEach(() => {+ cleanup();+ vi.clearAllMocks();+ });++ const renderShell = (onWindowForeground: () => void) => {+ let shell: WindowManagerValue | null = null;+ const Shell = ({ active }: { active: boolean }) => {+ // The shell reads the manager from ABOVE the layer, the way AppShell does.+ const value = useWindowManager();+ useEffect(() => {+ shell = value;+ }, [value]);+ return <WindowLayer active={active} />;+ };+ const view = render(+ <MemoryRouter>+ <I18nextProvider i18n={i18n}>+ <WindowManagerProvider onWindowForeground={onWindowForeground}>+ <Shell active />+ </WindowManagerProvider>+ </I18nextProvider>+ </MemoryRouter>,+ );+ return {+ shell: () => shell!,+ setActive: (active: boolean) => view.rerender(+ <MemoryRouter>+ <I18nextProvider i18n={i18n}>+ <WindowManagerProvider onWindowForeground={onWindowForeground}>+ <Shell active={active} />+ </WindowManagerProvider>+ </I18nextProvider>+ </MemoryRouter>,+ ),+ };+ };++ it('withholds the announcement from an await that resolves after Settings opens', () => {+ const onForeground = vi.fn();+ const { shell, setActive } = renderShell(onForeground);++ // A window exists, so a body is mounted and has taken its manager.+ act(() => void shell().openApp('preview'));+ expect(body.manager).not.toBeNull();+ // What the body captured before the await — `AppsPreviewPage` holds exactly+ // this across `await fileMeta()`.+ const openInEditor = body.manager!.openApp;+ onForeground.mockClear();++ // Settings opens: the shell hides the layer, and that is the whole signal.+ act(() => setActive(false));+ act(() => void openInEditor('editor'));++ // The editor opened and is on top of the window stack — it is simply waiting+ // behind Settings rather than throwing it away.+ expect(onForeground).not.toHaveBeenCalled();+ expect(shell().windows.some((win) => win.appId === 'editor')).toBe(true);+ });++ it('still announces once the layer is the live surface again', () => {+ const onForeground = vi.fn();+ const { shell, setActive } = renderShell(onForeground);++ act(() => void shell().openApp('preview'));+ const openInEditor = body.manager!.openApp;+ onForeground.mockClear(); // that open was the shell's own, and did announce+ act(() => setActive(false));+ act(() => void openInEditor('editor'));+ expect(onForeground).not.toHaveBeenCalled();++ // Same reference, live layer — so the test above is about who is asking at+ // the moment of the call, not a stale closure that stopped working.+ act(() => setActive(true));+ act(() => void openInEditor('editor'));+ expect(onForeground).toHaveBeenCalledTimes(1);+ });+});diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsxindex 495303db1..230aa0903 100644--- a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx@@ -20,6 +20,7 @@ import {import {closeSettingsOverlay,+ SettingsFocusHandoffContext,useSettingsOverlayOrigin,useSettingsOverlayContext,} from '@/lib/settingsOverlay';@@ -150,6 +151,16 @@ const ChatProbe = () => {}}, [location, navigate, routeSurfaceActive]);+ // Stands in for a command route — /apps/show/:id, /apps/library — reaching the+ // end of its errand while Settings holds the foreground: it opens its window+ // and replaces itself with the canvas. Retired is exactly when this happens,+ // because those routes are lazily loaded and the chunk can land after the+ // user has opened Settings.+ useEffect(() => {+ const handoff = (location.state as { handoff?: string } | null)?.handoff;+ if (!routeSurfaceActive && handoff === 'pending') navigate('/', { replace: true });+ }, [location, navigate, routeSurfaceActive]);+return (<main><div data-testid="chat-location">{`${location.pathname}${location.search}${location.hash}`}</div>@@ -232,9 +243,37 @@ const SettingsToggle = () => {);};-const Harness = ({ desktop }: { desktop: boolean }) => (+// Stands in for the shell's own way out of Settings when a window comes+// forward: it raises the one-shot handoff flag and then leaves, in that order,+// exactly as AppShell does. Driven by `fireEvent.click` rather than a user+// gesture, because the real caller is not a control at all — the window manager+// announces the foreground change — so there is no pointer, nothing outside the+// surface is pressed, and nothing here becomes the origin's new focus owner.+const WindowForegroundExit = ({ handoffRef }: { handoffRef: { current: boolean } }) => {+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayOrigin(location);+ return (+ <button+ type="button"+ onClick={() => {+ if (!origin) return;+ handoffRef.current = true;+ closeSettingsOverlay(navigate, origin);+ }}+ >+ leave-for-window+ </button>+ );+};++const Harness = ({ desktop }: { desktop: boolean }) => {+ const handoffRef = useRef(false);+ return (+ <SettingsFocusHandoffContext.Provider value={handoffRef}><SettingsOverlayNavigationBoundary desktop={desktop}><SettingsToggle />+ <WindowForegroundExit handoffRef={handoffRef} />{/* Shell chrome that lives OUTSIDE the overlay. Inline, the app sidebar isstill on screen beside Settings and still live, so what an outsideinteraction means stops being hypothetical. */}@@ -257,7 +296,9 @@ const Harness = ({ desktop }: { desktop: boolean }) => (<Route path="/" element={<div>workbench</div>} /></SettingsOverlayRouteSurface></SettingsOverlayNavigationBoundary>-);+ </SettingsFocusHandoffContext.Provider>+ );+};const RoutedHarness = ({ desktop = true }: { desktop?: boolean }) => (<Routes>@@ -280,6 +321,9 @@ beforeEach(() => {chatMounts = 0;chatUnmounts = 0;window.localStorage.clear();+ // The exit reads the real history stack to decide between a pop and a+ // replace, so tests that care about which one it takes set `idx` themselves.+ window.history.replaceState(null, '');vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({matches: true,addEventListener: vi.fn(),@@ -346,6 +390,57 @@ describe('SettingsOverlayRouteSurface', () => {expect(screen.getByTestId('chat-maintenance').textContent).toBe('done');});+ // With a real history stack behind it the exit prefers a pop back to the+ // entry the origin was read from — cheaper, and it keeps the stack honest.+ // That entry is only the origin for as long as nobody has moved the origin.+ // A command route finishing under Settings moves it, and the pop would undo+ // that: back to the url the command was already spent on, which mounts it+ // again and puts its window over whatever the user opened Settings to reach.+ it('returns to a rewritten origin instead of the entry it was read from', async () => {+ const user = userEvent.setup();+ window.history.replaceState({ idx: 0 }, '');+ render(+ <MemoryRouter initialEntries={[{ pathname: '/chat/ses_1', state: { handoff: 'pending' } }]}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ // The browser pushed an entry for Settings; the origin still points at 0.+ window.history.replaceState({ idx: 1 }, '');++ // The command ran while retired and handed the canvas back to the surface,+ // so the retained route is already gone before the user leaves Settings.+ await waitFor(() => expect(screen.queryByTestId('chat-location')).toBeNull());+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(screen.getByText('workbench')).toBeTruthy();+ expect(screen.queryByTestId('chat-location')).toBeNull();+ });++ // The same rule with nothing but state rewritten. The pop would land on the+ // right url carrying the wrong payload, which is the same staleness wearing a+ // smaller hat — and it is what a browser, unlike a memory router, would+ // actually have done to the assertion two tests up.+ it('returns to a state-only rewrite of the origin as well', async () => {+ const user = userEvent.setup();+ window.history.replaceState({ idx: 0 }, '');+ render(+ <MemoryRouter initialEntries={[{ pathname: '/chat/ses_1', state: { maintenance: 'pending' } }]}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ window.history.replaceState({ idx: 1 }, '');+ await waitFor(() => expect(screen.getByTestId('chat-maintenance').textContent).toBe('done'));++ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');+ expect(screen.getByTestId('chat-maintenance').textContent).toBe('done');+ });+it('keeps a remounted retained modal editor focused for continued Unicode input', async () => {const user = userEvent.setup();render(@@ -424,6 +519,29 @@ describe('SettingsOverlayRouteSurface', () => {expect(document.activeElement).not.toBe(screen.getByRole('textbox', { name: inputName }));});+ // The exception to the rule above, and the only one. A retained window that+ // refocuses itself does not get to outrank the control that opened Settings —+ // unless that window is why Settings is closing. The window chords read their+ // target from DOM focus, so taking focus back here would leave the window the+ // user just asked for on screen and deaf to ⌘W, which would then fall through+ // to the browser's close-tab.+ it('leaves focus with the window that closed Settings', async () => {+ const user = userEvent.setup();+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('button', { name: 'open-app-window' }));+ await user.click(screen.getByRole('button', { name: 'open-settings-from-app-window' }));+ fireEvent.click(screen.getByRole('button', { name: 'leave-for-window' }));++ const input = await screen.findByRole('textbox', { name: 'retained app-window input' });+ await settleDeferredFocus();+ expect(document.activeElement).toBe(input);+ });+it('does not let a stale close callback focus the old origin after Settings reopens', async () => {const user = userEvent.setup();render(diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.tsxindex 425c3410f..dc9c93cde 100644--- a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx@@ -13,6 +13,7 @@ import {locationPath,SettingsOverlayOriginContext,settingsOverlayStateForOrigin,+ useSettingsFocusHandoff,useSettingsOverlayOrigin,} from '@/lib/settingsOverlay';import { useStandaloneSettingsMenu } from '@/lib/settingsMenuPlacement';@@ -56,6 +57,7 @@ export const SettingsOverlayRouteSurface = ({const locationRef = useRef(location);const settingsVisitRef = useRef(0);const focusFrameRef = useRef<number | null>(null);+ const focusHandoffRef = useSettingsFocusHandoff();useLayoutEffect(() => {settingsSurfaceOpenRef.current = settingsSurfaceOpen;locationRef.current = location;@@ -80,11 +82,26 @@ export const SettingsOverlayRouteSurface = ({// it in place, so the setup handoff reads it from here rather than guessing// from a component's lifecycle.useSetupHandoffDeparture(backgroundLocation.pathname);+ // A retained route replacing itself while Settings is open — a command route+ // like /apps/show/:id opening its window and handing back to the canvas —+ // moves the origin this surface returns to. The rewrite has to reach the+ // recorded history index as well as the recorded location, because that index+ // names the entry the origin was READ from and that entry still holds what+ // was there before. Left in place it outranks the rewrite: the exit prefers+ // its history pop, lands on the old entry, and re-runs the command the user+ // has already moved on from. Dropped, the exit replaces forward onto where+ // the origin now is, which is the only thing the rewrite ever claimed.+ //+ // Unconditional, including a rewrite that only carries new state. An origin+ // that has been rewritten is not that entry any more in either case, and one+ // rule for both is what makes this surface's answer the same one a browser+ // with a real history stack gives.const replaceBackground = useCallback<Navigator['replace']>((to, state) => {if (!origin) return;const path = resolvePath(to, origin.location.pathname);const nextOrigin = {...origin,+ historyIndex: null,location: {...origin.location,...path,@@ -186,6 +203,15 @@ export const SettingsOverlayRouteSurface = ({}}onCloseAutoFocus={(event) => {event.preventDefault();+ // This close IS a focus handoff: the shell left Settings because+ // a window came forward, and that window has already claimed DOM+ // focus. Returning it to the control that opened Settings would+ // take the window chords away from the window the user just+ // asked for. One-shot, so it is cleared as it is spent.+ if (focusHandoffRef?.current) {+ focusHandoffRef.current = false;+ return;+ }const visit = settingsVisitRef.current;const expectedOrigin = origin;const target = returnFocusRef.current;diff --git a/ui/src/context/UnsavedChangesProvider.test.tsx b/ui/src/context/UnsavedChangesProvider.test.tsxnew file mode 100644index 000000000..8c4941f1b--- /dev/null+++ b/ui/src/context/UnsavedChangesProvider.test.tsx@@ -0,0 +1,136 @@+/* @vitest-environment jsdom */++import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import {+ Navigate,+ Route,+ RouterProvider,+ createMemoryRouter,+ createRoutesFromElements,+ useLocation,+ useNavigate,+} from 'react-router-dom';++import { SettingsOverlayRouteSurface } from '../components/settings/SettingsOverlayRouteSurface';+import {+ closeSettingsOverlay,+ settingsOverlayOpenState,+ useSettingsOverlayOrigin,+} from '../lib/settingsOverlay';+import { UnsavedChangesProvider } from './UnsavedChangesProvider';+import { useUnsavedChanges } from './useUnsavedChanges';++const DIRTY_MESSAGE = 'Discard unsaved changes?';++const DirtyEditorRoute = () => {+ const navigate = useNavigate();+ useUnsavedChanges(DIRTY_MESSAGE);+ return (+ <main>+ <div data-testid="editor">editor</div>+ <button type="button" onClick={() => navigate('/chat/ses_1')}>leave-editor</button>+ </main>+ );+};++const OpenSettings = () => {+ const location = useLocation();+ const navigate = useNavigate();+ return (+ <button+ type="button"+ onClick={() => navigate('/settings/general', { state: settingsOverlayOpenState(location) })}+ >+ open-settings+ </button>+ );+};++// Stands in for AppShell's `onWindowForeground` exit: the same+// `closeSettingsOverlay` call, made from shell chrome rather than from a+// control inside the surface.+const WindowForegroundExit = () => {+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayOrigin(location);+ if (!origin) return null;+ return (+ <button type="button" onClick={() => closeSettingsOverlay(navigate, origin)}>+ leave-for-window+ </button>+ );+};++const Root = () => (+ <UnsavedChangesProvider>+ <OpenSettings />+ <WindowForegroundExit />+ <SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}>+ <Route path="/apps/editor" element={<DirtyEditorRoute />} />+ <Route path="/chat/:sessionId" element={<div data-testid="chat">chat</div>} />+ <Route path="/settings/general" element={<div data-testid="settings">settings</div>} />+ </SettingsOverlayRouteSurface>+ </UnsavedChangesProvider>+);++const renderApp = () => render(+ <RouterProvider+ router={createMemoryRouter(+ createRoutesFromElements(<Route path="*" element={<Root />} />),+ { initialEntries: ['/apps/editor'] },+ )}+ />,+);++let confirmSpy: ReturnType<typeof vi.fn>;++beforeEach(() => {+ confirmSpy = vi.fn(() => false);+ vi.stubGlobal('confirm', confirmSpy);+ window.localStorage.clear();+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }));+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe('UnsavedChangesProvider and the Settings overlay', () => {+ it('leaves the overlay without a discard prompt while the dirty route is retained', () => {+ renderApp();+ fireEvent.click(screen.getByText('open-settings'));+ expect(screen.getByTestId('settings')).toBeTruthy();+ // The dirty route did not unmount — it is retained behind the surface, with+ // its draft intact. That is what makes the exit below lossless.+ expect(screen.getByTestId('editor')).toBeTruthy();++ fireEvent.click(screen.getByText('leave-for-window'));++ // Closing the overlay returns to the route it was opened over, so there is+ // nothing to discard and nothing to confirm. An exit that cannot be refused+ // is also an exit its caller cannot half-apply: whatever brought the user+ // out of Settings — a window coming forward, the toggle, Escape — completes+ // whole. Should a future change re-arm the registration behind the surface,+ // this fails rather than silently reintroducing that split.+ expect(confirmSpy).not.toHaveBeenCalled();+ expect(screen.queryByTestId('settings')).toBeNull();+ expect(screen.getByTestId('editor')).toBeTruthy();+ });++ it('still prompts when the navigation really does leave the dirty route', () => {+ renderApp();++ fireEvent.click(screen.getByText('leave-editor'));++ expect(confirmSpy).toHaveBeenCalledWith(DIRTY_MESSAGE);+ // Cancelled, so the editor keeps the route it never left.+ expect(screen.queryByTestId('chat')).toBeNull();+ expect(screen.getByTestId('editor')).toBeTruthy();+ });+});diff --git a/ui/src/context/WindowManagerContext.ts b/ui/src/context/WindowManagerContext.tsindex ddfa8110c..5654e64c6 100644--- a/ui/src/context/WindowManagerContext.ts+++ b/ui/src/context/WindowManagerContext.ts@@ -1,6 +1,7 @@-import { createContext, useContext, useEffect } from 'react';+import { createContext, useCallback, useContext, useEffect, useMemo } from 'react';import type { AppId } from '../apps/registry';+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';import { useLatestRef } from '@/lib/useLatestRef';// One open app window. Bounds are in CSS px relative to the window LAYER (the@@ -37,6 +38,13 @@ export interface WindowManagerValue {windows: WindowInstance[];/** The app window that owns foreground focus, or null while the canvas owns it. */focusedId: string | null;+ /**+ * Tell the shell a window is coming to the front so it can clear whatever hides the+ * window layer (Settings does). `useWindowManager` calls this for you from `openApp`,+ * `focus` and `restore` when the caller is entitled to it; there is no reason to call+ * it directly, and the methods below deliberately do not.+ */+ announceForeground: () => void;openApp: (appId: AppId, opts?: OpenAppOptions) => string;close: (id: string) => void;focus: (id: string) => void;@@ -85,12 +93,59 @@ export interface WindowManagerValue {export const WindowManagerContext = createContext<WindowManagerValue | null>(null);-export function useWindowManager(): WindowManagerValue {+/**+ * The window manager, with the foreground announcement already wired in.+ *+ * Bringing a window forward has to clear whatever hides the window layer, but only when+ * the caller still speaks for what the user is looking at. A route retained behind the+ * Settings overlay is still mounted and still running: an `await` it started before the+ * overlay opened — `ShowPageLaunchControl` preparing a page, `ChatPage` reading a file's+ * metadata — resumes after it, and its `openApp` would otherwise throw Settings away on+ * behalf of a user who has moved on. So the provider's methods announce nothing and this+ * hook announces for them, which puts the decision where the answer lives: one gate the+ * launcher, the Dock, a deep link and every future caller inherit without knowing the+ * rule exists.+ *+ * The check is read when the method is CALLED, not when the closure was made, because+ * that is the moment being judged — the suspended continuation above was created while+ * its surface was still live, and only the call is late.+ */+function useWindowManagerContext(): WindowManagerValue {const ctx = useContext(WindowManagerContext);if (!ctx) throw new Error('useWindowManager must be used within a WindowManagerProvider');return ctx;}+export function useWindowManager(): WindowManagerValue {+ const ctx = useWindowManagerContext();+ const surfaceActiveRef = useLatestRef(useRouteSurfaceActive());+ const announceIfLive = useCallback(() => {+ if (surfaceActiveRef.current) ctx.announceForeground();+ }, [ctx, surfaceActiveRef]);+ return useMemo(() => {+ const { openApp, focus, restore, toggleMaximize } = ctx;+ return {+ ...ctx,+ openApp: (appId: AppId, opts?: OpenAppOptions) => {+ announceIfLive();+ return openApp(appId, opts);+ },+ focus: (id: string) => {+ announceIfLive();+ focus(id);+ },+ restore: (id: string) => {+ announceIfLive();+ restore(id);+ },+ toggleMaximize: (id: string) => {+ announceIfLive();+ toggleMaximize(id);+ },+ };+ }, [ctx, announceIfLive]);+}+// A window body calls this to veto its own close while there's unsaved work: pass// the owning window id and a confirm message (or null when clean). No-ops for a// non-windowed (full-page) mount, where windowId is undefined.diff --git a/ui/src/context/WindowManagerProvider.test.tsx b/ui/src/context/WindowManagerProvider.test.tsxindex 3d5fadacb..5e21a99b5 100644--- a/ui/src/context/WindowManagerProvider.test.tsx+++ b/ui/src/context/WindowManagerProvider.test.tsx@@ -2,8 +2,9 @@import { act, render } from '@testing-library/react';import { useEffect } from 'react';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';+import { RouteSurfaceActiveContext } from '../lib/routeSurfaceActivity';import { useWindowManager, type WindowManagerValue } from './WindowManagerContext';import { WindowManagerProvider } from './WindowManagerProvider';@@ -73,3 +74,176 @@ describe('WindowManagerProvider focus ownership', () => {expect(manager!.focusedId).toBe(firstId);});});++// The shell can have the whole window layer hidden — Settings does — so a window+// brought forward would arrive invisible. Rather than teach every caller to ask+// what is covering the layer, the manager announces that a window is coming+// forward and the shell clears the way. Announcing it late would be the same bug+// with extra steps, so it goes first, before the state that raises the window.+describe('WindowManagerProvider foreground announcements', () => {+ const renderManager = (onWindowForeground: () => void) => {+ let manager: WindowManagerValue | null = null;+ const Probe = () => {+ const value = useWindowManager();+ useEffect(() => {+ manager = value;+ }, [value]);+ return null;+ };++ render(+ <WindowManagerProvider onWindowForeground={onWindowForeground}>+ <Probe />+ </WindowManagerProvider>,+ );+ return () => manager!;+ };++ it('announces every way a window reaches the top', () => {+ const onForeground = vi.fn();+ const manager = renderManager(onForeground);++ let first = '';+ let second = '';+ act(() => {+ first = manager().openApp('files');+ second = manager().openApp('files');+ });+ expect(onForeground).toHaveBeenCalledTimes(2);++ act(() => manager().focus(first));+ expect(onForeground).toHaveBeenCalledTimes(3);++ // Restoring and maximizing are ways to the top like any other — both raise+ // the window — and must not be left out.+ act(() => manager().minimize(second));+ act(() => manager().restore(second));+ expect(onForeground).toHaveBeenCalledTimes(4);++ act(() => manager().toggleMaximize(first));+ expect(onForeground).toHaveBeenCalledTimes(5);+ });++ it('leaves the ways down alone', () => {+ const onForeground = vi.fn();+ const manager = renderManager(onForeground);++ let id = '';+ act(() => {+ id = manager().openApp('files');+ });+ onForeground.mockClear();++ // Minimize and close do re-focus whatever was underneath, but nothing new+ // comes forward from behind the shell's own surfaces, so there is nothing+ // to clear out of the way.+ act(() => manager().focusCanvas());+ act(() => manager().minimize(id));+ act(() => manager().close(id));+ expect(onForeground).not.toHaveBeenCalled();+ });++ it('works without a listener at all', () => {+ let manager: WindowManagerValue | null = null;+ const Probe = () => {+ const value = useWindowManager();+ useEffect(() => {+ manager = value;+ }, [value]);+ return null;+ };+ render(+ <WindowManagerProvider>+ <Probe />+ </WindowManagerProvider>,+ );++ let id = '';+ act(() => {+ id = manager!.openApp('files');+ });+ expect(manager!.focusedId).toBe(id);+ });+});++// Clearing the way is the one thing a window manager does on someone else's+// behalf, so it is the one thing that depends on who is asking. A route retained+// behind the Settings overlay is still mounted and still running; if it reaches+// the manager anyway it must get its window without taking the overlay down with+// it. The gate lives in `useWindowManager` so no caller has to know it exists.+describe('useWindowManager foreground ownership', () => {+ const renderManager = (onWindowForeground: () => void) => {+ let manager: WindowManagerValue | null = null;+ const Probe = () => {+ const value = useWindowManager();+ useEffect(() => {+ manager = value;+ }, [value]);+ return null;+ };+ const view = render(+ <RouteSurfaceActiveContext.Provider value>+ <WindowManagerProvider onWindowForeground={onWindowForeground}>+ <Probe />+ </WindowManagerProvider>+ </RouteSurfaceActiveContext.Provider>,+ );+ return {+ manager: () => manager!,+ setSurfaceActive: (active: boolean) => view.rerender(+ <RouteSurfaceActiveContext.Provider value={active}>+ <WindowManagerProvider onWindowForeground={onWindowForeground}>+ <Probe />+ </WindowManagerProvider>+ </RouteSurfaceActiveContext.Provider>,+ ),+ };+ };++ it('stops announcing once the caller is no longer the live surface', () => {+ const onForeground = vi.fn();+ const { manager, setSurfaceActive } = renderManager(onForeground);++ act(() => void manager().openApp('files'));+ expect(onForeground).toHaveBeenCalledTimes(1);++ act(() => setSurfaceActive(false));+ onForeground.mockClear();++ let id = '';+ act(() => {+ id = manager().openApp('files');+ });+ act(() => manager().focus(id));+ act(() => manager().minimize(id));+ act(() => manager().restore(id));++ // Only the announcement is withheld. The window still opened and still came+ // to the top — it is simply waiting behind whatever the user is looking at,+ // which is exactly where an obsolete caller's window belongs.+ expect(onForeground).not.toHaveBeenCalled();+ expect(manager().windows).toHaveLength(2);+ expect(manager().focusedId).toBe(id);+ });++ it('judges the call, not the closure it was made in', () => {+ const onForeground = vi.fn();+ const { manager, setSurfaceActive } = renderManager(onForeground);++ // What an awaited launch holds: `ShowPageLaunchControl` reads `openApp` off+ // the manager, awaits `prepare()`, and calls it afterwards. The user opening+ // Settings mid-await retires the surface without touching this reference.+ const suspendedLaunch = manager().openApp;++ act(() => setSurfaceActive(false));+ act(() => void suspendedLaunch('files'));+ expect(onForeground).not.toHaveBeenCalled();++ // The same reference, once its surface is the live one again — so the test+ // above is about ownership at the moment of the call, not a stale closure+ // that stopped working.+ act(() => setSurfaceActive(true));+ act(() => void suspendedLaunch('files'));+ expect(onForeground).toHaveBeenCalledTimes(1);+ });+});diff --git a/ui/src/context/WindowManagerProvider.tsx b/ui/src/context/WindowManagerProvider.tsxindex da427fc4a..d8188f617 100644--- a/ui/src/context/WindowManagerProvider.tsx+++ b/ui/src/context/WindowManagerProvider.tsx@@ -40,11 +40,28 @@ function highestVisibleWindow(windows: readonly WindowInstance[]): WindowInstanc* save would clobber the real workbench layout with `[]` in every other tab. Windows* opened later inside that tab still work (WindowLayer stays mounted); they just live* and die with it. The flag is frozen by the shell at mount, so it never flips mid-life.+ *+ * `onWindowForeground`: the shell can hide the whole window layer (Settings does), in+ * which case a window brought forward would arrive invisible. Rather than teach every+ * caller — launcher, Dock, deep link, a window focusing itself on restore — to ask what+ * is covering it, the manager offers `announceForeground` and lets the shell clear the+ * way. The announcement is made for the caller by `useWindowManager`, not by the methods+ * here, because whether it is warranted depends on the caller and only the caller's own+ * context can answer it — see the hook.*/-export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standalone?: boolean }> = ({+export const WindowManagerProvider: React.FC<{+ children: React.ReactNode;+ standalone?: boolean;+ onWindowForeground?: () => void;+}> = ({children,standalone = false,+ onWindowForeground,}) => {+ // Through a ref: `focus` and `openApp` are part of the context value every window+ // consumes, so their identity must not change each time the shell recomputes its+ // exit route.+ const foregroundRef = useLatestRef(onWindowForeground);const idSeq = useRef(0);const zSeq = useRef(0);const openCount = useRef(0);@@ -164,6 +181,10 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standareturn !message || window.confirm(message);}, []);+ const announceForeground = useCallback(() => {+ foregroundRef.current?.();+ }, [foregroundRef]);+const focus = useCallback((id: string) => {setFocusedId(id);setWindows((prev) => {@@ -321,6 +342,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standa() => ({windows,focusedId,+ announceForeground,openApp,close,focus,@@ -338,7 +360,7 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode; standagestureActive,setGestureActive,}),- [windows, focusedId, openApp, close, focus, focusCanvas, minimize, restore, toggleMaximize, setBounds, setTitle, setParams, setCloseGuard, setStateProvider, markClosing, confirmClose, gestureActive],+ [windows, focusedId, announceForeground, openApp, close, focus, focusCanvas, minimize, restore, toggleMaximize, setBounds, setTitle, setParams, setCloseGuard, setStateProvider, markClosing, confirmClose, gestureActive],);return <WindowManagerContext.Provider value={value}>{children}</WindowManagerContext.Provider>;diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.tsindex 5d3c9d1cc..4cca66f12 100644--- a/ui/src/lib/settingsOverlay.ts+++ b/ui/src/lib/settingsOverlay.ts@@ -20,6 +20,24 @@ export const SettingsOverlayOriginContext = createContext<SettingsOverlayOriginexport const useSettingsOverlayContext = (): SettingsOverlayOrigin | null =>useContext(SettingsOverlayOriginContext);+/**+ * Closing Settings hands focus back to the control that opened it. One exit must+ * not: when Settings closes BECAUSE a window came forward, that window is the+ * new focus owner — the window chords (⌘W / ⌘M) resolve their target from DOM+ * focus, so returning focus to the sidebar toggle would leave the window on+ * screen and deaf, and ⌘W would fall through to the browser's close-tab.+ *+ * The surface owns the focus decision, only the shell knows the reason, and the+ * shell is the ancestor here — so the shell publishes a one-shot flag that the+ * surface reads and clears on its way out. A ref rather than state: nothing+ * renders differently for it, and it has to be readable from Radix's deferred+ * close callback, which runs after the render that closed the surface.+ */+export const SettingsFocusHandoffContext = createContext<{ current: boolean } | null>(null);++export const useSettingsFocusHandoff = (): { current: boolean } | null =>+ useContext(SettingsFocusHandoffContext);+export const isSettingsRoutePath = (pathname: string): boolean =>pathname === '/settings' || pathname.startsWith('/settings/');