Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): keep settings over current page (#1800)
Call White0cb916a30fd7
diff --git a/ui/src/App.tsx b/ui/src/App.tsxindex 28e9510f9..d8f0b3cf3 100644--- a/ui/src/App.tsx+++ b/ui/src/App.tsx@@ -36,6 +36,7 @@ import { SettingsPlatformsPage } from './components/settings/SettingsPlatformsPaimport { SettingsServicePage } from './components/settings/SettingsServicePage';import { SettingsShortcutsPage } from './components/settings/SettingsShortcutsPage';import { SettingsLayout } from './components/settings/SettingsLayout';+import { SettingsOverlayRouteSurface } from './components/settings/SettingsOverlayRouteSurface';import { StatusProvider } from './context/StatusProvider';import { ApiProvider, useApi, ApiError } from './context/ApiContext';import type { SessionInfo } from './context/ApiContext';@@ -671,6 +672,102 @@ const PwaRouteMemory = () => {return null;};+const settingsRoute = () => (+ <Route path="/settings" element={<SettingsLayout />}>+ <Route index element={null} />+ <Route path="appearance" element={<Navigate to="/settings/replies" replace />} />+ <Route path="account" element={<Navigate to="/settings/replies" replace />} />+ <Route path="shortcuts" element={<SettingsShortcutsPage />} />+ <Route path="service" element={<SettingsServicePage />} />+ <Route path="platforms" element={<SettingsPlatformsPage />} />+ <Route path="platforms/groups" element={<ChannelList isPage />} />+ <Route path="platforms/users" element={<UserList />} />+ <Route path="remote-access" element={<RemoteAccessPage />} />+ <Route path="backends" element={<SettingsBackendsPage />} />+ <Route path="backends/opencode" element={<SettingsOpencodeProviderPage />} />+ <Route path="backends/claude" element={<SettingsClaudeProviderPage />} />+ <Route path="backends/codex" element={<SettingsCodexProviderPage />} />+ <Route+ path="models"+ element={+ <ModelHubCapabilityGate>+ <Suspense fallback={<AppsRouteFallback />}>+ <SettingsModelsPage />+ </Suspense>+ </ModelHubCapabilityGate>+ }+ />+ <Route path="dependencies" element={<SettingsDependenciesPage />} />+ <Route path="memory" element={<SettingsMemoryPage />} />+ <Route path="replies" element={<SettingsMessagingPage />} />+ <Route path="diagnostics" element={<SettingsDiagnosticsPage />} />+ <Route path="diagnostics/logs" element={<SettingsLogsPage />} />+ <Route path="access" element={<PermissionsPage />} />+ </Route>+);++const WorkbenchRouteSurface = () => (+ <SettingsOverlayRouteSurface+ fallbackElement={<Navigate to="/" replace />}+ >+ <Route path="/setup" element={<Wizard />} />++ {/* Workbench mode — `/` is the canvas root, the five capability+ entries (Inbox + Agents/Skills/Harness/Vaults) live alongside it. */}+ <Route path="/" element={<Workbench />} />+ <Route path="/inbox" element={<InboxPage />} />+ <Route path="/search" element={<SearchPage />} />+ <Route path="/agents" element={<AgentsPage />} />+ <Route path="/skills" element={<SkillsPage />} />+ <Route path="/harness" element={<HarnessPage />} />+ <Route path="/vaults" element={<VaultsPage />} />+ <Route path="/projects" element={<ProjectsPage />} />+ <Route path="/more" element={<Navigate to="/" replace />} />++ <Route path="/apps" element={<Navigate to="/apps/files" replace />} />+ <Route+ path="/apps/files"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <AppsFileBrowserPage />+ </Suspense>+ }+ />+ <Route+ path="/apps/terminal"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <AppsTerminalPage />+ </Suspense>+ }+ />+ <Route+ path="/apps/editor"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <AppsEditorPage />+ </Suspense>+ }+ />+ <Route path="/apps/library" element={<LibraryRoute />} />+ <Route+ path="/apps/show/:sessionId"+ element={+ <Suspense fallback={<AppsRouteFallback />}>+ <ShowPageRoute />+ </Suspense>+ }+ />+ <Route path="/chat/:sessionId" element={<ChatPage />} />++ {settingsRoute()}++ {LEGACY_SETTINGS_REDIRECTS.map(({ from, to }) => (+ <Route key={from} path={from} element={<LegacySettingsRedirectRoute to={to} />} />+ ))}+ </SettingsOverlayRouteSurface>+);+function RouterRoot() {return (<UnsavedChangesProvider>@@ -687,107 +784,7 @@ const router = createBrowserRouter(createRoutesFromElements(<Route element={<ErrorBoundary variant="page"><RouterRoot /></ErrorBoundary>}><Route element={<AuthGuard><AppShell /></AuthGuard>}>- <Route path="/setup" element={<Wizard />} />-- {/* Workbench mode — `/` is the canvas root, the five capability- entries (Inbox + Agents/Skills/Harness/Vaults) live alongside- it. Commit 02 ships sidebar + placeholder pages; the real- module screens land in later commits. */}- <Route path="/" element={<Workbench />} />- <Route path="/inbox" element={<InboxPage />} />- <Route path="/search" element={<SearchPage />} />- <Route path="/agents" element={<AgentsPage />} />- <Route path="/skills" element={<SkillsPage />} />- <Route path="/harness" element={<HarnessPage />} />- <Route path="/vaults" element={<VaultsPage />} />- <Route path="/projects" element={<ProjectsPage />} />- {/* /more retired: the workbench Apps tab now summons the Dock drawer- (§7.1b), which absorbed the old More-page content. Redirect any- lingering link/bookmark home. */}- <Route path="/more" element={<Navigate to="/" replace />} />- {/* Apps layer — File Browser (Phase 1) + Terminal (Phase 2). The- sidebar Apps launcher opens these; /apps lands on the file browser. */}- <Route path="/apps" element={<Navigate to="/apps/files" replace />} />- <Route- path="/apps/files"- element={- <Suspense fallback={<AppsRouteFallback />}>- <AppsFileBrowserPage />- </Suspense>- }- />- <Route- path="/apps/terminal"- element={- <Suspense fallback={<AppsRouteFallback />}>- <AppsTerminalPage />- </Suspense>- }- />- <Route- path="/apps/editor"- element={- <Suspense fallback={<AppsRouteFallback />}>- <AppsEditorPage />- </Suspense>- }- />- <Route path="/apps/library" element={<LibraryRoute />} />- {/* A pinned Show Page opened as an app. Desktop opens a window and hands- back to the canvas; mobile frames it full-screen (§7.1b). */}- <Route- path="/apps/show/:sessionId"- element={- <Suspense fallback={<AppsRouteFallback />}>- <ShowPageRoute />- </Suspense>- }- />- <Route path="/chat/:sessionId" element={<ChatPage />} />-- {/* Settings stays inside the Workbench shell. The section rail is the- only second-level navigation; provider/platform routes remain- inline detail screens beneath their owning section. */}- <Route path="/settings" element={<SettingsLayout />}>- <Route index element={null} />- <Route path="appearance" element={<Navigate to="/settings/replies" replace />} />- <Route path="account" element={<Navigate to="/settings/replies" replace />} />- <Route path="shortcuts" element={<SettingsShortcutsPage />} />- <Route path="service" element={<SettingsServicePage />} />- <Route path="platforms" element={<SettingsPlatformsPage />} />- <Route path="platforms/groups" element={<ChannelList isPage />} />- <Route path="platforms/users" element={<UserList />} />- <Route path="remote-access" element={<RemoteAccessPage />} />- <Route path="backends" element={<SettingsBackendsPage />} />- <Route path="backends/opencode" element={<SettingsOpencodeProviderPage />} />- <Route path="backends/claude" element={<SettingsClaudeProviderPage />} />- <Route path="backends/codex" element={<SettingsCodexProviderPage />} />- <Route- path="models"- element={- <ModelHubCapabilityGate>- <Suspense fallback={<AppsRouteFallback />}>- <SettingsModelsPage />- </Suspense>- </ModelHubCapabilityGate>- }- />- <Route path="dependencies" element={<SettingsDependenciesPage />} />- <Route path="memory" element={<SettingsMemoryPage />} />- <Route path="replies" element={<SettingsMessagingPage />} />- <Route path="diagnostics" element={<SettingsDiagnosticsPage />} />- <Route path="diagnostics/logs" element={<SettingsLogsPage />} />- <Route path="access" element={<PermissionsPage />} />- </Route>-- {/* Retired admin and top-level routes only translate old deep links. */}- {LEGACY_SETTINGS_REDIRECTS.map(({ from, to }) => (- <Route key={from} path={from} element={<LegacySettingsRedirectRoute to={to} />} />- ))}- {/* The server intentionally serves the SPA shell for every extensionless- path. Keep stale bookmarks and retired push targets inside AuthGuard,- then recover authenticated/local clients to the workbench root. */}- <Route path="*" element={<Navigate to="/" replace />} />+ <Route path="*" element={<WorkbenchRouteSurface />} /></Route></Route>,),diff --git a/ui/src/components/AppShell.test.tsx b/ui/src/components/AppShell.test.tsxindex 570fad6e7..30871a54a 100644--- a/ui/src/components/AppShell.test.tsx+++ b/ui/src/components/AppShell.test.tsx@@ -310,26 +310,56 @@ describe('AppShell persistent Workbench chrome', () => {expect(screen.queryByTestId('account-menu')).toBeNull();});- it('uses the Settings button to close an open Settings surface', async () => {+ it('uses the Settings button to return to the route that opened Settings', async () => {viewport.isDesktop = true;const user = userEvent.setup();render(- <MemoryRouter initialEntries={['/settings/replies']}>+ <MemoryRouter initialEntries={['/chat/session-1']}><Routes><Route element={<AppShell />}><Route index element={<div data-testid="workbench" />} />+ <Route path="chat/:sessionId" element={<div data-testid="chat" />} /><Route path="settings/replies" element={<div data-testid="settings" />} /></Route></Routes></MemoryRouter>,);+ expect(await screen.findByTestId('chat')).toBeTruthy();+ let settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });+ expect(settingsToggle.getAttribute('href')).toBe('/settings/replies');+ await user.click(settingsToggle);+expect(await screen.findByTestId('settings')).toBeTruthy();- const settingsToggle = screen.getByRole('link', { name: 'appShell.openControlPanel' });- expect(settingsToggle.getAttribute('href')).toBe('/');+ settingsToggle = screen.getByRole('button', { name: 'appShell.openControlPanel' });await user.click(settingsToggle);- expect(await screen.findByTestId('workbench')).toBeTruthy();+ expect(await screen.findByTestId('chat')).toBeTruthy();+ });++ it('returns to chat when a recovery action opens Settings without route state', async () => {+ viewport.isDesktop = true;+ api.getConfig.mockResolvedValue({+ config_recovery: { required: true, warnings: ['invalid-config'] },+ });+ const user = userEvent.setup();++ render(+ <MemoryRouter initialEntries={['/chat/session-1']}>+ <Routes>+ <Route element={<AppShell />}>+ <Route path="chat/:sessionId" element={<div data-testid="chat" />} />+ <Route path="settings/diagnostics" element={<div data-testid="diagnostics" />} />+ </Route>+ </Routes>+ </MemoryRouter>,+ );++ 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' }));+ expect(await screen.findByTestId('chat')).toBeTruthy();});});diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsxindex 25aea620c..2671db7f8 100644--- a/ui/src/components/AppShell.tsx+++ b/ui/src/components/AppShell.tsx@@ -1,5 +1,5 @@import React, { useEffect, useState } from 'react';-import { Link, Navigate, NavLink, Outlet, useLocation } from 'react-router-dom';+import { Link, Navigate, NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';import { AlertTriangle, FolderTree, Grid2x2, Inbox, LayoutGrid, Plus, Settings } from 'lucide-react';import { useTranslation } from 'react-i18next';import clsx from 'clsx';@@ -32,6 +32,13 @@ import {isOwnerOnlyPath,settingsLandingPath,} from '../lib/adminNavigation';+import {+ closeSettingsOverlay,+ isSettingsEntryPath,+ isSettingsRoutePath,+ useSettingsOverlayOrigin,+} from '../lib/settingsOverlay';+import { SettingsOverlayNavigationBoundary } from './settings/SettingsOverlayNavigationBoundary';type ShellNavItem = {to?: string;@@ -171,6 +178,13 @@ export const AppShell: React.FC = () => {} = useInstanceAuthorization();const api = useApi();const location = useLocation();+ const navigate = useNavigate();+ const settingsOverlayOrigin = useSettingsOverlayOrigin(location);+ const settingsOpen = isSettingsRoutePath(location.pathname);+ const settingsOverlayOpen = isDesktop+ && isSettingsEntryPath(location.pathname)+ && settingsOverlayOrigin !== null;+ const surfaceLocation = settingsOverlayOpen ? settingsOverlayOrigin.location : location;useEffect(() => {forgetMobileProjectsListUnlessPreserved(location.pathname);}, [location.pathname]);@@ -235,7 +249,7 @@ export const AppShell: React.FC = () => {// that read it must stay decided for the tab's whole life (see the context doc). The// app pages read the same context and mount only on these routes, so for them the two// agree anyway.- const chromeless = standaloneAppTab && isStandaloneAppRoutePath(location.pathname);+ const chromeless = standaloneAppTab && isStandaloneAppRoutePath(surfaceLocation.pathname);// Keep the visible URL honest about standalone mode. An in-tab app-to-app navigation// (Files → "Open in Editor" / "Open Terminal Here") lands on `/apps/editor` WITHOUT the@@ -328,11 +342,11 @@ export const AppShell: React.FC = () => {// surface (own header + back button), and built-in apps own their toolbars.// These mobile surfaces render their own top chrome, so the shell's mobile// brand header AND the bottom tab bar are hidden on them.- const isChat = location.pathname.startsWith('/chat/');- const isSearch = location.pathname === '/search';- const isSettings = location.pathname === '/settings' || location.pathname.startsWith('/settings/');- const isShowPageApp = location.pathname.startsWith('/apps/show/');- const isBuiltinApp = isStandaloneAppRoutePath(location.pathname);+ const isChat = surfaceLocation.pathname.startsWith('/chat/');+ const isSearch = surfaceLocation.pathname === '/search';+ const isSettings = isSettingsRoutePath(surfaceLocation.pathname);+ const isShowPageApp = surfaceLocation.pathname.startsWith('/apps/show/');+ const isBuiltinApp = isStandaloneAppRoutePath(surfaceLocation.pathname);const isFullScreenMobile = isChat || isSearch || isSettings || isShowPageApp || isBuiltinApp;const showBottomNav = !isFullScreenMobile && !chromeless && location.pathname !== '/setup';@@ -346,6 +360,7 @@ export const AppShell: React.FC = () => {// fought iOS's own scroll-into-view and threw the input off-screen. iOS instead// pans the locked page to lift the focused composer above the keyboard.// Desktop: normal document flow.+ <SettingsOverlayNavigationBoundary desktop={isDesktop}><WindowManagerProvider standalone={standaloneAppTab}><StandaloneAppTabContext.Provider value={standaloneAppTab}><DockProvider enabled={canUseApps}>@@ -397,23 +412,33 @@ export const AppShell: React.FC = () => {<div className="relative flex flex-col gap-3 px-4 pb-4"><div className="flex items-stretch gap-2">{canUseApps && <AppsLauncher />}- <Link- to={isSettings- ? '/'- : isDesktop+ {settingsOpen ? (+ <button+ type="button"+ data-settings-toggle="true"+ onClick={() => {+ if (settingsOverlayOrigin) closeSettingsOverlay(navigate, settingsOverlayOrigin);+ else navigate('/');+ }}+ title={t('appShell.openControlPanel')}+ aria-label={t('appShell.openControlPanel')}+ className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-mint/40 bg-mint/[0.08] text-foreground transition-colors"+ >+ <Settings className="size-[18px] text-mint-ink" />+ </button>+ ) : (+ <Link+ data-settings-toggle="true"+ to={isDesktop? settingsLandingPath(capabilities.can_manage_instance): '/settings'}- title={t('appShell.openControlPanel')}- aria-label={t('appShell.openControlPanel')}- className={clsx(- 'group flex w-11 shrink-0 items-center justify-center rounded-lg border text-foreground transition-colors',- isSettings- ? 'border-mint/40 bg-mint/[0.08]'- : 'border-border-strong hover:bg-foreground/[0.04]',- )}- >- <Settings className={clsx('size-[18px]', isSettings ? 'text-mint-ink' : 'text-muted group-hover:text-foreground')} />- </Link>+ title={t('appShell.openControlPanel')}+ aria-label={t('appShell.openControlPanel')}+ className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-border-strong text-foreground transition-colors hover:bg-foreground/[0.04]"+ >+ <Settings className="size-[18px] text-muted group-hover:text-foreground" />+ </Link>+ )}</div>{config?.runtime?.hostname && (@@ -496,7 +521,7 @@ export const AppShell: React.FC = () => {{/* A crashing page only replaces the content area — the sidebar + chrome stay usable, andnavigating elsewhere clears the error without a manual retry. Key on location.key (notjust pathname) so a query-only navigation (e.g. /search?q=…) also resets. */}- <ErrorBoundary variant="page" resetKeys={[location.key]}>+ <ErrorBoundary variant="page" resetKeys={[surfaceLocation.key]}><Outlet /></ErrorBoundary></div>@@ -542,5 +567,6 @@ export const AppShell: React.FC = () => {</DockProvider></StandaloneAppTabContext.Provider></WindowManagerProvider>+ </SettingsOverlayNavigationBoundary>);};diff --git a/ui/src/components/RouteSurfaceActivityBoundary.tsx b/ui/src/components/RouteSurfaceActivityBoundary.tsxnew file mode 100644index 000000000..c5d827092--- /dev/null+++ b/ui/src/components/RouteSurfaceActivityBoundary.tsx@@ -0,0 +1,43 @@+import { useContext, useMemo } from 'react';+import type { ReactNode } from 'react';+import {+ UNSAFE_NavigationContext as NavigationContext,+} from 'react-router-dom';+import type { Navigator } from 'react-router-dom';++import { RouteSurfaceActiveContext } from '@/lib/routeSurfaceActivity';++export const RouteSurfaceActivityBoundary = ({+ active,+ children,+ inactiveReplace,+}: {+ active: boolean;+ children: ReactNode;+ 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 scopedNavigation = useMemo(+ () => ({ ...navigation, navigator }),+ [navigation, navigator],+ );++ return (+ <RouteSurfaceActiveContext.Provider value={active}>+ <NavigationContext.Provider value={scopedNavigation}>+ {children}+ </NavigationContext.Provider>+ </RouteSurfaceActiveContext.Provider>+ );+};diff --git a/ui/src/components/ShowPagesPage.tsx b/ui/src/components/ShowPagesPage.tsxindex e79ccdafc..db78825b1 100644--- a/ui/src/components/ShowPagesPage.tsx+++ b/ui/src/components/ShowPagesPage.tsx@@ -278,9 +278,9 @@ function ShowPageRow({<div className="flex flex-wrap items-center gap-1.5 text-[11px]"><TriangleAlert size={13} className="text-gold-ink" /><span className="text-muted">{t('showPages.cloudOff')}</span>- <a href="/settings/remote-access" className="font-semibold text-gold-ink hover:underline">+ <Link to="/settings/remote-access" className="font-semibold text-gold-ink hover:underline">{t('showPages.connectCloud')} →- </a>+ </Link></div>) : null}</div>diff --git a/ui/src/components/settings/SettingsLayout.test.tsx b/ui/src/components/settings/SettingsLayout.test.tsxindex c64c02919..b53696190 100644--- a/ui/src/components/settings/SettingsLayout.test.tsx+++ b/ui/src/components/settings/SettingsLayout.test.tsx@@ -3,8 +3,14 @@import { act, cleanup, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';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 { Location } from 'react-router-dom';++import {+ SettingsOverlayOriginContext,+ settingsOverlayOpenState,+ useSettingsOverlayOrigin,+} from '@/lib/settingsOverlay';import { SettingsLayout } from './SettingsLayout';const api = vi.hoisted(() => {@@ -58,15 +64,24 @@ const NavigationProbe = () => {);};-const SettingsLayoutHarness = () => (- <>- <SettingsLayout />- <NavigationProbe />- </>-);+const SettingsLayoutHarness = () => {+ const location = useLocation();+ const origin = useSettingsOverlayOrigin(location);+ return (+ <SettingsOverlayOriginContext.Provider value={origin}>+ <SettingsLayout />+ <NavigationProbe />+ </SettingsOverlayOriginContext.Provider>+ );+};++type SettingsTestEntry = string | {+ pathname: string;+ state?: unknown;+};-const renderLayout = (path: string) => render(- <MemoryRouter initialEntries={[path]}>+const renderLayout = (entry: SettingsTestEntry) => render(+ <MemoryRouter initialEntries={[entry]}><Routes><Route path="/settings" element={<SettingsLayoutHarness />}><Route path="backends" element={<div>backends-body</div>} />@@ -79,6 +94,7 @@ const renderLayout = (path: string) => render(<Route path="platforms/users" element={<div>users-body</div>} /><Route path="platforms/groups" element={<div>groups-body</div>} /></Route>+ <Route path="/chat/:sessionId" element={<div>chat-body</div>} /></Routes></MemoryRouter>,);@@ -114,6 +130,27 @@ afterEach(() => {});describe('SettingsLayout', () => {+ it('closes a desktop overlay back to its exact opening route', async () => {+ media.matches = true;+ const user = userEvent.setup();+ const origin: Location = {+ pathname: '/chat/ses_7',+ search: '?message=m1',+ hash: '#tail',+ state: { source: 'search' },+ key: 'chat-origin',+ };++ renderLayout({+ pathname: '/settings/replies',+ state: settingsOverlayOpenState(origin),+ });++ const close = screen.getByRole('button', { name: 'settings.close' });+ await user.click(close);+ expect(await screen.findByText('chat-body')).toBeTruthy();+ });+it('keeps the settings rail fixed while the route pane owns vertical scrolling', () => {renderLayout('/settings/replies');diff --git a/ui/src/components/settings/SettingsLayout.tsx b/ui/src/components/settings/SettingsLayout.tsxindex 9e9f13959..939a2b241 100644--- a/ui/src/components/settings/SettingsLayout.tsx+++ b/ui/src/components/settings/SettingsLayout.tsx@@ -28,6 +28,10 @@ import { memoryNavShouldBeVisible } from '@/lib/memorySettings';import { rememberSettingsPath, settingsLandingPath } from '@/lib/adminNavigation';import { getEnabledPlatforms, platformSupportsChannels } from '@/lib/platforms';import { useIsDesktop } from '@/lib/useIsDesktop';+import {+ closeSettingsOverlay,+ useSettingsOverlayContext,+} from '@/lib/settingsOverlay';import { AccountMenu } from '../AccountMenu';import { LanguageSwitcher } from '../LanguageSwitcher';import { ThemeToggle } from '../ThemeToggle';@@ -185,6 +189,7 @@ export const SettingsLayout: React.FC = () => {const location = useLocation();const navigate = useNavigate();const isDesktop = useIsDesktop();+ const overlayOrigin = useSettingsOverlayContext();const [modelHubVisible, setModelHubVisible] = useState(false);const [memoryVisible, setMemoryVisible] = useState(false);const [channelSettingsVisible, setChannelSettingsVisible] = useState(false);@@ -327,13 +332,24 @@ export const SettingsLayout: React.FC = () => {<VersionBadge /></div>)}- <NavLink- to="/"- aria-label={t('settings.close')}- className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"- >- <X className="size-4" />- </NavLink>+ {overlayOrigin ? (+ <button+ type="button"+ onClick={() => closeSettingsOverlay(navigate, overlayOrigin)}+ aria-label={t('settings.close')}+ className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"+ >+ <X className="size-4" />+ </button>+ ) : (+ <NavLink+ to="/"+ aria-label={t('settings.close')}+ className="hidden size-8 shrink-0 place-items-center rounded-lg text-muted transition hover:bg-foreground/[0.05] hover:text-foreground md:grid"+ >+ <X className="size-4" />+ </NavLink>+ )}</div></header>diff --git a/ui/src/components/settings/SettingsOverlayNavigationBoundary.tsx b/ui/src/components/settings/SettingsOverlayNavigationBoundary.tsxnew file mode 100644index 000000000..aad61f97f--- /dev/null+++ b/ui/src/components/settings/SettingsOverlayNavigationBoundary.tsx@@ -0,0 +1,61 @@+import { useContext, useMemo } from 'react';+import type { ReactNode } from 'react';+import {+ parsePath,+ UNSAFE_NavigationContext as NavigationContext,+ useLocation,+} from 'react-router-dom';+import type { Navigator, To } from 'react-router-dom';++import { settingsOverlayNavigationState } from '@/lib/settingsOverlay';++const destinationPathname = (to: To, fallback: string): string => {+ const pathname = typeof to === 'string' ? parsePath(to).pathname : to.pathname;+ return pathname ?? fallback;+};++export const SettingsOverlayNavigationBoundary = ({+ children,+ desktop,+}: {+ children: ReactNode;+ desktop: boolean;+}) => {+ const location = useLocation();+ const navigation = useContext(NavigationContext);+ // Every Settings-bound navigation carries one durable origin. This is the+ // ownership point for all links, redirects, and programmatic navigation.+ const navigator = useMemo<Navigator>(() => ({+ ...navigation.navigator,+ push: (to, state, options) => navigation.navigator.push(+ to,+ settingsOverlayNavigationState({+ destinationPathname: destinationPathname(to, location.pathname),+ desktop,+ source: location,+ targetState: state,+ }),+ options,+ ),+ replace: (to, state, options) => navigation.navigator.replace(+ to,+ settingsOverlayNavigationState({+ destinationPathname: destinationPathname(to, location.pathname),+ desktop,+ source: location,+ targetState: state,+ }),+ options,+ ),+ }), [desktop, location, navigation.navigator]);+ const scopedNavigation = useMemo(+ () => ({ ...navigation, navigator }),+ [navigation, navigator],+ );++ return (+ <NavigationContext.Provider value={scopedNavigation}>+ {children}+ </NavigationContext.Provider>+ );+};diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsxnew file mode 100644index 000000000..9a0929589--- /dev/null+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.test.tsx@@ -0,0 +1,299 @@+/* @vitest-environment jsdom */++import { cleanup, 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 {+ Link,+ MemoryRouter,+ Navigate,+ Outlet,+ Route,+ Routes,+ useLocation,+ useNavigate,+} from 'react-router-dom';++import {+ closeSettingsOverlay,+ useSettingsOverlayOrigin,+ useSettingsOverlayContext,+} from '@/lib/settingsOverlay';+import { useRouteSurfaceActive } from '@/lib/routeSurfaceActivity';+import { SettingsOverlayNavigationBoundary } from './SettingsOverlayNavigationBoundary';+import { SettingsOverlayRouteSurface } from './SettingsOverlayRouteSurface';++let chatMounts = 0;+let chatUnmounts = 0;++const ChatProbe = () => {+ const location = useLocation();+ const navigate = useNavigate();+ const routeSurfaceActive = useRouteSurfaceActive();+ const [count, setCount] = useState(0);++ useEffect(() => {+ chatMounts += 1;+ return () => {+ chatUnmounts += 1;+ };+ }, []);++ useEffect(() => {+ if (!routeSurfaceActive) navigate('/escaped');+ }, [navigate, routeSurfaceActive]);++ useEffect(() => {+ const maintenance = (location.state as { maintenance?: string } | null)?.maintenance;+ if (!routeSurfaceActive && maintenance === 'pending') {+ navigate(`${location.pathname}${location.search}${location.hash}`, {+ replace: true,+ state: { maintenance: 'done' },+ });+ }+ }, [location, navigate, routeSurfaceActive]);++ return (+ <main>+ <div data-testid="chat-location">{`${location.pathname}${location.search}${location.hash}`}</div>+ <div data-testid="chat-count">{count}</div>+ <div data-testid="chat-active">{String(routeSurfaceActive)}</div>+ <div data-testid="chat-maintenance">+ {(location.state as { maintenance?: string } | null)?.maintenance ?? 'none'}+ </div>+ <button type="button" onClick={() => setCount((value) => value + 1)}>increment-chat</button>+ <Link to="/settings/replies">open-settings</Link>+ <Link to="/settings/diagnostics">open-diagnostics</Link>+ <Link to="/doctor">open-legacy-settings</Link>+ </main>+ );+};++const SettingsFrame = () => {+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayContext();+ const [count, setCount] = useState(0);++ return (+ <aside>+ <button+ type="button"+ onClick={() => {+ if (origin) closeSettingsOverlay(navigate, origin);+ else navigate('/');+ }}+ >+ close-settings+ </button>+ <button type="button" onClick={() => navigate('/settings/advanced')}>open-advanced</button>+ <button type="button" onClick={() => setCount((value) => value + 1)}>increment-settings</button>+ <div data-testid="settings-count">{count}</div>+ <div data-testid="settings-location">{location.pathname}</div>+ <Outlet />+ </aside>+ );+};++const settingsRoute = () => (+ <Route path="/settings" element={<SettingsFrame />}>+ <Route path="replies" element={<div>replies-settings</div>} />+ <Route path="advanced" element={<div>advanced-settings</div>} />+ <Route path="diagnostics" element={<div>diagnostics-settings</div>} />+ </Route>+);++const SettingsToggle = () => {+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayOrigin(location);+ return origin ? (+ <button+ type="button"+ data-settings-toggle="true"+ onClick={() => closeSettingsOverlay(navigate, origin)}+ >+ shell-settings+ </button>+ ) : (+ <Link to="/settings/replies" data-settings-toggle="true">shell-settings</Link>+ );+};++const Harness = ({ desktop }: { desktop: boolean }) => (+ <SettingsOverlayNavigationBoundary desktop={desktop}>+ <SettingsToggle />+ <SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}>+ <Route path="/chat/:sessionId" element={<ChatProbe />} />+ <Route path="/escaped" element={<div>escaped-route</div>} />+ {settingsRoute()}+ <Route path="/doctor" element={<Navigate to="/settings/diagnostics" replace />} />+ <Route path="/" element={<div>workbench</div>} />+ </SettingsOverlayRouteSurface>+ </SettingsOverlayNavigationBoundary>+);++const RoutedHarness = ({ desktop = true }: { desktop?: boolean }) => (+ <Routes>+ <Route path="*" element={<Harness desktop={desktop} />} />+ </Routes>+);++const RemountingHarness = () => {+ const location = useLocation();+ const guardKey = location.pathname.startsWith('/settings/diagnostics') ? 'diagnostics' : 'default';+ return <Harness key={guardKey} desktop />;+};++beforeEach(() => {+ chatMounts = 0;+ chatUnmounts = 0;+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({+ matches: true,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ }));+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+});++describe('SettingsOverlayRouteSurface', () => {+ it('keeps the background route mounted across Settings navigation and close', async () => {+ const user = userEvent.setup();+ const view = render(+ <MemoryRouter initialEntries={[{+ pathname: '/chat/ses_1',+ search: '?view=chat',+ hash: '#tail',+ state: { maintenance: 'pending' },+ }]}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('button', { name: 'increment-chat' }));+ expect(screen.getByTestId('chat-count').textContent).toBe('1');+ expect(chatMounts).toBe(1);++ const settingsIngress = screen.getByRole('link', { name: 'shell-settings' });+ await user.click(settingsIngress);+ expect(screen.getByText('replies-settings')).toBeTruthy();+ const dialog = screen.getByRole('dialog', { name: 'nav.settings' });+ expect(dialog).toBeTruthy();+ await waitFor(() => expect(document.activeElement).toBe(+ screen.getByRole('button', { name: 'close-settings' }),+ ));+ await user.tab({ shift: true });+ expect(dialog.contains(document.activeElement)).toBe(true);+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1?view=chat#tail');+ expect(screen.getByTestId('chat-count').textContent).toBe('1');+ expect(screen.getByTestId('chat-active').textContent).toBe('false');+ expect(screen.getByTestId('chat-maintenance').textContent).toBe('done');+ expect(screen.queryByText('escaped-route')).toBeNull();+ expect(chatMounts).toBe(1);+ expect(chatUnmounts).toBe(0);++ await user.click(screen.getByRole('button', { name: 'open-advanced' }));+ expect(screen.getByText('advanced-settings')).toBeTruthy();+ expect(screen.getByTestId('chat-count').textContent).toBe('1');+ expect(chatMounts).toBe(1);+ expect(chatUnmounts).toBe(0);++ await user.click(screen.getByRole('button', { name: 'increment-settings' }));+ expect(screen.getByTestId('settings-count').textContent).toBe('1');+ view.rerender(+ <MemoryRouter initialEntries={['/chat/ses_1?view=chat#tail']}>+ <RoutedHarness desktop={false} />+ </MemoryRouter>,+ );+ expect(screen.getByTestId('settings-count').textContent).toBe('1');++ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull();+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1?view=chat#tail');+ expect(screen.getByTestId('chat-count').textContent).toBe('1');+ expect(screen.getByTestId('chat-active').textContent).toBe('true');+ expect(screen.getByTestId('chat-maintenance').textContent).toBe('done');+ expect(chatMounts).toBe(1);+ expect(chatUnmounts).toBe(0);+ await waitFor(() => expect(document.activeElement).toBe(+ screen.getByRole('link', { name: 'shell-settings' }),+ ));+ });++ it('carries the origin through a guard remount', async () => {+ const user = userEvent.setup();+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <Routes>+ <Route path="*" element={<RemountingHarness />} />+ </Routes>+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'open-diagnostics' }));+ expect(await screen.findByText('diagnostics-settings')).toBeTruthy();+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();++ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(await screen.findByTestId('chat-location')).toBeTruthy();+ });++ it('closes when the persistent Settings toggle is clicked again', async () => {+ const user = userEvent.setup();+ render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();+ const backdrop = document.querySelector<HTMLElement>('[data-dialog-surface-backdrop="true"]');+ expect(backdrop).not.toBeNull();+ await user.click(backdrop!);++ await waitFor(() => expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull());+ expect(screen.getByTestId('chat-location').textContent).toBe('/chat/ses_1');+ });++ it('keeps legacy redirects out of origins while preserving real ingress origins', async () => {+ const user = userEvent.setup();+ const view = render(+ <MemoryRouter initialEntries={['/chat/ses_1']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ await user.click(screen.getByRole('link', { name: 'open-legacy-settings' }));+ expect(await screen.findByText('diagnostics-settings')).toBeTruthy();+ expect(screen.getByRole('dialog', { name: 'nav.settings' })).toBeTruthy();+ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(await screen.findByTestId('chat-location')).toBeTruthy();++ view.unmount();+ render(+ <MemoryRouter initialEntries={['/doctor']}>+ <RoutedHarness />+ </MemoryRouter>,+ );+ expect(await screen.findByText('diagnostics-settings')).toBeTruthy();+ expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull();+ });++ it('renders a direct Settings URL as the primary route', () => {+ render(+ <MemoryRouter initialEntries={['/settings/replies']}>+ <RoutedHarness />+ </MemoryRouter>,+ );++ expect(screen.getByText('replies-settings')).toBeTruthy();+ expect(document.querySelector('[data-settings-overlay="true"]')).toBeNull();+ expect(screen.queryByTestId('chat-count')).toBeNull();+ });+});diff --git a/ui/src/components/settings/SettingsOverlayRouteSurface.tsx b/ui/src/components/settings/SettingsOverlayRouteSurface.tsxnew file mode 100644index 000000000..7c9f1ac7e--- /dev/null+++ b/ui/src/components/settings/SettingsOverlayRouteSurface.tsx@@ -0,0 +1,95 @@+import { useCallback } 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';+import { useTranslation } from 'react-i18next';++import { RouteSurfaceActivityBoundary } from '@/components/RouteSurfaceActivityBoundary';+import { Dialog, DialogSurfaceContent, DialogTitle } from '@/components/ui/dialog';+import {+ closeSettingsOverlay,+ isSettingsEntryPath,+ locationPath,+ SettingsOverlayOriginContext,+ settingsOverlayStateForOrigin,+ useSettingsOverlayOrigin,+} from '@/lib/settingsOverlay';++type SettingsOverlayRouteSurfaceProps = {+ children: ReactNode;+ fallbackElement: ReactElement;+};++export const SettingsOverlayRouteSurface = ({+ children,+ fallbackElement,+}: SettingsOverlayRouteSurfaceProps) => {+ const { t } = useTranslation();+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayOrigin(location);+ const settingsSurfaceOpen = isSettingsEntryPath(location.pathname) && origin !== null;+ const replaceBackground = useCallback<Navigator['replace']>((to, state) => {+ if (!origin) return;+ const path = resolvePath(to, origin.location.pathname);+ const nextOrigin = {+ ...origin,+ location: {+ ...origin.location,+ ...path,+ state,+ },+ };+ navigate(locationPath(location), {+ replace: true,+ state: settingsOverlayStateForOrigin(nextOrigin, location.state),+ });+ }, [location, navigate, origin]);++ return (+ <>+ <div+ className="contents"+ aria-hidden={settingsSurfaceOpen || undefined}+ inert={settingsSurfaceOpen || undefined}+ >+ <RouteSurfaceActivityBoundary+ active={!settingsSurfaceOpen}+ inactiveReplace={replaceBackground}+ >+ <Routes location={settingsSurfaceOpen ? origin.location : location}>+ {children}+ <Route path="*" element={fallbackElement} />+ </Routes>+ </RouteSurfaceActivityBoundary>+ </div>+ {settingsSurfaceOpen ? (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open) closeSettingsOverlay(navigate, origin);+ }}+ >+ <SettingsOverlayOriginContext.Provider value={origin}>+ <DialogSurfaceContent+ data-settings-overlay="true"+ aria-describedby={undefined}+ onCloseAutoFocus={(event) => {+ event.preventDefault();+ window.requestAnimationFrame(() => {+ document.querySelector<HTMLElement>('[data-settings-toggle="true"]')?.focus();+ });+ }}+ >+ <DialogTitle className="sr-only">{t('nav.settings')}</DialogTitle>+ <Routes location={location}>+ {children}+ <Route path="*" element={fallbackElement} />+ </Routes>+ </DialogSurfaceContent>+ </SettingsOverlayOriginContext.Provider>+ </Dialog>+ ) : null}+ </>+ );+};diff --git a/ui/src/components/ui/dialog.tsx b/ui/src/components/ui/dialog.tsxindex fe38e69b0..9edc70a49 100644--- a/ui/src/components/ui/dialog.tsx+++ b/ui/src/components/ui/dialog.tsx@@ -64,6 +64,29 @@ export const DialogContent = React.forwardRef<));DialogContent.displayName = DialogPrimitive.Content.displayName;+// Route-sized modal: the transparent backdrop preserves visual context while Radix owns focus,+// outside interaction, and accessibility isolation for the foreground surface.+export const DialogSurfaceContent = React.forwardRef<+ React.ComponentRef<typeof DialogPrimitive.Content>,+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>+>(({ className, ...props }, ref) => (+ <DialogPortal>+ <DialogOverlay+ data-dialog-surface-backdrop="true"+ className="z-20 bg-transparent backdrop-blur-none"+ />+ <DialogPrimitive.Content+ ref={ref}+ className={cn(+ 'fixed inset-y-0 left-0 right-0 z-30 overflow-hidden border-l border-border bg-background shadow-2xl focus:outline-none md:left-[240px]',+ className,+ )}+ {...props}+ />+ </DialogPortal>+));+DialogSurfaceContent.displayName = 'DialogSurfaceContent';+export const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (<div className={cn('flex flex-col gap-1.5 text-left', className)} {...props} />);diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsxindex fc243a05d..233669b27 100644--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx@@ -35,6 +35,7 @@ import {type LucideIcon,} from 'lucide-react';import { isDesktopViewport, useIsDesktop } from '../../lib/useIsDesktop';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import clsx from 'clsx';import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';@@ -231,15 +232,10 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striselectionAnchorRef.current = null;}, []);- // Escape is the universal way out of a selection. Preview/dialog handlers still own their own- // Escape behavior; clearing a background selection at the same time is harmless and predictable.- useEffect(() => {- const onKey = (ev: KeyboardEvent) => {- if (ev.key === 'Escape') clearSelection();- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [clearSelection]);+ // Escape is the universal way out of a selection while this route owns the foreground.+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if (event.key === 'Escape') clearSelection();+ });// Long-press is only a selection gesture on coarse pointers. Movement beyond a small slop cancels// it so scrolling the list never unexpectedly enters selection mode.@@ -261,17 +257,12 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri// Mobile quick look stays inside the Files surface because phones have no window layer. Keep the// edit capability with the preview so editable formats can switch surfaces from its toolbar.const [preview, setPreview] = useState<{ path: string; name: string; mtime: number | null; editable: boolean } | null>(null);- useEffect(() => {- if (!preview) return;- const onKey = (ev: KeyboardEvent) => {- if (ev.key === 'Escape') {- ev.preventDefault();- setPreview(null);- }- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [preview]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if (event.key === 'Escape') {+ event.preventDefault();+ setPreview(null);+ }+ }, preview !== null);const navSeq = useRef(0);const navigate = useCallback(diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 7bcd06524..be2d40f86 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -40,6 +40,7 @@ import { recentPathLabel } from '../../lib/editorRecents';import type { LocalFileLinkTarget } from '../../lib/localFileLinks';import { formatLocalDateTime, formatRelativeTime } from '../../lib/relativeTime';import { canMarkConversationRead, usePageActive } from '../../lib/pageActivity';+import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { isDesktopViewport, useIsDesktop } from '../../lib/useIsDesktop';import { resultFooterParts } from '../../lib/resultFooter';import {@@ -147,6 +148,7 @@ import {type TurnActivityGroupWire,} from '../../lib/agentActivity';import { errorMessage } from '@/lib/errorMessage';+import { pendingInitialMessageHandoff } from '@/lib/chatInitialMessage';import { sessionAgentDisplayName } from './sessionAgentName';// While a turn is in flight, reconcile the working/Stop state against the@@ -272,6 +274,7 @@ export const ChatPage: React.FC = () => {const { unreadBySession, markRead: markInboxRead } = useWorkbenchInbox({ feed: false });const { focusedId: foregroundAppWindowId, focusCanvas } = useWindowManager();const isDesktop = useIsDesktop();+ const routeSurfaceActive = useRouteSurfaceActive();const pageActive = usePageActive();// The mobile chat surface is a fixed full-screen flex column; this keeps the// composer glued to the iOS keyboard (settle-then-correct; see the hook).@@ -364,14 +367,10 @@ export const ChatPage: React.FC = () => {// user-configured chord such as Ctrl+Z. Starting remains limited to a writable,// visible Chat surface; once recording, Composer still accepts the chord as// Finish after focus moves elsewhere in this document.- const voiceShortcutCanStart = pageActive && writable && !showPageActive;- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- composerRef.current?.handleVoiceShortcut(event, voiceShortcutCanStart);- };- window.addEventListener('keydown', onKeyDown, true);- return () => window.removeEventListener('keydown', onKeyDown, true);- }, [voiceShortcutCanStart]);+ const voiceShortcutCanStart = routeSurfaceActive && pageActive && writable && !showPageActive;+ useRouteSurfaceWindowEvent('keydown', (event) => {+ composerRef.current?.handleVoiceShortcut(event, voiceShortcutCanStart);+ }, true, true);// True while the share popover is open. The popover floats over the Show Page// iframe; making the iframe inert lets an outside tap there reach the parent// document so the (non-modal) popover dismisses, without modal-blocking the@@ -2394,6 +2393,7 @@ export const ChatPage: React.FC = () => {if (!canChat) return;if (!canMarkConversationRead({pageActive,+ routeSurfaceActive,sessionReady: !loading && session?.id === sessionId,viewResolved: showPageViewResolved,historicalWindow,@@ -2412,6 +2412,7 @@ export const ChatPage: React.FC = () => {showPageViewResolved,historicalWindow,pageActive,+ routeSurfaceActive,showPageActive,isDesktop,foregroundAppWindowId,@@ -2423,14 +2424,28 @@ export const ChatPage: React.FC = () => {// starts. Clear the state afterwards so a manual page refresh (which preserves// history state) doesn't resend it.useEffect(() => {- const initialMessage = (location.state as { initialMessage?: string } | null)?.initialMessage;- if (!initialMessage || !sessionId) return;- if (initialHandledSessionRef.current === sessionId) return;- if (loading || !session) return;- initialHandledSessionRef.current = sessionId;+ const handoff = pendingInitialMessageHandoff({+ handledSessionId: initialHandledSessionRef.current,+ loadedSessionId: session?.id,+ loading,+ locationState: location.state,+ routeSurfaceActive,+ sessionId,+ });+ if (!handoff) return;+ initialHandledSessionRef.current = handoff.sessionId;navigate(location.pathname, { replace: true, state: null });- void sendMessage(initialMessage);- }, [location.state, location.pathname, loading, session, sessionId, navigate, sendMessage]);+ void sendMessage(handoff.message);+ }, [+ location.state,+ location.pathname,+ loading,+ session?.id,+ sessionId,+ navigate,+ routeSurfaceActive,+ sendMessage,+ ]);// Scoped to the open chat: a write still draining for a session the user has// left must not spin the header of the one they are looking at. Either group@@ -2514,26 +2529,21 @@ export const ChatPage: React.FC = () => {// and do nothing in return. And "ChatPage is mounted" is not "chat owns the// keyboard" — it stays mounted under app windows and dialogs — so a keystroke// belonging to a foreground surface is left to that surface (Codex).- useEffect(() => {- if (!canArchive) return;- const onKeyDown = (e: KeyboardEvent) => {- if (!isArchiveSessionKeydown(e, e.target as Element | null)) return;- e.preventDefault();- requestArchive();- };- window.addEventListener('keydown', onKeyDown);- return () => window.removeEventListener('keydown', onKeyDown);- }, [canArchive, requestArchive]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if (!isArchiveSessionKeydown(event, event.target as Element | null)) return;+ event.preventDefault();+ requestArchive();+ }, canArchive);// A keydown inside the Show Page iframe never reaches this window, so the same// chord is bound to the frame's own document while it is mounted — otherwise the// shortcut silently dies as soon as the user clicks into the page they asked for.useEffect(() => {- if (!canArchive) return;+ if (!canArchive || !routeSurfaceActive) return;const frame = showPageFrameRef.current;if (!frame) return;return bindFrameChord(frame, (event) => isArchiveSessionChord(event), requestArchive);- }, [canArchive, requestArchive, showPageActive, showPageUrl]);+ }, [canArchive, requestArchive, routeSurfaceActive, showPageActive, showPageUrl]);// Ordered media-proxy image URLs across the whole session — feeds the lightbox// so it pages left/right through every image, in render order (each message'sdiff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsxindex 56060f3ea..3c5baf444 100644--- a/ui/src/components/workbench/Composer.tsx+++ b/ui/src/components/workbench/Composer.tsx@@ -57,6 +57,7 @@ import {} from '../../lib/workbenchUpload';import { Button } from '../ui/button';import { inForegroundSurface } from './chatShortcuts';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import {MentionEditor,type AgentSearchResult,@@ -1147,17 +1148,12 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo};// ESC aborts an in-progress recording (discard, no transcribe).- useEffect(() => {- if (!recording) return;- const onKey = (e: KeyboardEvent) => {- if (isPlainEscape(e)) {- e.preventDefault();- abortRecording();- }- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [abortRecording, recording]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if (isPlainEscape(event)) {+ event.preventDefault();+ abortRecording();+ }+ }, recording);const trimmed = value.trim();const readyAttachments = attachments.filter((a) => a.status === 'ready');diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsxindex 6b8924c3b..0f3041da4 100644--- a/ui/src/components/workbench/EditorApp.tsx+++ b/ui/src/components/workbench/EditorApp.tsx@@ -9,6 +9,7 @@ import { FilesApiError, contentUrl, downloadFile, fileMeta, joinPath, parentDir,import { isEditableFile, isEditableMeta, previewOverlayKind, previewRenderKind } from '../../lib/filePreview';import { adjustEditorFontSize, resetEditorFontSize } from '../../lib/editorFontSize';import { IS_APPLE } from '../../lib/platform';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { forgetRecentFile, loadEditorRecents, recentPathLabel, rememberRecentFile, rememberRecentFolder, removeRecentFile, type EditorRecents, type RecentFile } from '../../lib/editorRecents';import { FileTree } from './FileTree';import { FilePreview } from '../ui/file-preview';@@ -578,56 +579,47 @@ export const EditorApp: React.FC<{// ⌘O Open Folder · ⌘N New File — only while THIS editor window holds focus (several windows can// be open). Capture phase + preventDefault so ⌘O doesn't fall through to the browser's open dialog.- useEffect(() => {- if (!windowId) return;- const onKey = (e: KeyboardEvent) => {- if (!(e.metaKey || e.ctrlKey) || e.altKey) return;- // Only the frontmost editor window, and not while its own dialog is open. Scope by the window- // manager's focused id (not DOM focus) so the shortcut keeps working after a dialog closes.- if (picker || wm.focusedId !== windowId) return;- const k = e.key.toLowerCase();- // ⇧⌘F opens the cross-file Search view and focuses its query input. (Plain ⌘F is left to- // Monaco's built-in in-file find widget when the editor has focus.)- if (e.shiftKey) {- if (k !== 'f') return;- e.preventDefault();- setView('search');- setExplorerCollapsed(false); // ⇧⌘F must reveal the panel even when it's collapsed- setSearchFocus((n) => n + 1);- return;- }- if (k !== 'o' && k !== 'n') return;- e.preventDefault();- if (k === 'o') openFolder();- else newFile();- };- window.addEventListener('keydown', onKey, true);- return () => window.removeEventListener('keydown', onKey, true);- }, [windowId, openFolder, newFile, picker, wm.focusedId]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if (!(event.metaKey || event.ctrlKey) || event.altKey) return;+ // Only the frontmost editor window, and not while its own dialog is open. Scope by the window+ // manager's focused id (not DOM focus) so the shortcut keeps working after a dialog closes.+ if (picker || wm.focusedId !== windowId) return;+ const k = event.key.toLowerCase();+ // ⇧⌘F opens the cross-file Search view and focuses its query input. (Plain ⌘F is left to+ // Monaco's built-in in-file find widget when the editor has focus.)+ if (event.shiftKey) {+ if (k !== 'f') return;+ event.preventDefault();+ setView('search');+ setExplorerCollapsed(false); // ⇧⌘F must reveal the panel even when it's collapsed+ setSearchFocus((n) => n + 1);+ return;+ }+ if (k !== 'o' && k !== 'n') return;+ event.preventDefault();+ if (k === 'o') openFolder();+ else newFile();+ }, Boolean(windowId), true);// Claim browser-style zoom only for the focused Editor surface. A window additionally checks real// DOM focus so an Editor left open while the user works in the sidebar doesn't steal browser zoom.// The route stays inactive while a floating window is on top. Capture prevents Monaco's session-only// font zoom from also handling the key.- useEffect(() => {- const onKey = (e: KeyboardEvent) => {- const focusedWindow = document.activeElement instanceof Element- ? document.activeElement.closest('[data-window-id]')?.getAttribute('data-window-id')- : null;- const foreground = windowId- ? wm.focusedId === windowId && focusedWindow === windowId- : wm.focusedId === null && !!rootRef.current?.contains(document.activeElement);- if (!foreground) return;- const zoom = fontZoomIntent(e);- if (!zoom) return;- e.preventDefault();- e.stopPropagation();- if (zoom === 'reset') resetEditorFontSize();- else adjustEditorFontSize(zoom === 'in' ? 1 : -1);- };- window.addEventListener('keydown', onKey, true);- return () => window.removeEventListener('keydown', onKey, true);- }, [windowId, wm.focusedId]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ const focusedWindow = document.activeElement instanceof Element+ ? document.activeElement.closest('[data-window-id]')?.getAttribute('data-window-id')+ : null;+ const foreground = windowId+ ? wm.focusedId === windowId && focusedWindow === windowId+ : wm.focusedId === null && !!rootRef.current?.contains(document.activeElement);+ if (!foreground) return;+ const zoom = fontZoomIntent(event);+ if (!zoom) return;+ event.preventDefault();+ event.stopPropagation();+ if (zoom === 'reset') resetEditorFontSize();+ else adjustEditorFontSize(zoom === 'in' ? 1 : -1);+ }, true, true);// Selecting a file from the mobile explorer returns the editor to the foreground. This keeps// the narrow screen useful after every open while leaving the desktop panel behavior unchanged.diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsxindex b487ae844..13b4e95be 100644--- a/ui/src/components/workbench/FileEditorPane.tsx+++ b/ui/src/components/workbench/FileEditorPane.tsx@@ -8,6 +8,7 @@ import { useWindowCloseGuard } from '../../context/WindowManagerContext';import { Button } from '../ui/button';import { FilesApiError, fileBrowserErrorMessage, fileMeta, readText, writeFile } from '../../lib/filesApi';import { editorPreviewKind } from '../../lib/filePreview';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { FilePreview } from '../ui/file-preview';// Monaco (the VS Code kernel) is heavy; lazy-load it so it stays out of the main@@ -155,17 +156,12 @@ export const FileEditorPane: React.FC<{// While previewing, Monaco (the usual ⌘S owner) is unmounted, so the foreground tab registers a// window-level ⌘S. `saveRef` holds the latest save() so the listener never saves a stale buffer.const saveRef = useRef<() => void>(() => {});- useEffect(() => {- if (!(saveHotkey && previewable && mode === 'preview')) return;- const onKey = (e: KeyboardEvent) => {- if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 's') {- e.preventDefault();- void saveRef.current();- }- };- window.addEventListener('keydown', onKey, true);- return () => window.removeEventListener('keydown', onKey, true);- }, [saveHotkey, previewable, mode]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ if ((event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 's') {+ event.preventDefault();+ void saveRef.current();+ }+ }, saveHotkey && Boolean(previewable) && mode === 'preview', true);// Tracks the path the last read targeted, so a rename (path changing from one real file to another)// can be told apart from an initial open or a forced reload.diff --git a/ui/src/components/workbench/NewAgentDialog.tsx b/ui/src/components/workbench/NewAgentDialog.tsxindex 940377324..e480a82f8 100644--- a/ui/src/components/workbench/NewAgentDialog.tsx+++ b/ui/src/components/workbench/NewAgentDialog.tsx@@ -15,6 +15,7 @@ import { Textarea } from '../ui/textarea';import { EditorDialog } from '../ui/editor-dialog';import { Button } from '../ui/button';import { errorMessage } from '@/lib/errorMessage';+import { useRouteSurfaceWindowEvent } from '@/lib/routeSurfaceActivity';type BackendKey = 'claude' | 'opencode' | 'codex';@@ -105,16 +106,11 @@ export const NewAgentDialog: React.FC<NewAgentDialogProps> = ({ open, onClose, o}}, [effortOptions, effort]);- useEffect(() => {- if (!open) return;- const onKey = (e: KeyboardEvent) => {- // Don't let Esc close the whole create dialog when the expand editor is- // open on top — that Esc belongs to the editor.- if (e.key === 'Escape' && !editorOpen) onClose();- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [open, onClose, editorOpen]);+ useRouteSurfaceWindowEvent('keydown', (event) => {+ // Don't let Esc close the whole create dialog when the expand editor is+ // open on top — that Esc belongs to the editor.+ if (event.key === 'Escape' && !editorOpen) onClose();+ }, open);if (!open) return null;diff --git a/ui/src/components/workbench/ShowPageLaunchControl.tsx b/ui/src/components/workbench/ShowPageLaunchControl.tsxindex 337b72432..95eda502a 100644--- a/ui/src/components/workbench/ShowPageLaunchControl.tsx+++ b/ui/src/components/workbench/ShowPageLaunchControl.tsx@@ -20,6 +20,7 @@ import {type ViewportPoint,} from '../../lib/showPageLaunch';import { isDesktopViewport } from '../../lib/useIsDesktop';+import { useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { Button } from '../ui/button';import { Popover, PopoverAnchor, PopoverContent } from '../ui/popover';@@ -140,44 +141,35 @@ export const ShowPageLaunchControl: React.FC<ShowPageLaunchControlProps> = ({else await dock.pin(sessionId);}, [dock, prepare, sessionId]);- useEffect(() => {- const onDragOver = (event: DragEvent) => {- const active = dragRef.current;- if (!active) return;- const target = event.target instanceof Element ? event.target : null;- if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) {- return;- }- const point = { x: event.clientX, y: event.clientY };- if (!isShowPageWindowDrop(active.start, point)) {- if (event.dataTransfer) event.dataTransfer.dropEffect = 'none';- return;- }- event.preventDefault();- if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';- };-- const onDrop = (event: DragEvent) => {- const active = dragRef.current;- if (!active) return;- const target = event.target instanceof Element ? event.target : null;- if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) return;- const point = { x: event.clientX, y: event.clientY };- if (!isShowPageWindowDrop(active.start, point)) return;- event.preventDefault();- dragRef.current = null;- endShowPageDrag();- setGestureActive(false);- void openWindow(point);- };+ useRouteSurfaceWindowEvent('dragover', (event) => {+ const active = dragRef.current;+ if (!active) return;+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) {+ return;+ }+ const point = { x: event.clientX, y: event.clientY };+ if (!isShowPageWindowDrop(active.start, point)) {+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'none';+ return;+ }+ event.preventDefault();+ if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';+ });- window.addEventListener('dragover', onDragOver);- window.addEventListener('drop', onDrop);- return () => {- window.removeEventListener('dragover', onDragOver);- window.removeEventListener('drop', onDrop);- };- }, [endShowPageDrag, openWindow, setGestureActive]);+ useRouteSurfaceWindowEvent('drop', (event) => {+ const active = dragRef.current;+ if (!active) return;+ const target = event.target instanceof Element ? event.target : null;+ if (target?.closest(SHOW_PAGE_DOCK_DROP_SELECTOR)) return;+ const point = { x: event.clientX, y: event.clientY };+ if (!isShowPageWindowDrop(active.start, point)) return;+ event.preventDefault();+ dragRef.current = null;+ endShowPageDrag();+ setGestureActive(false);+ void openWindow(point);+ });const endDrag = () => {dragRef.current = null;diff --git a/ui/src/components/workbench/useShowPageAnnotation.ts b/ui/src/components/workbench/useShowPageAnnotation.tsindex 0254af8a8..5d4411c2a 100644--- a/ui/src/components/workbench/useShowPageAnnotation.ts+++ b/ui/src/components/workbench/useShowPageAnnotation.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';import { actionShortcutMatches, isPlainEscape, useActionShortcuts } from '../../lib/actionShortcuts';import { useLatestRef } from '../../lib/useLatestRef';+import { useRouteSurfaceActive, useRouteSurfaceWindowEvent } from '../../lib/routeSurfaceActivity';import { bindFrameChord } from '../apps/windowChords';// postMessage bridge between the chat host and the annotation overlay running@@ -64,6 +65,7 @@ function annotationShortcutBlocked(target: Element | null): boolean {* and so one session's state never briefly shows over another's page.*/export function useShowPageAnnotation(src: string | null): AnnotationBridge {+ const routeSurfaceActive = useRouteSurfaceActive();const iframeRef = useRef<HTMLIFrameElement | null>(null);const frameShortcutCleanupRef = useRef<() => void>(() => undefined);const [state, setState] = useState<AnnotationState | null>(null);@@ -143,23 +145,11 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {}}, []);- const escapeListeningRef = useRef(false);- const startEscapeListening = useCallback(() => {- if (escapeListeningRef.current) return;- window.addEventListener('keydown', onParentKeyDown);- escapeListeningRef.current = true;- }, [onParentKeyDown]);- const stopEscapeListening = useCallback(() => {- if (!escapeListeningRef.current) return;- window.removeEventListener('keydown', onParentKeyDown);- escapeListeningRef.current = false;- }, [onParentKeyDown]);-- useEffect(() => {- if (state?.enabled === true && iframeRef.current) startEscapeListening();- else stopEscapeListening();- return stopEscapeListening;- }, [startEscapeListening, state?.enabled, stopEscapeListening]);+ useRouteSurfaceWindowEvent(+ 'keydown',+ onParentKeyDown,+ state?.enabled === true,+ );const post = useCallback((message: ControlMessage) => {const win = iframeRef.current?.contentWindow;@@ -203,21 +193,18 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {const setIframe = useCallback<React.RefCallback<HTMLIFrameElement>>((iframe) => {- if (iframeRef.current !== iframe) {- stopEscapeListening();- }frameShortcutCleanupRef.current();frameShortcutCleanupRef.current = () => undefined;iframeRef.current = iframe;if (!iframe) return;startListening();- if (stateRef.current?.enabled === true) startEscapeListening();frameShortcutCleanupRef.current = bindFrameChord(iframe,(event, activeInFrame) => {return (!event.defaultPrevented&& !event.repeat+ && routeSurfaceActive&& stateRef.current?.available === true&& stateRef.current.enabled !== true&& actionShortcutMatches(event, shortcutRef.current)@@ -229,11 +216,10 @@ export function useShowPageAnnotation(src: string | null): AnnotationBridge {},[enableFromShortcut,+ routeSurfaceActive,shortcutRef,- startEscapeListening,startListening,stateRef,- stopEscapeListening,],);diff --git a/ui/src/context/UnsavedChangesProvider.tsx b/ui/src/context/UnsavedChangesProvider.tsxindex aaa387631..5732b7e9a 100644--- a/ui/src/context/UnsavedChangesProvider.tsx+++ b/ui/src/context/UnsavedChangesProvider.tsx@@ -1,4 +1,5 @@import { useBlocker } from 'react-router-dom';+import type { Location } from 'react-router-dom';import { useCallback, useEffect, useMemo, useRef } from 'react';import type { ReactNode } from 'react';@@ -14,6 +15,7 @@ import {type UnsavedChangesRegistrationId,type UnsavedChangesRegistry,} from '../lib/unsavedChangesRegistry';+import { settingsOverlayPreservesCurrentLocation } from '../lib/settingsOverlay';export const UnsavedChangesProvider: React.FC<{ children: ReactNode }> = ({ children }) => {const registryRef = useRef<UnsavedChangesRegistry>(new Map());@@ -31,7 +33,14 @@ export const UnsavedChangesProvider: React.FC<{ children: ReactNode }> = ({ chil// React Router 7.17 supports one blocker per router. Keep that blocker mounted here and let the// registry decide synchronously whether the current transition needs confirmation.- const shouldBlock = useCallback(() => {+ const shouldBlock = useCallback(({+ currentLocation,+ nextLocation,+ }: {+ currentLocation: Location;+ nextLocation: Location;+ }) => {+ if (settingsOverlayPreservesCurrentLocation(currentLocation, nextLocation)) return false;const hasUnsavedChanges = getUnsavedChangesMessage(registryRef.current) !== null;return navigationGateRef.current.shouldBlock(hasUnsavedChanges);}, []);diff --git a/ui/src/context/useUnsavedChanges.test.tsx b/ui/src/context/useUnsavedChanges.test.tsxnew file mode 100644index 000000000..16bb69f02--- /dev/null+++ b/ui/src/context/useUnsavedChanges.test.tsx@@ -0,0 +1,42 @@+/* @vitest-environment jsdom */++import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { RouteSurfaceActiveContext } from '../lib/routeSurfaceActivity';+import { UnsavedChangesContext } from './unsavedChangesContext';+import { useUnsavedChanges } from './useUnsavedChanges';++const DirtyProbe = () => {+ useUnsavedChanges('Unsaved editor changes');+ return null;+};++afterEach(cleanup);++describe('useUnsavedChanges', () => {+ it('withdraws a retained route registration while its surface is inactive', () => {+ const setRegistration = vi.fn();+ const context = {+ setRegistration,+ authorizeRouteAction: vi.fn(() => null),+ };+ const view = render(+ <UnsavedChangesContext.Provider value={context}>+ <RouteSurfaceActiveContext.Provider value>+ <DirtyProbe />+ </RouteSurfaceActiveContext.Provider>+ </UnsavedChangesContext.Provider>,+ );+ expect(setRegistration.mock.calls.at(-1)?.[1]).toBe('Unsaved editor changes');++ view.rerender(+ <UnsavedChangesContext.Provider value={context}>+ <RouteSurfaceActiveContext.Provider value={false}>+ <DirtyProbe />+ </RouteSurfaceActiveContext.Provider>+ </UnsavedChangesContext.Provider>,+ );+ expect(setRegistration.mock.calls.at(-1)?.[1]).toBeNull();+ });+});diff --git a/ui/src/context/useUnsavedChanges.ts b/ui/src/context/useUnsavedChanges.tsindex 21e2bdf5c..bc6a24ce2 100644--- a/ui/src/context/useUnsavedChanges.ts+++ b/ui/src/context/useUnsavedChanges.ts@@ -1,6 +1,7 @@import { useContext, useId, useLayoutEffect } from 'react';import { UnsavedChangesContext } from './unsavedChangesContext';+import { useRouteSurfaceActive } from '../lib/routeSurfaceActivity';/** Register one dirty surface with the router-wide blocker. Pass null while the surface is clean. */export function useUnsavedChanges(message: string | null): void {@@ -8,12 +9,13 @@ export function useUnsavedChanges(message: string | null): void {if (!context) throw new Error('useUnsavedChanges must be used within an UnsavedChangesProvider');const registrationId = useId();+ const routeSurfaceActive = useRouteSurfaceActive();// Layout timing closes the gap between a dirty render and the next user navigation. The identity is// stable across message changes, while the separate unmount cleanup removes stale registrations.useLayoutEffect(() => {- context.setRegistration(registrationId, message);- }, [context, message, registrationId]);+ context.setRegistration(registrationId, routeSurfaceActive ? message : null);+ }, [context, message, registrationId, routeSurfaceActive]);useLayoutEffect(() => () => {diff --git a/ui/src/lib/chatInitialMessage.test.ts b/ui/src/lib/chatInitialMessage.test.tsnew file mode 100644index 000000000..b33583cb4--- /dev/null+++ b/ui/src/lib/chatInitialMessage.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { pendingInitialMessageHandoff } from './chatInitialMessage';++const candidate = (overrides: Partial<Parameters<typeof pendingInitialMessageHandoff>[0]> = {}) => ({+ handledSessionId: null,+ loadedSessionId: 'ses_1',+ loading: false,+ locationState: { initialMessage: 'hello' },+ routeSurfaceActive: true,+ sessionId: 'ses_1',+ ...overrides,+});++describe('initial chat message handoff', () => {+ it('waits until the retained route is foreground before consuming the message', () => {+ expect(pendingInitialMessageHandoff(candidate({ routeSurfaceActive: false }))).toBeNull();+ expect(pendingInitialMessageHandoff(candidate())).toEqual({+ message: 'hello',+ sessionId: 'ses_1',+ });+ });++ it('requires the matching loaded session and an unhandled message', () => {+ expect(pendingInitialMessageHandoff(candidate({ loading: true }))).toBeNull();+ expect(pendingInitialMessageHandoff(candidate({ loadedSessionId: 'ses_2' }))).toBeNull();+ expect(pendingInitialMessageHandoff(candidate({ handledSessionId: 'ses_1' }))).toBeNull();+ expect(pendingInitialMessageHandoff(candidate({ locationState: null }))).toBeNull();+ });+});diff --git a/ui/src/lib/chatInitialMessage.ts b/ui/src/lib/chatInitialMessage.tsnew file mode 100644index 000000000..9264063fb--- /dev/null+++ b/ui/src/lib/chatInitialMessage.ts@@ -0,0 +1,26 @@+export type InitialMessageHandoff = {+ message: string;+ sessionId: string;+};++export const pendingInitialMessageHandoff = ({+ handledSessionId,+ loadedSessionId,+ loading,+ locationState,+ routeSurfaceActive,+ sessionId,+}: {+ handledSessionId: string | null;+ loadedSessionId: string | undefined;+ loading: boolean;+ locationState: unknown;+ routeSurfaceActive: boolean;+ sessionId: string | undefined;+}): InitialMessageHandoff | null => {+ if (!routeSurfaceActive || loading || !sessionId || loadedSessionId !== sessionId) return null;+ if (handledSessionId === sessionId) return null;++ const message = (locationState as { initialMessage?: unknown } | null)?.initialMessage;+ return typeof message === 'string' && message.length > 0 ? { message, sessionId } : null;+};diff --git a/ui/src/lib/navigationHistory.test.ts b/ui/src/lib/navigationHistory.test.tsindex a69abe683..2b381625f 100644--- a/ui/src/lib/navigationHistory.test.ts+++ b/ui/src/lib/navigationHistory.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { hasInAppBackEntry } from './navigationHistory';+import { hasInAppBackEntry, inAppHistoryIndex } from './navigationHistory';describe('browser navigation history', () => {it('allows back navigation only when React Router has an earlier in-app entry', () => {@@ -14,4 +14,13 @@ describe('browser navigation history', () => {expect(hasInAppBackEntry({})).toBe(false);expect(hasInAppBackEntry({ idx: '1' })).toBe(false);});++ it('reads non-negative integer router indexes for multi-entry returns', () => {+ expect(inAppHistoryIndex({ idx: 0 })).toBe(0);+ expect(inAppHistoryIndex({ idx: 4 })).toBe(4);+ expect(inAppHistoryIndex({ idx: -1 })).toBeNull();+ expect(inAppHistoryIndex({ idx: 1.5 })).toBeNull();+ expect(inAppHistoryIndex({ idx: Number.POSITIVE_INFINITY })).toBeNull();+ expect(inAppHistoryIndex({ idx: '4' })).toBeNull();+ });});diff --git a/ui/src/lib/navigationHistory.ts b/ui/src/lib/navigationHistory.tsindex 4b35e4648..1f8e9c762 100644--- a/ui/src/lib/navigationHistory.ts+++ b/ui/src/lib/navigationHistory.ts@@ -1,6 +1,11 @@-export function hasInAppBackEntry(historyState: unknown): boolean {- if (!historyState || typeof historyState !== 'object') return false;+export function inAppHistoryIndex(historyState: unknown): number | null {+ if (!historyState || typeof historyState !== 'object') return null;const index = (historyState as { idx?: unknown }).idx;- return typeof index === 'number' && Number.isFinite(index) && index > 0;+ return typeof index === 'number' && Number.isSafeInteger(index) && index >= 0 ? index : null;+}++export function hasInAppBackEntry(historyState: unknown): boolean {+ const index = inAppHistoryIndex(historyState);+ return index !== null && index > 0;}diff --git a/ui/src/lib/pageActivity.test.ts b/ui/src/lib/pageActivity.test.tsindex 537a0d85e..e07c0480d 100644--- a/ui/src/lib/pageActivity.test.ts+++ b/ui/src/lib/pageActivity.test.ts@@ -412,6 +412,7 @@ describe('canMarkConversationRead', () => {it('requires the visible chat transcript to be current and active', () => {const visibleTranscript = {pageActive: true,+ routeSurfaceActive: true,sessionReady: true,viewResolved: true,historicalWindow: false,@@ -421,6 +422,7 @@ describe('canMarkConversationRead', () => {expect(canMarkConversationRead(visibleTranscript)).toBe(true);expect(canMarkConversationRead({ ...visibleTranscript, pageActive: false })).toBe(false);+ expect(canMarkConversationRead({ ...visibleTranscript, routeSurfaceActive: false })).toBe(false);expect(canMarkConversationRead({ ...visibleTranscript, sessionReady: false })).toBe(false);expect(canMarkConversationRead({ ...visibleTranscript, viewResolved: false })).toBe(false);expect(canMarkConversationRead({ ...visibleTranscript, historicalWindow: true })).toBe(false);diff --git a/ui/src/lib/pageActivity.ts b/ui/src/lib/pageActivity.tsindex 6db6110db..ff724de9a 100644--- a/ui/src/lib/pageActivity.ts+++ b/ui/src/lib/pageActivity.ts@@ -12,6 +12,7 @@ export function isPageActive(snapshot: PageActivitySnapshot): boolean {export function canMarkConversationRead({pageActive,+ routeSurfaceActive,sessionReady,viewResolved,historicalWindow,@@ -19,6 +20,7 @@ export function canMarkConversationRead({foregroundAppWindow,}: {pageActive: boolean;+ routeSurfaceActive: boolean;sessionReady: boolean;viewResolved: boolean;historicalWindow: boolean;@@ -27,6 +29,7 @@ export function canMarkConversationRead({}): boolean {return (pageActive &&+ routeSurfaceActive &&sessionReady &&viewResolved &&!historicalWindow &&diff --git a/ui/src/lib/routeSurfaceActivity.test.tsx b/ui/src/lib/routeSurfaceActivity.test.tsxnew file mode 100644index 000000000..7127d49e5--- /dev/null+++ b/ui/src/lib/routeSurfaceActivity.test.tsx@@ -0,0 +1,46 @@+/* @vitest-environment jsdom */++import { cleanup, render } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ RouteSurfaceActiveContext,+ useRouteSurfaceWindowEvent,+} from './routeSurfaceActivity';++const KeyProbe = ({ onKey }: { onKey: () => void }) => {+ useRouteSurfaceWindowEvent('keydown', onKey);+ return null;+};++afterEach(cleanup);++describe('route surface window events', () => {+ it('withdraws global event ownership while the route is retained but inactive', () => {+ const onKey = vi.fn();+ const view = render(+ <RouteSurfaceActiveContext.Provider value>+ <KeyProbe onKey={onKey} />+ </RouteSurfaceActiveContext.Provider>,+ );++ window.dispatchEvent(new KeyboardEvent('keydown', { key: 's' }));+ expect(onKey).toHaveBeenCalledTimes(1);++ view.rerender(+ <RouteSurfaceActiveContext.Provider value={false}>+ <KeyProbe onKey={onKey} />+ </RouteSurfaceActiveContext.Provider>,+ );+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 's' }));+ expect(onKey).toHaveBeenCalledTimes(1);++ view.rerender(+ <RouteSurfaceActiveContext.Provider value>+ <KeyProbe onKey={onKey} />+ </RouteSurfaceActiveContext.Provider>,+ );+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 's' }));+ expect(onKey).toHaveBeenCalledTimes(2);+ });+});diff --git a/ui/src/lib/routeSurfaceActivity.ts b/ui/src/lib/routeSurfaceActivity.tsnew file mode 100644index 000000000..624b662dd--- /dev/null+++ b/ui/src/lib/routeSurfaceActivity.ts@@ -0,0 +1,26 @@+import { createContext, useContext, useEffect, useLayoutEffect, useRef } from 'react';++export const RouteSurfaceActiveContext = createContext(true);++export const useRouteSurfaceActive = (): boolean => useContext(RouteSurfaceActiveContext);++export const useRouteSurfaceWindowEvent = <K extends keyof WindowEventMap>(+ type: K,+ listener: (event: WindowEventMap[K]) => void,+ enabled = true,+ options?: boolean | AddEventListenerOptions,+): void => {+ const active = useRouteSurfaceActive();+ const listenerRef = useRef(listener);++ useLayoutEffect(() => {+ listenerRef.current = listener;+ }, [listener]);++ useEffect(() => {+ if (!active || !enabled) return;+ const handler = (event: WindowEventMap[K]) => listenerRef.current(event);+ window.addEventListener(type, handler as EventListener, options);+ return () => window.removeEventListener(type, handler as EventListener, options);+ }, [active, enabled, options, type]);+};diff --git a/ui/src/lib/settingsOverlay.test.ts b/ui/src/lib/settingsOverlay.test.tsnew file mode 100644index 000000000..a45fef48f--- /dev/null+++ b/ui/src/lib/settingsOverlay.test.ts@@ -0,0 +1,123 @@+import { describe, expect, it, vi } from 'vitest';+import type { Location } from 'react-router-dom';++import {+ closeSettingsOverlay,+ isSettingsEntryPath,+ settingsOverlayHistoryDelta,+ settingsOverlayNavigationState,+ settingsOverlayOriginFromState,+ settingsOverlayPreservesCurrentLocation,+ type SettingsOverlayOrigin,+} from './settingsOverlay';++const origin = (historyIndex: number | null = 2): SettingsOverlayOrigin => ({+ historyIndex,+ location: {+ pathname: '/chat/ses_1',+ search: '?message=m1',+ hash: '#tail',+ state: { source: 'search' },+ key: 'chat-origin',+ } satisfies Location,+});++const location = (pathname: string, state: unknown = null): Location => ({+ pathname,+ search: '',+ hash: '',+ state,+ key: pathname,+});++describe('Settings overlay history', () => {+ it('unwinds every entry added after the opening route', () => {+ expect(settingsOverlayHistoryDelta(origin(), { idx: 5 })).toBe(-3);+ expect(settingsOverlayHistoryDelta(origin(), { idx: 2 })).toBeNull();+ expect(settingsOverlayHistoryDelta(origin(null), { idx: 5 })).toBeNull();++ const navigate = vi.fn();+ closeSettingsOverlay(navigate, origin(), { idx: 5 });+ expect(navigate).toHaveBeenCalledWith(-3);+ });++ it('falls back to replacing the exact origin when no history index exists', () => {+ const navigate = vi.fn();+ closeSettingsOverlay(navigate, origin(null), null);++ expect(navigate).toHaveBeenCalledWith('/chat/ses_1?message=m1#tail', {+ replace: true,+ state: { source: 'search' },+ });+ });+});++describe('Settings overlay navigation ownership', () => {+ it('attaches one origin at desktop ingress and carries it through Settings', () => {+ const firstState = settingsOverlayNavigationState({+ destinationPathname: '/settings/replies',+ desktop: true,+ historyState: { idx: 2 },+ source: origin().location,+ targetState: { draft: 'first' },+ });+ expect(settingsOverlayOriginFromState(firstState)).toEqual(origin());+ expect(firstState).toMatchObject({ draft: 'first' });++ const nextState = settingsOverlayNavigationState({+ destinationPathname: '/settings/diagnostics',+ desktop: true,+ source: location('/settings/replies', firstState),+ targetState: { draft: 'next' },+ });+ expect(settingsOverlayOriginFromState(nextState)).toEqual(origin());+ expect(nextState).toMatchObject({ draft: 'next' });+ });++ it('does not turn direct or non-Settings legacy redirects into origins', () => {+ expect(isSettingsEntryPath('/doctor')).toBe(true);+ expect(isSettingsEntryPath('/admin/show-pages')).toBe(false);++ const directRedirectState = settingsOverlayNavigationState({+ destinationPathname: '/settings/diagnostics',+ desktop: true,+ source: location('/doctor'),+ targetState: undefined,+ });+ expect(settingsOverlayOriginFromState(directRedirectState)).toBeNull();+ });++ it('leaves mobile Settings ingress as a primary route', () => {+ const state = settingsOverlayNavigationState({+ destinationPathname: '/settings/replies',+ desktop: false,+ source: origin().location,+ targetState: undefined,+ });+ expect(settingsOverlayOriginFromState(state)).toBeNull();+ });++ it('identifies only an ingress that preserves the current route', () => {+ const current = origin().location;+ const overlayState = settingsOverlayNavigationState({+ destinationPathname: '/settings/replies',+ desktop: true,+ historyState: { idx: 2 },+ source: current,+ targetState: undefined,+ });++ expect(settingsOverlayPreservesCurrentLocation(+ current,+ location('/settings/replies', overlayState),+ )).toBe(true);+ expect(settingsOverlayPreservesCurrentLocation(+ location('/chat/another'),+ location('/settings/replies', overlayState),+ )).toBe(false);+ expect(settingsOverlayPreservesCurrentLocation(+ current,+ location('/settings/replies'),+ )).toBe(false);+ });+});diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.tsnew file mode 100644index 000000000..e15596b65--- /dev/null+++ b/ui/src/lib/settingsOverlay.ts@@ -0,0 +1,160 @@+import { createContext, useContext } from 'react';+import type { Location, NavigateFunction } from 'react-router-dom';++import { inAppHistoryIndex } from './navigationHistory';+import { isLegacySettingsEntryPath } from './settingsRoutes';++const SETTINGS_BACKGROUND_KEY = 'settingsBackgroundLocation';++type SettingsOverlayState = {+ [SETTINGS_BACKGROUND_KEY]?: unknown;+};++export type SettingsOverlayOrigin = {+ historyIndex: number | null;+ location: Location;+};++export const SettingsOverlayOriginContext = createContext<SettingsOverlayOrigin | null>(null);++export const useSettingsOverlayContext = (): SettingsOverlayOrigin | null =>+ useContext(SettingsOverlayOriginContext);++export const isSettingsRoutePath = (pathname: string): boolean =>+ pathname === '/settings' || pathname.startsWith('/settings/');++export const isSettingsEntryPath = (pathname: string): boolean =>+ isSettingsRoutePath(pathname) || isLegacySettingsEntryPath(pathname);++export const settingsOverlayOriginFromState = (state: unknown): SettingsOverlayOrigin | null => {+ if (!state || typeof state !== 'object') return null;+ const candidate = (state as SettingsOverlayState)[SETTINGS_BACKGROUND_KEY];+ if (!candidate || typeof candidate !== 'object') return null;++ const stored = candidate as Partial<Location> & { historyIndex?: unknown };+ if (typeof stored.pathname !== 'string' || isSettingsEntryPath(stored.pathname)) return null;+ if (typeof stored.search !== 'string' || typeof stored.hash !== 'string') return null;+ if (typeof stored.key !== 'string') return null;+ const location: Location = {+ pathname: stored.pathname,+ search: stored.search,+ hash: stored.hash,+ state: stored.state,+ key: stored.key,+ };+ const storedHistoryIndex = stored.historyIndex;+ const historyIndex = inAppHistoryIndex({ idx: storedHistoryIndex });+ return { historyIndex, location };+};++const currentHistoryState = (): unknown =>+ typeof window === 'undefined' ? null : window.history.state;++const originFromLocation = (+ location: Location,+ historyState: unknown = currentHistoryState(),+): SettingsOverlayOrigin => ({+ historyIndex: inAppHistoryIndex(historyState),+ location,+});++const overlayStateForOrigin = (origin: SettingsOverlayOrigin): SettingsOverlayState => ({+ [SETTINGS_BACKGROUND_KEY]: {+ pathname: origin.location.pathname,+ search: origin.location.search,+ hash: origin.location.hash,+ state: origin.location.state,+ key: origin.location.key,+ historyIndex: origin.historyIndex,+ },+});++export const settingsOverlayOpenState = (+ location: Location,+ historyState: unknown = currentHistoryState(),+): SettingsOverlayState => overlayStateForOrigin(originFromLocation(location, historyState));++const stateRecord = (state: unknown): Record<string, unknown> =>+ state && typeof state === 'object' && !Array.isArray(state)+ ? state as Record<string, unknown>+ : {};++export const settingsOverlayStateForOrigin = (+ origin: SettingsOverlayOrigin,+ state: unknown,+): SettingsOverlayState & Record<string, unknown> => ({+ ...stateRecord(state),+ ...overlayStateForOrigin(origin),+});++export const settingsOverlayNavigationState = ({+ destinationPathname,+ desktop,+ source,+ targetState,+ historyState = currentHistoryState(),+}: {+ destinationPathname: string;+ desktop: boolean;+ source: Location;+ targetState: unknown;+ historyState?: unknown;+}): unknown => {+ if (!isSettingsEntryPath(destinationPathname)) return targetState;+ if (settingsOverlayOriginFromState(targetState)) return targetState;++ const retainedOrigin = settingsOverlayOriginFromState(source.state);+ const origin = retainedOrigin+ ?? (desktop && !isSettingsEntryPath(source.pathname)+ ? originFromLocation(source, historyState)+ : null);+ if (!origin) return targetState;+ return settingsOverlayStateForOrigin(origin, targetState);+};++export const locationPath = (location: Pick<Location, 'pathname' | 'search' | 'hash'>): string =>+ `${location.pathname}${location.search}${location.hash}`;++export const settingsOverlayPreservesCurrentLocation = (+ currentLocation: Location,+ nextLocation: Location,+): boolean => {+ const origin = settingsOverlayOriginFromState(nextLocation.state);+ return origin !== null+ && origin.location.key === currentLocation.key+ && locationPath(origin.location) === locationPath(currentLocation);+};++export const settingsOverlayHistoryDelta = (+ origin: SettingsOverlayOrigin,+ historyState: unknown = currentHistoryState(),+): number | null => {+ const currentIndex = inAppHistoryIndex(historyState);+ if (+ origin.historyIndex === null ||+ currentIndex === null ||+ currentIndex <= origin.historyIndex+ ) return null;+ return origin.historyIndex - currentIndex;+};++export const closeSettingsOverlay = (+ navigate: NavigateFunction,+ origin: SettingsOverlayOrigin,+ historyState: unknown = currentHistoryState(),+): void => {+ const delta = settingsOverlayHistoryDelta(origin, historyState);+ if (delta !== null) {+ navigate(delta);+ return;+ }+ navigate(locationPath(origin.location), {+ replace: true,+ state: origin.location.state,+ });+};++export const useSettingsOverlayOrigin = (location: Location): SettingsOverlayOrigin | null => {+ if (!isSettingsEntryPath(location.pathname)) return null;+ return settingsOverlayOriginFromState(location.state);+};diff --git a/ui/src/lib/settingsRoutes.ts b/ui/src/lib/settingsRoutes.tsindex 981d8432a..45315baf1 100644--- a/ui/src/lib/settingsRoutes.ts+++ b/ui/src/lib/settingsRoutes.ts@@ -40,3 +40,12 @@ export const LEGACY_SETTINGS_REDIRECTS: LegacySettingsRedirect[] = [{ from: '/doctor', to: '/settings/diagnostics' },{ from: '/doctor/logs', to: '/settings/diagnostics/logs' },];++const LEGACY_SETTINGS_ENTRY_PATHS = new Set(+ LEGACY_SETTINGS_REDIRECTS+ .filter(({ to }) => to === '/settings' || to.startsWith('/settings/'))+ .map(({ from }) => from),+);++export const isLegacySettingsEntryPath = (pathname: string): boolean =>+ LEGACY_SETTINGS_ENTRY_PATHS.has(pathname);