Skip to content

armgit / avibe

Public Imported from GitHub
0

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

feat(ui): align standalone Settings shell (#2051)

Max66fc91dbef41
diff --git a/docs/plans/2026-09-19-sidebar-dock-layering.md b/docs/plans/2026-09-19-sidebar-dock-layering.md
index 48722f578..95ed6bfaa 100644
--- a/docs/plans/2026-09-19-sidebar-dock-layering.md
+++ b/docs/plans/2026-09-19-sidebar-dock-layering.md
@@ -3,13 +3,19 @@
## Contract
- Restore the desktop Settings entry to the previous 44px icon-only control,
- with a translated accessible name and tooltip in both open and closed states.
- Apps consumes the remaining row width, including after sidebar resizing.
-- The desktop Apps launcher and Dock paint above application windows and the
- route-sized Settings panel, regardless of which surface opened first.
-- Activating a Dock tile dismisses Settings through its existing outside-
- interaction behavior; newly opened, focused, or restored windows must receive
- pointer input rather than merely exist in the DOM.
+ with a translated accessible name and tooltip in English and Chinese before
+ Settings entry and after return. Apps consumes the remaining row width,
+ including after sidebar resizing.
+- The desktop Apps launcher and Dock paint above application windows while the
+ Workbench is foreground. Standalone Settings owns the full viewport; the
+ retained sidebar is hidden/inert and launcher/Dock presentation is withdrawn.
+- Return through the foreground Settings close control or browser history before
+ activating a Dock tile. Pinned Dock state survives the round trip; transient
+ hover can reopen after return. Newly opened, focused, or restored windows must
+ receive pointer input, and existing windows retain their identity/state.
+- This replaces the former route-panel/outside-interaction premise under the
+ September 20 integration ruling `99b63fc52`. Preserve the compact footer and
+ foreground z40 launcher; do not restore interaction with inactive surfaces.
- Version details escape the sidebar stacking context, paint as one opaque
surface above the launcher, and remain anchored to the version badge.
Desktop placement follows resizing and stays inside the viewport.
@@ -21,7 +27,11 @@
Use the existing hermetic Workbench browser harness to exercise real Settings,
Dock, and version components together. Assert hit targets at overlapping points,
-icon-only Settings width, Apps width, version opacity, and placement after resize.
+icon-only Settings width, Apps width before/after Settings at both sidebar sizes,
+full-viewport Settings isolation, retained pin/window identity, version opacity,
+and placement after resize. Keep all eight upstream cases, including both
+unchanged VersionBadge theme oracles, with traffic/page-error evidence on failure
+as well as completion.
Run the existing badge browser suite for desktop/mobile interaction, focused shell
unit tests, UI lint, and the production build. The focused sidebar floating-surface
suite also runs in the existing CI browser-interaction job.
diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.ts
index 4e62870a9..5b7964fd5 100644
--- a/ui/e2e/workbench-general/geometry.spec.ts
+++ b/ui/e2e/workbench-general/geometry.spec.ts
@@ -1,13 +1,12 @@
import { expect, test } from '@playwright/test';
-import { DESKTOP, NARROW, ORIGIN, WIDE, open, serveProduct } from './support';
+import { DESKTOP, NARROW, ORIGIN, WIDE, config, open, serveProduct } from './support';
/**
* The packet's geometry claims, measured in a browser rather than inferred from
- * class names. Two of them are fixed numbers (sidebar 248, settings rail 196)
- * and the rest are the opposite claim — that the content beside them is fluid,
- * which a capture at the 1200 staging width alone cannot distinguish from a
- * column that happens to be 856 or 924 wide.
+ * 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.
*/
const SIDEBAR = 'aside.fixed';
@@ -27,12 +26,101 @@ const ULTRA = { width: 1920, height: 1000 };
// because of where it is anchored, not because 844 happens to leave room.
const NARROW_SHORT = { width: 390, height: 667 };
+const MODEL_HUB_AGENT = {
+ backend: 'codex',
+ cli_present: true,
+ mode: 'hub',
+ menu_kind: 'fixed',
+ selected_model_id: 'fixture-model-中文',
+ selected_model_explicit: true,
+ sources: { order: [], eligibility: [] },
+ routes: {},
+ supply_status: 'interrupted',
+ model_supply: [{ model_id: 'fixture-model-中文', route_origin: null, chain_length: 0, has_runnable_hop: false }],
+ builtin_models: ['fixture-model-中文'],
+ named_agents: [],
+ menu: null,
+};
+
+const MODEL_HUB_RUNTIME = {
+ contract_version: 10,
+ enabled: true,
+ manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'f'.repeat(40), assets: [] },
+ status: { installed_version: 'fixture', verified: true, listening: { host: '127.0.0.1', port: 43123 }, health: 'ok' },
+};
+
+const MODEL_HUB_SESSION = {
+ remote: false,
+ authenticated: true,
+ authorization_state: 'current',
+ instance_kind: 'personal',
+ instance_role: 'owner',
+ capabilities: {
+ is_instance_owner: true, can_read_instance: true, can_chat: true,
+ can_manage_projects: true, can_manage_agents: true, can_manage_instance: true,
+ can_manage_access_members: true, can_use_agents: true, can_use_skills: true,
+ can_use_vault_secrets: true, can_use_show_pages: true, can_use_terminal_files: true,
+ can_use_terminal: true, can_use_files: true, can_use_system: true,
+ },
+};
+
+/**
+ * Render the actual Model Hub route with a ready capability, runtime, and
+ * Gateway backend. Every response remains test-owned; mutations fall through
+ * to serveProduct's strict request guard.
+ */
+async function serveModelHub(page: import('@playwright/test').Page) {
+ const denied = await serveProduct(page);
+ const unexpectedModelReads: string[] = [];
+ const getOnly = async (route: import('@playwright/test').Route, body: unknown) => {
+ if (route.request().method() !== 'GET' && route.request().method() !== 'HEAD') {
+ denied.push(`${route.request().method()} ${new URL(route.request().url()).pathname}`);
+ return route.abort();
+ }
+ return route.fulfill({ json: body });
+ };
+ await page.route('**/api/session', (route) => getOnly(route, MODEL_HUB_SESSION));
+ await page.route('**/api/config', (route) => getOnly(route, { ...config('en'), capabilities: { model_hub: { enabled: true } } }));
+ await page.route('**/api/models/**', (route) => {
+ const path = new URL(route.request().url()).pathname;
+ const query = new URL(route.request().url()).search;
+ if (path === '/api/models/sources' && !query) return getOnly(route, { sources: [] });
+ if (path === '/api/models/runtime/status' && !query) return getOnly(route, MODEL_HUB_RUNTIME);
+ if (path === '/api/models/agents' && !query) return getOnly(route, { agents: [MODEL_HUB_AGENT] });
+ if (path === '/api/models/agents' && query === '?refresh_cli_presence=1') {
+ return getOnly(route, { agents: [MODEL_HUB_AGENT] });
+ }
+ if (path === '/api/models/agents/codex/chains' && !query) return getOnly(route, { chains: [] });
+ unexpectedModelReads.push(`${route.request().method()} ${path}${query}`);
+ return route.abort();
+ });
+ return { denied, unexpectedModelReads };
+}
+
const widthOf = async (page: import('@playwright/test').Page, selector: string) => {
const box = await page.locator(selector).first().boundingBox();
expect(box, `${selector} should be laid out`).not.toBeNull();
return box!.width;
};
+const frameGeometry = async (page: import('@playwright/test').Page) => page.locator(SETTINGS_CONTENT).evaluate((node) => {
+ const style = getComputedStyle(node);
+ const box = node.getBoundingClientRect();
+ return {
+ x: box.x,
+ width: box.width,
+ contentWidth: node.clientWidth - Number.parseFloat(style.paddingLeft) - Number.parseFloat(style.paddingRight),
+ paddingLeft: Number.parseFloat(style.paddingLeft),
+ paddingRight: Number.parseFloat(style.paddingRight),
+ };
+});
+
+const settleSettingsFrame = async (page: import('@playwright/test').Page) => {
+ await page.locator(SETTINGS_CONTENT).evaluate(async (node) => {
+ await Promise.all(node.getAnimations().map((animation) => animation.finished));
+ });
+};
+
/**
* What the user's finger would actually land on. `toBeVisible()` cannot answer
* this: an element covered by a fixed bar is still visible, still has a box, and
@@ -105,58 +193,92 @@ test.describe('workbench home geometry', () => {
];
for (const { lang, placeholder, send, lastRow } of PHONE_COMPOSER) {
- test(`keeps the composer's controls off the tab bar on a phone (${lang})`, async ({ page }) => {
+ test(`keeps the composer's controls off the tab bar on a phone (${lang})`, async ({ page }, info) => {
+ const pageErrors: string[] = [];
+ const unknown: string[] = [];
+ const reads: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
const denied = await serveProduct(page, lang);
- await page.setViewportSize(NARROW);
- await open(page, '/', { lang });
-
- const composer = page.getByPlaceholder(placeholder);
- const sendButton = page.getByRole('button', { name: send });
- const nav = page.locator(MOBILE_NAV);
- await expect(composer).toBeVisible();
- await expect(nav).toBeVisible();
-
- // The premise: this page really does overflow, so clearing the bar is the
- // anchoring and not a lucky fit. If this ever stops being true the rest of
- // the test would pass for the wrong reason.
- const overflow = await page.locator(SHELL_SCROLL).evaluate((node) => ({
- top: node.scrollTop,
- hidden: node.scrollHeight - node.clientHeight,
- }));
- expect(overflow.top).toBe(0);
- expect(overflow.hidden).toBeGreaterThan(0);
-
- // Nothing in the block may reach under the bar — asserted on the block's
- // last row, which is below the action row.
- const navTop = (await nav.boundingBox())!.y;
- expect(await bottomOf(page.getByRole('link', { name: lastRow }))).toBeLessThanOrEqual(navTop);
- // …and the primary control specifically: what a tap would hit, at rest.
- expect(await topmostOver(page, sendButton)).toBe(send);
-
- // Typing is when it matters, and a focused textarea is also when the page
- // could scroll under the user. It must not have to.
- await composer.click();
- await composer.fill('给手机上的我写一句话');
- await expect(composer).toBeFocused();
- expect(await page.locator(SHELL_SCROLL).evaluate((node) => node.scrollTop)).toBe(0);
- expect(await topmostOver(page, sendButton)).toBe(send);
- // Playwright's own actionability check, which is the product's tap path.
- await sendButton.click({ trial: true });
-
- // A shorter phone has less room above, never less clearance below.
- await page.setViewportSize(NARROW_SHORT);
- await page.waitForFunction(() => window.innerHeight === 667);
- expect(await topmostOver(page, sendButton)).toBe(send);
- expect(await bottomOf(page.getByRole('link', { name: lastRow })))
- .toBeLessThanOrEqual((await nav.boundingBox())!.y);
-
+ // Only the inherited, explicitly answered Home reads may fall through.
+ // Record failures too; a generic empty API response is not guard proof.
+ const inheritedReads = new Set([
+ '/api/session', '/api/config', '/api/csrf-token', '/api/projects',
+ '/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents',
+ '/api/inbox', '/api/version', '/api/memory/settings', '/api/events',
+ ]);
+ await page.route('**/api/**', (route) => {
+ const request = route.request();
+ const url = new URL(request.url());
+ if (request.method() !== 'GET' || url.origin !== ORIGIN) {
+ denied.push(`${request.method()} ${request.url()}`);
+ return route.abort();
+ }
+ reads.push(url.pathname);
+ if (url.pathname === '/api/asr/status') return route.fulfill({ json: { available: false } });
+ if (url.pathname === '/api/dock') return route.fulfill({ json: {
+ dock: { order: ['files', 'terminal', 'editor', 'library'], pins: [] },
+ } });
+ if (inheritedReads.has(url.pathname)) return route.fallback();
+ unknown.push(`${request.method()} ${request.url()}`);
+ return route.abort();
+ });
+ try {
+ await page.setViewportSize(NARROW);
+ await open(page, '/', { lang });
+
+ const composer = page.getByPlaceholder(placeholder);
+ const sendButton = page.getByRole('button', { name: send });
+ const nav = page.locator(MOBILE_NAV);
+ await expect(composer).toBeVisible();
+ await expect(nav).toBeVisible();
+
+ // The normal-height phone may fit without scrolling. Clearance and
+ // actual hit targets are the invariant, not overflow at this height.
+ expect(await page.locator(SHELL_SCROLL).evaluate((node) => node.scrollTop)).toBe(0);
+ const navTop = (await nav.boundingBox())!.y;
+ expect(await bottomOf(page.getByRole('link', { name: lastRow }))).toBeLessThanOrEqual(navTop);
+ expect(await topmostOver(page, sendButton)).toBe(send);
+
+ const draft = '给手机上的我写一句话';
+ await composer.click();
+ await composer.fill(draft);
+ await expect(composer).toBeFocused();
+ await expect(composer).toHaveValue(draft);
+ expect(await page.locator(SHELL_SCROLL).evaluate((node) => node.scrollTop)).toBe(0);
+ expect(await topmostOver(page, sendButton)).toBe(send);
+ await sendButton.click({ trial: true });
+
+ // Continue the typed draft on the existing short phone. Here overflow
+ // must be real: the controls clear the bar even in a crowded layout.
+ await page.setViewportSize(NARROW_SHORT);
+ await page.waitForFunction(() => window.innerHeight === 667);
+ const overflow = await page.locator(SHELL_SCROLL).evaluate((node) => ({
+ top: node.scrollTop,
+ hidden: node.scrollHeight - node.clientHeight,
+ }));
+ expect(overflow.top).toBe(0);
+ expect(overflow.hidden).toBeGreaterThan(0);
+ await expect(composer).toHaveValue(draft);
+ await expect(composer).toBeFocused();
+ expect(await topmostOver(page, sendButton)).toBe(send);
+ expect(await bottomOf(page.getByRole('link', { name: lastRow })))
+ .toBeLessThanOrEqual((await nav.boundingBox())!.y);
+ await sendButton.click({ trial: true });
+ } finally {
+ const evidence = info.outputPath('phone-traffic-and-page-errors.json');
+ const { writeFile } = await import('node:fs/promises');
+ await writeFile(evidence, JSON.stringify({ denied, unknown, pageErrors, reads }, null, 2));
+ await info.attach('phone-traffic-and-page-errors', { path: evidence, contentType: 'application/json' });
+ }
expect(denied).toEqual([]);
+ expect(unknown).toEqual([]);
+ expect(pageErrors).toEqual([]);
});
}
});
test.describe('settings overlay geometry', () => {
- test('opens at the sidebar edge and gives the home back its draft on close', async ({ page }) => {
+ test('opens as a standalone zero-offset surface and gives the home back its draft on close', async ({ page }) => {
const denied = await serveProduct(page);
await page.setViewportSize(DESKTOP);
@@ -176,18 +298,15 @@ test.describe('settings overlay geometry', () => {
const overlay = page.locator('[data-settings-overlay="true"]');
await expect(overlay).toBeVisible();
- // The overlay covers the work area and stops exactly at the sidebar's own
- // edge — measured off the sidebar rather than compared to a literal, so the
- // two cannot drift apart the way a second hard-coded width did.
- const sidebar = await page.locator(SIDEBAR).boundingBox();
+ // Standalone Settings owns the viewport at every sidebar width. The origin
+ // remains mounted behind the surface for draft/session/selection retention,
+ // but no Workbench offset is allowed to leak into the foreground.
const surface = await overlay.boundingBox();
- expect(sidebar!.x).toBe(0);
- expect(surface!.x).toBe(sidebar!.x + sidebar!.width);
- expect(surface!.width).toBe(DESKTOP.width - sidebar!.width);
- // Covering the sidebar would be the same defect from the other side.
- await expect(page.locator(SIDEBAR)).toBeVisible();
+ expect(surface!.x).toBe(0);
+ expect(surface!.width).toBe(DESKTOP.width);
+ await expect(page.locator(SIDEBAR)).toBeHidden();
- await page.locator('aside [data-settings-toggle="true"]').click();
+ await page.getByRole('button', { name: 'Close Settings' }).click();
await expect(page).toHaveURL(`${ORIGIN}/`);
await expect(overlay).toHaveCount(0);
await expect(page.getByPlaceholder('Describe a task or ask a question...')).toHaveValue(draft);
@@ -216,7 +335,7 @@ test.describe('page background family', () => {
});
test.describe('general settings geometry', () => {
- test('keeps the rail at 196 and keeps the page fluid past the shared cap', async ({ page }) => {
+ test('keeps the rail at 196 and the common content at 880px', async ({ page }) => {
const denied = await serveProduct(page);
await page.setViewportSize(DESKTOP);
@@ -226,20 +345,15 @@ test.describe('general settings geometry', () => {
expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);
const cardAtStaging = await widthOf(page, APPEARANCE_CARD);
- // Wide enough to pass the shared 1180 reading column on purpose. Measuring
- // below it could not tell a fluid page from a capped one, which is the whole
- // question: the source draws General as content that fills whatever the rail
- // leaves, so a cap of any size — inherited or not — contradicts it.
+ // The desktop Settings frame is 944px wide with 32px horizontal padding,
+ // leaving an 880px common content column.
await page.setViewportSize(ULTRA);
await page.waitForFunction(() => window.innerWidth === 1920);
expect(await widthOf(page, SETTINGS_RAIL)).toBe(196);
const cardAtUltra = await widthOf(page, APPEARANCE_CARD);
- expect(cardAtUltra).toBeGreaterThan(1180);
- expect(cardAtUltra - cardAtStaging).toBe(ULTRA.width - DESKTOP.width);
-
- // eslint-disable-next-line no-console
- console.log(`general card: ${cardAtStaging} @1200, ${cardAtUltra} @1920`);
+ expect(cardAtStaging).toBe(880);
+ expect(cardAtUltra).toBe(880);
expect(denied).toEqual([]);
});
@@ -263,23 +377,15 @@ test.describe('general settings geometry', () => {
expect(await headingOf('/settings/shortcuts')).toEqual({ size: '28px', weight: '700' });
});
- // Assessed rather than inherited: the shell sidebar stays on a direct Settings
- // route, where the source board draws a standalone window with none. The board
- // is a native window (the same reason Web drops its titlebar and traffic
- // lights); on Web, Settings is a route in the one shell, and the overlay path
- // deliberately keeps the sidebar visible so the origin work stays in view.
- // Hiding it only on the direct route would give one URL two chromes and jump
- // the layout on close. What the source actually fixes is the frame beside the
- // rail, and that is reproduced exactly at a real window width.
- test('reaches the source content frame at a real desktop width', async ({ page }) => {
+ test('uses the same standalone frame for a direct URL at a real desktop width', async ({ page }) => {
await serveProduct(page);
await page.setViewportSize({ width: 1448, height: 900 });
await open(page, '/settings/general');
await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
- // dqfES — the source's Settings content frame.
- expect(await widthOf(page, SETTINGS_PAGE)).toBe(1004);
- expect(await widthOf(page, SIDEBAR)).toBe(248);
+ // dqfES — the source's standalone Settings content frame.
+ expect(await widthOf(page, SETTINGS_CONTENT)).toBe(944);
+ await expect(page.locator(SIDEBAR)).toBeHidden();
});
// A rail label is the only thing that says where a row goes, and English has
@@ -313,17 +419,101 @@ test.describe('general settings geometry', () => {
expect(new Set(rows).size).toBe(1);
});
- test('leaves the shared reading column on every other settings page', async ({ page }) => {
+ test('keeps the common 880px content width on every ordinary settings page', async ({ page }) => {
await serveProduct(page);
await page.setViewportSize(ULTRA);
await open(page, '/settings/shortcuts');
await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
- // General opts out by route, so the pages that wanted the reading column
- // still have it at a width where the difference is visible.
- expect(await widthOf(page, SETTINGS_CONTENT)).toBe(1180);
+ expect(await widthOf(page, SETTINGS_CONTENT)).toBe(944);
});
+ for (const viewport of [
+ { width: 1366, height: 768 },
+ { width: 1920, height: 1000 },
+ { width: 390, height: 844 },
+ ]) {
+ test(`keeps Model Hub fluid and ordinary pages constrained at ${viewport.width}px`, async ({ page }) => {
+ const { denied, unexpectedModelReads } = await serveModelHub(page);
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ await page.setViewportSize(viewport);
+
+ const modelHub = async (path: string) => {
+ await open(page, path);
+ const shell = page.locator('.model-hub-shell');
+ await expect(shell).toBeVisible();
+ await settleSettingsFrame(page);
+ await expect(page.locator('[data-agent-backend="codex"]')).toBeVisible();
+ const pane = page.locator(SETTINGS_PAGE);
+ const frame = page.locator(SETTINGS_CONTENT);
+ const [paneBox, frameBox] = await Promise.all([pane.boundingBox(), frame.boundingBox()]);
+ expect(paneBox).not.toBeNull();
+ expect(frameBox).not.toBeNull();
+ expect(frameBox!.width).toBe(paneBox!.width);
+ expect(frameBox!.x).toBe(paneBox!.x);
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(viewport.width);
+ };
+
+ await modelHub('/settings/models');
+ await modelHub('/settings/models/');
+
+ // A retained origin reaches the same real Model Hub route through the
+ // supported desktop Settings toggle or the supported mobile Apps drawer,
+ // proving the fluid exception survives overlay entry at every width.
+ await open(page, '/');
+ if (viewport.width >= 768) {
+ await page.locator('aside [data-settings-toggle="true"]').click();
+ } else {
+ await page.getByRole('button', { name: 'Apps', exact: true }).click();
+ await page.getByRole('dialog', { name: 'Apps' }).getByRole('link', { name: 'Settings', exact: true }).click();
+ await page.getByRole('link', { name: 'All settings', exact: true }).click();
+ }
+ await expect(page.locator('[data-settings-overlay="true"]')).toBeVisible();
+ await page.getByRole('navigation', { name: 'Settings sections' })
+ .getByRole('link', { name: 'Models', exact: true }).click();
+ await expect(page).toHaveURL(/\/settings\/models$/);
+ await expect(page.locator('.model-hub-shell')).toBeVisible();
+ await settleSettingsFrame(page);
+ const retainedPane = await page.locator(SETTINGS_PAGE).boundingBox();
+ const retainedFrame = await page.locator(SETTINGS_CONTENT).boundingBox();
+ expect(retainedFrame?.width).toBe(retainedPane?.width);
+ expect(retainedFrame?.x).toBe(retainedPane?.x);
+
+ // General and Shortcuts remain ordinary pages with the shared 944px
+ // outer frame and 880px content column whenever the viewport provides
+ // enough room. Measure the actual bounds because auto margins resolve to
+ // pixels in computed style.
+ for (const path of ['/settings/general', '/settings/shortcuts']) {
+ 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.paddingRight).toBe(frame.paddingLeft);
+ expect(frame.contentWidth).toBe(viewport.width >= 944 + 196 ? 880 : viewport.width - 32);
+ const pane = await page.locator(SETTINGS_PAGE).boundingBox();
+ expect(pane).not.toBeNull();
+ if (viewport.width >= 944 + 196) {
+ expect(Math.abs(frame.x - pane!.x - (pane!.width - frame.width) / 2)).toBeLessThanOrEqual(0.5);
+ await expect(page.locator(SETTINGS_RAIL)).toBeVisible();
+ } else {
+ expect(frame.x).toBeGreaterThanOrEqual(pane!.x);
+ expect(frame.x + frame.width).toBeLessThanOrEqual(pane!.x + pane!.width);
+ }
+ if (path.endsWith('general')) {
+ await expect(page.getByRole('radiogroup', { name: 'Appearance' })).toBeVisible();
+ } else {
+ await expect(page.getByRole('button', { name: /Change Chat voice input shortcut/ })).toBeVisible();
+ }
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(viewport.width);
+ }
+ expect(denied).toEqual([]);
+ expect(unexpectedModelReads).toEqual([]);
+ expect(pageErrors).toEqual([]);
+ });
+ }
+
test('draws the preference card, the selector and the selected choice to spec', async ({ page }) => {
await serveProduct(page);
await page.setViewportSize(DESKTOP);
diff --git a/ui/e2e/workbench-general/sidebar-floating.spec.ts b/ui/e2e/workbench-general/sidebar-floating.spec.ts
index a56275dcf..8e6086828 100644
--- a/ui/e2e/workbench-general/sidebar-floating.spec.ts
+++ b/ui/e2e/workbench-general/sidebar-floating.spec.ts
@@ -1,6 +1,8 @@
-import { expect, test, type Locator } from '@playwright/test';
+import { writeFile } from 'node:fs/promises';
-import { open, serveProduct } from './support';
+import { expect, test, type Locator, type Page } from '@playwright/test';
+
+import { open, ORIGIN, serveProduct as serveWorkbench, type Lang } from './support';
const VIEWPORT = { width: 1665, height: 1329 };
const SETTINGS = 'aside [data-settings-toggle="true"]';
@@ -8,6 +10,73 @@ const LAUNCHER = '[data-show-page-dock-drop-target] > button';
const DOCK = '[data-show-page-dock-drop-target] [role="menu"]';
const OVERLAY = '[data-settings-overlay="true"]';
+// Keep failure evidence as well as passing guards: these cases must never
+// accept the support harness's generic unknown-API fallback as an empty result.
+const audits = new WeakMap<Page, { denied: string[]; unknown: string[]; pageErrors: string[]; reads: string[] }>();
+async function serveProduct(page: Page, lang: Lang = 'en') {
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ const denied = await serveWorkbench(page, lang);
+ const audit = { denied, unknown: [] as string[], pageErrors, reads: [] as string[] };
+ audits.set(page, audit);
+ const inheritedReads = new Set([
+ '/api/session', '/api/config', '/api/csrf-token', '/api/projects',
+ '/api/workbench/projects-bootstrap', '/api/sessions', '/api/agents',
+ '/api/inbox', '/api/version', '/api/memory/settings', '/api/events',
+ ]);
+ await page.route('**/api/**', (route) => {
+ const request = route.request();
+ const path = new URL(request.url()).pathname;
+ if (request.method() !== 'GET' || new URL(request.url()).origin !== ORIGIN) {
+ denied.push(`${request.method()} ${request.url()}`);
+ return route.abort();
+ }
+ audit.reads.push(path);
+ if (path === '/api/asr/status') return route.fulfill({ json: { available: false } });
+ if (path === '/api/show-pages') return route.fulfill({ json: { pages: [] } });
+ if (path === '/api/dock') return route.fulfill({ json: {
+ dock: { order: ['files', 'terminal', 'editor', 'library'], pins: [] },
+ } });
+ if (inheritedReads.has(path)) return route.fallback();
+ audit.unknown.push(`${request.method()} ${request.url()}`);
+ return route.abort();
+ });
+ return denied;
+}
+
+test.afterEach(async ({ page }, info) => {
+ const audit = audits.get(page);
+ expect(audit).toBeDefined();
+ const evidence = info.outputPath('traffic-and-page-errors.json');
+ await writeFile(evidence, JSON.stringify(audit, null, 2));
+ await info.attach('traffic-and-page-errors', { path: evidence, contentType: 'application/json' });
+ expect(audit!.denied).toEqual([]);
+ expect(audit!.unknown).toEqual([]);
+ expect(audit!.pageErrors).toEqual([]);
+});
+
+async function expectStandaloneSettings(page: Page) {
+ const overlay = page.locator(OVERLAY);
+ await expect(overlay).toBeVisible();
+ await expect.poll(async () => {
+ const box = (await overlay.boundingBox())!;
+ return { x: box.x, y: box.y, width: box.width, height: box.height };
+ }).toEqual({ x: 0, y: 0, ...page.viewportSize()! });
+ const sidebar = page.locator('aside.fixed');
+ await expect(sidebar).toBeHidden();
+ await expect(sidebar).toHaveAttribute('inert');
+ await expect(sidebar).toHaveAttribute('aria-hidden', 'true');
+ await expect(page.locator(LAUNCHER)).toHaveCount(0);
+ await expect(page.locator(DOCK)).toHaveCount(0);
+}
+
+async function returnToWorkbench(page: Page) {
+ await page.locator(OVERLAY).getByRole('button', { name: 'Close Settings', exact: true }).click();
+ await expect(page.locator(OVERLAY)).toHaveCount(0);
+ await expect(page.locator('aside.fixed')).toBeVisible();
+ await expect(page.locator('aside.fixed')).not.toHaveAttribute('inert');
+}
+
// Visibility alone passes for covered controls. Ask which surface receives an
// actual hit at the element's center, across independent portal roots.
const receivesPointer = (locator: Locator) => locator.evaluate((element) => {
@@ -25,45 +94,51 @@ for (const lang of ['en', 'zh'] as const) {
const settings = page.locator(SETTINGS);
const apps = page.locator(LAUNCHER);
const label = lang === 'en' ? 'Settings' : '设置';
- await expect(settings).toHaveAccessibleName(label);
- await expect(settings).toHaveText('');
- await expect(settings).toHaveAttribute('title', label);
-
- const widths = async () => ({
- settings: (await settings.boundingBox())!.width,
- apps: (await apps.boundingBox())!.width,
- });
- await expect.poll(widths).toEqual({ settings: 44, apps: 163 });
- await settings.click();
- await expect(page.locator(OVERLAY)).toBeVisible();
- await expect(settings).toHaveAccessibleName(label);
- await expect(settings).toHaveText('');
- await expect.poll(widths).toEqual({ settings: 44, apps: 163 });
-
- await page.locator('aside [role="separator"]').focus();
- await page.keyboard.press('End');
- await expect.poll(widths).toEqual({ settings: 44, apps: 411 });
- await settings.click();
- await expect(page.locator(OVERLAY)).toHaveCount(0);
+ const expectControls = async (appsWidth: number) => {
+ await expect(settings).toHaveAccessibleName(label);
+ await expect(settings).toHaveText('');
+ await expect(settings).toHaveAttribute('title', label);
+ await expect.poll(async () => ({
+ settings: (await settings.boundingBox())!.width,
+ apps: (await apps.boundingBox())!.width,
+ })).toEqual({ settings: 44, apps: appsWidth });
+ };
+ for (const width of [163, 411]) {
+ if (width === 411) {
+ await page.locator('aside [role="separator"]').focus();
+ await page.keyboard.press('End');
+ }
+ await expectControls(width);
+ await settings.click();
+ await expectStandaloneSettings(page);
+ // Actual history return works in both languages without operating the
+ // retained, hidden sidebar controls.
+ await page.goBack();
+ await expect(page.locator(OVERLAY)).toHaveCount(0);
+ await expectControls(width);
+ await expect.poll(() => receivesPointer(settings)).toBe(true);
+ }
expect(denied).toEqual([]);
});
}
for (const order of ['dock-first', 'settings-first'] as const) {
- test(`Dock remains usable above Settings (${order})`, async ({ page }) => {
+ test(`Dock returns to the foreground after standalone Settings (${order})`, async ({ page }) => {
const denied = await serveProduct(page);
await page.setViewportSize(VIEWPORT);
await open(page, '/');
if (order === 'dock-first') await page.locator(LAUNCHER).click();
await page.locator(SETTINGS).click();
- await expect(page.locator(OVERLAY)).toBeVisible();
- if (order === 'settings-first') await page.locator(LAUNCHER).hover();
+ await expectStandaloneSettings(page);
+ await returnToWorkbench(page);
+ await expect(page.locator(LAUNCHER)).toHaveAttribute('aria-pressed', String(order === 'dock-first'));
+ if (order === 'settings-first') {
+ await expect(page.locator(DOCK)).toHaveCount(0);
+ await page.locator(LAUNCHER).hover();
+ }
const library = page.locator(DOCK).getByRole('button', { name: 'App Library', exact: true });
await expect(library).toBeVisible();
- const libraryBox = (await library.boundingBox())!;
- const overlayBox = (await page.locator(OVERLAY).boundingBox())!;
- expect(libraryBox.x + libraryBox.width / 2).toBeGreaterThan(overlayBox.x);
await expect.poll(() => receivesPointer(library)).toBe(true);
await page.screenshot({
path: `e2e/.artifacts/workbench-general/shots/${order}.png`, scale: 'css', animations: 'disabled',
@@ -79,7 +154,7 @@ for (const order of ['dock-first', 'settings-first'] as const) {
}
for (const state of ['running', 'minimized'] as const) {
- test(`Dock activation dismisses Settings and reaches an existing ${state} window`, async ({ page }) => {
+ test(`Dock activation after Settings return reaches the same ${state} window`, async ({ page }) => {
const denied = await serveProduct(page);
await page.setViewportSize(VIEWPORT);
await open(page, '/');
@@ -89,19 +164,23 @@ for (const state of ['running', 'minimized'] as const) {
const appWindow = page.locator('[data-window-id][aria-label="App Library"]');
await expect(appWindow).toBeVisible();
const windowId = await appWindow.getAttribute('data-window-id');
+ const originalWindow = await appWindow.elementHandle();
if (state === 'minimized') {
await appWindow.getByRole('button', { name: 'Minimize', exact: true }).click();
await expect(appWindow).toHaveAttribute('inert');
}
await page.locator(SETTINGS).click();
await expect(page.locator(OVERLAY)).toBeVisible();
- // The existing Settings outside-interaction dismissal must handle focus
- // and restore just as it handles opening a fresh window.
+ await expectStandaloneSettings(page);
+ await returnToWorkbench(page);
+ await expect(page.locator(LAUNCHER)).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(() => receivesPointer(library)).toBe(true);
await library.click();
await expect(page.locator(OVERLAY)).toHaveCount(0);
await expect(appWindow).toHaveCount(1);
await expect(appWindow).toHaveAttribute('data-window-id', windowId!);
await expect(appWindow).not.toHaveAttribute('inert');
+ expect(await appWindow.evaluate((node, original) => node === original, originalWindow)).toBe(true);
await expect.poll(() => receivesPointer(appWindow)).toBe(true);
await appWindow.getByRole('button', { name: 'Close', exact: true }).click();
await expect(appWindow).toHaveCount(0);
diff --git a/ui/e2e/workbench-general/sidebar-resize.spec.ts b/ui/e2e/workbench-general/sidebar-resize.spec.ts
index fc5933a15..65a6d2a68 100644
--- a/ui/e2e/workbench-general/sidebar-resize.spec.ts
+++ b/ui/e2e/workbench-general/sidebar-resize.spec.ts
@@ -5,9 +5,8 @@ import { DESKTOP, NARROW, open, serveProduct } from './support';
/**
* Sidebar resizing (#2044), measured in a real browser: the gesture uses actual
- * pointer capture, and the claim is about boxes — the sidebar, the content
- * offset and the Settings overlay's left edge all following ONE width — which no
- * class name or jsdom pointer event can answer.
+ * pointer capture, and the claim is about boxes — the sidebar and Workbench
+ * content offset follow ONE width, while standalone Settings keeps zero offset.
*/
const SIDEBAR = 'aside.fixed';
@@ -217,32 +216,31 @@ test.describe('sidebar resizing', () => {
expect(denied).toEqual([]);
});
- test('keeps the Settings overlay open and on the edge it is being dragged to', async ({ page }) => {
+ test('keeps standalone Settings zero-offset while preserving the Workbench width', async ({ page }) => {
const denied = await serveProduct(page);
await page.setViewportSize(DESKTOP);
await open(page, '/');
+ await dragEdge(page, 160);
+ const before = await layout(page);
+ expect(before).toEqual({ sidebar: 408, contentLeft: 408 });
await page.locator(SETTINGS_TOGGLE).click();
const overlay = page.locator(OVERLAY);
await expect(overlay).toBeVisible();
-
- // The overlay is portaled outside the shell, so this is the case the shared
- // document-level width exists for. Grabbing the edge must not dismiss it.
- await dragEdge(page, 900);
- await expect(overlay).toBeVisible();
-
- const surface = await boxOf(overlay, 'settings overlay');
- expect(await layout(page)).toEqual({ sidebar: MAX, contentLeft: MAX });
- expect(surface.x).toBe(MAX);
- expect(surface.width).toBe(DESKTOP.width - MAX);
- await expect(page.locator(SIDEBAR)).toBeVisible();
-
- // And back: the overlay follows the sidebar in, not just out.
- await dragEdge(page, -900);
- const narrowed = await boxOf(overlay, 'settings overlay');
- expect(narrowed.x).toBe(MIN);
- expect(narrowed.width).toBe(DESKTOP.width - MIN);
-
+ expect(await boxOf(overlay, 'settings')).toMatchObject({ x: 0, width: DESKTOP.width });
+ await expect(page.locator(SIDEBAR)).toBeHidden();
+ await expect(page.getByRole('separator')).toHaveCount(0);
+ await expect(page.locator(SIDEBAR)).toHaveAttribute('inert', '');
+
+ await overlay.getByRole('button', { name: 'Close Settings' }).click();
+ await expect(overlay).toHaveCount(0);
+ expect(await layout(page)).toEqual(before);
+ await expect(page.locator(SETTINGS_TOGGLE)).toBeFocused();
+ await dragEdge(page, 20);
+ expect(await layout(page)).toEqual({ sidebar: 428, contentLeft: 428 });
+ await page.locator(SEPARATOR).focus();
+ await page.keyboard.press('ArrowLeft');
+ expect(await layout(page)).toEqual({ sidebar: 412, contentLeft: 412 });
expect(denied).toEqual([]);
});
diff --git a/ui/e2e/workbench-general/standalone-settings.spec.ts b/ui/e2e/workbench-general/standalone-settings.spec.ts
new file mode 100644
index 000000000..c1e8323c9
--- /dev/null
+++ b/ui/e2e/workbench-general/standalone-settings.spec.ts
@@ -0,0 +1,531 @@
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import { open, serveProduct } from './support';
+
+// Lane C: actual App/router/Composer/AgentRoutePicker with API responses confined
+// to this Playwright context. No component, navigation, or persistence mocks.
+const origin = 'http://127.0.0.1:5213';
+const draft = '你好,整理项目「星河」的交付计划 🌱';
+const projects = [
+ { id: 'proj-recent', display_name: '近期项目', folder_path: '/fixture/近期项目' },
+ { id: 'proj-picked', display_name: '星河项目', folder_path: '/fixture/星河项目' },
+].map((project) => ({
+ ...project, scope_id: 'fixture', archived: false,
+ created_at: '2026-09-01T00:00:00Z', last_active_at: null,
+ capabilities: { can_chat: true, has_folder: true },
+}));
+const caps = {
+ is_instance_owner: false, can_read_instance: true, can_chat: true,
+ can_manage_projects: false, can_manage_agents: false, can_manage_instance: false,
+ can_manage_access_members: false, can_use_agents: true, can_use_skills: true,
+ can_use_vault_secrets: true, can_use_show_pages: true, can_use_terminal_files: true,
+ can_use_terminal: true, can_use_files: true, can_use_system: false,
+};
+const editor = { remote: true, authenticated: true, authorization_state: 'current',
+ instance_kind: 'organization', instance_role: 'editor', capabilities: caps };
+const textarea = (page: Page) => page.getByPlaceholder('Describe a task or ask a question...');
+const settings = (page: Page) => page.locator('[data-settings-overlay="true"]');
+const rail = (page: Page) => page.getByRole('navigation', { name: 'Settings sections' });
+const toggle = (page: Page) => page.locator('aside [data-settings-toggle="true"]');
+const fixtureImages = {
+ med_1: '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="48"><rect width="64" height="48" fill="#10b981"/></svg>',
+ med_2: '<svg xmlns="http://www.w3.org/2000/svg" width="48" height="64"><rect width="48" height="64" fill="#2563eb"/></svg>',
+};
+
+const settledScale = (style: string | null): number => {
+ const match = style?.match(/scale\(([-+]?\d*\.?\d+)\)/);
+ return match ? Number(match[1]) : 1;
+};
+
+async function memberFixture(page: Page) {
+ const denied = await serveProduct(page);
+ await page.route('**/api/session', (route) => route.fulfill({ json: editor }));
+ await page.route('**/api/projects**', (route) => route.fulfill({ json: { projects, sessions: {} } }));
+ await page.route('**/api/workbench/projects-bootstrap**', (route) => route.fulfill({ json: { projects, sessions: {} } }));
+ return denied;
+}
+
+async function frame(page: Page) {
+ const nav = await rail(page).boundingBox();
+ const pane = page.locator('nav[aria-label="Settings sections"] + section');
+ return { rail: nav, content: await pane.locator(':scope > div').boundingBox() };
+}
+
+for (const width of [1200, 1366, 1920]) {
+ test(`C-SETTINGS-01: direct and retained Settings have identical frame at ${width}`, async ({ page }) => {
+ const denied = await serveProduct(page);
+ await page.setViewportSize({ width, height: 768 });
+ await open(page, '/');
+ await page.getByRole('separator').focus();
+ await page.keyboard.press('End');
+ await textarea(page).fill(draft);
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ expect(await settings(page).boundingBox()).toMatchObject({ x: 0, y: 0, width, height: 768 });
+ await expect(page.getByRole('button', { name: 'Apps', exact: true })).toHaveCount(0);
+ await expect(page.getByRole('separator')).toHaveCount(0);
+ 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);
+ 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.
+ for (let i = 0; i < 24; i += 1) {
+ await page.keyboard.press('Tab');
+ expect(await settings(page).evaluate((node) => node.contains(document.activeElement))).toBe(true);
+ }
+ await page.keyboard.press('Control+k');
+ 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();
+ expect(denied).toEqual([]);
+ });
+}
+
+test('C-SETTINGS-02: preserves picked Agent/workspace, Unicode draft and history through internal navigation', async ({ page }) => {
+ const denied = await memberFixture(page);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ await textarea(page).fill(draft);
+ const workspace = page.getByRole('button', { name: /^Workspace: / });
+ await workspace.click();
+ await page.locator('[data-radix-popper-content-wrapper]').getByRole('button', { name: '星河项目', exact: true }).click();
+ const agent = page.getByRole('button', { name: /codex|claude/ }).first();
+ await agent.click();
+ await page.locator('[data-radix-popper-content-wrapper]').getByRole('button', { name: 'claude', exact: true }).click();
+ await expect(agent).toContainText('claude');
+ await textarea(page).evaluate((node) => { node.setAttribute('data-origin-instance', 'preserved'); });
+ const index = await page.evaluate(() => window.history.state.idx);
+ await toggle(page).click();
+ await expect(rail(page).getByRole('link', { name: 'Backends', exact: true })).toHaveCount(0);
+ await rail(page).getByRole('link', { name: 'Shortcuts', exact: true }).click();
+ await expect(page).toHaveURL(/\/settings\/shortcuts$/);
+ await page.goBack();
+ await expect(page).toHaveURL(/\/settings\/general$/);
+ await settings(page).getByRole('button', { name: 'Back to Avibe' }).click();
+ await expect(page).toHaveURL(`${origin}/`);
+ await expect(textarea(page)).toHaveValue(draft);
+ await expect(textarea(page)).toHaveAttribute('data-origin-instance', 'preserved');
+ await expect(workspace).toHaveAccessibleName('Workspace: /fixture/星河项目');
+ await expect(agent).toContainText('claude');
+ await expect(toggle(page)).toBeFocused();
+ expect(await page.evaluate(() => window.history.state.idx)).toBe(index);
+ // Browser Back also restores the same retained instance.
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ await page.goBack();
+ await expect(textarea(page)).toHaveValue(draft);
+ await expect(toggle(page)).toBeFocused();
+ expect(denied).toEqual([]);
+});
+
+for (const width of [320, 375, 390]) {
+ test(`C-SETTINGS-03: direct alias and section navigation fit phone ${width}`, async ({ page }) => {
+ const denied = await serveProduct(page);
+ 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.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 page.getByRole('link', { name: 'All settings' }).click();
+ await page.getByRole('link', { name: 'Back to Workbench' }).click();
+ await expect(textarea(page)).toBeVisible();
+ expect(denied).toEqual([]);
+ });
+}
+
+test('C-SETTINGS-05: retains sidebar editor draft while withdrawing modal effects', async ({ page }) => {
+ const denied = await serveProduct(page);
+ await page.route('**/api/projects/proj-1/agents-md', (route) => route.fulfill({ json: {
+ content: '# 项目约定', source: 'agents', symlinked: true, claude_is_regular_file: false,
+ } }));
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ // Keep a real Settings history entry so browser Forward can suspend an open
+ // modal without bypassing its pointer/focus trap or inventing a router mock.
+ await toggle(page).click();
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await page.getByRole('button', { name: 'Project actions' }).click();
+ await page.getByRole('button', { name: 'Edit AGENTS.md', exact: true }).click();
+ const editorDraft = page.getByPlaceholder("Write this project's AGENTS.md in Markdown…");
+ await editorDraft.fill('# 未保存的约定\n保留星河项目 🌱');
+ await expect(page.locator('body')).toHaveCSS('pointer-events', 'none');
+ await page.goForward();
+ await expect(settings(page)).toBeVisible();
+ await expect(editorDraft).toHaveCount(0);
+ await expect(page.locator('body')).not.toHaveCSS('pointer-events', 'none');
+ await expect(page.locator('body')).not.toHaveAttribute('data-scroll-locked');
+ await rail(page).getByRole('link', { name: 'Shortcuts', exact: true }).click();
+ await expect(page).toHaveURL(/\/settings\/shortcuts$/);
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(editorDraft).toBeVisible();
+ await expect(editorDraft).toHaveValue('# 未保存的约定\n保留星河项目 🌱');
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(editorDraft).toHaveCount(0);
+ await expect(page.locator('body')).not.toHaveCSS('pointer-events', 'none');
+ expect(denied).toEqual([]);
+});
+
+test('C-SETTINGS-05: sidebar rename suspension keeps typed input without an implicit save', async ({ page }) => {
+ const denied = await serveProduct(page);
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ await toggle(page).click();
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await page.getByRole('button', { name: 'Project actions' }).click();
+ await page.getByRole('button', { name: 'Rename', exact: true }).click();
+ const rename = page.locator('aside.fixed input');
+ await rename.fill('星河项目未保存');
+ await page.goForward();
+ await expect(settings(page)).toBeVisible();
+ await expect(rename).toBeHidden();
+ await expect(rename).toHaveValue('星河项目未保存');
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(rename).toBeVisible();
+ await expect(rename).toHaveValue('星河项目未保存');
+ expect(denied).toEqual([]);
+});
+
+test('C-SETTINGS-06: retained image viewer releases keys while Settings is foreground', async ({ page }) => {
+ const denied = await memberFixture(page);
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ const sessionId = 'ses-c-image-viewer';
+ const session = {
+ id: sessionId,
+ scope_id: 'fixture',
+ project_id: 'proj-picked',
+ title: '图片会话',
+ agent_id: null,
+ agent_name: 'claude',
+ agent_backend: 'claude',
+ agent_variant: null,
+ model: null,
+ reasoning_effort: null,
+ status: 'active',
+ pinned: false,
+ agent_status: 'idle',
+ workdir: '/fixture/星河项目',
+ native_session_id: null,
+ created_at: '2026-09-01T00:00:00Z',
+ updated_at: '2026-09-01T00:00:00Z',
+ last_active_at: null,
+ metadata: {},
+ };
+ const message = {
+ id: 'msg-image',
+ scope_id: 'fixture',
+ session_id: sessionId,
+ platform: 'avibe',
+ author: 'user',
+ type: 'user',
+ source: 'user',
+ author_id: null,
+ author_name: null,
+ native_message_id: null,
+ parent_native_message_id: null,
+ projection: null,
+ text: '附件',
+ content: { attachments: [
+ { url: '/api/media/med_1', name: '星河.svg', mime: 'image/svg+xml', width: 64, height: 48 },
+ { url: '/api/media/med_2', name: '山海.svg', mime: 'image/svg+xml', width: 48, height: 64 },
+ ] },
+ metadata: {},
+ created_at: '2026-09-01T00:00:00Z',
+ updated_at: '2026-09-01T00:00:00Z',
+ delivered_at: '2026-09-01T00:00:01Z',
+ read_at: null,
+ };
+ await page.route(`**/api/sessions/${sessionId}/bootstrap`, (route) => route.fulfill({ json: {
+ session,
+ capabilities: { can_chat: true },
+ agents: [{ id: 'agent-claude', name: 'claude', display_name: 'claude', description: null,
+ backend: 'claude', model: null, reasoning_effort: null, enabled: true, archived: false,
+ archived_at: null, source: 'builtin', updated_at: '2026-09-01T00:00:00Z' }],
+ default_agent_name: 'claude',
+ config: { ui: {} },
+ messages: [message],
+ next_after_id: null,
+ next_before_id: null,
+ queued: [],
+ draft: { text: '', updated_at: null },
+ turn_state: { in_flight: false, foreground: 'idle', native_turn_started: false,
+ pending_input_count: 0, background_activities: [], pending_activity_output_count: 0,
+ connection: 'connected' },
+ } }));
+ await page.route(`**/api/sessions/${sessionId}`, (route) => route.fulfill({ json: session }));
+ await page.route(`**/api/sessions/${sessionId}/activity**`, (route) => route.fulfill({ json: { groups: [] } }));
+ await page.route(`**/api/sessions/${sessionId}/turn-state`, (route) => route.fulfill({ json: {
+ in_flight: false, foreground: 'idle', native_turn_started: false, pending_input_count: 0,
+ background_activities: [], pending_activity_output_count: 0, connection: 'connected',
+ } }));
+ await page.route(`**/api/sessions/${sessionId}/queue`, (route) => route.fulfill({ json: [] }));
+ await page.route('**/api/media/med_*', (route) => {
+ const body = route.request().url().endsWith('/med_2') ? fixtureImages.med_2 : fixtureImages.med_1;
+ return route.fulfill({ status: 200, contentType: 'image/svg+xml', body });
+ });
+
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, `/chat/${sessionId}`);
+ // Seed a real forward Settings entry before opening the viewer. Browser
+ // Forward then suspends the retained Chat route without inventing a control
+ // inside the hidden lightbox.
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(settings(page)).toBeHidden();
+ const inlineImage = page.locator('span img[src="/api/media/med_1"]');
+ await expect(inlineImage).toBeVisible();
+ await expect(inlineImage).toHaveJSProperty('naturalWidth', 64);
+ await expect(inlineImage).toHaveJSProperty('naturalHeight', 48);
+ // Click the image body away from its hover download affordance so this is the
+ // same pointer path a user takes on the media itself.
+ await inlineImage.click({ position: { x: 8, y: 8 } });
+ const viewer = page.locator('[role="dialog"][aria-modal="true"]');
+ await expect(viewer).toBeVisible();
+ const viewerImage = viewer.locator('img');
+ const originalSrc = await viewerImage.getAttribute('src');
+ const originalImageHandle = await viewerImage.elementHandle();
+ expect(originalImageHandle).not.toBeNull();
+ await expect(viewerImage).toHaveJSProperty('naturalWidth', 64);
+ await expect(viewerImage).toHaveJSProperty('naturalHeight', 48);
+ const originalTransform = viewer.locator('.react-transform-component');
+ await viewer.getByRole('button', { name: 'Zoom in' }).click();
+ let previousScale = 1;
+ let stableSamples = 0;
+ await expect.poll(async () => {
+ const scale = settledScale(await originalTransform.getAttribute('style'));
+ stableSamples = scale > 1 && Math.abs(scale - previousScale) < 0.01 ? stableSamples + 1 : 0;
+ previousScale = scale;
+ return stableSamples >= 3;
+ }).toBe(true);
+ const originalScale = previousScale;
+ expect(Number.isFinite(originalScale)).toBe(true);
+
+ await page.evaluate(() => {
+ (window as Window & { __viewerLowerEscape?: number }).__viewerLowerEscape = 0;
+ window.addEventListener('keydown', (event) => {
+ if (event.key === 'Escape') {
+ const state = window as Window & { __viewerLowerEscape?: number };
+ state.__viewerLowerEscape = (state.__viewerLowerEscape ?? 0) + 1;
+ }
+ });
+ });
+
+ // Forward returns to a real retained Settings entry. The viewer stays mounted
+ // in the hidden origin, but its capture listener must withdraw so Settings
+ // receives Escape and the viewer's image/zoom state remains intact.
+ await page.goForward();
+ await expect(settings(page)).toBeVisible();
+ await expect(viewer).toBeHidden();
+ await page.keyboard.press('ArrowRight');
+ await expect(viewerImage).toHaveAttribute('src', originalSrc!);
+ await page.keyboard.press('Escape');
+ await expect(settings(page)).toBeHidden();
+ await expect(viewer).toBeVisible();
+ await expect(viewerImage).toHaveAttribute('src', originalSrc!);
+ await expect(viewerImage).toHaveJSProperty('naturalWidth', 64);
+ await expect.poll(async () => settledScale(await originalTransform.getAttribute('style'))).toBeCloseTo(originalScale);
+ expect(await page.evaluate((node) => node === document.querySelector('[role="dialog"][aria-modal="true"] img'), originalImageHandle)).toBe(true);
+
+ await page.evaluate(() => {
+ (window as Window & { __viewerLowerEscape?: number }).__viewerLowerEscape = 0;
+ });
+ await page.keyboard.press('ArrowRight');
+ await expect(viewerImage).toHaveAttribute('src', '/api/media/med_2');
+ await expect(viewerImage).toHaveJSProperty('naturalWidth', 48);
+ await page.keyboard.press('Escape');
+ await expect(viewer).toHaveCount(0);
+ expect(await page.evaluate(() => (window as Window & { __viewerLowerEscape?: number }).__viewerLowerEscape)).toBe(0);
+
+ // Repeat the history/suspension path from the other end of the gallery so an
+ // inactive ArrowLeft cannot wrap the retained viewer back to med_1.
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(settings(page)).toBeHidden();
+ await page.locator('span img[src="/api/media/med_2"]').click({ position: { x: 8, y: 8 } });
+ await expect(viewer).toBeVisible();
+ await expect(viewerImage).toHaveAttribute('src', '/api/media/med_2');
+ await page.goForward();
+ await expect(settings(page)).toBeVisible();
+ await expect(viewer).toBeHidden();
+ await page.keyboard.press('ArrowLeft');
+ await expect(viewerImage).toHaveAttribute('src', '/api/media/med_2');
+ await page.keyboard.press('Escape');
+ await expect(settings(page)).toBeHidden();
+ await expect(viewer).toBeVisible();
+ await expect(viewerImage).toHaveAttribute('src', '/api/media/med_2');
+ await page.keyboard.press('Escape');
+ await expect(viewer).toHaveCount(0);
+ expect(denied).toEqual([]);
+ expect(pageErrors).toEqual([]);
+});
+
+for (const width of [1366, 390]) {
+ test(`C-SETTINGS-07: retained search query/filter/selection, history and true close at ${width}`, async ({ page }) => {
+ const denied = await serveProduct(page);
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ const searches: string[] = [];
+ await page.route('**/api/show-pages', (route) => route.fulfill({ json: { pages: [] } }));
+ await page.route('**/api/search/messages?**', (route) => {
+ searches.push(route.request().url());
+ return route.fulfill({ json: { sessions: [{ session_id: 'search-session', title: '星河', project_name: '项目', archived: true,
+ matches: [1, 2].map((id) => ({ id: `search-${id}`, author: 'user', type: 'user', source: 'user', created_at: '2026-09-19T00:00:00Z',
+ snippet: { prefix: '', match: `星河结果${id}`, suffix: '' } })),
+ }] } });
+ });
+ // The palette's phone case is an explicit desktop-history resize continuation.
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ await toggle(page).click();
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(settings(page)).toBeHidden();
+ await page.setViewportSize({ width, height: 768 });
+ await page.keyboard.press('Control+k');
+ const palette = page.getByRole('dialog', { name: 'Search', exact: true });
+ const query = palette.getByRole('textbox');
+ await query.fill('星河 🌱');
+ await palette.getByRole('switch').click();
+ await expect(palette.locator('[aria-current="true"]')).toContainText('星河结果1');
+ await query.focus();
+ await page.keyboard.press('ArrowDown');
+ await expect(palette.locator('[aria-current="true"]')).toContainText('星河结果2');
+ for (let round = 0; round < 2; round += 1) {
+ await page.goForward();
+ await expect(settings(page)).toBeVisible();
+ await expect(palette).toHaveCount(0);
+ await expect(page.locator('body')).not.toHaveCSS('pointer-events', 'none');
+ await expect(page.locator('body')).not.toHaveAttribute('data-scroll-locked');
+ const count = searches.length;
+ await page.keyboard.press('Control+k');
+ await page.keyboard.press('ArrowDown');
+ await page.waitForTimeout(300);
+ expect(searches.length).toBe(count);
+ expect(await settings(page).evaluate((node) => node.contains(document.activeElement))).toBe(true);
+ await page.goBack();
+ await expect(query).toHaveValue('星河 🌱');
+ await expect(palette.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
+ await expect(palette.locator('[aria-current="true"]')).toContainText('星河结果2');
+ await page.waitForTimeout(300);
+ await expect(query).toBeFocused();
+ }
+ await page.keyboard.press('a');
+ await page.keyboard.insertText('续');
+ await expect(query).toHaveValue('星河 🌱a续');
+ await page.keyboard.press('Escape');
+ await expect(palette).toHaveCount(0);
+ await page.keyboard.press('Control+k');
+ await expect(query).toHaveValue('');
+ await expect(palette.getByRole('switch')).toHaveAttribute('aria-checked', 'false');
+ expect(denied).toEqual([]);
+ expect(pageErrors).toEqual([]);
+ });
+}
+
+test('C-SETTINGS-08: pinned Apps survives repeated Settings and measures its current placement', async ({ page }) => {
+ const denied = await serveProduct(page);
+ const pageErrors: string[] = [];
+ page.on('pageerror', (error) => pageErrors.push(error.message));
+ let inventoryReads = 0;
+ await page.route('**/api/show-pages', (route) => {
+ inventoryReads += 1;
+ return route.fulfill({ json: { pages: [] } });
+ });
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ const apps = page.getByRole('button', { name: 'Apps', exact: true });
+ await apps.click();
+ await expect(apps).toHaveAttribute('aria-pressed', 'true');
+ for (const width of [1920, 1366]) {
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ await expect(apps).toHaveCount(0);
+ await expect(page.getByRole('menu', { name: 'Apps', exact: true })).toHaveCount(0);
+ const count = inventoryReads;
+ await page.setViewportSize({ width, height: 768 });
+ await page.waitForTimeout(300);
+ expect(inventoryReads).toBe(count);
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(apps).toHaveAttribute('aria-pressed', 'true');
+ await expect(page.getByRole('menu', { name: 'Apps', exact: true })).toBeVisible();
+ const appBox = await apps.boundingBox();
+ const settingsBox = await toggle(page).boundingBox();
+ expect(Math.abs(appBox!.y - settingsBox!.y)).toBeLessThan(2);
+ expect(appBox!.x).toBeGreaterThanOrEqual(0);
+ }
+ await apps.click();
+ await expect(apps).toHaveAttribute('aria-pressed', 'false');
+ await expect(page.getByRole('menu', { name: 'Apps', exact: true })).toHaveCount(0);
+ await apps.click({ button: 'right' });
+ await expect(page.getByRole('menuitem', { name: 'Open App Library' })).toBeVisible();
+ expect(denied).toEqual([]);
+ expect(pageErrors).toEqual([]);
+});
+
+test('C-SETTINGS-09: a held sidebar create cannot navigate through foreground Settings; active create navigates once', 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: [] } }));
+ const session = { id: 'ses-sidebar-create', title: 'Created fixture', scope_id: 'scope-1', project_id: 'proj-1',
+ agent_name: 'codex', agent_backend: 'codex', status: 'active', pinned: false, agent_status: 'idle',
+ workdir: '/fixture/work', metadata: {}, created_at: '2026-09-19T00:00:00Z', updated_at: '2026-09-19T00:00:00Z' };
+ let release!: () => void;
+ const held = new Promise<void>((resolve) => { release = resolve; });
+ let creates = 0;
+ await page.route('**/api/sessions', async (route) => {
+ if (route.request().method() !== 'POST') return route.fallback();
+ expect(route.request().postDataJSON()).toEqual({ project_id: 'proj-1' });
+ creates += 1;
+ if (creates === 1) await held;
+ return route.fulfill({ json: session });
+ });
+ await page.route('**/api/sessions/ses-sidebar-create/bootstrap', (route) => route.fulfill({ json: {
+ session, capabilities: { can_chat: true }, agents: [], default_agent_name: 'codex', config: { ui: {} },
+ messages: [], queued: [], draft: { text: '', updated_at: null }, next_before_id: null, next_after_id: null,
+ turn_state: { in_flight: false, foreground: 'idle', native_turn_started: false, pending_input_count: 0,
+ background_activities: [], pending_activity_output_count: 0, connection: 'connected' },
+ } }));
+ await page.route('**/api/sessions/ses-sidebar-create', (route) => route.fulfill({ json: session }));
+ await page.route('**/api/sessions/ses-sidebar-create/queue', (route) => route.fulfill({ json: [] }));
+ await page.route('**/api/sessions/ses-sidebar-create/activity**', (route) => route.fulfill({ json: { groups: [] } }));
+ await page.setViewportSize({ width: 1366, height: 768 });
+ await open(page, '/');
+ const create = page.locator('aside button[aria-label="New session in this project"]');
+ await create.click();
+ await expect.poll(() => creates).toBe(1);
+ await toggle(page).click();
+ await expect(settings(page)).toBeVisible();
+ const index = await page.evaluate(() => history.state.idx);
+ release();
+ await expect(create).toBeEnabled();
+ await page.waitForTimeout(300);
+ await expect(page).toHaveURL(/\/settings\/general$/);
+ expect(await page.evaluate(() => history.state.idx)).toBe(index);
+ await settings(page).getByRole('button', { name: 'Close Settings' }).click();
+ await expect(page).toHaveURL(`${origin}/`);
+ await page.waitForTimeout(300);
+ await expect(page).toHaveURL(`${origin}/`);
+ const beforeCreate = await page.evaluate(() => history.state.idx);
+ await create.click();
+ await expect(page).toHaveURL(/\/chat\/ses-sidebar-create$/);
+ expect(creates).toBe(2);
+ expect(await page.evaluate(() => history.state.idx)).toBe(beforeCreate + 1);
+ expect(denied).toEqual([]);
+ expect(pageErrors).toEqual([]);
+});
diff --git a/ui/e2e/workbench-general/standalone-windows.spec.ts b/ui/e2e/workbench-general/standalone-windows.spec.ts
new file mode 100644
index 000000000..65d6de4ff
--- /dev/null
+++ b/ui/e2e/workbench-general/standalone-windows.spec.ts
@@ -0,0 +1,112 @@
+import { expect, test } from '@playwright/test';
+import { open, serveProduct } from './support';
+
+// Real AppShell -> Dock -> WindowLayer -> AppWindow -> ShowPageApp, with only
+// HTTP replies replaced. The frame is test-owned unsaved data, not a real file.
+const sid = 'ses-c-foreground';
+const title = '星河未保存页面';
+const draft = '保留这段未保存内容 🌱';
+const pagePayload = {
+ session_id: sid, title, visibility: 'private', active_url: `/show/${sid}/`,
+ url_available: true, offline: false, icon_version: null,
+};
+const frameHtml = `<!doctype html><html><head><meta charset="utf-8"></head><body>
+<label>Unsaved buffer<textarea id="buffer"></textarea></label>
+<script>
+window.instanceId = crypto.randomUUID();
+window.commands = [];
+let enabled = false;
+function report() {
+ parent.postMessage({ type: 'avibe:annotation:state', enabled, mode: 'smart', available: true }, location.origin);
+}
+addEventListener('message', (event) => {
+ if (event.origin !== location.origin) return;
+ const data = event.data;
+ if (data.type === 'avibe:annotation:query') report();
+ if (data.type === 'avibe:annotation:control') {
+ window.commands.push(data.action);
+ if (data.action === 'enable') enabled = true;
+ if (data.action === 'disable') enabled = false;
+ report();
+ }
+});
+report();
+</script></body></html>`;
+
+for (const chrome of ['Annotate', 'Share']) {
+ test(`C-SETTINGS-04: retains the real app frame and suspends ${chrome} portals and chords`, async ({ page }) => {
+ const denied = await serveProduct(page);
+ await page.route('**/api/dock', (route) => route.fulfill({ json: {
+ ok: true, dock: { order: [`show:${sid}`, 'library'], pins: [{
+ session_id: sid, title_snapshot: title, pinned_at: '2026-09-19T00:00:00Z',
+ }] },
+ } }));
+ await page.route('**/api/show-pages', (route) => route.fulfill({ json: { pages: [pagePayload] } }));
+ await page.route(`**/api/show-pages/${sid}`, (route) => route.fulfill({ json: pagePayload }));
+ await page.route(`**/api/show-pages/${sid}/access`, (route) => route.fulfill({ json: {
+ ok: true, mode: 'unmanaged', ownership_status: 'unmanaged', access_level: 'private',
+ can_use: true, can_manage: false, can_publish_public: false, group_ids: [],
+ } }));
+ await page.route(`**/api/sessions/${sid}`, (route) => route.fulfill({ json: {
+ id: sid, title, status: 'active', project_id: 'proj-1',
+ } }));
+ await page.route(`**/show/${sid}/**`, (route) => route.fulfill({ contentType: 'text/html', body: frameHtml }));
+ await page.setViewportSize({ width: 1366, height: 900 });
+ await open(page, '/');
+ const apps = page.getByRole('button', { name: 'Apps', exact: true });
+ await apps.click();
+ await page.getByRole('button', { name: title, exact: true }).click();
+ const app = page.locator('[data-window-id]').first();
+ await expect(app).toBeVisible();
+ const frame = page.frameLocator('iframe[title="Show Page"]');
+ await frame.getByRole('textbox', { name: 'Unsaved buffer' }).fill(draft);
+ const iframe = page.locator('iframe[title="Show Page"]');
+ const frameState = () => iframe.evaluate((node) => {
+ const win = (node as HTMLIFrameElement).contentWindow as Window & { instanceId: string; commands: string[] };
+ return { id: win.instanceId, commands: win.commands };
+ });
+ const original = await frameState();
+ await app.getByRole('button', { name: chrome, exact: true }).click();
+ const portal = page.locator('[data-window-owner-id]');
+ await expect(portal).toBeVisible();
+ const id = await app.getAttribute('data-window-id');
+ await page.locator('aside [data-settings-toggle]').click();
+ const settings = page.locator('[data-settings-overlay]');
+ await expect(settings).toBeVisible();
+ await expect(app).toBeHidden();
+ await expect(app).toHaveAttribute('inert', '');
+ await expect(portal).toHaveCount(0);
+ await expect(app).toHaveAttribute('aria-hidden', 'true');
+ await expect(apps).toHaveCount(0);
+ const before = await frameState();
+ // Programmatic frame delivery verifies the listener itself is suspended;
+ // real user input cannot reach this hidden/inert frame in the first place.
+ await iframe.evaluate((node) => {
+ const win = (node as HTMLIFrameElement).contentWindow!;
+ for (const code of ['KeyX', 'KeyW']) {
+ win.dispatchEvent(new KeyboardEvent('keydown', { code, altKey: true, bubbles: true, cancelable: true }));
+ }
+ });
+ for (const chord of ['Alt+2', 'Alt+w', 'Control+m', 'Control+w']) {
+ // dispatchEvent avoids invoking the browser's own tab-close reservation.
+ await settings.dispatchEvent('keydown', {
+ key: chord.slice(-1), code: chord.endsWith('2') ? 'Digit2' : `Key${chord.slice(-1).toUpperCase()}`,
+ altKey: chord.startsWith('Alt'), ctrlKey: chord.startsWith('Control'), bubbles: true,
+ });
+ }
+ expect(await frameState()).toEqual(before);
+ expect(before.id).toBe(original.id);
+ await expect(page.locator('[data-window-id]')).toHaveCount(1);
+ const unloadGuard = await page.evaluate(() => !window.dispatchEvent(new Event('beforeunload', { cancelable: true })));
+ expect(unloadGuard).toBe(true);
+ await settings.getByRole('button', { name: 'Close Settings' }).click();
+ await expect(app).toBeVisible();
+ await expect(app).toHaveAttribute('data-window-id', id!);
+ await expect(frame.getByRole('textbox', { name: 'Unsaved buffer' })).toHaveValue(draft);
+ expect((await frameState()).id).toBe(original.id);
+ await expect(page.locator('aside [data-settings-toggle]')).toBeFocused();
+ await app.getByRole('button', { name: chrome, exact: true }).click();
+ await expect(portal).toBeVisible();
+ expect(denied).toEqual([]);
+ });
+}
diff --git a/ui/src/apps/ShowPageApp.tsx b/ui/src/apps/ShowPageApp.tsx
index dd468b5d1..0c410bcea 100644
--- a/ui/src/apps/ShowPageApp.tsx
+++ b/ui/src/apps/ShowPageApp.tsx
@@ -6,6 +6,8 @@ import { bindShowPageFrameCloseShortcut } from '../components/apps/windowChords'
import { useRequiredShowPageAnnotationHost } from '../components/workbench/ShowPageAnnotationHostContext';
import { useDock } from '../context/DockContext';
import { useWindowManager } from '../context/WindowManagerContext';
+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';
+import { useLatestRef } from '../lib/useLatestRef';
// A pinned Show Page opened as a workbench app. The body always frames the
// PRIVATE /show/<session_id>/ surface (authenticated workbench context, live
@@ -21,6 +23,7 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u
const { close, confirmClose } = useWindowManager();
const { unpin } = useDock();
const { annotation, src } = useRequiredShowPageAnnotationHost();
+ const routeSurfaceActiveRef = useLatestRef(useRouteSurfaceActive());
const { setIframe: setAnnotationIframe, handleIframeLoad } = annotation;
const shortcutCleanupRef = useRef<() => void>(() => undefined);
const setIframe = useCallback(
@@ -30,10 +33,11 @@ export const ShowPageApp: React.FC<{ windowId: string; params?: Record<string, u
setAnnotationIframe(iframe);
if (!iframe) return;
shortcutCleanupRef.current = bindShowPageFrameCloseShortcut(iframe, () => {
+ if (!routeSurfaceActiveRef.current) return;
if (confirmClose(windowId)) close(windowId);
});
},
- [close, confirmClose, setAnnotationIframe, windowId],
+ [close, confirmClose, routeSurfaceActiveRef, setAnnotationIframe, windowId],
);
const sessionId = typeof params?.sessionId === 'string' ? params.sessionId : '';
diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsx
index ebaa05ec5..30f7f4084 100644
--- a/ui/src/components/AppShell.test.tsx
+++ b/ui/src/components/AppShell.test.tsx
@@ -3,8 +3,9 @@
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, useNavigate } from 'react-router-dom';
+import { MemoryRouter, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import type { ReactNode } from 'react';
+import { closeSettingsOverlay, useSettingsOverlayOrigin } from '../lib/settingsOverlay';
import { APP_TAB_PARAM } from '../apps/appLaunch';
import {
@@ -130,6 +131,15 @@ vi.mock('react-i18next', () => ({
}),
}));
+const SettingsExit = ({ testId }: { testId: string }) => {
+ const location = useLocation();
+ const navigate = useNavigate();
+ const origin = useSettingsOverlayOrigin(location);
+ return <div data-testid={testId}>
+ <button onClick={() => { if (origin) closeSettingsOverlay(navigate, origin); }}>settings.close</button>
+ </div>;
+};
+
beforeEach(() => {
viewport.isDesktop = false;
clearMobileProjectsListSnapshot();
@@ -458,20 +468,19 @@ describe('AppShell persistent Workbench chrome', () => {
<Route element={<AppShell />}>
<Route index element={<div data-testid="workbench" />} />
<Route path="chat/:sessionId" element={<div data-testid="chat" />} />
- <Route path="settings/general" element={<div data-testid="settings" />} />
+ <Route path="settings/general" element={<SettingsExit testId="settings" />} />
</Route>
</Routes>
</MemoryRouter>,
);
expect(await screen.findByTestId('chat')).toBeTruthy();
- let settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });
+ const settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });
expect(settingsToggle.getAttribute('href')).toBe('/settings/general');
await user.click(settingsToggle);
expect(await screen.findByTestId('settings')).toBeTruthy();
- settingsToggle = screen.getByRole('button', { name: 'appShell.openControlPanel' });
- await user.click(settingsToggle);
+ await user.click(screen.getByRole('button', { name: 'settings.close' }));
expect(await screen.findByTestId('chat')).toBeTruthy();
});
@@ -487,7 +496,7 @@ describe('AppShell persistent Workbench chrome', () => {
<Routes>
<Route element={<AppShell />}>
<Route path="chat/:sessionId" element={<div data-testid="chat" />} />
- <Route path="settings/diagnostics" element={<div data-testid="diagnostics" />} />
+ <Route path="settings/diagnostics" element={<SettingsExit testId="diagnostics" />} />
</Route>
</Routes>
</MemoryRouter>,
@@ -496,7 +505,7 @@ describe('AppShell persistent Workbench chrome', () => {
await user.click(await screen.findByRole('link', { name: 'configRecovery.action' }));
expect(await screen.findByTestId('diagnostics')).toBeTruthy();
- await user.click(screen.getByRole('button', { name: 'appShell.openControlPanel' }));
+ await user.click(screen.getByRole('button', { name: 'settings.close' }));
expect(await screen.findByTestId('chat')).toBeTruthy();
});
});
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 3f44efa18..d89cee92e 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -22,6 +22,7 @@ import { WindowLayer } from './apps/WindowLayer';
import { MobileDockDrawer } from './apps/MobileDockDrawer';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
+import { RouteSurfaceActivityBoundary } from './RouteSurfaceActivityBoundary';
import { Button } from './ui/button';
import { InstallHint } from './InstallHint';
import logoImg from '../assets/logo.png';
@@ -36,7 +37,6 @@ import {
import {
closeSettingsOverlay,
isSettingsEntryPath,
- isSettingsRoutePath,
useSettingsOverlayOrigin,
} from '../lib/settingsOverlay';
import { SettingsOverlayNavigationBoundary } from './settings/SettingsOverlayNavigationBoundary';
@@ -178,7 +178,10 @@ export const AppShell: React.FC = () => {
const location = useLocation();
const navigate = useNavigate();
const settingsOverlayOrigin = useSettingsOverlayOrigin(location);
- const settingsOpen = isSettingsRoutePath(location.pathname);
+ // Settings owns the foreground surface, even while a retained Workbench
+ // origin stays mounted behind it. Keep this distinction at the shell boundary
+ // so the origin cannot bring back Workbench chrome or its desktop offset.
+ const settingsOpen = isSettingsEntryPath(location.pathname);
// An origin can now exist on a phone too (the Workbench home retains its
// composer behind Settings), but only the desktop overlay is a layer *over*
// this shell. Below md the Settings surface covers the shell outright, so the
@@ -226,7 +229,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) return;
+ if (e.defaultPrevented || settingsOpen) return;
if ((e.metaKey || e.ctrlKey) && (e.key === 'k' || e.key === 'K')) {
e.preventDefault();
setSearchOpen((prev) => !prev);
@@ -234,7 +237,7 @@ export const AppShell: React.FC = () => {
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, []);
+ }, [settingsOpen]);
// Close the mobile Dock drawer on navigation.
useEffect(() => {
@@ -323,7 +326,7 @@ export const AppShell: React.FC = () => {
// brand header AND the bottom tab bar are hidden on them.
const isChat = surfaceLocation.pathname.startsWith('/chat/');
const isSearch = surfaceLocation.pathname === '/search';
- const isSettings = isSettingsRoutePath(surfaceLocation.pathname);
+ const isSettings = settingsOpen;
const isShowPageApp = surfaceLocation.pathname.startsWith('/apps/show/');
const isBuiltinApp = isStandaloneAppRoutePath(surfaceLocation.pathname);
const isFullScreenMobile = isChat || isSearch || isSettings || isShowPageApp || isBuiltinApp;
@@ -362,12 +365,23 @@ export const AppShell: React.FC = () => {
{/* Sidebar Y1TiVV — 248 wide by default, 20/16 padding, top group and bottom
cluster pushed apart. The brand row, navigation and projects are one unit
inside WorkbenchSidebar; this frame owns only the column and the bottom.
- The width is SidebarResizer's --app-sidebar-w, which <main> below and the
- Settings overlay read too, so a drag moves the whole layout at once. */}
+ The width is SidebarResizer's --app-sidebar-w, shared with Workbench
+ content. Settings owns the viewport and never reads this offset. */}
{!chromeless && (
- <aside className="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 py-5 md:flex">
+ <aside
+ aria-hidden={settingsOpen || undefined}
+ inert={settingsOpen || 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 py-5 md:flex',
+ settingsOpen && 'invisible pointer-events-none',
+ )}
+ >
<div className="flex min-h-0 flex-1 flex-col">
- {isDesktop && <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />}
+ {isDesktop && (
+ <RouteSurfaceActivityBoundary active={!settingsOpen}>
+ <WorkbenchSidebar onOpenSearch={() => setSearchOpen(true)} />
+ </RouteSurfaceActivityBoundary>
+ )}
</div>
{/* Bottom cluster: Apps fills the row beside the compact Settings icon,
@@ -376,7 +390,11 @@ export const AppShell: React.FC = () => {
floats above app windows. */}
<div className="relative flex shrink-0 flex-col gap-2.5">
<div className="flex h-[39px] items-stretch gap-2">
- {canUseApps && <AppsLauncher />}
+ {canUseApps && (
+ <RouteSurfaceActivityBoundary active={!settingsOpen}>
+ <AppsLauncher />
+ </RouteSurfaceActivityBoundary>
+ )}
{settingsOpen ? (
<button
type="button"
@@ -463,6 +481,8 @@ 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
+ ? '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'
: 'flex-1 min-h-0 overflow-y-auto md:ml-[var(--app-sidebar-w)] md:min-h-screen md:flex-none md:overflow-visible md:pb-0',
@@ -511,25 +531,33 @@ 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 same
docked tiles + order as the desktop Dock. */}
- {canUseApps && (
+ {!settingsOpen && canUseApps && (
<MobileDockDrawer open={appsDrawerOpen} onClose={() => setAppsDrawerOpen(false)} />
)}
{capabilities.can_chat && (
- <NewSessionSheet
- open={newSessionOpen}
- onClose={() => setNewSessionOpen(false)}
- onOpen={() => setNewSessionOpen(true)}
- />
+ <RouteSurfaceActivityBoundary active={!settingsOpen}>
+ <NewSessionSheet
+ open={newSessionOpen}
+ onClose={() => setNewSessionOpen(false)}
+ onOpen={() => setNewSessionOpen(true)}
+ />
+ </RouteSurfaceActivityBoundary>
)}
{/* ⌘K message-search palette. Mounted shell-wide; the sidebar field is the
Workbench entry point. */}
- <SearchPalette open={searchOpen} onClose={() => setSearchOpen(false)} />
+ <RouteSurfaceActivityBoundary active={!settingsOpen}>
+ <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. */}
- {canUseApps && <WindowLayer />}
+ {canUseApps && (
+ <div hidden={settingsOpen} inert={settingsOpen || undefined} aria-hidden={settingsOpen || undefined}>
+ <WindowLayer active={!settingsOpen} />
+ </div>
+ )}
</div>
</ShowPageDragProvider>
</DockProvider>
diff --git a/ui/src/components/AppsLauncher.test.tsx b/ui/src/components/AppsLauncher.test.tsx
new file mode 100644
index 000000000..9dc60361f
--- /dev/null
+++ b/ui/src/components/AppsLauncher.test.tsx
@@ -0,0 +1,148 @@
+/** @vitest-environment jsdom */
+
+import { createInstance } from 'i18next';
+import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import en from '../i18n/en.json';
+import { RouteSurfaceActiveContext } from '../lib/routeSurfaceActivity';
+import { AppsLauncher } from './AppsLauncher';
+
+const windowManager = vi.hoisted(() => ({ openApp: vi.fn() }));
+const drag = vi.hoisted(() => ({ active: false, dropToDock: vi.fn() }));
+
+vi.mock('./apps/Dock', () => ({ Dock: () => <div data-testid="dock-content">Dock content</div> }));
+vi.mock('../context/WindowManagerContext', () => ({ useWindowManager: () => windowManager }));
+vi.mock('../context/showPageDrag', () => ({
+ useShowPageDrag: () => drag,
+}));
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+const launcher = (active = true) => (
+ <I18nextProvider i18n={i18n}>
+ <RouteSurfaceActiveContext.Provider value={active}><AppsLauncher /></RouteSurfaceActiveContext.Provider>
+ </I18nextProvider>
+);
+
+const renderLauncher = () => render(launcher());
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ disconnect() {}
+ },
+ );
+ windowManager.openApp.mockReset();
+ drag.active = false;
+ drag.dropToDock.mockReset();
+});
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+describe('AppsLauncher foreground affordance', () => {
+ it('keeps pin, hover Dock and context-menu launch behavior on the scoped mint treatment', () => {
+ renderLauncher();
+ const button = screen.getByRole('button', { name: 'Apps' });
+ const trigger = button.parentElement;
+ expect(trigger).toBeTruthy();
+ expect(button.className).toContain('bg-mint/[0.16]');
+ expect(button.className).toContain('text-foreground');
+ expect(button.className).not.toContain('shadow-glow');
+ expect(button.querySelector('svg')?.className.baseVal).toContain('text-mint-ink');
+
+ fireEvent.mouseEnter(trigger!);
+ expect(screen.getByTestId('dock-content')).toBeTruthy();
+
+ fireEvent.click(button);
+ expect(button.getAttribute('aria-pressed')).toBe('true');
+ fireEvent.click(button);
+ expect(button.getAttribute('aria-pressed')).toBe('false');
+
+ fireEvent.contextMenu(button, { clientX: 12, clientY: 18 });
+ const openLibrary = screen.getByRole('menuitem', { name: 'Open App Library' });
+ fireEvent.click(openLibrary);
+ expect(windowManager.openApp).toHaveBeenCalledWith('library');
+ });
+
+ it('removes its body portal on final unmount', () => {
+ const view = renderLauncher();
+ const button = screen.getByRole('button', { name: 'Apps' });
+ fireEvent.click(button);
+ fireEvent.contextMenu(button, { clientX: 12, clientY: 18 });
+ expect(screen.getByRole('menuitem', { name: 'Open App Library' })).toBeTruthy();
+
+ view.unmount();
+
+ expect(document.body.querySelector('[role="menu"]')).toBeNull();
+ expect(document.body.querySelector('button[aria-label="Apps"]')).toBeNull();
+ });
+});
+
+
+describe('AppsLauncher Settings suspension', () => {
+ it('keeps pin while retiring Dock/menu/listeners and recomputing placement on return', () => {
+ const add = vi.spyOn(window, 'addEventListener');
+ const remove = vi.spyOn(window, 'removeEventListener');
+ const rendered = render(launcher());
+ fireEvent.click(screen.getByRole('button', { name: 'Apps' }));
+ fireEvent.contextMenu(screen.getByRole('button', { name: 'Apps' }));
+ const listeners = add.mock.calls.filter(([type]) => ['resize', 'scroll', 'dragend'].includes(type));
+ for (let round = 0; round < 2; round += 1) {
+ rendered.rerender(launcher(false));
+ expect(screen.queryByRole('button', { name: 'Apps' })).toBeNull();
+ expect(screen.queryByTestId('dock-content')).toBeNull();
+ expect(screen.queryByRole('menuitem')).toBeNull();
+ for (const args of listeners) expect(remove.mock.calls).toContainEqual(args);
+ rendered.rerender(launcher());
+ expect(screen.getByRole('button', { name: 'Apps' }).getAttribute('aria-pressed')).toBe('true');
+ expect(screen.getByTestId('dock-content')).toBeTruthy();
+ expect(screen.queryByRole('menuitem')).toBeNull();
+ }
+ fireEvent.click(screen.getByRole('button', { name: 'Apps' }));
+ expect(screen.queryByTestId('dock-content')).toBeNull();
+ add.mockRestore(); remove.mockRestore();
+ });
+
+ it('keeps foreground drag/drop and retires the preview and timer on suspension', () => {
+ vi.useFakeTimers();
+ drag.active = true;
+ const rendered = render(launcher());
+ const trigger = screen.getByRole('button', { name: 'Apps' }).parentElement!;
+ fireEvent.dragEnter(trigger);
+ expect(screen.getByTestId('dock-content')).toBeTruthy();
+ fireEvent.drop(trigger);
+ expect(drag.dropToDock).toHaveBeenCalledTimes(1);
+ rendered.rerender(launcher(false));
+ expect(vi.getTimerCount()).toBe(0);
+ rendered.rerender(launcher());
+ expect(screen.queryByTestId('dock-content')).toBeNull();
+ vi.useRealTimers();
+ });
+
+ it('does not revive hover or its close timer after suspension', () => {
+ vi.useFakeTimers();
+ const rendered = render(launcher());
+ const trigger = screen.getByRole('button', { name: 'Apps' }).parentElement!;
+ fireEvent.mouseEnter(trigger);
+ expect(screen.getByTestId('dock-content')).toBeTruthy();
+ fireEvent.mouseLeave(trigger);
+ rendered.rerender(launcher(false));
+ expect(vi.getTimerCount()).toBe(0);
+ rendered.rerender(launcher());
+ expect(screen.queryByTestId('dock-content')).toBeNull();
+ vi.useRealTimers();
+ });
+});
diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsx
index 06944b9ea..176bf8651 100644
--- a/ui/src/components/AppsLauncher.tsx
+++ b/ui/src/components/AppsLauncher.tsx
@@ -8,6 +8,7 @@ import { Dock } from './apps/Dock';
import { ContextMenu, ContextMenuItem } from './ui/context-menu';
import { useWindowManager } from '../context/WindowManagerContext';
import { useShowPageDrag } from '../context/showPageDrag';
+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';
// The sidebar bottom-left "Apps" button that reveals the Dock.
// - hover → the Dock floats up ABOVE the button (transient preview; the
@@ -19,10 +20,20 @@ import { useShowPageDrag } from '../context/showPageDrag';
// and the empty-Dock hint), complementing §7.1c point 7. It
// does NOT touch the hover/pin behavior.
export const AppsLauncher: React.FC = () => {
+ const active = useRouteSurfaceActive();
+ const [pinned, setPinned] = useState(false);
+ // Pinning belongs to the launcher owner. Hover/menu/drag and Dock demand
+ // belong to the visible presentation and retire together on suspension.
+ return active ? <LauncherPresentation pinned={pinned} setPinned={setPinned} /> : null;
+};
+
+const LauncherPresentation = ({ pinned, setPinned }: {
+ pinned: boolean;
+ setPinned: (value: boolean) => void;
+}) => {
const { t } = useTranslation();
const wm = useWindowManager();
const showPageDrag = useShowPageDrag();
- const [pinned, setPinned] = useState(false);
const [hovering, setHovering] = useState(false);
const [dragHovering, setDragHovering] = useState(false);
// Cursor-positioned right-click menu, on the shared ContextMenu primitive.
@@ -91,12 +102,9 @@ export const AppsLauncher: React.FC = () => {
closeTimer.current = null;
}, 180);
};
- useEffect(
- () => () => {
- if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
- },
- [],
- );
+ useEffect(() => () => {
+ if (closeTimer.current !== null) window.clearTimeout(closeTimer.current);
+ }, []);
const onClick = () => {
if (pinned) {
@@ -164,16 +172,19 @@ export const AppsLauncher: React.FC = () => {
aria-expanded={visible}
aria-pressed={pinned}
className={clsx(
- 'group flex w-full items-center gap-2.5 rounded-full border bg-cyan-soft px-4 py-2.5 text-[13px] font-bold text-foreground transition-colors',
+ // Keep the Apps control soft and mint scoped to this shell affordance.
+ // Its label stays ordinary foreground text; the fill and icon carry
+ // the brand without changing shared mint-soft tokens or adding glow.
+ 'group flex w-full items-center gap-2.5 rounded-full border bg-mint/[0.16] px-4 py-2.5 text-[13px] font-bold text-foreground transition-colors',
visible
- ? 'border-cyan shadow-glow-md-cyan'
- : 'border-cyan/45 shadow-glow-sm-cyan hover:border-cyan/70',
+ ? 'border-mint'
+ : 'border-mint/45 hover:border-mint/70',
)}
>
- <LayoutGrid className="size-4 shrink-0 text-cyan-ink" />
+ <LayoutGrid className="size-4 shrink-0 text-mint-ink" />
<span className="flex-1 whitespace-nowrap text-left">{t('apps.title')}</span>
{pinned ? (
- <Pin className="size-3.5 shrink-0 rotate-45 fill-cyan text-cyan-ink" />
+ <Pin className="size-3.5 shrink-0 rotate-45 fill-mint text-mint-ink" />
) : (
<ChevronUp className={clsx('size-3.5 shrink-0 text-muted transition-transform', !visible && 'rotate-180')} />
)}
@@ -194,7 +205,7 @@ export const AppsLauncher: React.FC = () => {
{menu && (
<ContextMenu x={menu.x} y={menu.y} onClose={() => setMenu(null)} width={184} itemCount={1}>
<ContextMenuItem
- icon={<LayoutGrid className="size-[15px] text-cyan-ink" />}
+ icon={<LayoutGrid className="size-[15px] text-mint-ink" />}
label={t('apps.launcher.openLibrary')}
onClick={openLibrary}
/>
diff --git a/ui/src/components/RouteSurfaceActivityBoundary.test.tsx b/ui/src/components/RouteSurfaceActivityBoundary.test.tsx
new file mode 100644
index 000000000..6b3bc7fcb
--- /dev/null
+++ b/ui/src/components/RouteSurfaceActivityBoundary.test.tsx
@@ -0,0 +1,97 @@
+/* @vitest-environment jsdom */
+import { useLayoutEffect, useState } from 'react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { createMemoryRouter, MemoryRouter, Outlet, Route, RouterProvider, Routes, useLocation, useNavigate } from 'react-router-dom';
+import type { NavigateFunction } from 'react-router-dom';
+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';
+import { RouteSurfaceActivityBoundary } from './RouteSurfaceActivityBoundary';
+
+afterEach(cleanup);
+for (const mode of ['declarative', 'data'] as const) {
+ describe(`Route surface call-time navigation: ${mode}`, () => {
+ const setup = (layoutNavigation = false) => {
+ let captured!: NavigateFunction;
+ let foreground!: NavigateFunction;
+ const replaces = [vi.fn(), vi.fn()];
+ const Consumer = () => {
+ const navigate = useNavigate();
+ const active = useRouteSurfaceActive();
+ useLayoutEffect(() => {
+ if (layoutNavigation && !active) void navigate('/layout-escape');
+ }, [active, navigate]);
+ useLayoutEffect(() => { captured ??= navigate; }, [navigate]);
+ return null;
+ };
+ const Surface = () => {
+ const [active, setActive] = useState(true);
+ const [mounted, setMounted] = useState(true);
+ const [version, setVersion] = useState(0);
+ const location = useLocation();
+ const navigate = useNavigate();
+ useLayoutEffect(() => { foreground = navigate; }, [navigate]);
+ return <>
+ <button onClick={() => setActive((value) => !value)}>toggle</button>
+ <button onClick={() => setMounted(false)}>retire</button>
+ <button onClick={() => setVersion(1)}>callback</button>
+ <output data-testid="location">{location.pathname}{location.search}{location.hash}</output>
+ <output data-testid="state">{JSON.stringify(location.state)}</output>
+ {mounted && <RouteSurfaceActivityBoundary active={active} inactiveReplace={replaces[version]}>
+ <Outlet /><Consumer />
+ </RouteSurfaceActivityBoundary>}
+ </>;
+ };
+ const initialEntries = ['/before', '/project/item'];
+ if (mode === 'data') {
+ const router = createMemoryRouter([{ path: 'project/*', element: <Surface /> },
+ { path: '*', element: <Surface /> }], { initialEntries });
+ render(<RouterProvider router={router} />);
+ } else render(<MemoryRouter initialEntries={initialEntries}>
+ <Routes><Route path="project/*" element={<Surface />} /><Route path="*" element={<Surface />} /></Routes>
+ </MemoryRouter>);
+ return { navigate: (...args: Parameters<NavigateFunction>) => captured(...args),
+ foreground: (...args: Parameters<NavigateFunction>) => foreground(...args), replaces };
+ };
+ it('commits inactive admission before a descendant layout effect can navigate', () => {
+ setup(true);
+ fireEvent.click(screen.getByText('toggle'));
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ });
+ it.each(['push', 'go', 'replace'] as const)('denies captured %s after suspension and retirement, never replaying on resume', async (kind) => {
+ const { navigate, replaces } = setup();
+ const invoke = () => kind === 'go' ? navigate(-1) : navigate('/late-result', { replace: kind === 'replace' });
+ fireEvent.click(screen.getByText('toggle'));
+ fireEvent.click(screen.getByText('callback'));
+ await act(async () => { await invoke(); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ expect(replaces[0]).not.toHaveBeenCalled();
+ expect(replaces[1]).toHaveBeenCalledTimes(kind === 'replace' ? 1 : 0);
+ fireEvent.click(screen.getByText('toggle'));
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ fireEvent.click(screen.getByText('retire'));
+ await act(async () => { await invoke(); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ expect(replaces[1]).toHaveBeenCalledTimes(kind === 'replace' ? 1 : 0);
+ });
+ it('preserves route-relative foreground arguments and history', async () => {
+ const { navigate } = setup();
+ await act(async () => { await navigate('../result', { state: { relative: 'route' } }); });
+ expect(screen.getByTestId('location').textContent).toBe('/result');
+ expect(screen.getByTestId('state').textContent).toBe('{"relative":"route"}');
+ await act(async () => { await navigate(-1); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ });
+ it('preserves foreground relative replace/state/history and readmits a captured callback on resume', async () => {
+ const { navigate, foreground } = setup();
+ fireEvent.click(screen.getByText('toggle'));
+ await act(async () => { await foreground('/project/settings'); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/settings');
+ fireEvent.click(screen.getByText('toggle'));
+ await act(async () => { await navigate('../next?q=1#result', { relative: 'path', replace: true, state: { source: 'retained' }, preventScrollReset: true }); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/next?q=1#result');
+ expect(screen.getByTestId('state').textContent).toBe('{"source":"retained"}');
+ await act(async () => { await navigate(-1); });
+ expect(screen.getByTestId('location').textContent).toBe('/project/item');
+ });
+ });
+}
diff --git a/ui/src/components/RouteSurfaceActivityBoundary.tsx b/ui/src/components/RouteSurfaceActivityBoundary.tsx
index c5d827092..95fd9278f 100644
--- a/ui/src/components/RouteSurfaceActivityBoundary.tsx
+++ b/ui/src/components/RouteSurfaceActivityBoundary.tsx
@@ -1,9 +1,10 @@
-import { useContext, useMemo } from 'react';
+import { useContext, useInsertionEffect, useMemo, useRef } from 'react';
import type { ReactNode } from 'react';
import {
+ UNSAFE_DataRouterContext as DataRouterContext,
UNSAFE_NavigationContext as NavigationContext,
} from 'react-router-dom';
-import type { Navigator } from 'react-router-dom';
+import type { Navigator, RouterNavigateOptions, To } from 'react-router-dom';
import { RouteSurfaceActiveContext } from '@/lib/routeSurfaceActivity';
@@ -17,26 +18,63 @@ export const RouteSurfaceActivityBoundary = ({
inactiveReplace?: Navigator['replace'];
}) => {
const navigation = useContext(NavigationContext);
- // A retained route owns visual state, not the foreground URL. Deny route
- // maintenance effects while it is hidden so they cannot dismiss the overlay.
- const navigator = useMemo<Navigator>(() => {
- if (active) return navigation.navigator;
- return {
- ...navigation.navigator,
- go: () => {},
- push: () => {},
- replace: inactiveReplace ?? (() => {}),
- };
- }, [active, inactiveReplace, navigation.navigator]);
+ const dataNavigation = useContext(DataRouterContext);
+ // Old async callers retain these wrappers. Admission belongs to the current
+ // committed surface, not the render that supplied their navigate callback.
+ // Publish before descendants run layout effects; speculative renders cannot
+ // revoke an active surface or authorize an inactive one.
+ const committed = useRef({ active: false, navigation, dataNavigation, inactiveReplace });
+ useInsertionEffect(() => {
+ committed.current = { active, navigation, dataNavigation, inactiveReplace };
+ return () => { committed.current = { ...committed.current, active: false, inactiveReplace: undefined }; };
+ }, [active, navigation, dataNavigation, inactiveReplace]);
+ const navigator = useMemo<Navigator>(() => ({
+ ...navigation.navigator,
+ go: (...args) => {
+ if (committed.current.active) committed.current.navigation.navigator.go(...args);
+ },
+ push: (...args) => {
+ if (committed.current.active) committed.current.navigation.navigator.push(...args);
+ },
+ replace: (...args) => {
+ const current = committed.current;
+ if (current.active) current.navigation.navigator.replace(...args);
+ else current.inactiveReplace?.(...args);
+ },
+ }), [navigation.navigator]);
const scopedNavigation = useMemo(
() => ({ ...navigation, navigator }),
[navigation, navigator],
);
+ const scopedDataNavigation = useMemo(() => {
+ if (!dataNavigation) return null;
+ // Data-router useNavigate bypasses Navigator. Scope the router facade, never
+ // mutate the shared router used by foreground Settings or other surfaces.
+ const router = Object.create(dataNavigation.router) as typeof dataNavigation.router;
+ router.navigate = ((to: number | To | null, options?: RouterNavigateOptions): Promise<void> => {
+ const current = committed.current;
+ if (current.active && current.dataNavigation) {
+ return typeof to === 'number'
+ ? current.dataNavigation.router.navigate(to)
+ : current.dataNavigation.router.navigate(to, options);
+ }
+ if (typeof to !== 'number' && options?.replace) {
+ current.inactiveReplace?.(to ?? '.', options.state, options);
+ }
+ return Promise.resolve();
+ }) as typeof router.navigate;
+ return { ...dataNavigation, router };
+ }, [dataNavigation]);
+ const content = dataNavigation ? (
+ <DataRouterContext.Provider value={scopedDataNavigation}>
+ {children}
+ </DataRouterContext.Provider>
+ ) : children;
return (
<RouteSurfaceActiveContext.Provider value={active}>
<NavigationContext.Provider value={scopedNavigation}>
- {children}
+ {content}
</NavigationContext.Provider>
</RouteSurfaceActiveContext.Provider>
);
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index 8e6331149..a2175fc56 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -33,13 +33,17 @@ const RESIZE_HANDLES: { dir: ResizeDir; className: string }[] = [
];
export const AppWindow: React.FC<{
+ /** Whether this retained window is the active shell surface. Inactive windows
+ * stay mounted so app bodies keep their in-memory state, but their chrome and
+ * event handlers must not compete with the foreground route. */
+ active?: boolean;
win: WindowInstance;
layerWidth: number;
layerHeight: number;
/** The Show Page icon's opaque cache token for a `showpage` window's title-bar
* chip, threaded from the WindowLayer inventory join (§7.1f/g). */
iconVersion?: string | null;
-}> = ({ win, layerWidth, layerHeight, iconVersion }) => {
+}> = ({ active = true, win, layerWidth, layerHeight, iconVersion }) => {
const { t } = useTranslation();
const wm = useWindowManager();
const navigate = useNavigate();
@@ -85,6 +89,15 @@ export const AppWindow: React.FC<{
);
const { capabilities } = useInstanceAuthorization();
+ useEffect(() => {
+ if (active) return;
+ // Radix popovers portal to document.body, outside the retained window's
+ // inert subtree. Close their local state when Settings takes foreground so
+ // stale app chrome cannot remain reachable through that portal.
+ setAnnotateOpen(false);
+ setShareOpen(false);
+ }, [active]);
+
// Keep a visible window reachable when the geometry around it changes without a
// drag: the layer shrinking, or the window being restored / un-maximized after the
// layer shrank (the gesture clamps can't fire in those cases). Deliberately not
@@ -106,11 +119,11 @@ export const AppWindow: React.FC<{
// window wouldn't receive ⌘W/⌘M. The `contains` guard avoids yanking focus from an
// inner field the user just clicked (pointerdown already focuses those).
useEffect(() => {
- if (win.minimized || wm.focusedId !== win.id) return;
+ if (!active || win.minimized || wm.focusedId !== win.id) return;
if (rootRef.current?.contains(document.activeElement)) return;
rootRef.current?.focus({ preventScroll: true });
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [wm.focusedId, win.minimized]);
+ }, [active, wm.focusedId, win.minimized]);
// One pointer gesture (move or resize). Capturing `win.bounds` at gesture start
// keeps the math stable even as state updates re-render mid-drag.
@@ -124,7 +137,7 @@ export const AppWindow: React.FC<{
// flicker). Cleanup is idempotent + runs on BOTH pointerup and lostpointercapture, so
// a missed/stolen release can never leave the shield or listeners stuck.
const startGesture = (e: React.PointerEvent, kind: 'move' | ResizeDir) => {
- if (win.maximized) return;
+ if (!active || win.maximized) return;
e.preventDefault();
e.stopPropagation();
wm.focus(win.id);
@@ -260,24 +273,28 @@ export const AppWindow: React.FC<{
// Minimized windows stay mounted (to preserve their body state) but go fully
// inert: hidden from assistive tech, out of the tab order, non-interactive —
// and React/the browser moves focus out automatically.
- inert={win.minimized}
+ aria-hidden={!active || undefined}
+ inert={!active || win.minimized}
tabIndex={-1}
- onKeyDown={annotationHost?.annotation.handleShortcutKeyDown}
+ onKeyDown={active ? annotationHost?.annotation.handleShortcutKeyDown : undefined}
onPointerDownCapture={() => {
// Capture runs before toolbar controls stop propagation, so every pointer
// activation claims the window without stealing DOM focus from the target.
- wm.focus(win.id);
+ if (active) wm.focus(win.id);
}}
onPointerDown={(e) => {
// Give the window DOM focus (so ⌘W/⌘M target it) — but don't steal focus from
// an inner control/editor/terminal the click lands in. FocusCapture below
// then gives the same window foreground ownership and raises its z-order.
+ if (!active) return;
const tgt = e.target as HTMLElement;
if (!tgt.closest('input,textarea,select,button,a,[contenteditable="true"],.monaco-editor,.xterm')) {
rootRef.current?.focus({ preventScroll: true });
}
}}
- onFocusCapture={() => wm.focus(win.id)}
+ onFocusCapture={() => {
+ if (active) wm.focus(win.id);
+ }}
onAnimationEnd={(e) => {
// Only the root's own close animation drives the unmount (ignore the
// entrance, and any child animation bubbling up). Minimize doesn't animate
@@ -352,7 +369,7 @@ export const AppWindow: React.FC<{
open-in-new-tab — up to four size-6 controls plus gaps (108px), so both
clusters reserve w-28 (112px) to keep them from crowding the title. */}
<div className={clsx('flex shrink-0 items-center justify-end gap-1', showpageSid ? 'w-28' : 'w-[52px]')}>
- {showpageSid && annotationHost?.src && !win.minimized && exitKind === null && (
+ {active && showpageSid && annotationHost?.src && !win.minimized && exitKind === null && (
<div
onPointerDown={(e) => e.stopPropagation()}
onClick={(e) => e.stopPropagation()}
@@ -370,7 +387,7 @@ export const AppWindow: React.FC<{
/>
</div>
)}
- {chatHref && (
+ {active && chatHref && (
<button
type="button"
title={t('apps.window.openChat')}
@@ -398,7 +415,7 @@ export const AppWindow: React.FC<{
<MessageCircle className="size-3.5" />
</button>
)}
- {showpageSid && annotationHost?.src && !win.minimized && exitKind === null
+ {active && showpageSid && annotationHost?.src && !win.minimized && exitKind === null
&& capabilities.can_use_show_pages && (
<div
onPointerDown={(e) => e.stopPropagation()}
@@ -444,12 +461,12 @@ export const AppWindow: React.FC<{
transparent overlay so a gesture's pointer can't be stolen by the iframe and the
cursor doesn't flicker over it — belt-and-braces with the gesture's pointer capture. */}
<WindowBodyGestureShield active={shouldShieldWindowBody(wm.gestureActive, win.minimized)} />
- {(annotateOpen || shareOpen) && annotationHost?.src && (
+ {active && (annotateOpen || shareOpen) && annotationHost?.src && (
<div aria-hidden data-annotation-shield className="absolute inset-0 z-20" />
)}
</div>
- {!win.maximized &&
+ {active && !win.maximized &&
RESIZE_HANDLES.map((h) => (
<div
key={h.dir}
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index 2579e480c..632f1536c 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -19,8 +19,10 @@ import {
import { inTerminalSurface, inTextEntrySurface, windowIdForKeyboardTarget } from './windowChords';
import { shouldGuardUnload } from './windowUnload';
import { isDesktopViewport } from '../../lib/useIsDesktop';
+import { RouteSurfaceActivityBoundary } from '../RouteSurfaceActivityBoundary';
const ShowPageWindow: React.FC<{
+ active: boolean;
archived: boolean;
iconVersion: string | null;
layerHeight: number;
@@ -28,7 +30,7 @@ const ShowPageWindow: React.FC<{
revalidateVersion: number;
sessionId: string;
win: WindowInstance;
-}> = ({ archived, iconVersion, layerHeight, layerWidth, revalidateVersion, sessionId, win }) => {
+}> = ({ active, archived, iconVersion, layerHeight, layerWidth, revalidateVersion, sessionId, win }) => {
const api = useApi();
const { setTitle } = useWindowManager();
const [status, setStatus] = useState<ShowPageWindowStatus>(sessionId ? 'loading' : 'missing');
@@ -59,18 +61,18 @@ const ShowPageWindow: React.FC<{
const src = showPageWindowSource(sessionId, status, archived);
return (
<ShowPageAnnotationHost src={src}>
- <AppWindow win={win} layerWidth={layerWidth} layerHeight={layerHeight} iconVersion={iconVersion} />
+ <AppWindow active={active} win={win} layerWidth={layerWidth} layerHeight={layerHeight} iconVersion={iconVersion} />
</ShowPageAnnotationHost>
);
};
-// The portal layer that hosts app windows. Covers the workbench main area (right
-// of the 248px sidebar on desktop). The layer itself is pointer-events-none so
+// The portal layer that hosts app windows. It spans the viewport so windows can
+// use the same geometry before and after route changes. The layer itself is pointer-events-none so
// empty space passes clicks through to the workbench underneath; each AppWindow
// re-enables pointer events on itself (minimized windows stay mounted but inert,
// so their terminal/editor state survives a minimize). Desktop-only — mobile opens
// apps full screen (P5), so no free-floating windows there.
-export const WindowLayer: React.FC = () => {
+export const WindowLayer: React.FC<{ active?: boolean }> = ({ active = true }) => {
const { t } = useTranslation();
const api = useApi();
const { order, pins } = useDock();
@@ -127,6 +129,7 @@ export const WindowLayer: React.FC = () => {
// page — the chord falls through to the browser. Inside the terminal only Meta counts,
// so its Ctrl control-chars (^W/^M) reach the shell (see inTerminalSurface).
useEffect(() => {
+ if (!active) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
if (!(e.metaKey || e.ctrlKey) || e.altKey) return;
@@ -145,7 +148,7 @@ export const WindowLayer: React.FC = () => {
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [close, minimize, confirmClose, standaloneTab]);
+ }, [active, close, minimize, confirmClose, standaloneTab]);
// ⌥W closes the focused in-app window — a browser-safe alternative to ⌘W, which
// the browser reserves for tab-close (not interceptable). Uses `code` (macOS
@@ -153,6 +156,7 @@ export const WindowLayer: React.FC = () => {
// guard as the ⌘/Ctrl chord above. Text-entry surfaces (inputs, Monaco, terminal)
// keep Option+W for character entry — consistent with the Alt+1-9 chord.
useEffect(() => {
+ if (!active) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
if (e.code !== 'KeyW' || !e.altKey || e.metaKey || e.ctrlKey || e.shiftKey) return;
@@ -165,7 +169,7 @@ export const WindowLayer: React.FC = () => {
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [close, confirmClose]);
+ }, [active, close, confirmClose]);
// While any app window is open and visible (not just minimized), guard tab-close
// / navigation-away with the browser's native confirm — the window state
@@ -192,6 +196,7 @@ export const WindowLayer: React.FC = () => {
// turn Option+digit into punctuation. Text inputs and terminals keep the chord
// for character entry; the Windows layer is desktop-only.
useEffect(() => {
+ if (!active) return;
const onKeyDown = (e: KeyboardEvent) => {
if (e.defaultPrevented) return;
if (!isDesktopViewport()) return;
@@ -239,7 +244,7 @@ export const WindowLayer: React.FC = () => {
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
- }, [focus, openApp, restore, t]);
+ }, [active, focus, openApp, restore, t]);
// Session mutations broadcast `session.activity`. Keep every open Show Page
// window's title live, and treat archive as terminal for the frame plus every
@@ -280,38 +285,42 @@ export const WindowLayer: React.FC = () => {
// actually shown (`anyShown`, computed above).
return (
- <div
- ref={ref}
- aria-hidden={!anyShown}
- // Theme is per-window now (AppWindow sets it from each app's registry `lockTheme`): the File
- // Browser follows the workbench light/dark, while the Editor and Terminal stay dark like a VS
- // Code editor / a terminal. So the layer itself no longer forces a theme — each window opts in.
- // Spans the FULL viewport (no longer offset past the sidebar): windows can move over
- // the sidebar and maximize fills the whole screen. This layer (z-20) sits ABOVE the sidebar
- // (z-10), but below the portaled Apps launcher and Dock (z-30).
- className="pointer-events-none fixed inset-0 z-20 hidden md:block"
- >
- {windows.map((w) => {
- // For a showpage window, join the inventory (already loaded above — no new
- // fetch) to hand its own HTML icon to the title-bar chip (§7.1f/g).
- const sid = w.appId === 'showpage' && typeof w.params?.sessionId === 'string' ? w.params.sessionId : undefined;
- const iconVersion = sid ? pages.find((p) => p.session_id === sid)?.icon_version ?? null : null;
- if (w.appId !== 'showpage') {
- return <AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} iconVersion={iconVersion} />;
- }
- return (
- <ShowPageWindow
- key={w.id}
- archived={Boolean(sid && archivedSessionIds.has(sid))}
- iconVersion={iconVersion}
- layerHeight={size.h}
- layerWidth={size.w}
- revalidateVersion={showPageRevalidateVersion}
- sessionId={sid ?? ''}
- win={w}
- />
- );
- })}
- </div>
+ <RouteSurfaceActivityBoundary active={active}>
+ <div
+ ref={ref}
+ aria-hidden={!active || !anyShown}
+ inert={!active || undefined}
+ // Theme is per-window now (AppWindow sets it from each app's registry `lockTheme`): the File
+ // Browser follows the workbench light/dark, while the Editor and Terminal stay dark like a VS
+ // Code editor / a terminal. So the layer itself no longer forces a theme — each window opts in.
+ // Spans the FULL viewport (no longer offset past the sidebar): windows can move over
+ // the sidebar and maximize fills the whole screen. This layer (z-20) sits ABOVE the sidebar
+ // (z-10), but below the portaled Apps launcher and Dock (z-30).
+ className="pointer-events-none fixed inset-0 z-20 hidden md:block"
+ >
+ {windows.map((w) => {
+ // For a showpage window, join the inventory (already loaded above — no new
+ // fetch) to hand its own HTML icon to the title-bar chip (§7.1f/g).
+ const sid = w.appId === 'showpage' && typeof w.params?.sessionId === 'string' ? w.params.sessionId : undefined;
+ const iconVersion = sid ? pages.find((p) => p.session_id === sid)?.icon_version ?? null : null;
+ if (w.appId !== 'showpage') {
+ return <AppWindow active={active} key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} iconVersion={iconVersion} />;
+ }
+ return (
+ <ShowPageWindow
+ active={active}
+ key={w.id}
+ archived={Boolean(sid && archivedSessionIds.has(sid))}
+ iconVersion={iconVersion}
+ layerHeight={size.h}
+ layerWidth={size.w}
+ revalidateVersion={showPageRevalidateVersion}
+ sessionId={sid ?? ''}
+ win={w}
+ />
+ );
+ })}
+ </div>
+ </RouteSurfaceActivityBoundary>
);
};
diff --git a/ui/src/components/apps/windowLayerInventory.test.tsx b/ui/src/components/apps/windowLayerInventory.test.tsx
index 70375db3a..e032e1196 100644
--- a/ui/src/components/apps/windowLayerInventory.test.tsx
+++ b/ui/src/components/apps/windowLayerInventory.test.tsx
@@ -7,8 +7,10 @@
// what the document renders decides what is fetched.
import { createInstance } from 'i18next';
-import { act, cleanup, render, screen } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { useState } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import en from '../../i18n/en.json';
@@ -17,6 +19,7 @@ import type { WindowInstance } from '../../context/WindowManagerContext';
import { WindowLayer } from './WindowLayer';
const windowsRef = { current: [] as WindowInstance[] };
+const dockState = { order: [] as string[], pins: [] as unknown[] };
const windowManager = vi.hoisted(() => ({
close: vi.fn(),
focus: vi.fn(),
@@ -29,7 +32,7 @@ const windowManager = vi.hoisted(() => ({
}));
vi.mock('../../context/DockContext', () => ({
- useDock: () => ({ order: [], pins: [] }),
+ useDock: () => dockState,
}));
vi.mock('../../context/WindowManagerContext', () => ({
@@ -46,7 +49,20 @@ vi.mock('../../context/StandaloneAppTabContext', () => ({
// Every window body is an app of its own (iframe, terminal, editor); the layer's
// own fetch decision is what is under test, so the frame is stubbed out.
vi.mock('./AppWindow', () => ({
- AppWindow: () => <button type="button" data-testid="app-window" data-window-id="win_1" />,
+ AppWindow: ({ active = true }: { active?: boolean }) => {
+ const [draft, setDraft] = useState('initial app state');
+ return (
+ <div data-testid="app-window" data-window-id="win_1">
+ <input
+ aria-label="Unsaved app buffer"
+ value={draft}
+ onChange={(event) => setDraft(event.target.value)}
+ />
+ <button type="button" aria-label="Close app window">Close</button>
+ <span data-testid="app-window-active">{String(active)}</span>
+ </div>
+ );
+ },
}));
vi.mock('../workbench/ShowPageAnnotationHost', () => ({
ShowPageAnnotationHost: ({ children }: { children: React.ReactNode }) => <>{children}</>,
@@ -83,11 +99,13 @@ const appWindow = (): WindowInstance =>
params: {},
}) as unknown as WindowInstance;
-const renderLayer = () =>
+const renderLayer = (active = true) =>
render(
- <I18nextProvider i18n={i18n}>
- <WindowLayer />
- </I18nextProvider>,
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <WindowLayer active={active} />
+ </I18nextProvider>
+ </MemoryRouter>,
);
describe('WindowLayer show-pages inventory', () => {
@@ -101,6 +119,8 @@ describe('WindowLayer show-pages inventory', () => {
},
);
windowsRef.current = [];
+ dockState.order = [];
+ dockState.pins = [];
api.getShowPages.mockReset();
api.getShowPages.mockResolvedValue([] as ShowPage[]);
api.getSessionResult.mockReset();
@@ -146,4 +166,43 @@ describe('WindowLayer show-pages inventory', () => {
expect(windowManager.minimize).not.toHaveBeenCalled();
});
+
+ it('keeps a stateful app mounted but makes its controls and global chords inactive', async () => {
+ windowsRef.current = [appWindow()];
+ const view = renderLayer();
+ const buffer = await screen.findByRole('textbox', { name: 'Unsaved app buffer' });
+ fireEvent.change(buffer, { target: { value: '未保存的草稿' } });
+ expect((buffer as HTMLInputElement).value).toBe('未保存的草稿');
+ dockState.order = ['terminal'];
+
+ view.rerender(
+ <MemoryRouter>
+ <I18nextProvider i18n={i18n}>
+ <WindowLayer active={false} />
+ </I18nextProvider>
+ </MemoryRouter>,
+ );
+
+ expect(screen.getByTestId('app-window')).toBeTruthy();
+ expect((screen.getByLabelText('Unsaved app buffer', { selector: 'input' }) as HTMLInputElement).value)
+ .toBe('未保存的草稿');
+ expect(screen.getByTestId('app-window-active').textContent).toBe('false');
+ expect(screen.getByTestId('app-window').parentElement?.getAttribute('inert')).toBe('');
+ expect(screen.getByTestId('app-window').parentElement?.getAttribute('aria-hidden')).toBe('true');
+
+ act(() => {
+ window.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'm', code: 'KeyM', metaKey: true, bubbles: true, cancelable: true,
+ }));
+ window.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'w', code: 'KeyW', metaKey: true, bubbles: true, cancelable: true,
+ }));
+ window.dispatchEvent(new KeyboardEvent('keydown', {
+ key: '1', code: 'Digit1', altKey: true, bubbles: true, cancelable: true,
+ }));
+ });
+ expect(windowManager.minimize).not.toHaveBeenCalled();
+ expect(windowManager.close).not.toHaveBeenCalled();
+ expect(windowManager.openApp).not.toHaveBeenCalled();
+ });
});
diff --git a/ui/src/components/settings/SettingsGeneralPage.tsx b/ui/src/components/settings/SettingsGeneralPage.tsx
index f52f58b26..ff7bdb72a 100644
--- a/ui/src/components/settings/SettingsGeneralPage.tsx
+++ b/ui/src/components/settings/SettingsGeneralPage.tsx
@@ -70,8 +70,8 @@ const THEME_CHOICES: { mode: ThemeMode; icon: LucideIcon; labelKey: TranslationK
];
// design r6G6P — ordinary Settings: interface language and appearance, both
-// saved the moment they are picked. Content is fluid; the 924 column in the
-// source is what 1200 minus the 196 rail happens to leave, not a max width.
+// 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();
diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsx
index e1d7cd51d..743492dac 100644
--- a/ui/src/components/settings/SettingsLayout.test.tsx
+++ b/ui/src/components/settings/SettingsLayout.test.tsx
@@ -184,22 +184,21 @@ describe('SettingsLayout', () => {
const modelHubFrame = screen.getByText('models-body').parentElement;
expect(modelHubFrame?.className).toContain('min-h-full');
expect(modelHubFrame?.className).not.toContain('mx-auto');
- expect(modelHubFrame?.className).not.toContain('max-w-[1180px]');
+ expect(modelHubFrame?.className).not.toMatch(/(?:^|\s)(?:[\w-]+:)*max-w-/);
},
);
- // The source draws General as content that simply fills whatever the rail
- // leaves, so the shared reading column would re-introduce a fixed width the
- // design does not have. It opts out the way Model Hub already does — without
- // Model Hub's `min-h-full`, which is a full-height pane, not a width.
+ // General and the other ordinary Settings sections share the standalone
+ // 944px outer frame (880px content after desktop padding). Model Hub keeps
+ // the full route pane for its own full-height surface.
it.each(['/settings/general', '/settings/general/'])(
- 'lets General fill the route pane at %s',
+ 'keeps General in the common standalone content column at %s',
(path) => {
renderLayout(path);
const generalFrame = screen.getByText('general-body').parentElement;
- expect(generalFrame?.className).not.toContain('mx-auto');
- expect(generalFrame?.className).not.toContain('max-w-[1180px]');
+ expect(generalFrame?.className).toContain('mx-auto');
+ expect(generalFrame?.className).toContain('max-w-[944px]');
expect(generalFrame?.className).not.toContain('min-h-full');
},
);
@@ -209,7 +208,7 @@ describe('SettingsLayout', () => {
const standardFrame = screen.getByText('replies-body').parentElement;
expect(standardFrame?.className).toContain('mx-auto');
- expect(standardFrame?.className).toContain('max-w-[1180px]');
+ expect(standardFrame?.className).toContain('max-w-[944px]');
expect(standardFrame?.className).not.toContain('min-h-full');
});
@@ -330,6 +329,28 @@ describe('SettingsLayout', () => {
expect(screen.getByTestId('account-menu').getAttribute('data-open-upward')).toBe('true');
});
+ it('updates the retained rail when instance-management permission changes', async () => {
+ const surface = () => (
+ <MemoryRouter initialEntries={['/settings/general']}>
+ <Routes>
+ <Route path="/settings" element={<SettingsLayoutHarness />}>
+ <Route path="general" element={<div>general-body</div>} />
+ </Route>
+ </Routes>
+ </MemoryRouter>
+ );
+ const view = render(surface());
+ expect(await screen.findByRole('link', { name: 'settings.sections.backends' })).toBeTruthy();
+ authorization.capabilities.can_manage_instance = false;
+ view.rerender(surface());
+ expect(screen.queryByRole('link', { name: 'settings.sections.backends' })).toBeNull();
+ expect(screen.getByText('general-body')).toBeTruthy();
+ expect(screen.getByRole('link', { name: 'settings.sections.replies' })).toBeTruthy();
+ authorization.capabilities.can_manage_instance = true;
+ view.rerender(surface());
+ expect(await screen.findByRole('link', { name: 'settings.sections.backends' })).toBeTruthy();
+ });
+
it('keeps member preferences, Replies, and Access while preserving the phase-2 permission gate', () => {
authorization.capabilities.can_manage_instance = false;
renderLayout('/settings/replies');
diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsx
index 6be60af7a..279ab74f7 100644
--- a/ui/src/components/settings/SettingsLayout.tsx
+++ b/ui/src/components/settings/SettingsLayout.tsx
@@ -132,7 +132,7 @@ const SettingsNavLink: React.FC<{ item: SettingsItem }> = ({ item }) => {
title={t(item.labelKey)}
className={clsx(
'flex min-h-11 items-center gap-2 rounded-[9px] px-2.5 py-2 text-[12.5px] transition-colors md:min-h-[34px] md:py-0',
- 'md:justify-center lg:justify-start',
+ 'md:justify-start',
active
? 'bg-mint-soft font-semibold text-foreground'
: 'font-medium text-muted hover:bg-foreground/[0.04] hover:text-foreground',
@@ -145,7 +145,7 @@ const SettingsNavLink: React.FC<{ item: SettingsItem }> = ({ item }) => {
in English). Wrapping keeps every label readable in any language, and
two lines at this size still fit the row's min height, so nothing moves
for the labels that already fitted. */}
- <span className="min-w-0 leading-[1.3] break-words md:hidden lg:block">{t(item.labelKey)}</span>
+ <span className="min-w-0 leading-[1.3] break-words">{t(item.labelKey)}</span>
</NavLink>
);
};
@@ -168,23 +168,23 @@ const SettingsNavGroup: React.FC<{ item: SettingsItem }> = ({ item }) => {
onClick={() => setManualOpen(!open)}
className={clsx(
'flex min-h-11 w-full items-center gap-2 rounded-[9px] px-2.5 py-2 text-[12.5px] font-medium transition-colors md:min-h-[34px] md:py-0',
- 'md:justify-center lg:justify-start',
+ 'md:justify-start',
childActive
? 'text-foreground'
: 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
)}
>
<Icon className={clsx('size-3.5 shrink-0', childActive ? 'text-mint-ink' : 'text-muted')} />
- <span className="min-w-0 flex-1 leading-[1.3] break-words text-left md:hidden lg:block">{t(item.labelKey)}</span>
+ <span className="min-w-0 flex-1 leading-[1.3] break-words text-left">{t(item.labelKey)}</span>
<ChevronDown
className={clsx(
- 'size-3.5 shrink-0 text-muted transition-transform md:hidden lg:block',
+ 'size-3.5 shrink-0 text-muted transition-transform',
open && 'rotate-180',
)}
/>
</button>
{open && (
- <div className="ml-3 flex flex-col gap-0.5 border-l border-border pl-2 md:ml-0 md:border-l-0 md:pl-0 lg:ml-3 lg:border-l lg:pl-2">
+ <div className="ml-3 flex flex-col gap-0.5 border-l border-border pl-2">
{children.map((child) => <SettingsNavLink key={child.path} item={child} />)}
</div>
)}
@@ -239,12 +239,10 @@ export const SettingsLayout: React.FC = () => {
const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);
const atRoot = location.pathname === '/settings' || location.pathname === '/settings/';
const isModelHub = pathMatches(location.pathname, '/settings/models');
- // The shared `max-w-[1180px]` is a reading column for pages made of prose and
- // form rows. General is not one: its source (r6G6P) draws content that simply
- // fills whatever the rail leaves, so capping it would re-introduce a fixed
- // column the design does not have. Opting one route out — the way Model Hub
- // already does — leaves every other Settings page exactly as it was.
- const isFluidContent = isModelHub || pathMatches(location.pathname, SETTINGS_LANDING_PATH);
+ // Settings is a standalone page: ordinary sections use one 944px outer
+ // frame with an 880px content column after 32px desktop padding. Model Hub
+ // keeps its full route-pane width and its own full-height surface.
+ const isFluidContent = isModelHub;
useEffect(() => {
if (!capabilities.can_manage_instance) return;
@@ -406,23 +404,23 @@ export const SettingsLayout: React.FC = () => {
aria-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-14 lg:w-[196px]',
+ 'w-full flex-col md:w-[196px]',
atRoot ? 'flex' : 'hidden md:flex',
)}
>
<ReturnToApp
aria-label={t('settings.backToApp')}
- className="mb-2 hidden min-h-10 shrink-0 items-center gap-2.5 rounded-[9px] px-2.5 text-[14px] text-foreground transition-colors hover:bg-foreground/[0.05] md:flex md:justify-center lg:justify-start"
+ className="mb-2 hidden min-h-10 shrink-0 items-center gap-2.5 rounded-[9px] px-2.5 text-[14px] text-foreground transition-colors hover:bg-foreground/[0.05] md:flex md:justify-start"
>
<ArrowLeft className="size-[17px] shrink-0" />
- <span className="truncate md:hidden lg:block">{t('settings.backToApp')}</span>
+ <span className="truncate">{t('settings.backToApp')}</span>
</ReturnToApp>
<div className="min-h-0 flex-1 overflow-y-auto">
{visibleGroups.map((group) => (
<div key={group.labelKey ?? group.items[0]?.path} className="mb-2 last:mb-0">
{group.labelKey && (
- <div className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted md:hidden lg:block">
+ <div className="px-2 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-[0.12em] text-muted">
{t(group.labelKey)}
</div>
)}
@@ -448,9 +446,9 @@ export const SettingsLayout: React.FC = () => {
<div
key={location.pathname}
className={clsx(
- 'w-full px-4 pb-[calc(1.25rem+env(safe-area-inset-bottom))] pt-5 motion-safe:animate-in motion-safe:slide-in-from-right-4 motion-safe:duration-200 md:px-6 md:pb-7 md:pt-7 md:animate-none lg:px-8',
+ 'w-full px-4 pb-[calc(1.25rem+env(safe-area-inset-bottom))] pt-5 motion-safe:animate-in motion-safe:slide-in-from-right-4 motion-safe:duration-200 md:px-8 md:pb-7 md:pt-7 md:animate-none',
isModelHub && 'min-h-full',
- !isFluidContent && 'mx-auto max-w-[1180px]',
+ !isFluidContent && 'mx-auto max-w-[944px]',
)}
>
<Outlet />
diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
index f86495d98..9f9e0dca2 100644
--- a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx
@@ -1,9 +1,9 @@
/* @vitest-environment jsdom */
-import { cleanup, render, screen, waitFor } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { useEffect, useState } from 'react';
+import { useEffect, useRef, useState } from 'react';
import {
Link,
MemoryRouter,
@@ -23,12 +23,103 @@ import {
useSettingsOverlayContext,
} from '@/lib/settingsOverlay';
import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
+import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog';
import { SettingsOverlayNavigationBoundary } from './SettingsOverlayNavigationBoundary';
import { SettingsOverlayRouteSurface } from './SettingsOverlayRouteSurface';
let chatMounts = 0;
let chatUnmounts = 0;
+const RetainedModalEditor = () => {
+ const navigate = useNavigate();
+ const [open, setOpen] = useState(false);
+ const [draft, setDraft] = useState('保留');
+ const inputRef = useRef<HTMLInputElement | null>(null);
+ const selectionRef = useRef({ start: 2, end: 2 });
+
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>open-retained-editor</button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent
+ aria-describedby={undefined}
+ onOpenAutoFocus={(event) => {
+ event.preventDefault();
+ const input = inputRef.current;
+ input?.focus();
+ input?.setSelectionRange(selectionRef.current.start, selectionRef.current.end);
+ }}
+ >
+ <DialogTitle className="sr-only">retained editor</DialogTitle>
+ <input
+ ref={inputRef}
+ aria-label="retained editor input"
+ value={draft}
+ onChange={(event) => {
+ setDraft(event.target.value);
+ selectionRef.current = {
+ start: event.target.selectionStart ?? event.target.value.length,
+ end: event.target.selectionEnd ?? event.target.value.length,
+ };
+ }}
+ onSelect={(event) => {
+ selectionRef.current = {
+ start: event.currentTarget.selectionStart ?? 0,
+ end: event.currentTarget.selectionEnd ?? 0,
+ };
+ }}
+ />
+ <button
+ type="button"
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => navigate('/settings/replies')}
+ >
+ open-settings-from-editor
+ </button>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
+
+type RetainedFocusOwnerKind = 'explicit-modal' | 'app-window' | 'popover';
+
+const RetainedFocusOwner = ({ kind }: { kind: RetainedFocusOwnerKind }) => {
+ const active = useRouteSurfaceActive();
+ const navigate = useNavigate();
+ const [open, setOpen] = useState(false);
+ const inputRef = useRef<HTMLInputElement | null>(null);
+
+ useEffect(() => {
+ if (active && open) inputRef.current?.focus();
+ }, [active, open]);
+
+ const dialogProps = kind === 'explicit-modal'
+ ? { 'aria-modal': 'true' }
+ : kind === 'app-window'
+ ? { 'data-window-id': 'retained-window' }
+ : { 'data-state': 'open', 'aria-label': 'retained popover' };
+ const label = `retained ${kind} input`;
+
+ return (
+ <>
+ <button type="button" onClick={() => setOpen(true)}>open-{kind}</button>
+ {open && active ? (
+ <div role="dialog" {...dialogProps}>
+ <input ref={inputRef} aria-label={label} defaultValue="保留" />
+ <button
+ type="button"
+ onMouseDown={(event) => event.preventDefault()}
+ onClick={() => navigate('/settings/replies')}
+ >
+ open-settings-from-{kind}
+ </button>
+ </div>
+ ) : null}
+ </>
+ );
+};
+
const ChatProbe = () => {
const location = useLocation();
const navigate = useNavigate();
@@ -65,6 +156,13 @@ const ChatProbe = () => {
{(location.state as { maintenance?: string } | null)?.maintenance ?? 'none'}
</div>
<button type="button" onClick={() => setCount((value) => value + 1)}>increment-chat</button>
+ <RetainedModalEditor />
+ <RetainedFocusOwner kind="explicit-modal" />
+ <RetainedFocusOwner kind="app-window" />
+ <RetainedFocusOwner kind="popover" />
+ <button type="button" onClick={() => navigate('/settings/replies')} onMouseDown={(event) => event.preventDefault()}>
+ open-settings-preserving-focus
+ </button>
<Link to="/settings/replies">open-settings</Link>
<Link to="/settings/diagnostics">open-diagnostics</Link>
<Link to="/doctor">open-legacy-settings</Link>
@@ -148,6 +246,11 @@ const RemountingHarness = () => {
return <Harness key={guardKey} desktop />;
};
+const settleDeferredFocus = async () => {
+ await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
+ await new Promise<void>((resolve) => window.requestAnimationFrame(() => resolve()));
+};
+
beforeEach(() => {
chatMounts = 0;
chatUnmounts = 0;
@@ -185,6 +288,129 @@ describe('SettingsOverlayRouteSurface', () => {
expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');
});
+ it('maintains only the retained origin through data-router scoped replacement', async () => {
+ const user = userEvent.setup();
+ const router = createMemoryRouter([{ path: '*', element: <Harness desktop /> }], {
+ initialEntries: [{ pathname: '/chat/ses_1', search: '?view=chat', hash: '#tail', state: { maintenance: 'pending' } }],
+ });
+ render(<RouterProvider router={router} />);
+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));
+ await waitFor(() => expect(screen.getByTestId('chat-maintenance').textContent).toBe('done'));
+ expect(router.state.location.pathname).toBe('/settings/replies');
+ expect(screen.queryByText('escaped-route')).toBeNull();
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+ expect(router.state.location.pathname).toBe('/chat/ses_1');
+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1?view=chat#tail');
+ 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(
+ <MemoryRouter initialEntries={['/chat/ses_1']}>
+ <RoutedHarness />
+ </MemoryRouter>,
+ );
+
+ await user.click(screen.getByRole('button', { name: 'open-retained-editor' }));
+ const editorInput = screen.getByRole('textbox', { name: 'retained editor input' });
+ expect(document.activeElement).toBe(editorInput);
+ editorInput.setSelectionRange(1, 2);
+ fireEvent.select(editorInput);
+ expect(editorInput.selectionStart).toBe(1);
+ expect(editorInput.selectionEnd).toBe(2);
+
+ // The mousedown guard models a retained modal's explicit Settings handoff:
+ // navigation changes the foreground route without making the shell button
+ // the editor's new owner of focus.
+ await user.click(screen.getByRole('button', { name: 'open-settings-from-editor' }));
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+
+ const resumedInput = await screen.findByRole('textbox', { name: 'retained editor input' });
+ expect(resumedInput).not.toBe(editorInput);
+ await settleDeferredFocus();
+ expect(document.activeElement).toBe(resumedInput);
+ expect((resumedInput as HTMLInputElement).selectionStart).toBe(1);
+ expect((resumedInput as HTMLInputElement).selectionEnd).toBe(2);
+ await user.keyboard('x');
+ expect((resumedInput as HTMLInputElement).value).toBe('保x');
+ expect(document.activeElement).toBe(resumedInput);
+ await user.keyboard('{End}续写🌱');
+ expect((resumedInput as HTMLInputElement).value).toBe('保x续写🌱');
+ });
+
+ it('keeps an explicit retained modal as the return-focus owner after its editor remounts', async () => {
+ const user = userEvent.setup();
+ render(
+ <MemoryRouter initialEntries={['/chat/ses_1']}>
+ <RoutedHarness />
+ </MemoryRouter>,
+ );
+
+ await user.click(screen.getByRole('button', { name: 'open-explicit-modal' }));
+ const editor = screen.getByRole('textbox', { name: 'retained explicit-modal input' });
+ expect(document.activeElement).toBe(editor);
+ await user.click(screen.getByRole('button', { name: 'open-settings-from-explicit-modal' }));
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+
+ const resumedEditor = await screen.findByRole('textbox', { name: 'retained explicit-modal input' });
+ await settleDeferredFocus();
+ expect(document.activeElement).toBe(resumedEditor);
+ });
+
+ it.each([
+ ['app-window', 'retained app-window input'],
+ ['popover', 'retained popover input'],
+ ] as const)('falls back from a retained non-modal %s instead of restoring its input', async (kind, inputName) => {
+ const user = userEvent.setup();
+ render(
+ <MemoryRouter initialEntries={['/chat/ses_1']}>
+ <RoutedHarness />
+ </MemoryRouter>,
+ );
+
+ await user.click(screen.getByRole('button', { name: `open-${kind}` }));
+ const input = screen.getByRole('textbox', { name: inputName });
+ expect(document.activeElement).toBe(input);
+ await user.click(screen.getByRole('button', { name: `open-settings-from-${kind}` }));
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+
+ await screen.findByRole('textbox', { name: inputName });
+ await waitFor(() => expect(document.activeElement).toBe(
+ screen.getByRole('link', { name: 'shell-settings' }),
+ ));
+ expect(document.activeElement).not.toBe(screen.getByRole('textbox', { name: inputName }));
+ });
+
+ it('does not let a stale close callback focus the old origin after Settings reopens', async () => {
+ const user = userEvent.setup();
+ render(
+ <MemoryRouter initialEntries={['/chat/ses_1']}>
+ <RoutedHarness />
+ </MemoryRouter>,
+ );
+
+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));
+ const queuedFrames: FrameRequestCallback[] = [];
+ const requestFrame = vi.spyOn(window, 'requestAnimationFrame').mockImplementation((callback) => {
+ queuedFrames.push(callback);
+ return queuedFrames.length;
+ });
+ const cancelFrame = vi.spyOn(window, 'cancelAnimationFrame').mockImplementation(() => undefined);
+
+ await user.click(screen.getByRole('button', { name: 'close-settings' }));
+ await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());
+ expect(requestFrame).toHaveBeenCalledTimes(1);
+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));
+ expect(cancelFrame).toHaveBeenCalledWith(1);
+
+ queuedFrames[0](performance.now());
+ expect(screen.getByRole('dialog', { name: 'nav.settings' }).contains(document.activeElement)).toBe(true);
+
+ requestFrame.mockRestore();
+ cancelFrame.mockRestore();
+ });
+
it('keeps the background route mounted across Settings navigation and close', async () => {
const user = userEvent.setup();
const view = render(
diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
index c75538872..07238d9ef 100644
--- a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx
@@ -1,4 +1,4 @@
-import { useCallback } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useRef } from 'react';
import type { ReactElement, ReactNode } from 'react';
import { resolvePath, Route, Routes, useLocation, useNavigate } from 'react-router-dom';
import type { Navigator } from 'react-router-dom';
@@ -21,6 +21,24 @@ type SettingsOverlayRouteSurfaceProps = {
fallbackElement: ReactElement;
};
+const isForegroundFocusOwner = (element: Element | null): element is HTMLElement => {
+ if (!(element instanceof HTMLElement) || !element.isConnected) return false;
+ if (element.closest('[data-settings-overlay], [inert], [aria-hidden="true"]')) return false;
+ // Retained modal owners can recreate their editor while Settings is open. A
+ // recreated input is the owner of the return focus, but it cannot be the
+ // frozen target because that DOM node did not exist when Settings opened.
+ // Radix's modal DialogContent intentionally exposes role=dialog and its
+ // open state, but does not emit aria-modal. AppWindow also uses role=dialog;
+ // its data-window-id keeps ordinary retained windows out of this branch.
+ if (element.closest(
+ '[role="dialog"][aria-modal="true"]:not([data-window-id]), '
+ + '[role="dialog"][data-state="open"][aria-labelledby]:not([data-window-id])',
+ )) {
+ return true;
+ }
+ return false;
+};
+
export const SettingsOverlayRouteSurface = ({
children,
fallbackElement,
@@ -30,6 +48,28 @@ export const SettingsOverlayRouteSurface = ({
const navigate = useNavigate();
const origin = useSettingsOverlayOrigin(location);
const settingsSurfaceOpen = isSettingsEntryPath(location.pathname) && origin !== null;
+ const lastFocusRef = useRef<HTMLElement | null>(null);
+ const returnFocusRef = useRef<HTMLElement | null>(null);
+ const settingsSurfaceOpenRef = useRef(settingsSurfaceOpen);
+ const locationRef = useRef(location);
+ const settingsVisitRef = useRef(0);
+ const focusFrameRef = useRef<number | null>(null);
+ useLayoutEffect(() => {
+ settingsSurfaceOpenRef.current = settingsSurfaceOpen;
+ locationRef.current = location;
+ }, [location, settingsSurfaceOpen]);
+ useEffect(() => {
+ const onFocusIn = (event: FocusEvent) => {
+ if (event.target instanceof HTMLElement && !event.target.closest('[data-settings-overlay]')) {
+ lastFocusRef.current = event.target;
+ }
+ };
+ document.addEventListener('focusin', onFocusIn);
+ return () => document.removeEventListener('focusin', onFocusIn);
+ }, []);
+ useEffect(() => () => {
+ if (focusFrameRef.current !== null) window.cancelAnimationFrame(focusFrameRef.current);
+ }, []);
// The route this surface renders behind any overlay — the retained origin
// while Settings is open, the foreground route otherwise.
const backgroundLocation = settingsSurfaceOpen ? origin.location : location;
@@ -58,7 +98,7 @@ export const SettingsOverlayRouteSurface = ({
return (
<>
<div
- className="contents"
+ className={settingsSurfaceOpen ? 'hidden' : 'contents'}
aria-hidden={settingsSurfaceOpen || undefined}
inert={settingsSurfaceOpen || undefined}
>
@@ -83,36 +123,56 @@ export const SettingsOverlayRouteSurface = ({
<SettingsOverlayOriginContext.Provider value={origin}>
<DialogSurfaceContent
data-settings-overlay="true"
- // The overlay covers the work area and stops at the shell sidebar,
- // which is what keeps the origin project/session visible behind it.
- // This overrides the primitive's historical 240 default with the
- // sidebar's own live width: the dialog is portaled outside the
- // shell's subtree, so that document-level custom property is what
- // keeps the two edges together while the sidebar is being dragged.
- //
- // Below md the surface is the whole viewport, so the primitive's
- // left border would draw a hairline down the screen edge and make
- // Settings-from-home look different from a direct Settings link.
- // There is no sidebar to divide from until the offset applies.
- className="border-l-0 md:left-[var(--app-sidebar-w)] md:border-l"
+ // 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"
aria-describedby={undefined}
onInteractOutside={(event) => {
const target = event.target;
if (
target instanceof Element
- // The toggle closes the overlay itself, and the sidebar's
- // resize edge is not a dismissal at all: it moves this
- // surface's own left edge, so grabbing it must not close what
- // the drag is laying out.
- && target.closest('[data-settings-toggle="true"], [data-sidebar-resizer="true"]')
+ && target.closest('[data-settings-toggle="true"]')
) {
event.preventDefault();
}
}}
+ onOpenAutoFocus={() => {
+ if (focusFrameRef.current !== null) {
+ window.cancelAnimationFrame(focusFrameRef.current);
+ focusFrameRef.current = null;
+ }
+ settingsVisitRef.current += 1;
+ // Freeze the origin focus for this visit. Retained app windows
+ // may focus themselves on return, before Radix's deferred close
+ // callback runs; that must not replace the initiating control.
+ returnFocusRef.current = lastFocusRef.current;
+ }}
onCloseAutoFocus={(event) => {
event.preventDefault();
- window.requestAnimationFrame(() => {
- document.querySelector<HTMLElement>('[data-settings-toggle="true"]')?.focus();
+ const visit = settingsVisitRef.current;
+ const expectedOrigin = origin;
+ const target = returnFocusRef.current;
+ focusFrameRef.current = window.requestAnimationFrame(() => {
+ focusFrameRef.current = null;
+ // A close callback may outlive a rapid Settings reopen or a
+ // route change. Its old focus decision must not cross either
+ // boundary and land in the new foreground surface.
+ if (
+ settingsSurfaceOpenRef.current
+ || settingsVisitRef.current !== visit
+ || expectedOrigin === null
+ || locationPath(locationRef.current) !== locationPath(expectedOrigin.location)
+ ) return;
+ if (target?.isConnected && !target.closest('[inert]')) {
+ target.focus({ preventScroll: true });
+ return;
+ }
+ if (isForegroundFocusOwner(document.activeElement)) return;
+ const fallback = Array.from(
+ document.querySelectorAll<HTMLElement>('[data-settings-toggle="true"]'),
+ ).find((candidate) => !candidate.closest('[inert]'));
+ fallback?.focus({ preventScroll: true });
});
}}
>
diff --git a/ui/src/components/ui/button-variants.ts b/ui/src/components/ui/button-variants.ts
index 2427e3aba..5f080126b 100644
--- a/ui/src/components/ui/button-variants.ts
+++ b/ui/src/components/ui/button-variants.ts
@@ -34,8 +34,11 @@ export const buttonVariants = cva(
// codebase has no `light:`/`dark:` Tailwind variant, so a per-theme value is
// always a CSS variable. design.pen has no glow on any Button, so the value is
// ours to hold, not the design's; keep the four in lockstep.
+ // Solid mint buttons use the semantic primary pair. This keeps the
+ // foreground contract owned by the theme (`--primary-foreground`) in
+ // both modes instead of coupling the variant to the palette alias.
brand:
- 'gap-2 bg-mint font-bold text-primary-foreground shadow-glow-cta-mint hover:bg-mint-hover disabled:shadow-none',
+ 'gap-2 bg-primary font-bold text-primary-foreground shadow-glow-cta-mint hover:bg-primary-hover disabled:shadow-none',
'brand-cyan':
'gap-2 bg-cyan font-bold text-accent-foreground shadow-glow-cta-cyan hover:bg-cyan-hover disabled:shadow-none',
'brand-gold':
diff --git a/ui/src/components/ui/context-menu.test.tsx b/ui/src/components/ui/context-menu.test.tsx
index d245843ee..289d5eafb 100644
--- a/ui/src/components/ui/context-menu.test.tsx
+++ b/ui/src/components/ui/context-menu.test.tsx
@@ -1,8 +1,9 @@
/* @vitest-environment jsdom */
-import { act, cleanup, render } from '@testing-library/react';
+import { act, cleanup, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
import { ContextMenu } from './context-menu';
afterEach(cleanup);
@@ -22,4 +23,40 @@ describe('ContextMenu', () => {
expect(onClose).toHaveBeenCalledTimes(1);
expect(event.defaultPrevented).toBe(true);
});
+
+ it('withdraws while inactive without closing the owner state', () => {
+ const onClose = vi.fn();
+ const view = render(
+ <RouteSurfaceActiveContext.Provider value>
+ <ContextMenu x={0} y={0} onClose={onClose}>
+ <button type="button">Menu item</button>
+ </ContextMenu>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+
+ expect(screen.getByRole('menu')).toBeTruthy();
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value={false}>
+ <ContextMenu x={0} y={0} onClose={onClose}>
+ <button type="button">Menu item</button>
+ </ContextMenu>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+
+ const event = new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true });
+ act(() => window.dispatchEvent(event));
+
+ expect(screen.queryByRole('menu')).toBeNull();
+ expect(onClose).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value>
+ <ContextMenu x={0} y={0} onClose={onClose}>
+ <button type="button">Menu item</button>
+ </ContextMenu>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.getByRole('menu')).toBeTruthy();
+ });
});
diff --git a/ui/src/components/ui/context-menu.tsx b/ui/src/components/ui/context-menu.tsx
index c6a19f739..3a27f21ec 100644
--- a/ui/src/components/ui/context-menu.tsx
+++ b/ui/src/components/ui/context-menu.tsx
@@ -1,6 +1,8 @@
import { useEffect } from 'react';
import clsx from 'clsx';
+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
+
// A cursor-positioned right-click menu, shared by the editor's file tree and the File Browser app.
// Rendered inline (not portaled) so it inherits the surrounding window's theme scope, exactly like
// the original FileTree menu it was extracted from. A full-viewport backdrop closes it on any click
@@ -43,7 +45,10 @@ export const ContextMenu: React.FC<{
/** Number of items, used to estimate height for vertical viewport clamping. */
itemCount?: number;
}> = ({ x, y, onClose, children, width = 196, itemCount = 4 }) => {
+ const active = useRouteSurfaceActive();
+
useEffect(() => {
+ if (!active) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
e.preventDefault();
@@ -52,7 +57,12 @@ export const ContextMenu: React.FC<{
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
- }, [onClose]);
+ }, [active, onClose]);
+
+ // The owner keeps its selected item and can render the menu again when its
+ // route returns to the foreground. Suspension withdraws this inline surface
+ // without asking the owner to close or discard that state.
+ if (!active) return null;
// Clamp inside the viewport: a cursor near the right/bottom edge would otherwise overflow. The
// height is an estimate (item count × row height + padding) — good enough to nudge it back in.
diff --git a/ui/src/components/ui/dialog.test.tsx b/ui/src/components/ui/dialog.test.tsx
index 4e9d90421..4d323d77f 100644
--- a/ui/src/components/ui/dialog.test.tsx
+++ b/ui/src/components/ui/dialog.test.tsx
@@ -1,8 +1,9 @@
/* @vitest-environment jsdom */
-import { cleanup, render, screen } from '@testing-library/react';
-import { afterEach, describe, expect, it } from 'vitest';
+import { act, cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
import { Dialog, DialogContent, DialogTitle } from './dialog';
afterEach(cleanup);
@@ -22,4 +23,43 @@ describe('DialogContent mobile sheet', () => {
expect(dialog.className).toContain('max-md:data-[state=open]:slide-in-from-bottom');
expect(dialog.className).toContain('max-md:data-[state=closed]:slide-out-to-bottom');
});
+
+ it('withdraws inactive content without changing the owner open state', () => {
+ const onOpenChange = vi.fn();
+ const view = render(
+ <RouteSurfaceActiveContext.Provider value>
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle>Preview</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.getByRole('dialog')).toBeTruthy();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value={false}>
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle>Preview</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ act(() => undefined);
+
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value>
+ <Dialog open onOpenChange={onOpenChange}>
+ <DialogContent aria-describedby={undefined}>
+ <DialogTitle>Preview</DialogTitle>
+ </DialogContent>
+ </Dialog>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ });
});
diff --git a/ui/src/components/ui/dialog.tsx b/ui/src/components/ui/dialog.tsx
index 3735ada9a..bfbade9cf 100644
--- a/ui/src/components/ui/dialog.tsx
+++ b/ui/src/components/ui/dialog.tsx
@@ -3,6 +3,8 @@ import * as DialogPrimitive from '@radix-ui/react-dialog';
import { X } from 'lucide-react';
import { cn } from '@/lib/utils';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
+import { useLatestRef } from '@/lib/useLatestRef';
export const Dialog = DialogPrimitive.Root;
export const DialogTrigger = DialogPrimitive.Trigger;
@@ -34,34 +36,45 @@ type DialogContentProps = React.ComponentPropsWithoutRef<typeof DialogPrimitive.
export const DialogContent = React.forwardRef<
React.ComponentRef<typeof DialogPrimitive.Content>,
DialogContentProps
->(({ className, children, mobileSheetHeight = 'content', closeLabel = 'Close', ...props }, ref) => (
- <DialogPortal>
- <DialogOverlay />
- <DialogPrimitive.Content
- ref={ref}
- className={cn(
- // Desktop: centered modal. Mobile (max-md): a bottom sheet — full-width,
- // slides up from the bottom edge, rounded top + drag handle, capped height
- // with internal scroll and a safe-area bottom inset. A caller's custom
- // max-w (e.g. max-w-sm) still applies on desktop; max-md:max-w-none forces
- // the full-width sheet on phones. Content-heavy callers can opt into a
- // resolved 90dvh height without re-declaring the shared sheet behavior.
- 'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95 max-md:left-0 max-md:right-0 max-md:top-auto max-md:bottom-0 max-md:w-full max-md:max-w-none max-md:max-h-[90dvh] max-md:translate-x-0 max-md:translate-y-0 max-md:rounded-2xl max-md:rounded-b-none max-md:p-5 max-md:pb-[calc(1.5rem+env(safe-area-inset-bottom))] max-md:data-[state=open]:zoom-in-100 max-md:data-[state=closed]:zoom-out-100 max-md:data-[state=open]:slide-in-from-bottom max-md:data-[state=closed]:slide-out-to-bottom max-md:data-[state=open]:duration-300 max-md:data-[state=closed]:duration-200',
- mobileSheetHeight === 'tall' && 'max-md:h-[90dvh]',
- className
- )}
- {...props}
- >
- {/* Bottom-sheet drag handle — mobile only. */}
- <div className="mx-auto h-1.5 w-10 shrink-0 rounded-full bg-border-strong md:hidden" aria-hidden />
- {children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-md p-1 text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring">
- <X className="size-4" />
- <span className="sr-only">{closeLabel}</span>
- </DialogPrimitive.Close>
- </DialogPrimitive.Content>
- </DialogPortal>
-));
+>(({ className, children, mobileSheetHeight = 'content', closeLabel = 'Close', onCloseAutoFocus, ...props }, ref) => {
+ const active = useRouteSurfaceActive();
+ const activeRef = useLatestRef(active);
+ if (!active) return null;
+ return (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ // Desktop: centered modal. Mobile (max-md): a bottom sheet — full-width,
+ // slides up from the bottom edge, rounded top + drag handle, capped height
+ // with internal scroll and a safe-area bottom inset. A caller's custom
+ // max-w (e.g. max-w-sm) still applies on desktop; max-md:max-w-none forces
+ // the full-width sheet on phones. Content-heavy callers can opt into a
+ // resolved 90dvh height without re-declaring the shared sheet behavior.
+ 'fixed left-1/2 top-1/2 z-50 grid w-full max-w-lg max-h-[calc(100dvh-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95 max-md:left-0 max-md:right-0 max-md:top-auto max-md:bottom-0 max-md:w-full max-md:max-w-none max-md:max-h-[90dvh] max-md:translate-x-0 max-md:translate-y-0 max-md:rounded-2xl max-md:rounded-b-none max-md:p-5 max-md:pb-[calc(1.5rem+env(safe-area-inset-bottom))] max-md:data-[state=open]:zoom-in-100 max-md:data-[state=closed]:zoom-out-100 max-md:data-[state=open]:slide-in-from-bottom max-md:data-[state=closed]:slide-out-to-bottom max-md:data-[state=open]:duration-300 max-md:data-[state=closed]:duration-200',
+ mobileSheetHeight === 'tall' && 'max-md:h-[90dvh]',
+ className
+ )}
+ {...props}
+ onCloseAutoFocus={(event) => {
+ // Suspension is not a user close. Do not run owner close effects or
+ // return focus into the inactive surface from Radix's delayed cleanup.
+ if (!activeRef.current) event.preventDefault();
+ else onCloseAutoFocus?.(event);
+ }}
+ >
+ {/* Bottom-sheet drag handle — mobile only. */}
+ <div className="mx-auto h-1.5 w-10 shrink-0 rounded-full bg-border-strong md:hidden" aria-hidden />
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-md p-1 text-muted opacity-70 transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring">
+ <X className="size-4" />
+ <span className="sr-only">{closeLabel}</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+ );
+});
DialogContent.displayName = DialogPrimitive.Content.displayName;
// Route-sized modal: the transparent backdrop preserves visual context while Radix owns focus,
diff --git a/ui/src/components/ui/image-viewer.test.tsx b/ui/src/components/ui/image-viewer.test.tsx
index c3dbe743e..f74e86daf 100644
--- a/ui/src/components/ui/image-viewer.test.tsx
+++ b/ui/src/components/ui/image-viewer.test.tsx
@@ -5,11 +5,13 @@
// it when they arrive there, which happens on every flush. So "on its own" is a
// property of the open call, and these tests are what make it one.
-import { cleanup, fireEvent, render, screen } from '@testing-library/react';
+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { createInstance } from 'i18next';
import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RouteSurfaceActivityBoundary } from '../RouteSurfaceActivityBoundary';
import en from '../../i18n/en.json';
import { ImageViewerProvider } from './image-viewer';
import { useImageViewer, type ImageViewerOpenOptions } from './image-viewer-context';
@@ -48,6 +50,16 @@ const paging = () => ({
counter: screen.queryByText('1 / 3'),
});
+const transformScale = (element: Element | null): number => {
+ if (!(element instanceof HTMLElement)) return 1;
+ const inline = element.getAttribute('style') ?? '';
+ const inlineScale = inline.match(/scale\(([-+]?\d*\.?\d+)\)/)?.[1];
+ if (inlineScale) return Number(inlineScale);
+ const transform = window.getComputedStyle(element).transform;
+ const matrix = transform.match(/^matrix\(([^)]+)\)$/)?.[1]?.split(',').map(Number);
+ return matrix && matrix.length >= 2 ? Math.hypot(matrix[0], matrix[1]) : 1;
+};
+
// The zoom stage observes its own box; jsdom has no layout to report.
beforeEach(() => {
vi.stubGlobal('ResizeObserver', class { observe() {} unobserve() {} disconnect() {} });
@@ -118,3 +130,99 @@ describe('ImageViewerProvider — paging belongs to the gallery, not to every im
expect(screen.queryByRole('dialog')).toBeNull();
});
});
+
+describe('ImageViewerProvider — retained route activity owns global keys', () => {
+ const retained = (active: boolean, options?: ImageViewerOpenOptions) => (
+ <I18nextProvider i18n={i18n}>
+ <MemoryRouter>
+ <RouteSurfaceActivityBoundary active={active}>
+ <div hidden={!active} inert={!active || undefined} aria-hidden={!active || undefined}>
+ <ImageViewerProvider images={GALLERY}>
+ <Opener src={GALLERY[0]} options={options} />
+ </ImageViewerProvider>
+ </div>
+ </RouteSurfaceActivityBoundary>
+ </MemoryRouter>
+ </I18nextProvider>
+ );
+
+ it.each(['Escape', 'ArrowLeft', 'ArrowRight'] as const)(
+ 'passes hidden %s to the foreground while retaining the open image',
+ (key) => {
+ const view = render(retained(true));
+ fireEvent.click(screen.getByText('open'));
+ const image = document.querySelector('img');
+ expect(image?.getAttribute('src')).toBe(GALLERY[0]);
+
+ view.rerender(retained(false));
+ const foreground = vi.fn();
+ window.addEventListener('keydown', foreground);
+ try {
+ fireEvent.keyDown(window, { key });
+ expect(foreground).toHaveBeenCalledTimes(1);
+ expect(document.querySelector('img')).toBe(image);
+ expect(document.querySelector('img')?.getAttribute('src')).toBe(GALLERY[0]);
+ expect(document.querySelector('[role="dialog"]')).not.toBeNull();
+ } finally {
+ window.removeEventListener('keydown', foreground);
+ }
+ },
+ );
+
+ it('restores foreground capture after repeated suspension without replacing the viewer instance', () => {
+ const view = render(retained(true));
+ fireEvent.click(screen.getByText('open'));
+ const image = document.querySelector('img');
+ expect(image).not.toBeNull();
+
+ for (let cycle = 0; cycle < 2; cycle += 1) {
+ view.rerender(retained(false));
+ view.rerender(retained(true));
+ }
+ expect(document.querySelector('img')).toBe(image);
+ fireEvent.keyDown(window, { key: 'ArrowRight' });
+ expect(document.querySelector('img')?.getAttribute('src')).toBe(GALLERY[1]);
+
+ const recordingAbort = vi.fn();
+ window.addEventListener('keydown', recordingAbort);
+ try {
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(recordingAbort).not.toHaveBeenCalled();
+ expect(screen.queryByRole('dialog')).toBeNull();
+ } finally {
+ window.removeEventListener('keydown', recordingAbort);
+ }
+ });
+
+ it('retains the zoom transform across suspension and resume', async () => {
+ const view = render(retained(true));
+ fireEvent.click(screen.getByText('open'));
+ const image = document.querySelector('img');
+ const transform = document.querySelector('.react-transform-component');
+ expect(image).not.toBeNull();
+ expect(transform).not.toBeNull();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Zoom in' }));
+ await waitFor(() => expect(transformScale(transform)).toBeGreaterThan(1));
+ const zoomedScale = transformScale(transform);
+
+ view.rerender(retained(false));
+ view.rerender(retained(true));
+ expect(document.querySelector('img')).toBe(image);
+ expect(transformScale(document.querySelector('.react-transform-component'))).toBeCloseTo(zoomedScale);
+ });
+
+ it('keeps isolated image semantics after returning to the foreground', () => {
+ const view = render(retained(true, { isolated: true }));
+ fireEvent.click(screen.getByText('open'));
+ view.rerender(retained(false, { isolated: true }));
+ view.rerender(retained(true, { isolated: true }));
+
+ expect(screen.getByRole('dialog')).toBeTruthy();
+ expect(screen.queryByLabelText('Next')).toBeNull();
+ expect(screen.queryByLabelText('Previous')).toBeNull();
+ expect(document.querySelector('img')?.getAttribute('src')).toBe(GALLERY[0]);
+ fireEvent.keyDown(window, { key: 'ArrowRight' });
+ expect(document.querySelector('img')?.getAttribute('src')).toBe(GALLERY[0]);
+ });
+});
diff --git a/ui/src/components/ui/image-viewer.tsx b/ui/src/components/ui/image-viewer.tsx
index f745c0ef6..bda4bee41 100644
--- a/ui/src/components/ui/image-viewer.tsx
+++ b/ui/src/components/ui/image-viewer.tsx
@@ -5,6 +5,7 @@ import { TransformWrapper, TransformComponent, type ReactZoomPanPinchRef } from
import { Button } from '@/components/ui/button';
import { handleMediaDownloadClick, mediaDownloadHref } from '@/lib/downloadMedia';
+import { useRouteSurfaceWindowEvent } from '@/lib/routeSurfaceActivity';
import { ImageViewerContext, type ImageViewerOpenOptions } from './image-viewer-context';
// A session-scoped image lightbox. ChatPage computes the ordered list of media-
@@ -73,15 +74,15 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R
[index, images],
);
- React.useEffect(() => {
- if (src === null) return;
- // The lightbox is a modal: while open it OWNS Escape / arrows. Listen in the
- // capture phase and stop immediate propagation on the keys we handle so a
- // lower global handler (notably the Composer's "Escape aborts recording")
- // can't also fire — Escape here must only close the viewer, not discard an
- // in-progress voice recording. Capture runs before any bubble-phase window
- // listener regardless of registration order, so ownership is deterministic.
- const onKey = (e: KeyboardEvent) => {
+ // The lightbox is a modal while its route surface is foreground: it OWNS
+ // Escape / arrows. The activity-aware owner withdraws this capture listener
+ // while the retained Chat route is hidden under Settings, but keeps `view`
+ // and the rendered instance mounted for the return. Capture and immediate
+ // propagation preserve the modal's ownership over lower global handlers
+ // (notably the Composer's "Escape aborts recording" shortcut).
+ useRouteSurfaceWindowEvent(
+ 'keydown',
+ (e) => {
if (e.key === 'Escape') {
e.stopImmediatePropagation();
close();
@@ -92,10 +93,10 @@ export const ImageViewerProvider: React.FC<{ images: string[]; children: React.R
e.stopImmediatePropagation();
step(1);
}
- };
- window.addEventListener('keydown', onKey, { capture: true });
- return () => window.removeEventListener('keydown', onKey, { capture: true });
- }, [src, close, step]);
+ },
+ src !== null,
+ true,
+ );
const ctx = React.useMemo(() => ({ open }), [open]);
diff --git a/ui/src/components/ui/popover.test.tsx b/ui/src/components/ui/popover.test.tsx
new file mode 100644
index 000000000..46fca92e5
--- /dev/null
+++ b/ui/src/components/ui/popover.test.tsx
@@ -0,0 +1,43 @@
+/* @vitest-environment jsdom */
+
+import { cleanup, render, screen } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { RouteSurfaceActiveContext } from '../../lib/routeSurfaceActivity';
+import { Popover, PopoverContent } from './popover';
+
+afterEach(cleanup);
+
+describe('PopoverContent', () => {
+ it('withdraws inactive content without changing the owner open state', () => {
+ const onOpenChange = vi.fn();
+ const view = render(
+ <RouteSurfaceActiveContext.Provider value>
+ <Popover open onOpenChange={onOpenChange}>
+ <PopoverContent>Menu content</PopoverContent>
+ </Popover>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.getByText('Menu content')).toBeTruthy();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value={false}>
+ <Popover open onOpenChange={onOpenChange}>
+ <PopoverContent>Menu content</PopoverContent>
+ </Popover>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+
+ expect(screen.queryByText('Menu content')).toBeNull();
+ expect(onOpenChange).not.toHaveBeenCalled();
+
+ view.rerender(
+ <RouteSurfaceActiveContext.Provider value>
+ <Popover open onOpenChange={onOpenChange}>
+ <PopoverContent>Menu content</PopoverContent>
+ </Popover>
+ </RouteSurfaceActiveContext.Provider>,
+ );
+ expect(screen.getByText('Menu content')).toBeTruthy();
+ });
+});
diff --git a/ui/src/components/ui/popover.tsx b/ui/src/components/ui/popover.tsx
index d51ca2983..eb7faa0d9 100644
--- a/ui/src/components/ui/popover.tsx
+++ b/ui/src/components/ui/popover.tsx
@@ -1,31 +1,40 @@
-import * as React from "react"
-import * as PopoverPrimitive from "@radix-ui/react-popover"
+import * as React from 'react';
+import * as PopoverPrimitive from '@radix-ui/react-popover';
-import { cn } from "../../lib/utils"
+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
+import { useLatestRef } from '../../lib/useLatestRef';
+import { cn } from '../../lib/utils';
-const Popover = PopoverPrimitive.Root
-
-const PopoverTrigger = PopoverPrimitive.Trigger
-
-const PopoverAnchor = PopoverPrimitive.Anchor
+const Popover = PopoverPrimitive.Root;
+const PopoverTrigger = PopoverPrimitive.Trigger;
+const PopoverAnchor = PopoverPrimitive.Anchor;
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
->(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
- <PopoverPrimitive.Portal>
- <PopoverPrimitive.Content
- ref={ref}
- align={align}
- sideOffset={sideOffset}
- className={cn(
- "z-50 w-72 rounded-md border border-border bg-panel p-4 text-text shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- className
- )}
- {...props}
- />
- </PopoverPrimitive.Portal>
-))
-PopoverContent.displayName = PopoverPrimitive.Content.displayName
+>(({ className, align = 'center', sideOffset = 4, onCloseAutoFocus, ...props }, ref) => {
+ const active = useRouteSurfaceActive();
+ const activeRef = useLatestRef(active);
+ if (!active) return null;
+ return (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ 'z-50 w-72 rounded-md border border-border bg-panel p-4 text-text shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2',
+ className,
+ )}
+ {...props}
+ onCloseAutoFocus={(event) => {
+ if (!activeRef.current) event.preventDefault();
+ else onCloseAutoFocus?.(event);
+ }}
+ />
+ </PopoverPrimitive.Portal>
+ );
+});
+PopoverContent.displayName = PopoverPrimitive.Content.displayName;
-export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }
+export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor };
diff --git a/ui/src/components/workbench/ProjectDefaultFolder.test.tsx b/ui/src/components/workbench/ProjectDefaultFolder.test.tsx
index 63d7a6e91..0dcf48279 100644
--- a/ui/src/components/workbench/ProjectDefaultFolder.test.tsx
+++ b/ui/src/components/workbench/ProjectDefaultFolder.test.tsx
@@ -19,7 +19,7 @@ vi.mock('../../context/WorkbenchProjectsContext', () => ({
vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => null }));
vi.mock('../../context/StandaloneAppTabContext', () => ({ useStandaloneAppTab: () => false }));
vi.mock('../../lib/useIsDesktop', () => ({ useIsDesktop: () => true, isDesktopViewport: () => true }));
-vi.mock('../../lib/routeSurfaceActivity', () => ({ useRouteSurfaceWindowEvent: () => {} }));
+vi.mock('../../lib/routeSurfaceActivity', () => ({ useRouteSurfaceWindowEvent: () => {}, useRouteSurfaceActive: () => true }));
vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock('../../lib/filesApi', async (importOriginal) => ({
...await importOriginal<typeof import('../../lib/filesApi')>(),
diff --git a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx
index 907aa317a..49c6782e1 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.inbox.test.tsx
@@ -5,6 +5,8 @@ import { cleanup, render, screen } from '@testing-library/react';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { MemoryRouter } from 'react-router-dom';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { RouteSurfaceActivityBoundary } from '../RouteSurfaceActivityBoundary';
+import { tabModifierLabel } from '../../apps/appLaunch';
const inbox = vi.hoisted(() => ({
totalUnread: 0,
@@ -13,8 +15,17 @@ const inbox = vi.hoisted(() => ({
unreadBySession: {} as Record<string, number>,
markRead: vi.fn(),
}));
+const hookCalls = vi.hoisted(() => ({
+ inbox: vi.fn(),
+ tree: vi.fn(),
+}));
-vi.mock('../../context/WorkbenchInboxContext', () => ({ useWorkbenchInbox: () => inbox }));
+vi.mock('../../context/WorkbenchInboxContext', () => ({
+ useWorkbenchInbox: (options?: { feed?: boolean }) => {
+ hookCalls.inbox(options);
+ return inbox;
+ },
+}));
vi.mock('../../context/InstanceAuthorizationContext', () => ({
useInstanceAuthorization: () => ({
capabilities: {
@@ -27,20 +38,23 @@ vi.mock('../../context/InstanceAuthorizationContext', () => ({
}),
}));
vi.mock('../../context/WorkbenchProjectsContext', () => ({
- useWorkbenchProjectsTree: () => ({
- projects: [],
- projectsError: null,
- sessionsOf: () => [],
- isExpanded: () => false,
- toggleExpanded: vi.fn(),
- loadMore: vi.fn(),
- creatingSession: null,
- createSessionForProject: vi.fn(),
- renameProject: vi.fn(),
- archiveProject: vi.fn(),
- reorderProjects: vi.fn(),
- isReorderingProjects: false,
- }),
+ useWorkbenchProjectsTree: (options?: { active?: boolean }) => {
+ hookCalls.tree(options);
+ return {
+ projects: [],
+ projectsError: null,
+ sessionsOf: () => [],
+ isExpanded: () => false,
+ toggleExpanded: vi.fn(),
+ loadMore: vi.fn(),
+ creatingSession: null,
+ createSessionForProject: vi.fn(),
+ renameProject: vi.fn(),
+ archiveProject: vi.fn(),
+ reorderProjects: vi.fn(),
+ isReorderingProjects: false,
+ };
+ },
useWorkbenchProjectsActions: () => ({}),
}));
vi.mock('../../context/WindowManagerContext', () => ({ useWindowManager: () => ({ open: vi.fn() }) }));
@@ -59,10 +73,12 @@ void i18n.use(initReactI18next).init({
interpolation: { escapeValue: false },
});
-const renderSidebar = () => render(
+const renderSidebar = (active = true) => render(
<I18nextProvider i18n={i18n}>
<MemoryRouter initialEntries={['/']}>
- <WorkbenchSidebar />
+ <RouteSurfaceActivityBoundary active={active}>
+ <WorkbenchSidebar />
+ </RouteSurfaceActivityBoundary>
</MemoryRouter>
</I18nextProvider>,
);
@@ -74,6 +90,8 @@ beforeEach(() => {
inbox.unreadSessions = 0;
inbox.inboxSessions = [];
inbox.unreadBySession = {};
+ hookCalls.inbox.mockClear();
+ hookCalls.tree.mockClear();
});
afterEach(() => {
@@ -87,7 +105,7 @@ describe('Workbench sidebar inbox counter', () => {
const link = screen.getByRole('link', { name: en.workbench.nav.inbox });
// A zero badge is still a badge — an empty inbox draws no attention at all.
- expect(link.textContent).toBe('');
+ expect(link.textContent).toBe(en.workbench.nav.inbox);
expect(inboxIcon().getAttribute('class')).toContain('text-muted');
expect(inboxIcon().getAttribute('class')).not.toContain('text-cyan-ink');
});
@@ -98,7 +116,7 @@ describe('Workbench sidebar inbox counter', () => {
inbox.unreadBySession = { ses_a: 4, ses_b: 3 };
renderSidebar();
- expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe('7');
+ expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe(`${en.workbench.nav.inbox}7`);
expect(inboxIcon().getAttribute('class')).toContain('text-cyan-ink');
});
@@ -106,6 +124,19 @@ describe('Workbench sidebar inbox counter', () => {
inbox.totalUnread = 150;
renderSidebar();
- expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe('99+');
+ expect(screen.getByRole('link', { name: en.workbench.nav.inbox }).textContent).toBe(`${en.workbench.nav.inbox}99+`);
+ });
+
+ it('shows the platform-appropriate search shortcut', () => {
+ renderSidebar();
+
+ expect(screen.getByText(`${tabModifierLabel()}K`)).toBeTruthy();
+ });
+
+ it('withdraws feed and tree activation while the retained sidebar is hidden', () => {
+ renderSidebar(false);
+
+ expect(hookCalls.inbox).toHaveBeenCalledWith({ feed: false });
+ expect(hookCalls.tree).toHaveBeenCalledWith({ active: false });
});
});
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index 78b7f689c..c82744159 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -22,12 +22,15 @@ import {
Plus,
Search,
Settings2,
- SquarePen,
WandSparkles,
} from 'lucide-react';
import clsx from 'clsx';
import type { LucideIcon } from 'lucide-react';
+import { useRouteSurfaceActive } from '../../lib/routeSurfaceActivity';
+import { useLatestRef } from '../../lib/useLatestRef';
+import { tabModifierLabel } from '../../apps/appLaunch';
+
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsActions, useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';
@@ -266,6 +269,7 @@ export const SessionRow: React.FC<{
const [menuOpen, setMenuOpen] = useState(false);
const [renaming, setRenaming] = useState(false);
const [draft, setDraft] = useState(session.title ?? '');
+ const surfaceActiveRef = useLatestRef(useRouteSurfaceActive());
const inputRef = useRef<HTMLInputElement | null>(null);
// Guards a double commit: Enter (or click-away) commits, then the input
// unmounts and its onBlur would fire commitRename again; Escape cancels and
@@ -298,6 +302,8 @@ export const SessionRow: React.FC<{
}, [renaming]);
const commitRename = async () => {
+ // Inerting the retained sidebar blurs its input; suspension is not a save.
+ if (!surfaceActiveRef.current) return;
if (handledRef.current) return;
handledRef.current = true;
const trimmed = draft.trim();
@@ -479,6 +485,7 @@ const ProjectRow: React.FC<{
const Chevron = expanded ? ChevronDown : ChevronRight;
const [renaming, setRenaming] = useState(false);
const [renameDraft, setRenameDraft] = useState(project.display_name);
+ const surfaceActiveRef = useLatestRef(useRouteSurfaceActive());
const [menuOpen, setMenuOpen] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [agentsMdOpen, setAgentsMdOpen] = useState(false);
@@ -489,6 +496,8 @@ const ProjectRow: React.FC<{
}, [renaming]);
const commitRename = async () => {
+ // Inerting the retained sidebar blurs its input; suspension is not a save.
+ if (!surfaceActiveRef.current) return;
const trimmed = renameDraft.trim();
if (!trimmed || trimmed === project.display_name) {
setRenaming(false);
@@ -709,6 +718,7 @@ const ProjectRow: React.FC<{
export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpenSearch }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const surfaceActive = useRouteSurfaceActive();
const authorizeRouteAction = useUnsavedChangesActionGuard();
const {
capabilities,
@@ -724,7 +734,9 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
if (to === '/vaults') return capabilities.can_use_vault_secrets;
return false;
});
- const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();
+ const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox({
+ feed: surfaceActive,
+ });
// Projects/sessions tree — shared with the mobile ProjectsPage via the provider
// (one EventSource + one cache, not a per-component reimplementation). The
// sidebar owns only its inbox popover + the New Project dialog trigger.
@@ -741,7 +753,7 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
archiveProject,
reorderProjects,
isReorderingProjects,
- } = useWorkbenchProjectsTree();
+ } = useWorkbenchProjectsTree({ active: surfaceActive });
const [popoverOpen, setPopoverOpen] = useState(false);
const closeTimer = useRef<number | null>(null);
const [showNewProject, setShowNewProject] = useState(false);
@@ -795,12 +807,13 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
// hover popover stays OUT of any overflow box below, so it is never clipped.
return (
<div className="flex min-h-0 flex-1 flex-col gap-4">
- {/* Brand row tLDP1 — identity on the left, Search and Inbox on the right.
- Search and Inbox are siblings of the home link, not nested inside it. */}
- <div className="flex shrink-0 items-center gap-2.5 py-2">
+ {/* Brand row tLDP1 — the whole brand opens the new-conversation home.
+ Search and Inbox live in full-width rows below it so the shell keeps one
+ clear reading order at every supported sidebar width. */}
+ <div className="flex shrink-0 items-center py-2">
<Link
to="/"
- className="group flex min-w-0 flex-1 items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"
+ className="group flex min-w-0 items-center gap-2.5 rounded-lg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-mint/60"
>
{/* Decorative: the link's accessible name is the localized brand text
beside it, so naming the image too would read the destination twice. */}
@@ -812,71 +825,69 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
/>
<div className="min-w-0 leading-tight">
<div className="truncate text-[13px] font-semibold text-foreground">{t('appShell.title')}</div>
- {/* tLDP1 labels this row "Workbench", not the full "Agent OS ·
- Workbench" the settings shell uses: at 248 with Search and Inbox
- beside it, the longer line only ever renders truncated. */}
- <div className="truncate text-[11px] text-muted">{t('workbench.eyebrow')}</div>
+ <div className="truncate text-[11px] text-muted">{t('appShell.subtitle')}</div>
</div>
</Link>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="size-8 shrink-0 rounded-lg text-muted hover:text-foreground"
- aria-label={t('workbench.search.entry')}
- onClick={onOpenSearch}
- >
- <Search className="size-[18px]" />
- </Button>
- {/* Inbox entry — hover opens the floating popover (portaled above the chat).
- At zero unread there is no badge node at all and the icon stays muted;
- both reads come from the same real counter. */}
- <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>
- <PopoverAnchor asChild>
- <div className="shrink-0" onMouseEnter={openPopover} onMouseLeave={queueClose}>
- <NavLink
- to="/inbox"
- aria-label={t('workbench.nav.inbox')}
- className="relative flex size-8 items-center justify-center rounded-lg transition-colors hover:bg-[var(--nav-hover-bg)]"
- >
- {({ isActive }) => (
- <>
- <Inbox
- className={clsx(
- 'size-[18px]',
- badge ? 'text-cyan-ink' : isActive ? 'text-foreground' : 'text-muted',
- )}
- />
- {badge && (
- <span className="absolute right-0.5 top-0.5 inline-flex min-w-[14px] items-center justify-center rounded-full border border-surface bg-cyan px-[3px] font-mono text-[9px] font-bold leading-[12px] text-primary-foreground">
- {badge}
- </span>
- )}
- </>
- )}
- </NavLink>
- </div>
- </PopoverAnchor>
- <InboxHoverPopover
- sessions={inboxSessions}
- unreadBySession={unreadBySession}
- unreadSessions={unreadSessions}
- totalUnread={totalUnread}
- canMarkRead={canChat}
- onItemClick={onItemClick}
- onMarkAllRead={onMarkAllRead}
- onMouseEnter={openPopover}
- onMouseLeave={queueClose}
- />
- </Popover>
</div>
- {/* Navigation m8K59 — one always-expanded group. "New chat" is the home
- itself, which is where a task is described and a session is created. */}
+ <Button
+ type="button"
+ variant="ghost"
+ className="h-9 w-full justify-start rounded-lg px-2.5 text-[13px] text-muted hover:text-foreground"
+ aria-label={t('workbench.search.entry')}
+ onClick={onOpenSearch}
+ >
+ <Search className="size-[17px]" />
+ <span>{t('workbench.search.entry')}</span>
+ <kbd className="ml-auto rounded border border-border-strong px-1.5 py-0.5 font-mono text-[10px] font-medium text-muted">{tabModifierLabel()}K</kbd>
+ </Button>
+
+ {/* Inbox entry — hover opens the floating popover (portaled above the chat).
+ At zero unread there is no badge node at all and the icon stays muted;
+ both reads come from the same real counter. */}
+ <Popover open={popoverOpen} onOpenChange={(open) => { if (!open) setPopoverOpen(false); }}>
+ <PopoverAnchor asChild>
+ <div className="w-full" onMouseEnter={openPopover} onMouseLeave={queueClose}>
+ <NavLink
+ to="/inbox"
+ aria-label={t('workbench.nav.inbox')}
+ className="relative flex h-9 w-full items-center gap-2.5 rounded-lg px-2.5 text-[13px] transition-colors hover:bg-[var(--nav-hover-bg)]"
+ >
+ {({ isActive }) => (
+ <>
+ <Inbox
+ className={clsx(
+ 'size-[17px]',
+ badge ? 'text-cyan-ink' : isActive ? 'text-foreground' : 'text-muted',
+ )}
+ />
+ <span className={clsx(isActive ? 'font-semibold text-foreground' : 'font-medium text-muted')}>{t('workbench.nav.inbox')}</span>
+ {badge && (
+ <span className="ml-auto inline-flex min-w-[18px] items-center justify-center rounded-full border border-surface bg-cyan px-[4px] font-mono text-[9px] font-bold leading-[14px] text-primary-foreground">
+ {badge}
+ </span>
+ )}
+ </>
+ )}
+ </NavLink>
+ </div>
+ </PopoverAnchor>
+ <InboxHoverPopover
+ sessions={inboxSessions}
+ unreadBySession={unreadBySession}
+ unreadSessions={unreadSessions}
+ totalUnread={totalUnread}
+ canMarkRead={canChat}
+ onItemClick={onItemClick}
+ onMarkAllRead={onMarkAllRead}
+ onMouseEnter={openPopover}
+ onMouseLeave={queueClose}
+ />
+ </Popover>
+
+ {/* Navigation m8K59 — the home brand is the new-conversation entry, so
+ capability destinations are the only rows in this group. */}
<nav className="flex shrink-0 flex-col gap-0.5">
- {canChat && (
- <SidebarNavRow to="/" end icon={SquarePen} label={t('workbench.nav.newChat')} />
- )}
{capabilityNav.map(({ to, i18nKey, icon }) => (
<SidebarNavRow key={to} to={to} icon={icon} label={t(i18nKey)} />
))}
diff --git a/ui/src/components/workbench/search/SearchPalette.test.tsx b/ui/src/components/workbench/search/SearchPalette.test.tsx
new file mode 100644
index 000000000..37c87d327
--- /dev/null
+++ b/ui/src/components/workbench/search/SearchPalette.test.tsx
@@ -0,0 +1,95 @@
+/* @vitest-environment jsdom */
+import { createInstance } from 'i18next';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import en from '../../../i18n/en.json';
+import { RouteSurfaceActivityBoundary } from '../../RouteSurfaceActivityBoundary';
+import { SearchPalette } from './SearchPalette';
+
+const api = vi.hoisted(() => ({ searchMessages: vi.fn(), connectWorkbenchEvents: vi.fn() }));
+const inventory = vi.hoisted(() => ({ demand: vi.fn() }));
+vi.mock('../../../context/ApiContext', () => ({ useApi: () => api }));
+vi.mock('../../useShowPages', async () => {
+ const { useEffect } = await import('react');
+ return { useShowPageInventory: () => {
+ useEffect(() => { inventory.demand(true); return () => inventory.demand(false); }, []);
+ return { pages: [], loading: false, loaded: true };
+ } };
+});
+vi.mock('../../../context/WindowManagerContext', () => ({ useWindowManager: () => ({ openApp: vi.fn() }) }));
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({ lng: 'en', resources: { en: { translation: en } }, interpolation: { escapeValue: false } });
+const results = { sessions: [{ session_id: 's1', title: 'Search fixture', project_name: '项目', archived: true,
+ matches: [1, 2].map((id) => ({ id: `m${id}`, snippet: { prefix: '', match: `星河结果${id}`, suffix: '' }, author: 'user', type: 'user', source: 'user', created_at: '2026-09-19T00:00:00Z' })) }] };
+const queryInput = () => screen.getByRole('textbox') as HTMLInputElement;
+const selected = () => document.querySelector('[aria-current="true"]')?.textContent;
+const view = (active: boolean, open: boolean, close: () => void) => <I18nextProvider i18n={i18n}>
+ <MemoryRouter><RouteSurfaceActivityBoundary active={active}>
+ <SearchPalette open={open} onClose={close} />
+ </RouteSurfaceActivityBoundary></MemoryRouter>
+</I18nextProvider>;
+beforeEach(() => {
+ vi.clearAllMocks();
+ api.searchMessages.mockResolvedValue(results);
+ api.connectWorkbenchEvents.mockImplementation(() => vi.fn());
+ Element.prototype.scrollIntoView = vi.fn();
+});
+afterEach(cleanup);
+
+describe('SearchPalette owner and presentation lifetime', () => {
+ it('retains Unicode, archived opt-in and a nonfirst result across repeated suspension; true close starts fresh', async () => {
+ const close = vi.fn();
+ const rendered = render(view(true, true, close));
+ fireEvent.change(queryInput(), { target: { value: '星河 🌱' } });
+ fireEvent.click(screen.getByRole('switch'));
+ await waitFor(() => expect(selected()).toContain('星河结果1'));
+ queryInput().focus();
+ fireEvent.keyDown(queryInput(), { key: 'ArrowDown' });
+ expect(selected()).toContain('星河结果2');
+ for (let round = 0; round < 2; round += 1) {
+ rendered.rerender(view(false, true, close));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(inventory.demand).toHaveBeenLastCalledWith(false);
+ const requestCount = api.searchMessages.mock.calls.length;
+ await act(async () => { await new Promise((resolve) => setTimeout(resolve, 250)); });
+ expect(api.searchMessages).toHaveBeenCalledTimes(requestCount);
+ fireEvent.keyDown(window, { key: 'Escape' });
+ expect(close).not.toHaveBeenCalled();
+ rendered.rerender(view(true, true, close));
+ expect(queryInput().value).toBe('星河 🌱');
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('true');
+ await waitFor(() => expect(selected()).toContain('星河结果2'));
+ expect(document.activeElement).toBe(queryInput());
+ }
+ rendered.rerender(view(true, false, close));
+ rendered.rerender(view(true, true, close));
+ expect(queryInput().value).toBe('');
+ expect(screen.getByRole('switch').getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('retires a pending fetch with the presentation and ignores its late result', async () => {
+ let release!: (value: typeof results) => void;
+ api.searchMessages.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));
+ const close = vi.fn();
+ const rendered = render(view(true, true, close));
+ fireEvent.change(queryInput(), { target: { value: '星河' } });
+ await waitFor(() => expect(api.searchMessages).toHaveBeenCalledTimes(1));
+ rendered.rerender(view(false, true, close));
+ await act(async () => { release(results); });
+ expect(screen.queryByRole('dialog')).toBeNull();
+ api.searchMessages.mockResolvedValue({ sessions: [] });
+ rendered.rerender(view(true, true, close));
+ await waitFor(() => expect(api.searchMessages).toHaveBeenCalledTimes(2));
+ expect(selected()).toBeUndefined();
+ expect(queryInput().value).toBe('星河');
+ });
+
+ it('starts inactive with no modal, data subscription or demand', () => {
+ render(view(false, true, vi.fn()));
+ expect(screen.queryByRole('dialog')).toBeNull();
+ expect(api.connectWorkbenchEvents).not.toHaveBeenCalled();
+ expect(inventory.demand).not.toHaveBeenCalled();
+ });
+});
diff --git a/ui/src/components/workbench/search/SearchPalette.tsx b/ui/src/components/workbench/search/SearchPalette.tsx
index 1e68a240c..fc9e4fdf3 100644
--- a/ui/src/components/workbench/search/SearchPalette.tsx
+++ b/ui/src/components/workbench/search/SearchPalette.tsx
@@ -1,10 +1,11 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useEffect, useInsertionEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import * as DialogPrimitive from '@radix-ui/react-dialog';
import { AlertCircle, Loader2, Search } from 'lucide-react';
import { appTabHref, tabModifierLabel, type LaunchModifiers } from '../../../apps/appLaunch';
+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';
import { isComposingKey } from '@/lib/imeComposition';
import { useMessageSearch } from '../../../lib/useMessageSearch';
import { Dialog, DialogOverlay, DialogPortal, DialogTitle } from '../../ui/dialog';
@@ -39,15 +40,63 @@ const FooterHint: React.FC<{ keyLabel: string; label: string }> = ({ keyLabel, l
// server-driven; the Apps section filters the built-in registry + Show Pages
// inventory client-side. Selecting a message routes to /chat/<session>?msg=<message>.
export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) => {
- const { t } = useTranslation();
- const navigate = useNavigate();
+ const active = useRouteSurfaceActive();
+ const current = useRef({ active, open, onClose });
+ useLayoutEffect(() => { current.current = { active, open, onClose }; }, [active, open, onClose]);
+ // A genuine close retires this search. Suspension keeps its input owner but
+ // unmounts the presentation and its data/focus effects.
+ return open ? <SearchSession
+ active={active}
+ onClose={() => {
+ if (current.current.active && current.current.open) current.current.onClose();
+ }}
+ onCloseAutoFocus={(event) => {
+ if (!current.current.active || current.current.open) event.preventDefault();
+ }}
+ /> : null;
+};
+
+const SearchSession = ({ active, onClose, onCloseAutoFocus }: {
+ active: boolean;
+ onClose: () => void;
+ onCloseAutoFocus: (event: Event) => void;
+}) => {
+ const live = useRef(true);
+ useLayoutEffect(() => {
+ live.current = true;
+ return () => { live.current = false; };
+ }, []);
const [query, setQuery] = useState('');
- // Opt-in only, and reset on every open (see onOpenAutoFocus) — the palette
- // already resets the query there, and a sticky archived filter would quietly
- // change what ⌘K returns by default.
const [includeArchived, setIncludeArchived] = useState(false);
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
+ return active ? <SearchPresentation
+ query={query} setQuery={setQuery}
+ includeArchived={includeArchived} setIncludeArchived={setIncludeArchived}
+ selectedKey={selectedKey} setSelectedKey={setSelectedKey}
+ onClose={() => { if (live.current) onClose(); }} onCloseAutoFocus={onCloseAutoFocus}
+ /> : null;
+};
+
+const SearchPresentation = ({ query, setQuery, includeArchived, setIncludeArchived,
+ selectedKey, setSelectedKey, onClose, onCloseAutoFocus }: {
+ query: string;
+ setQuery: (value: string) => void;
+ includeArchived: boolean;
+ setIncludeArchived: (value: boolean) => void;
+ selectedKey: string | null;
+ setSelectedKey: (value: string | null) => void;
+ onClose: () => void;
+ onCloseAutoFocus: (event: Event) => void;
+}) => {
+ const { t } = useTranslation();
+ const navigate = useNavigate();
+ const presented = useRef(false);
+ useInsertionEffect(() => {
+ presented.current = true;
+ return () => { presented.current = false; };
+ }, []);
const { results, loading, error } = useMessageSearch(query, { includeArchived });
- const { results: appResults, loading: appsLoading } = useAppSearchResults(query, open);
+ const { results: appResults, loading: appsLoading } = useAppSearchResults(query);
const openSearchApp = useOpenSearchApp();
const inputRef = useRef<HTMLInputElement | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
@@ -68,7 +117,6 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
[appResults, results],
);
- const [selectedKey, setSelectedKey] = useState<string | null>(null);
// A changed result set falls back to its first row without a state-sync
// effect. Arrow navigation only stores an explicit key while it stays valid.
const selectedTarget = flatTargets.find((target) => target.key === selectedKey) ?? flatTargets[0];
@@ -84,6 +132,7 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
: null;
const handleSelect = (sessionId: string, messageId: string) => {
+ if (!presented.current) return;
navigate(`/chat/${encodeURIComponent(sessionId)}?msg=${encodeURIComponent(messageId)}`);
onClose();
};
@@ -91,6 +140,7 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
// `launch` carries the activating event's modifiers, so ⌘/Ctrl+click AND
// ⌘/Ctrl+Enter open the app in a browser tab (§7.1m).
const handleAppSelect = (result: (typeof appResults)[number], launch?: LaunchModifiers) => {
+ if (!presented.current) return;
openSearchApp(result, launch);
onClose();
};
@@ -144,7 +194,7 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
const showHint = trimmed.length === 0;
return (
- <Dialog open={open} onOpenChange={(next) => (next ? undefined : onClose())}>
+ <Dialog open onOpenChange={(next) => { if (!next && presented.current) onClose(); }}>
<DialogPortal>
<DialogOverlay className="bg-[#05050B]/85" />
<DialogPrimitive.Content
@@ -153,11 +203,9 @@ export const SearchPalette: React.FC<SearchPaletteProps> = ({ open, onClose }) =
// Focus the query field rather than the first row, so typing flows
// straight into the search input.
e.preventDefault();
- setQuery('');
- setSelectedKey(null);
- setIncludeArchived(false);
- inputRef.current?.focus();
+ if (presented.current) inputRef.current?.focus();
}}
+ onCloseAutoFocus={onCloseAutoFocus}
aria-describedby={undefined}
className="fixed left-1/2 top-[120px] z-50 flex max-h-[min(640px,calc(100dvh-160px))] w-[720px] max-w-[calc(100vw-2rem)] -translate-x-1/2 flex-col overflow-hidden rounded-2xl border border-border-strong bg-surface-2 shadow-[0_32px_80px_-16px_rgba(0,0,0,0.75)] data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=open]:fade-in-0 data-[state=closed]:fade-out-0 data-[state=open]:zoom-in-95 data-[state=closed]:zoom-out-95"
>
diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.ts
index a2b982028..4aa8f4751 100644
--- a/ui/src/components/workbench/useShowPageAnnotation.ts
+++ b/ui/src/components/workbench/useShowPageAnnotation.ts
@@ -235,7 +235,8 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
const handleShortcutKeyDown = useCallback<React.KeyboardEventHandler<HTMLElement>>((event) => {
if (
- event.defaultPrevented
+ !routeSurfaceActive
+ || event.defaultPrevented
|| event.repeat
|| stateRef.current?.available !== true
|| stateRef.current.enabled
@@ -246,7 +247,7 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {
}
event.preventDefault();
enableFromShortcut();
- }, [enableFromShortcut, shortcutRef, stateRef]);
+ }, [routeSurfaceActive, enableFromShortcut, shortcutRef, stateRef]);
const setIframe = useCallback<React.RefCallback<HTMLIFrameElement>>(
(iframe) => {