Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(ui): keep the unsaved-changes guard while Settings is open (#2236)
Call White62fd9a7a5058
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsxindex 65dffc58d..ab2694013 100644--- a/ui/src/components/apps/WindowLayer.tsx+++ b/ui/src/components/apps/WindowLayer.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef, useState } from 'react';+import { useContext, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { APP_REGISTRY, type AppId } from '../../apps/registry';@@ -6,6 +6,7 @@ import { dockIndexFromShortcut } from '../../apps/dockShortcuts';import { useDock } from '../../context/DockContext';import { dockIdToSession } from '../../context/dockDoc';import { useApi } from '../../context/ApiContext';+import { UnsavedChangesContext } from '../../context/unsavedChangesContext';import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';import { useStandaloneAppTab } from '../../context/StandaloneAppTabContext';import { useShowPageInventory } from '../useShowPages';@@ -96,6 +97,17 @@ export const WindowLayer: React.FC<{ active?: boolean }> = ({ active = true }) =// while it steps onto a chrome-bearing route like /chat, since Back takes the Dock away// again (the flag is the mount-frozen document one; see StandaloneAppTabContext).const standaloneTab = useStandaloneAppTab();+ // Windows outlive every route change, so no navigation can take a window's+ // unsaved work: the one exit that can is the window's own close, which its+ // body guards with `useWindowCloseGuard`. The route blocker therefore takes+ // no claim from inside this layer, whether Settings is open or not. The+ // route-action pre-flight stays live, because a window control can still+ // navigate the route behind it (the title bar's open-chat button).+ const routeUnsavedChanges = useContext(UnsavedChangesContext);+ const windowUnsavedChanges = useMemo(+ () => routeUnsavedChanges && { ...routeUnsavedChanges, setRegistration: () => undefined },+ [routeUnsavedChanges],+ );const ref = useRef<HTMLDivElement | null>(null);const [size, setSize] = useState({ w: 0, h: 0 });const [archivedSessionIds, setArchivedSessionIds] = useState<ReadonlySet<string>>(() => new Set());@@ -285,42 +297,44 @@ export const WindowLayer: React.FC<{ active?: boolean }> = ({ active = true }) =// actually shown (`anyShown`, computed above).return (- <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-x-0 bottom-0 top-[var(--shell-titlebar-inset)] 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>+ <UnsavedChangesContext.Provider value={windowUnsavedChanges}>+ <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-x-0 bottom-0 top-[var(--shell-titlebar-inset)] 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>+ </UnsavedChangesContext.Provider>);};diff --git a/ui/src/components/apps/windowLayerUnsavedChanges.test.tsx b/ui/src/components/apps/windowLayerUnsavedChanges.test.tsxnew file mode 100644index 000000000..2dfdda5cf--- /dev/null+++ b/ui/src/components/apps/windowLayerUnsavedChanges.test.tsx@@ -0,0 +1,177 @@+/** @vitest-environment jsdom */++// Windows outlive every route change: opening Settings hides the layer, closing+// it shows the layer again, and a route navigation leaves the layer mounted. So+// no navigation can take a window's work, and the route blocker must never ask+// on a window's behalf. The window's close guard owns its dirty state. This pins+// that at the layer, where it is decided, rather than leaving it to whether some+// window body happens to register a route claim.++import { createInstance } from 'i18next';+import { act, cleanup, render, screen } from '@testing-library/react';+import userEvent from '@testing-library/user-event';+import { useEffect } from 'react';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import {+ Link,+ RouterProvider,+ createMemoryRouter,+ useLocation,+ useNavigate,+} from 'react-router-dom';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import en from '../../i18n/en.json';+import { UnsavedChangesProvider } from '../../context/UnsavedChangesProvider';+import { useUnsavedChanges } from '../../context/useUnsavedChanges';+import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';+import { useWindowManager, type WindowManagerValue } from '../../context/WindowManagerContext';+import { WindowManagerProvider } from '../../context/WindowManagerProvider';+import {+ closeSettingsOverlay,+ isSettingsEntryPath,+ useSettingsOverlayOrigin,+} from '../../lib/settingsOverlay';+import { SettingsOverlayNavigationBoundary } from '../settings/SettingsOverlayNavigationBoundary';+import { WindowLayer } from './WindowLayer';++const WINDOW_MESSAGE = 'Discard window draft?';+const ROUTE_MESSAGE = 'Discard route draft?';++const api = vi.hoisted(() => ({+ getShowPages: vi.fn(),+ getSessionResult: vi.fn(),+ connectWorkbenchEvents: vi.fn(),+}));++vi.mock('../../context/DockContext', () => ({ useDock: () => ({ order: [], pins: [] }) }));+vi.mock('../../context/StandaloneAppTabContext', () => ({ useStandaloneAppTab: () => false }));+vi.mock('../../context/ApiContext', () => ({ useApi: () => api }));+vi.mock('../useShowPages', () => ({ useShowPageInventory: () => ({ pages: [] }) }));+vi.mock('../workbench/ShowPageAnnotationHost', () => ({+ ShowPageAnnotationHost: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}));++// A window body that is permanently dirty and tries to claim the route blocker,+// plus the title bar's route action (open-chat), which must still pre-flight+// against the route behind the window.+vi.mock('./AppWindow', () => ({+ AppWindow: () => {+ useUnsavedChanges(WINDOW_MESSAGE);+ const authorizeRouteAction = useUnsavedChangesActionGuard();+ return (+ <div data-window-id="win_1" data-testid="window-body">+ <button type="button" onClick={() => authorizeRouteAction()}>window-route-action</button>+ </div>+ );+ },+}));++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const RouteDraft = () => {+ useUnsavedChanges(ROUTE_MESSAGE);+ return null;+};++let manager: WindowManagerValue | null = null;++// AppShell's arrangement: the layer is hidden exactly while Settings is open.+const Shell = ({ dirtyRoute }: { dirtyRoute: boolean }) => {+ const location = useLocation();+ const navigate = useNavigate();+ const origin = useSettingsOverlayOrigin(location);+ const value = useWindowManager();+ useEffect(() => {+ manager = value;+ }, [value]);+ return (+ <SettingsOverlayNavigationBoundary desktop>+ {dirtyRoute ? <RouteDraft /> : null}+ {origin ? (+ <button type="button" onClick={() => closeSettingsOverlay(navigate, origin)}>close-settings</button>+ ) : (+ <Link to="/settings/general">open-settings</Link>+ )}+ <Link to="/chat/ses_2">sidebar-chat-link</Link>+ <div data-testid="location">{location.pathname}</div>+ <WindowLayer active={!isSettingsEntryPath(location.pathname)} />+ </SettingsOverlayNavigationBoundary>+ );+};++const renderShell = ({ dirtyRoute = false } = {}) => {+ const router = createMemoryRouter([{+ path: '*',+ element: (+ <UnsavedChangesProvider>+ <I18nextProvider i18n={i18n}>+ <WindowManagerProvider onWindowForeground={() => undefined}>+ <Shell dirtyRoute={dirtyRoute} />+ </WindowManagerProvider>+ </I18nextProvider>+ </UnsavedChangesProvider>+ ),+ }], { initialEntries: ['/chat/ses_1'] });+ render(<RouterProvider router={router} />);+ act(() => void manager!.openApp('editor'));+ expect(screen.getByTestId('window-body')).toBeTruthy();+};++let confirmSpy: ReturnType<typeof vi.fn>;++beforeEach(() => {+ vi.stubGlobal('ResizeObserver', class {+ observe() {}+ unobserve() {}+ disconnect() {}+ });+ confirmSpy = vi.fn(() => false);+ vi.stubGlobal('confirm', confirmSpy);+ window.history.replaceState(null, '');+ api.getShowPages.mockReset().mockResolvedValue([]);+ api.getSessionResult.mockReset().mockResolvedValue({ status: null, session: null });+ api.connectWorkbenchEvents.mockReset().mockReturnValue(vi.fn());+ manager = null;+});++afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ vi.clearAllMocks();+});++describe('WindowLayer and the route unsaved-changes blocker', () => {+ it('never prompts for a dirty window on Settings open, close or route navigation', async () => {+ const user = userEvent.setup();+ renderShell();++ await user.click(screen.getByRole('link', { name: 'open-settings' }));+ expect(screen.getByTestId('location').textContent).toBe('/settings/general');+ await user.click(screen.getByRole('button', { name: 'close-settings' }));+ expect(screen.getByTestId('location').textContent).toBe('/chat/ses_1');++ await user.click(screen.getByRole('link', { name: 'open-settings' }));+ await user.click(screen.getByRole('link', { name: 'sidebar-chat-link' }));+ expect(screen.getByTestId('location').textContent).toBe('/chat/ses_2');++ expect(confirmSpy).not.toHaveBeenCalled();+ expect(screen.getByTestId('window-body')).toBeTruthy();+ });++ it('still pre-flights a window route action against the dirty route behind it', async () => {+ const user = userEvent.setup();+ renderShell({ dirtyRoute: true });++ await user.click(screen.getByRole('button', { name: 'window-route-action' }));++ expect(confirmSpy).toHaveBeenCalledTimes(1);+ expect(confirmSpy).toHaveBeenCalledWith(ROUTE_MESSAGE);+ });+});diff --git a/ui/src/context/UnsavedChangesProvider.test.tsx b/ui/src/context/UnsavedChangesProvider.test.tsxindex 8c4941f1b..3c0694b99 100644--- a/ui/src/context/UnsavedChangesProvider.test.tsx+++ b/ui/src/context/UnsavedChangesProvider.test.tsx@@ -1,9 +1,13 @@/* @vitest-environment jsdom */-import { cleanup, fireEvent, render, screen } from '@testing-library/react';+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 { useState } from 'react';import {+ Link,Navigate,+ Outlet,Route,RouterProvider,createMemoryRouter,@@ -12,76 +16,97 @@ import {useNavigate,} from 'react-router-dom';+import { SettingsOverlayNavigationBoundary } from '../components/settings/SettingsOverlayNavigationBoundary';import { SettingsOverlayRouteSurface } from '../components/settings/SettingsOverlayRouteSurface';import {closeSettingsOverlay,- settingsOverlayOpenState,+ useSettingsOverlayContext,useSettingsOverlayOrigin,} from '../lib/settingsOverlay';+import { SETTINGS_MENU_PLACEMENT_STORAGE_KEY } from '../lib/settingsMenuPlacement';import { UnsavedChangesProvider } from './UnsavedChangesProvider';import { useUnsavedChanges } from './useUnsavedChanges';const DIRTY_MESSAGE = 'Discard unsaved changes?';+// The route's claim follows its draft, exactly as a real editor's does, so the+// assertions below can also prove the draft itself survived.const DirtyEditorRoute = () => {- const navigate = useNavigate();- useUnsavedChanges(DIRTY_MESSAGE);+ const [draft, setDraft] = useState('');+ useUnsavedChanges(draft ? DIRTY_MESSAGE : null);return (- <main>- <div data-testid="editor">editor</div>- <button type="button" onClick={() => navigate('/chat/ses_1')}>leave-editor</button>- </main>+ <input+ aria-label="editor draft"+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />);};-const OpenSettings = () => {+// AppShell's sidebar toggle: a link into Settings while it is closed, and the+// overlay's own exit while it is open.+const SettingsToggle = () => {const location = useLocation();const navigate = useNavigate();- return (+ const origin = useSettingsOverlayOrigin(location);+ return origin ? (<buttontype="button"- onClick={() => navigate('/settings/general', { state: settingsOverlayOpenState(location) })}+ data-settings-toggle="true"+ onClick={() => closeSettingsOverlay(navigate, origin)}>- open-settings+ shell-settings</button>+ ) : (+ <Link to="/settings/general" data-settings-toggle="true">shell-settings</Link>);};-// Stands in for AppShell's `onWindowForeground` exit: the same-// `closeSettingsOverlay` call, made from shell chrome rather than from a-// control inside the surface.-const WindowForegroundExit = () => {- const location = useLocation();+const SettingsFrame = () => {const navigate = useNavigate();- const origin = useSettingsOverlayOrigin(location);- if (!origin) return null;+ const origin = useSettingsOverlayContext();return (- <button type="button" onClick={() => closeSettingsOverlay(navigate, origin)}>- leave-for-window- </button>+ <section>+ <button type="button" onClick={() => origin && closeSettingsOverlay(navigate, origin)}>+ close-settings+ </button>+ <Link to="/settings/replies">replies-section</Link>+ <Outlet />+ </section>);};const Root = () => (<UnsavedChangesProvider>- <OpenSettings />- <WindowForegroundExit />- <SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}>- <Route path="/apps/editor" element={<DirtyEditorRoute />} />- <Route path="/chat/:sessionId" element={<div data-testid="chat">chat</div>} />- <Route path="/settings/general" element={<div data-testid="settings">settings</div>} />- </SettingsOverlayRouteSurface>+ <SettingsOverlayNavigationBoundary desktop>+ <SettingsToggle />+ {/* Shell chrome outside the overlay, live beside Settings in both menu placements. */}+ <aside>+ <Link to="/chat/ses_1">sidebar-chat-link</Link>+ </aside>+ <SettingsOverlayRouteSurface fallbackElement={<Navigate to="/" replace />}>+ <Route path="/apps/editor" element={<DirtyEditorRoute />} />+ <Route path="/chat/:sessionId" element={<div data-testid="chat">chat</div>} />+ <Route path="/settings" element={<SettingsFrame />}>+ <Route path="general" element={<div>general-settings</div>} />+ <Route path="replies" element={<div>replies-settings</div>} />+ </Route>+ </SettingsOverlayRouteSurface>+ </SettingsOverlayNavigationBoundary></UnsavedChangesProvider>);-const renderApp = () => render(- <RouterProvider- router={createMemoryRouter(- createRoutesFromElements(<Route path="*" element={<Root />} />),- { initialEntries: ['/apps/editor'] },- )}- />,-);+const renderApp = () => {+ const router = createMemoryRouter(+ createRoutesFromElements(<Route path="*" element={<Root />} />),+ { initialEntries: ['/apps/editor'] },+ );+ render(<RouterProvider router={router} />);+ return router;+};++const settingsOpen = () => document.querySelector('[data-settings-overlay="true"]') !== null;+const draft = () => (screen.getByLabelText('editor draft') as HTMLInputElement).value;let confirmSpy: ReturnType<typeof vi.fn>;@@ -89,6 +114,9 @@ beforeEach(() => {confirmSpy = vi.fn(() => false);vi.stubGlobal('confirm', confirmSpy);window.localStorage.clear();+ // Closing Settings reads the real history stack to choose between a pop and a+ // replace; each test that cares sets `idx` itself.+ window.history.replaceState(null, '');vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({matches: true,addEventListener: vi.fn(),@@ -101,36 +129,93 @@ afterEach(() => {vi.unstubAllGlobals();});-describe('UnsavedChangesProvider and the Settings overlay', () => {- it('leaves the overlay without a discard prompt while the dirty route is retained', () => {- renderApp();- fireEvent.click(screen.getByText('open-settings'));- expect(screen.getByTestId('settings')).toBeTruthy();- // The dirty route did not unmount — it is retained behind the surface, with- // its draft intact. That is what makes the exit below lossless.- expect(screen.getByTestId('editor')).toBeTruthy();-- fireEvent.click(screen.getByText('leave-for-window'));-- // Closing the overlay returns to the route it was opened over, so there is- // nothing to discard and nothing to confirm. An exit that cannot be refused- // is also an exit its caller cannot half-apply: whatever brought the user- // out of Settings — a window coming forward, the toggle, Escape — completes- // whole. Should a future change re-arm the registration behind the surface,- // this fails rather than silently reintroducing that split.- expect(confirmSpy).not.toHaveBeenCalled();- expect(screen.queryByTestId('settings')).toBeNull();- expect(screen.getByTestId('editor')).toBeTruthy();- });+describe('UnsavedChangesProvider with Settings closed', () => {+ it('prompts before a navigation leaves the dirty route', async () => {+ const user = userEvent.setup();+ const router = renderApp();+ await user.type(screen.getByLabelText('editor draft'), 'draft');- it('still prompts when the navigation really does leave the dirty route', () => {- renderApp();-- fireEvent.click(screen.getByText('leave-editor'));+ await user.click(screen.getByRole('link', { name: 'sidebar-chat-link' }));+ expect(confirmSpy).toHaveBeenCalledTimes(1);expect(confirmSpy).toHaveBeenCalledWith(DIRTY_MESSAGE);- // Cancelled, so the editor keeps the route it never left.- expect(screen.queryByTestId('chat')).toBeNull();- expect(screen.getByTestId('editor')).toBeTruthy();+ expect(router.state.location.pathname).toBe('/apps/editor');+ expect(draft()).toBe('draft');});});++// Both menu placements render the same overlay over the same blocker; they+// differ only in what an outside click means, which is why each is driven here.+describe.each(['standalone', 'inline'] as const)(+ 'UnsavedChangesProvider with Settings open (%s menu)',+ (placement) => {+ beforeEach(() => {+ window.localStorage.setItem(SETTINGS_MENU_PLACEMENT_STORAGE_KEY, placement);+ });++ const openSettingsOverDirtyEditor = async (user: ReturnType<typeof userEvent.setup>) => {+ const router = renderApp();+ await user.type(screen.getByLabelText('editor draft'), 'draft');+ window.history.replaceState({ idx: 0 }, '');+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ expect(settingsOpen()).toBe(true);+ return router;+ };++ it.each([+ // Two entries above the origin: the exit pops back to the origin entry.+ ['by history pop', { idx: 2 }],+ // No history index: the exit replaces onto the origin under a new key.+ ['by replace', null],+ ] as const)('opens, changes section and closes %s without a prompt', async (_, historyAtClose) => {+ const user = userEvent.setup();+ const router = await openSettingsOverDirtyEditor(user);++ await user.click(screen.getByRole('link', { name: 'replies-section' }));+ expect(screen.getByText('replies-settings')).toBeTruthy();+ window.history.replaceState(historyAtClose, '');+ await user.click(screen.getByRole('button', { name: 'close-settings' }));++ await waitFor(() => expect(settingsOpen()).toBe(false));+ expect(confirmSpy).not.toHaveBeenCalled();+ expect(router.state.location.pathname).toBe('/apps/editor');+ expect(draft()).toBe('draft');++ // Reopening over the same route and leaving by the shell toggle is just as quiet.+ await user.click(screen.getByRole('link', { name: 'shell-settings' }));+ await user.click(screen.getByRole('button', { name: 'shell-settings' }));+ await waitFor(() => expect(settingsOpen()).toBe(false));+ expect(confirmSpy).not.toHaveBeenCalled();+ expect(draft()).toBe('draft');+ });++ it('prompts once for a shell navigation and keeps everything in place on cancel', async () => {+ const user = userEvent.setup();+ const router = await openSettingsOverDirtyEditor(user);++ await user.click(screen.getByRole('link', { name: 'sidebar-chat-link' }));++ expect(confirmSpy).toHaveBeenCalledTimes(1);+ expect(confirmSpy).toHaveBeenCalledWith(DIRTY_MESSAGE);+ expect(router.state.location.pathname).toBe('/settings/general');+ expect(settingsOpen()).toBe(true);+ expect(screen.getByText('general-settings')).toBeTruthy();+ expect(screen.queryByTestId('chat')).toBeNull();+ expect(draft()).toBe('draft');+ });++ it('navigates and closes Settings when the discard is confirmed', async () => {+ const user = userEvent.setup();+ const router = await openSettingsOverDirtyEditor(user);+ confirmSpy.mockReturnValue(true);++ await user.click(screen.getByRole('link', { name: 'sidebar-chat-link' }));++ expect(confirmSpy).toHaveBeenCalledTimes(1);+ await waitFor(() => expect(router.state.location.pathname).toBe('/chat/ses_1'));+ expect(screen.getByTestId('chat')).toBeTruthy();+ await waitFor(() => expect(settingsOpen()).toBe(false));+ expect(screen.queryByLabelText('editor draft')).toBeNull();+ });+ },+);diff --git a/ui/src/context/UnsavedChangesProvider.tsx b/ui/src/context/UnsavedChangesProvider.tsxindex 5732b7e9a..17a61dd29 100644--- a/ui/src/context/UnsavedChangesProvider.tsx+++ b/ui/src/context/UnsavedChangesProvider.tsx@@ -15,7 +15,7 @@ import {type UnsavedChangesRegistrationId,type UnsavedChangesRegistry,} from '../lib/unsavedChangesRegistry';-import { settingsOverlayPreservesCurrentLocation } from '../lib/settingsOverlay';+import { settingsOverlayKeepsRetainedRoute } from '../lib/settingsOverlay';export const UnsavedChangesProvider: React.FC<{ children: ReactNode }> = ({ children }) => {const registryRef = useRef<UnsavedChangesRegistry>(new Map());@@ -40,7 +40,7 @@ export const UnsavedChangesProvider: React.FC<{ children: ReactNode }> = ({ chilcurrentLocation: Location;nextLocation: Location;}) => {- if (settingsOverlayPreservesCurrentLocation(currentLocation, nextLocation)) return false;+ if (settingsOverlayKeepsRetainedRoute(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.tsxdeleted file mode 100644index 16bb69f02..000000000--- a/ui/src/context/useUnsavedChanges.test.tsx+++ /dev/null@@ -1,42 +0,0 @@-/* @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 bc6a24ce2..9fdb1c742 100644--- a/ui/src/context/useUnsavedChanges.ts+++ b/ui/src/context/useUnsavedChanges.ts@@ -1,21 +1,26 @@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. */+/**+ * Register one dirty route surface with the router-wide blocker. Pass null while the surface is clean.+ *+ * A route retained behind Settings keeps its claim: the blocker exempts only the transitions that keep+ * that route mounted (`settingsOverlayKeepsRetainedRoute`), so any navigation that would unmount it+ * still prompts. App windows outlive every route change and guard their own close with+ * `useWindowCloseGuard`; the window layer therefore takes no claim here.+ */export function useUnsavedChanges(message: string | null): void {const context = useContext(UnsavedChangesContext);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, routeSurfaceActive ? message : null);- }, [context, message, registrationId, routeSurfaceActive]);+ context.setRegistration(registrationId, message);+ }, [context, message, registrationId]);useLayoutEffect(() => () => {diff --git a/ui/src/lib/settingsOverlay.test.ts b/ui/src/lib/settingsOverlay.test.tsindex f62df27ec..2e5dcfdcb 100644--- a/ui/src/lib/settingsOverlay.test.ts+++ b/ui/src/lib/settingsOverlay.test.ts@@ -7,7 +7,7 @@ import {settingsOverlayHistoryDelta,settingsOverlayNavigationState,settingsOverlayOriginFromState,- settingsOverlayPreservesCurrentLocation,+ settingsOverlayKeepsRetainedRoute,type SettingsOverlayOrigin,} from './settingsOverlay';@@ -174,7 +174,7 @@ describe('Settings overlay navigation ownership', () => {expect(settingsOverlayOriginFromState(state)).toBeNull();});- it('identifies only an ingress that preserves the current route', () => {+ it('exempts exactly the transitions that keep the route behind Settings mounted', () => {const current = origin().location;const overlayState = settingsOverlayNavigationState({destinationPathname: '/settings/replies',@@ -183,18 +183,26 @@ describe('Settings overlay navigation ownership', () => {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);+ const replies = location('/settings/replies', overlayState);+ const nextSection = location('/settings/diagnostics', settingsOverlayNavigationState({+ destinationPathname: '/settings/diagnostics',+ desktop: true,+ source: replies,+ targetState: undefined,+ }));++ // Opening over the current entry, and only that entry.+ expect(settingsOverlayKeepsRetainedRoute(current, replies)).toBe(true);+ expect(settingsOverlayKeepsRetainedRoute(location('/chat/another'), replies)).toBe(false);+ expect(settingsOverlayKeepsRetainedRoute(current, location('/settings/replies'))).toBe(false);+ // Moving between sections over the same origin.+ expect(settingsOverlayKeepsRetainedRoute(replies, nextSection)).toBe(true);+ // Closing onto the origin, by history pop (same key) or by replace (new key).+ expect(settingsOverlayKeepsRetainedRoute(replies, current)).toBe(true);+ expect(settingsOverlayKeepsRetainedRoute(replies, { ...current, key: 'replaced' })).toBe(true);+ // Any other navigation made while Settings is open leaves the retained route.+ expect(settingsOverlayKeepsRetainedRoute(replies, location('/chat/another'))).toBe(false);+ expect(settingsOverlayKeepsRetainedRoute(replies, { ...current, hash: '' })).toBe(false);+ expect(settingsOverlayKeepsRetainedRoute(replies, location('/settings/general'))).toBe(false);});});diff --git a/ui/src/lib/settingsOverlay.ts b/ui/src/lib/settingsOverlay.tsindex e05c693f2..ab124bc27 100644--- a/ui/src/lib/settingsOverlay.ts+++ b/ui/src/lib/settingsOverlay.ts@@ -169,14 +169,36 @@ export const settingsOverlayNavigationState = ({export const locationPath = (location: Pick<Location, 'pathname' | 'search' | 'hash'>): string =>`${location.pathname}${location.search}${location.hash}`;-export const settingsOverlayPreservesCurrentLocation = (+const overlayOrigin = (location: Location): SettingsOverlayOrigin | null =>+ isSettingsEntryPath(location.pathname) ? settingsOverlayOriginFromState(location.state) : null;++/**+ * Whether a navigation keeps the route behind Settings mounted, so a discard+ * prompt for that route would be false in both of its branches. Three+ * transitions do: opening Settings over the current route, moving between+ * Settings sections over the same origin, and closing back onto that origin.+ * Every other navigation leaves the route it came from, whether or not+ * Settings is open when it is made.+ */+export const settingsOverlayKeepsRetainedRoute = (currentLocation: Location,nextLocation: Location,): boolean => {- const origin = settingsOverlayOriginFromState(nextLocation.state);- return origin !== null- && origin.location.key === currentLocation.key- && locationPath(origin.location) === locationPath(currentLocation);+ // Opening: the next location records this very entry as its origin.+ const openedOrigin = settingsOverlayOriginFromState(nextLocation.state);+ if (+ openedOrigin !== null+ && openedOrigin.location.key === currentLocation.key+ && locationPath(openedOrigin.location) === locationPath(currentLocation)+ ) return true;+ // Moving within Settings or closing it: the next location renders the same+ // route behind (or instead of) the overlay. Matched by path, not key —+ // `closeSettingsOverlay` falls back to a replace that lands on the origin+ // under a new key.+ const origin = overlayOrigin(currentLocation);+ if (origin === null) return false;+ const nextRoute = overlayOrigin(nextLocation)?.location ?? nextLocation;+ return locationPath(nextRoute) === locationPath(origin.location);};export const settingsOverlayHistoryDelta = (@@ -208,7 +230,5 @@ export const closeSettingsOverlay = (});};-export const useSettingsOverlayOrigin = (location: Location): SettingsOverlayOrigin | null => {- if (!isSettingsEntryPath(location.pathname)) return null;- return settingsOverlayOriginFromState(location.state);-};+export const useSettingsOverlayOrigin = (location: Location): SettingsOverlayOrigin | null =>+ overlayOrigin(location);