Skip to content

armgit / avibe

Public Imported from GitHub
0

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

fix(ui): protect unsaved editor routes from navigation (#870)

Call White3a3f759ab55c
diff --git a/docs/plans/issue-803-unsaved-navigation-guard.md b/docs/plans/issue-803-unsaved-navigation-guard.md
new file mode 100644
index 000000000..de9e3e59b
--- /dev/null
+++ b/docs/plans/issue-803-unsaved-navigation-guard.md
@@ -0,0 +1,46 @@
+# Issue 803: Router-wide unsaved changes guard
+
+## Background
+
+The full-page Editor introduced in #800 keeps unsaved buffers inside the routed page. Its hard-unload
+and window-close guards do not protect desktop links, imperative SPA navigation, or browser Back.
+The interim `NavGuardContext` covers only selected mobile controls because `BrowserRouter` cannot use
+React Router's supported `useBlocker` API.
+
+## Goal
+
+Give every route-mounted dirty surface one reusable registration contract while keeping exactly one
+router blocker. Preserve hard-unload protection and keep windowed-app close behavior independent.
+
+## Design
+
+- Replace the root `BrowserRouter` with `createBrowserRouter` and `RouterProvider`, retaining the
+ current pathless auth/AppShell layout and all child routes.
+- Mount `UnsavedChangesProvider` as the data router's root layout. It owns the only `useBlocker` and a
+ stable-identity message registry.
+- Aggregate both full-page Editor variants' dirty state in `AppsEditorPage`, then register once and
+ retain the existing `beforeunload` listener.
+- Remove manual AppShell confirmation wrappers. Links, imperative navigation, and POP transitions all
+ pass through the central blocker; window close guards remain unchanged.
+- Keep unread clearing owned by the mounted `ChatPage`, not navigation click handlers, so a blocked
+ transition cannot mutate session state before the user confirms it.
+- Let data-mutating actions that need a generated route pre-authorize exactly one synchronous
+ navigation through the same Provider. Cancel happens before mutation and successful actions do not
+ trigger a second prompt or leave a reusable bypass behind.
+
+## Verification
+
+- [x] Registry unit tests
+- [x] Changed-file lint and UI typecheck/build
+- [x] Desktop sidebar cancel/confirm with buffer preservation
+- [x] Browser Back cancel, retry, and confirm
+- [x] Mobile bottom navigation and Back
+- [x] Imperative navigation, clean navigation, and hard-unload listener
+- [x] Canceled session navigation sends no mark-read request; confirmed navigation marks once
+- [x] Canceled new-session action creates nothing; confirmed creation navigates with one prompt
+- [x] Setup/auth/remote redirect, lazy Apps routes, and legacy redirects
+- [x] Local Incus worktree service and mobile blocker smoke
+
+The repository-wide ESLint command still reports the existing baseline (333 errors and 42 warnings,
+including unchanged code in `App.tsx` and `AppShell.tsx`). The new modules pass ESLint, and the
+changed existing files pass after suppressing only their baseline rule categories.
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index bbac7a4dd..c715ead4b 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -1,4 +1,13 @@
-import { BrowserRouter, Routes, Route, Navigate, useLocation, useNavigate } from 'react-router-dom';
+import {
+ createBrowserRouter,
+ createRoutesFromElements,
+ Navigate,
+ Outlet,
+ Route,
+ RouterProvider,
+ useLocation,
+ useNavigate,
+} from 'react-router-dom';
import { Wizard } from './components/Wizard';
import { AppShell } from './components/AppShell';
import { ErrorBoundary } from './components/ui/error-boundary';
@@ -35,7 +44,7 @@ import { VaultSandboxAppearanceBridge } from './components/VaultSandboxAppearanc
import { WorkbenchInboxProvider } from './context/WorkbenchInboxContext';
import { WorkbenchProjectsProvider } from './context/WorkbenchProjectsContext';
import { ComposerBridgeProvider } from './context/ComposerBridgeContext';
-import { NavGuardProvider } from './context/NavGuardContext';
+import { UnsavedChangesProvider } from './context/UnsavedChangesProvider';
import { AgentationToggle } from './components/AgentationToggle';
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
@@ -306,12 +315,19 @@ const DocumentTitle = () => {
return null;
};
-function AppRoutes() {
+function RouterRoot() {
return (
- <>
- <DocumentTitle />
- <WebPushNotificationNavigator />
- <Routes>
+ <UnsavedChangesProvider>
+ <DocumentTitle />
+ <WebPushNotificationNavigator />
+ <Outlet />
+ </UnsavedChangesProvider>
+ );
+}
+
+const router = createBrowserRouter(
+ createRoutesFromElements(
+ <Route element={<ErrorBoundary variant="page"><RouterRoot /></ErrorBoundary>}>
<Route element={<AuthGuard><AppShell /></AuthGuard>}>
<Route path="/setup" element={<Wizard />} />
@@ -405,10 +421,9 @@ function AppRoutes() {
<Route path="/doctor" element={<Navigate to="/admin/settings/diagnostics" replace />} />
<Route path="/doctor/logs" element={<Navigate to="/admin/logs" replace />} />
</Route>
- </Routes>
- </>
- );
-}
+ </Route>,
+ ),
+);
function App() {
return (
@@ -424,12 +439,8 @@ function App() {
<WorkbenchInboxProvider>
<WorkbenchProjectsProvider>
<ComposerBridgeProvider>
- <NavGuardProvider>
- <BrowserRouter>
- <AppRoutes />
- </BrowserRouter>
- <AgentationToggle />
- </NavGuardProvider>
+ <RouterProvider router={router} />
+ <AgentationToggle />
</ComposerBridgeProvider>
</WorkbenchProjectsProvider>
</WorkbenchInboxProvider>
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 70bb67ca9..c1b7a3873 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -15,7 +15,6 @@ import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
import { AppsLauncher } from './AppsLauncher';
import { ErrorBoundary } from './ui/error-boundary';
import { WindowManagerProvider } from '../context/WindowManagerContext';
-import { useNavGuard } from '../context/NavGuardContext';
import { WindowLayer } from './apps/WindowLayer';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
@@ -113,7 +112,6 @@ const ShellNavGroup: React.FC<{ item: ShellNavItem }> = ({ item }) => {
const MobileNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {
const location = useLocation();
- const { confirmLeave } = useNavGuard();
const active = item.match ? item.match(location.pathname) : location.pathname === item.to;
const Icon = item.icon;
const isWorkbench = item.variant === 'workbench';
@@ -149,12 +147,9 @@ const MobileNavLink: React.FC<{ item: ShellNavItem }> = ({ item }) => {
);
if (item.onClick) {
- const onClick = item.onClick;
- return <button type="button" onClick={() => { if (confirmLeave()) onClick(); }} className={className}>{inner}</button>;
+ return <button type="button" onClick={item.onClick} className={className}>{inner}</button>;
}
- // Confirm before leaving a page that registered an unsaved-changes guard (e.g. the mobile editor);
- // NavLink navigation bypasses `beforeunload`, so this is where in-app tab taps get intercepted.
- return <NavLink to={item.to ?? '#'} onClick={(e) => { if (!confirmLeave()) e.preventDefault(); }} className={className}>{inner}</NavLink>;
+ return <NavLink to={item.to ?? '#'} className={className}>{inner}</NavLink>;
};
type CenterButton = { label: string; icon: React.ComponentType<{ className?: string }>; to?: string; onClick?: () => void };
@@ -164,7 +159,6 @@ type CenterButton = { label: string; icon: React.ComponentType<{ className?: str
// Workbench (jump back) — the symmetric counterpart Alex asked for, so each
// shell can reach the other from the tab bar.
const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> = ({ items, center }) => {
- const { confirmLeave } = useNavGuard();
// No center FAB → a plain even row of tabs. The Control Panel uses this so
// "Workbench" is just the first tab, which reads cleaner than an asymmetric
// raised center button.
@@ -190,7 +184,7 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
<Button
type="button"
variant="brand"
- onClick={() => { if (confirmLeave()) center.onClick?.(); }}
+ onClick={center.onClick}
aria-label={center.label}
className="size-12 -translate-y-1 rounded-full p-0 shadow-[0_8px_20px_-4px_rgba(91,255,160,0.6)]"
>
@@ -202,7 +196,7 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
variant="brand"
className="size-12 -translate-y-1 rounded-full p-0 shadow-[0_8px_20px_-4px_rgba(91,255,160,0.6)]"
>
- <Link to={center.to ?? '/'} onClick={(e) => { if (!confirmLeave()) e.preventDefault(); }} aria-label={center.label}>
+ <Link to={center.to ?? '/'} aria-label={center.label}>
<CenterIcon className="size-6" />
</Link>
</Button>
diff --git a/ui/src/components/workbench/AppsEditorPage.tsx b/ui/src/components/workbench/AppsEditorPage.tsx
index 672fa4cca..7d9b0fb67 100644
--- a/ui/src/components/workbench/AppsEditorPage.tsx
+++ b/ui/src/components/workbench/AppsEditorPage.tsx
@@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next';
import { CodeXml, FolderOpen } from 'lucide-react';
import { Button } from '../ui/button';
-import { useNavGuard } from '../../context/NavGuardContext';
+import { useUnsavedChanges } from '../../context/useUnsavedChanges';
import { FileEditorPane } from './FileEditorPane';
// The Editor app as a full-page route (sibling of /apps/files and /apps/terminal). On desktop it
@@ -41,8 +41,7 @@ function useDesktopAtMount(): boolean {
}
// Warn before a hard unload (refresh / tab close / leaving the SPA) while there are unsaved edits.
-// SPA in-app navigation does NOT fire this — that's handled separately (mobile: the NavGuard on the
-// tab bar; both surfaces: the editor's own guarded controls).
+// React Router's blocker handles in-app navigation separately.
function useUnloadWarning(active: boolean): void {
useEffect(() => {
if (!active) return;
@@ -64,9 +63,12 @@ export const AppsEditorPage: React.FC = () => {
const { t } = useTranslation();
const location = useLocation();
const desktop = useDesktopAtMount();
+ const [dirty, setDirty] = useState(false);
// Re-read whenever the router state changes (each navigation carries a fresh state object) so
// opening another file while already on this route swaps the launch target.
const launch = useMemo(() => readLaunch(location.state), [location.state]);
+ useUnsavedChanges(dirty ? t('apps.editor.confirmDiscardSwitch') : null);
+ useUnloadWarning(dirty);
return (
<div className="flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]">
@@ -74,7 +76,11 @@ export const AppsEditorPage: React.FC = () => {
<h1 className="text-[18px] font-semibold text-foreground">{t('apps.editor.label')}</h1>
<p className="text-[12px] text-muted">{t('apps.editor.tagline')}</p>
</div>
- {desktop ? <DesktopEditor launch={launch} /> : <MobileEditor launch={launch} />}
+ {desktop ? (
+ <DesktopEditor launch={launch} onDirtyChange={setDirty} />
+ ) : (
+ <MobileEditor launch={launch} onDirtyChange={setDirty} />
+ )}
</div>
);
};
@@ -82,15 +88,16 @@ export const AppsEditorPage: React.FC = () => {
// Desktop / tablet: the full Editor IDE, forced dark like its Dock window (data-theme re-cascades the
// dark token set to this subtree). No windowId, so the window-only niceties (title, close guard,
// ⌘O/⌘N) stay inert; open/edit/save all work full-page. `useWindowCloseGuard` is a no-op without a
-// window, so a page-level unload warning covers a dirty refresh/close here.
-const DesktopEditor: React.FC<{ launch: LaunchFile | null }> = ({ launch }) => {
- const [dirty, setDirty] = useState(false);
- useUnloadWarning(dirty);
+// window, so the route page owns its navigation and unload guards.
+const DesktopEditor: React.FC<{
+ launch: LaunchFile | null;
+ onDirtyChange: (dirty: boolean) => void;
+}> = ({ launch, onDirtyChange }) => {
return (
<div data-theme="dark" className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">
<Suspense fallback={<PaneLoading />}>
<EditorApp
- onDirtyChange={setDirty}
+ onDirtyChange={onDirtyChange}
params={launch ? { path: launch.path, filename: launch.filename, mtime: launch.mtime } : undefined}
/>
</Suspense>
@@ -102,37 +109,25 @@ const DesktopEditor: React.FC<{ launch: LaunchFile | null }> = ({ launch }) => {
// renders the filename + dirty dot + Save header and the Monaco touch accessory bar; opening/switching
// a file reuses the File Browser (the mobile file-picking surface, which owns the editable-vs-download
// decision). The name-only launch has no live cursor/search — that richness stays on the desktop IDE.
-const MobileEditor: React.FC<{ launch: LaunchFile | null }> = ({ launch }) => {
+const MobileEditor: React.FC<{
+ launch: LaunchFile | null;
+ onDirtyChange: (dirty: boolean) => void;
+}> = ({ launch, onDirtyChange }) => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { setGuard } = useNavGuard();
const [file, setFile] = useState<LaunchFile | null>(launch);
- const [dirty, setDirty] = useState(false);
- // A fresh navigation from Files swaps the open file. Edits to a previous file were already
- // discarded when the user left this page to pick another (guarded in openAnother).
+ // A fresh navigation from Files swaps the open file. The router-wide blocker already confirmed
+ // before a dirty editor could leave this page to pick another.
useEffect(() => {
if (launch) {
setFile(launch);
- setDirty(false);
+ onDirtyChange(false);
}
- }, [launch]);
-
- // Open / switch a file via the File Browser. Confirm first when the current buffer is dirty, since
- // leaving unmounts this pane and drops the unsaved edits.
- const openAnother = () => {
- if (dirty && !window.confirm(t('apps.editor.confirmDiscardSwitch'))) return;
- navigate('/apps/files');
- };
+ }, [launch, onDirtyChange]);
- // Guard leaving with unsaved edits: the NavGuard confirms in-app mobile tab-bar navigation (whose
- // NavLinks bypass `beforeunload`); useUnloadWarning covers a hard unload. The header open button is
- // separately guarded in openAnother.
- useEffect(() => {
- setGuard(dirty ? t('apps.editor.confirmDiscardSwitch') : null);
- return () => setGuard(null);
- }, [dirty, setGuard, t]);
- useUnloadWarning(dirty);
+ // This imperative navigation uses the same router-level blocker as links and browser Back.
+ const openAnother = () => navigate('/apps/files');
return (
<div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded-xl border border-border bg-surface">
@@ -146,7 +141,7 @@ const MobileEditor: React.FC<{ launch: LaunchFile | null }> = ({ launch }) => {
filename={file.filename}
mtime={file.mtime}
onOpenFile={openAnother}
- onDirtyChange={setDirty}
+ onDirtyChange={onDirtyChange}
/>
) : (
<div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-4 p-8 text-center">
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index c2180f458..796513195 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1257,7 +1257,8 @@ export const ChatPage: React.FC = () => {
// not "new". Clear unread whenever it appears — on open, or when a realtime
// inbox.session.updated lands after a reply — so the Inbox/sidebar never badge
// the chat you're looking at. Reactive to the unread map, so it's race-free
- // against the cross-process event ordering.
+ // against the cross-process event ordering. Owning this on the mounted route
+ // also keeps a canceled blocked navigation from clearing unread state early.
useEffect(() => {
if (historicalWindow) return;
if (sessionId && (unreadBySession[sessionId] ?? 0) > 0) {
diff --git a/ui/src/components/workbench/InboxPage.tsx b/ui/src/components/workbench/InboxPage.tsx
index 12ff2a3b1..d6ebc517b 100644
--- a/ui/src/components/workbench/InboxPage.tsx
+++ b/ui/src/components/workbench/InboxPage.tsx
@@ -94,7 +94,6 @@ export const InboxPage: React.FC = () => {
}, [filter, inboxSessions, unreadBySession]);
const openSession = (s: InboxSession) => {
- if (unreadOf(s) > 0) markRead(s.session_id);
navigate(`/chat/${encodeURIComponent(s.session_id)}`);
};
diff --git a/ui/src/components/workbench/NewSessionSheet.tsx b/ui/src/components/workbench/NewSessionSheet.tsx
index 12de17f72..710fbf806 100644
--- a/ui/src/components/workbench/NewSessionSheet.tsx
+++ b/ui/src/components/workbench/NewSessionSheet.tsx
@@ -3,6 +3,7 @@ import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useNewSession } from '../../lib/useNewSession';
+import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import { Dialog, DialogContent, DialogTitle } from '../ui/dialog';
import { Composer } from './Composer';
import { NewProjectDialog } from './NewProjectDialog';
@@ -24,6 +25,7 @@ interface NewSessionSheetProps {
export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose, onOpen }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const authorizeRouteAction = useUnsavedChangesActionGuard();
// active: open → the hook reloads + resets per-open (the sheet is permanently
// mounted by AppShell, so stale submit/error state must not leak across opens).
const ns = useNewSession({
@@ -50,11 +52,23 @@ export const NewSessionSheet: React.FC<NewSessionSheetProps> = ({ open, onClose,
};
const send = async (text: string): Promise<boolean> => {
+ // Creating the session is irreversible and its target route does not exist until the API
+ // succeeds. Confirm before that mutation, then let its one resulting navigation bypass the
+ // router blocker so the user sees exactly one prompt.
+ const canCreate = text.trim() !== '' && ns.loaded && ns.target !== null && !ns.sending;
+ const authorization = canCreate ? authorizeRouteAction() : undefined;
+ if (authorization === null) return false;
+
const result = await ns.send(text);
if (result) {
setPendingDraft('');
+ const navigateToSession = () =>
+ navigate(`/chat/${encodeURIComponent(result.sessionId)}`, {
+ state: { initialMessage: result.initialMessage },
+ });
+ if (authorization) authorization.runNavigation(navigateToSession);
+ else navigateToSession();
onClose();
- navigate(`/chat/${encodeURIComponent(result.sessionId)}`, { state: { initialMessage: result.initialMessage } });
return true;
}
// No project to target → stash the prompt and route to the New Project flow.
diff --git a/ui/src/components/workbench/ProjectsPage.tsx b/ui/src/components/workbench/ProjectsPage.tsx
index a02388149..d5e76fadb 100644
--- a/ui/src/components/workbench/ProjectsPage.tsx
+++ b/ui/src/components/workbench/ProjectsPage.tsx
@@ -396,7 +396,7 @@ const MobileSessionRow: React.FC<{
export const ProjectsPage: React.FC = () => {
const { t } = useTranslation();
const navigate = useNavigate();
- const { markRead, unreadBySession } = useWorkbenchInbox();
+ const { unreadBySession } = useWorkbenchInbox();
const {
projects,
projectsError,
@@ -412,9 +412,6 @@ export const ProjectsPage: React.FC = () => {
const [visibleSessionCounts, setVisibleSessionCounts] = useState<Record<string, number>>({});
const openSession = (sessionId: string) => {
- // Opening a chat marks it read everywhere (matches the desktop tree + Inbox),
- // so unread badges/counts don't linger after a mobile drill-in.
- void markRead(sessionId);
navigate(`/chat/${sessionId}`);
};
const revealMoreSessions = (projectId: string, state: ProjectSessionsState, visibleCount: number, loadedCount: number) => {
diff --git a/ui/src/components/workbench/WorkbenchSidebar.tsx b/ui/src/components/workbench/WorkbenchSidebar.tsx
index debf742de..e24c9f345 100644
--- a/ui/src/components/workbench/WorkbenchSidebar.tsx
+++ b/ui/src/components/workbench/WorkbenchSidebar.tsx
@@ -32,6 +32,7 @@ import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useWindowManager } from '../../context/WindowManagerContext';
import { useComposerInsertTarget } from '../../context/ComposerBridgeContext';
+import { useUnsavedChangesActionGuard } from '../../context/useUnsavedChangesActionGuard';
import type { InboxSession, WorkbenchProject, WorkbenchSession } from '../../context/ApiContext';
import { formatRelativeTime } from '../../lib/relativeTime';
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from '../ui/popover';
@@ -203,13 +204,13 @@ const STATUS_DOT_CLASS: Record<string, string> = {
const SessionRow: React.FC<{
session: WorkbenchSession;
unread: number;
- onSessionMarkRead: (sessionId: string) => void;
onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
onRenameSession: (sessionId: string, title: string) => Promise<void>;
onArchiveSession: (sessionId: string) => Promise<void>;
-}> = ({ session, unread, onSessionMarkRead, onForkSession, onRenameSession, onArchiveSession }) => {
+}> = ({ session, unread, onForkSession, onRenameSession, onArchiveSession }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const authorizeRouteAction = useUnsavedChangesActionGuard();
const location = useLocation();
const active = location.pathname === `/chat/${session.id}`;
// "Reference this session" shows only when a chat composer is mounted (a chat
@@ -283,10 +284,7 @@ const SessionRow: React.FC<{
<PopoverAnchor asChild>
<button
type="button"
- onClick={() => {
- navigate(`/chat/${encodeURIComponent(session.id)}`);
- if (unread > 0) onSessionMarkRead(session.id);
- }}
+ onClick={() => navigate(`/chat/${encodeURIComponent(session.id)}`)}
onContextMenu={(e) => {
e.preventDefault();
setMenuOpen(true);
@@ -340,11 +338,15 @@ const SessionRow: React.FC<{
title={!session.native_session_id ? t('workbench.sessionForkUnavailable') : undefined}
onClick={async () => {
if (!canFork) return;
+ const authorization = authorizeRouteAction();
+ if (!authorization) return;
setMenuOpen(false);
setForking(true);
try {
const forked = await onForkSession(session.id);
- if (forked) navigate(`/chat/${encodeURIComponent(forked.id)}`);
+ if (forked) {
+ authorization.runNavigation(() => navigate(`/chat/${encodeURIComponent(forked.id)}`));
+ }
} finally {
setForking(false);
}
@@ -412,7 +414,6 @@ const ProjectRow: React.FC<{
onCreateSession: () => void;
creatingSession: boolean;
unreadBySession: Record<string, number>;
- onSessionMarkRead: (sessionId: string) => void;
onRename: (next: string) => Promise<void>;
onArchive: () => Promise<void>;
onForkSession: (sessionId: string) => Promise<WorkbenchSession | null>;
@@ -430,7 +431,6 @@ const ProjectRow: React.FC<{
onCreateSession,
creatingSession,
unreadBySession,
- onSessionMarkRead,
onRename,
onArchive,
onForkSession,
@@ -629,7 +629,6 @@ const ProjectRow: React.FC<{
key={session.id}
session={session}
unread={unreadBySession[session.id] || 0}
- onSessionMarkRead={onSessionMarkRead}
onForkSession={onForkSession}
onRenameSession={onRenameSession}
onArchiveSession={onArchiveSession}
@@ -666,6 +665,7 @@ const ProjectRow: React.FC<{
export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOpenSearch }) => {
const { t } = useTranslation();
const navigate = useNavigate();
+ const authorizeRouteAction = useUnsavedChangesActionGuard();
const { totalUnread, unreadSessions, inboxSessions, markRead, unreadBySession } = useWorkbenchInbox();
// Projects/sessions tree — shared with the mobile ProjectsPage via the provider
// (one EventSource + one cache, not a per-component reimplementation). The
@@ -737,7 +737,6 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
const onItemClick = (session: InboxSession) => {
setPopoverOpen(false);
navigate(`/chat/${encodeURIComponent(session.session_id)}`);
- if ((unreadBySession[session.session_id] ?? 0) > 0) markRead(session.session_id);
};
const onMarkAllRead = async () => {
@@ -911,14 +910,17 @@ export const WorkbenchSidebar: React.FC<{ onOpenSearch?: () => void }> = ({ onOp
onLoadMore={() => loadMore(project.id)}
onToggle={() => toggleExpanded(project.id)}
onCreateSession={async () => {
+ const authorization = authorizeRouteAction();
+ if (!authorization) return;
// The provider creates + caches; navigation stays here since
// it's mounted above the router.
const session = await createSessionForProject(project.id);
- if (session) navigate(`/chat/${encodeURIComponent(session.id)}`);
+ if (session) {
+ authorization.runNavigation(() => navigate(`/chat/${encodeURIComponent(session.id)}`));
+ }
}}
creatingSession={creatingSession(project.id)}
unreadBySession={unreadBySession}
- onSessionMarkRead={markRead}
onRename={(next) => renameProject(project.id, next)}
onArchive={() => archiveProject(project.id)}
onForkSession={(sessionId) => forkSession(project.id, sessionId)}
diff --git a/ui/src/context/NavGuardContext.tsx b/ui/src/context/NavGuardContext.tsx
deleted file mode 100644
index 9362c1e02..000000000
--- a/ui/src/context/NavGuardContext.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { createContext, useCallback, useContext, useMemo, useRef } from 'react';
-import type { ReactNode } from 'react';
-
-// A lightweight "unsaved changes" guard for in-app navigation. A page with unwritten work (the mobile
-// single-file editor) registers a confirm message; navigation surfaces that can't otherwise be blocked
-// — the mobile tab bar, whose NavLinks bypass `beforeunload` — call `confirmLeave()` first and cancel
-// the navigation when the user declines. The message lives in a ref so registering it never re-renders
-// consumers, mirroring the WindowManager close-guard pattern. `confirmLeave()` is a no-op (returns
-// true) whenever no guard is set, so every other page is unaffected.
-interface NavGuardValue {
- /** Register a confirm message while there is unsaved work, or null to clear the guard. */
- setGuard: (message: string | null) => void;
- /** Returns true when it's safe to leave (no guard, or the user confirmed discarding). */
- confirmLeave: () => boolean;
-}
-
-const NavGuardContext = createContext<NavGuardValue | null>(null);
-
-export const NavGuardProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
- const messageRef = useRef<string | null>(null);
-
- const setGuard = useCallback((message: string | null) => {
- messageRef.current = message;
- }, []);
-
- const confirmLeave = useCallback(() => {
- const message = messageRef.current;
- return !message || window.confirm(message);
- }, []);
-
- const value = useMemo<NavGuardValue>(() => ({ setGuard, confirmLeave }), [setGuard, confirmLeave]);
-
- return <NavGuardContext.Provider value={value}>{children}</NavGuardContext.Provider>;
-};
-
-export function useNavGuard(): NavGuardValue {
- const ctx = useContext(NavGuardContext);
- if (!ctx) throw new Error('useNavGuard must be used within a NavGuardProvider');
- return ctx;
-}
diff --git a/ui/src/context/UnsavedChangesProvider.tsx b/ui/src/context/UnsavedChangesProvider.tsx
new file mode 100644
index 000000000..aaa387631
--- /dev/null
+++ b/ui/src/context/UnsavedChangesProvider.tsx
@@ -0,0 +1,58 @@
+import { useBlocker } from 'react-router-dom';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import type { ReactNode } from 'react';
+
+import {
+ UnsavedChangesContext,
+ type UnsavedChangesContextValue,
+} from './unsavedChangesContext';
+import {
+ createUnsavedChangesNavigationGate,
+ getUnsavedChangesMessage,
+ setUnsavedChangesRegistration,
+ type UnsavedChangesActionAuthorization,
+ type UnsavedChangesRegistrationId,
+ type UnsavedChangesRegistry,
+} from '../lib/unsavedChangesRegistry';
+
+export const UnsavedChangesProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
+ const registryRef = useRef<UnsavedChangesRegistry>(new Map());
+ const handledLocationRef = useRef<object | null>(null);
+ const navigationGateRef = useRef(createUnsavedChangesNavigationGate());
+
+ const setRegistration = useCallback((id: UnsavedChangesRegistrationId, message: string | null) => {
+ setUnsavedChangesRegistration(registryRef.current, id, message);
+ }, []);
+
+ const authorizeRouteAction = useCallback((): UnsavedChangesActionAuthorization | null => {
+ const message = getUnsavedChangesMessage(registryRef.current);
+ return navigationGateRef.current.authorize(message, (confirmation) => window.confirm(confirmation));
+ }, []);
+
+ // 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 hasUnsavedChanges = getUnsavedChangesMessage(registryRef.current) !== null;
+ return navigationGateRef.current.shouldBlock(hasUnsavedChanges);
+ }, []);
+ const blocker = useBlocker(shouldBlock);
+
+ useEffect(() => {
+ if (blocker.state === 'unblocked') {
+ handledLocationRef.current = null;
+ return;
+ }
+ if (blocker.state !== 'blocked' || handledLocationRef.current === blocker.location) return;
+
+ handledLocationRef.current = blocker.location;
+ const message = getUnsavedChangesMessage(registryRef.current);
+ if (message === null || window.confirm(message)) blocker.proceed();
+ else blocker.reset();
+ }, [blocker]);
+
+ const value = useMemo<UnsavedChangesContextValue>(
+ () => ({ setRegistration, authorizeRouteAction }),
+ [setRegistration, authorizeRouteAction],
+ );
+ return <UnsavedChangesContext.Provider value={value}>{children}</UnsavedChangesContext.Provider>;
+};
diff --git a/ui/src/context/WorkbenchProjectsContext.tsx b/ui/src/context/WorkbenchProjectsContext.tsx
index a696df705..be3018bff 100644
--- a/ui/src/context/WorkbenchProjectsContext.tsx
+++ b/ui/src/context/WorkbenchProjectsContext.tsx
@@ -136,7 +136,7 @@ const WorkbenchProjectsContext = createContext<WorkbenchProjectsTree | null>(nul
// for the same "sidebar + page both need live SSE data" situation. Owns: load +
// paginate + dedupe sessions, reconnect reconcile (chunked, survives the 200-row
// server clamp), live status/title via SSE, create/rename/archive. Navigation
-// stays in consumers — this is mounted outside <BrowserRouter>. Unread stays in
+// stays in consumers — this is mounted outside <RouterProvider>. Unread stays in
// WorkbenchInboxContext (both consumers read it directly).
export const WorkbenchProjectsProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
const api = useApi();
diff --git a/ui/src/context/unsavedChangesContext.ts b/ui/src/context/unsavedChangesContext.ts
new file mode 100644
index 000000000..2403a7213
--- /dev/null
+++ b/ui/src/context/unsavedChangesContext.ts
@@ -0,0 +1,14 @@
+import { createContext } from 'react';
+
+import type {
+ UnsavedChangesActionAuthorization,
+ UnsavedChangesRegistrationId,
+} from '../lib/unsavedChangesRegistry';
+
+export interface UnsavedChangesContextValue {
+ setRegistration: (id: UnsavedChangesRegistrationId, message: string | null) => void;
+ /** Confirm before an action mutates data and later navigates. Null means the user canceled. */
+ authorizeRouteAction: () => UnsavedChangesActionAuthorization | null;
+}
+
+export const UnsavedChangesContext = createContext<UnsavedChangesContextValue | null>(null);
diff --git a/ui/src/context/useUnsavedChanges.ts b/ui/src/context/useUnsavedChanges.ts
new file mode 100644
index 000000000..21e2bdf5c
--- /dev/null
+++ b/ui/src/context/useUnsavedChanges.ts
@@ -0,0 +1,24 @@
+import { useContext, useId, useLayoutEffect } from 'react';
+
+import { UnsavedChangesContext } from './unsavedChangesContext';
+
+/** Register one dirty surface with the router-wide blocker. Pass null while the surface is clean. */
+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();
+
+ // 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]);
+
+ useLayoutEffect(
+ () => () => {
+ context.setRegistration(registrationId, null);
+ },
+ [context, registrationId],
+ );
+}
diff --git a/ui/src/context/useUnsavedChangesActionGuard.ts b/ui/src/context/useUnsavedChangesActionGuard.ts
new file mode 100644
index 000000000..df529eb54
--- /dev/null
+++ b/ui/src/context/useUnsavedChangesActionGuard.ts
@@ -0,0 +1,11 @@
+import { useContext } from 'react';
+
+import { UnsavedChangesContext } from './unsavedChangesContext';
+import type { UnsavedChangesActionAuthorization } from '../lib/unsavedChangesRegistry';
+
+/** Confirm before a side-effecting action whose successful result navigates to another route. */
+export function useUnsavedChangesActionGuard(): () => UnsavedChangesActionAuthorization | null {
+ const context = useContext(UnsavedChangesContext);
+ if (!context) throw new Error('useUnsavedChangesActionGuard must be used within an UnsavedChangesProvider');
+ return context.authorizeRouteAction;
+}
diff --git a/ui/src/lib/unsavedChangesRegistry.test.ts b/ui/src/lib/unsavedChangesRegistry.test.ts
new file mode 100644
index 000000000..399a35d0f
--- /dev/null
+++ b/ui/src/lib/unsavedChangesRegistry.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createUnsavedChangesNavigationGate,
+ getUnsavedChangesMessage,
+ setUnsavedChangesRegistration,
+ type UnsavedChangesRegistry,
+} from './unsavedChangesRegistry';
+
+describe('unsaved changes registry', () => {
+ it('updates a stable registration without creating duplicate entries', () => {
+ const registry: UnsavedChangesRegistry = new Map();
+
+ setUnsavedChangesRegistration(registry, 'editor-route', 'first message');
+ setUnsavedChangesRegistration(registry, 'editor-route', 'updated message');
+
+ expect(registry.size).toBe(1);
+ expect(getUnsavedChangesMessage(registry)).toBe('updated message');
+ });
+
+ it('falls back to another dirty surface when the active registration cleans up', () => {
+ const registry: UnsavedChangesRegistry = new Map();
+
+ setUnsavedChangesRegistration(registry, 'older-surface', 'older message');
+ setUnsavedChangesRegistration(registry, 'newer-surface', 'newer message');
+ expect(getUnsavedChangesMessage(registry)).toBe('newer message');
+
+ setUnsavedChangesRegistration(registry, 'newer-surface', null);
+ expect(getUnsavedChangesMessage(registry)).toBe('older message');
+
+ setUnsavedChangesRegistration(registry, 'older-surface', null);
+ expect(getUnsavedChangesMessage(registry)).toBeNull();
+ });
+
+ it('cancels a route action before mutation and leaves navigation blocked', () => {
+ const gate = createUnsavedChangesNavigationGate();
+ const authorization = gate.authorize('discard?', () => false);
+
+ expect(authorization).toBeNull();
+ expect(gate.shouldBlock(true)).toBe(true);
+ });
+
+ it('authorizes exactly one synchronous navigation after a confirmed action', () => {
+ const gate = createUnsavedChangesNavigationGate();
+ const authorization = gate.authorize('discard?', () => true);
+
+ expect(authorization).not.toBeNull();
+ authorization?.runNavigation(() => {
+ expect(gate.shouldBlock(true)).toBe(false);
+ });
+ expect(gate.shouldBlock(true)).toBe(true);
+ });
+
+ it('does not retain an authorization when its callback never navigates', () => {
+ const gate = createUnsavedChangesNavigationGate();
+ const authorization = gate.authorize('discard?', () => true);
+
+ authorization?.runNavigation(() => undefined);
+ expect(gate.shouldBlock(true)).toBe(true);
+ });
+});
diff --git a/ui/src/lib/unsavedChangesRegistry.ts b/ui/src/lib/unsavedChangesRegistry.ts
new file mode 100644
index 000000000..99a510f89
--- /dev/null
+++ b/ui/src/lib/unsavedChangesRegistry.ts
@@ -0,0 +1,64 @@
+export type UnsavedChangesRegistrationId = string;
+
+export type UnsavedChangesRegistry = Map<UnsavedChangesRegistrationId, string>;
+
+export interface UnsavedChangesActionAuthorization {
+ /** Run one synchronous router navigation without prompting again after the action was confirmed. */
+ runNavigation: (navigation: () => void) => void;
+}
+
+export interface UnsavedChangesNavigationGate {
+ authorize: (
+ message: string | null,
+ confirm: (message: string) => boolean,
+ ) => UnsavedChangesActionAuthorization | null;
+ shouldBlock: (hasUnsavedChanges: boolean) => boolean;
+}
+
+export function createUnsavedChangesNavigationGate(): UnsavedChangesNavigationGate {
+ let authorizedNavigation: symbol | null = null;
+
+ return {
+ authorize(message, confirm) {
+ if (message !== null && !confirm(message)) return null;
+
+ const token = message === null ? null : Symbol('unsaved-changes-route-action');
+ return {
+ runNavigation(navigation) {
+ if (token !== null) authorizedNavigation = token;
+ try {
+ navigation();
+ } finally {
+ // Never leave a bypass behind if the callback did not issue a synchronous navigation.
+ if (token !== null && authorizedNavigation === token) authorizedNavigation = null;
+ }
+ },
+ };
+ },
+ shouldBlock(hasUnsavedChanges) {
+ if (authorizedNavigation !== null) {
+ authorizedNavigation = null;
+ return false;
+ }
+ return hasUnsavedChanges;
+ },
+ };
+}
+
+export function setUnsavedChangesRegistration(
+ registry: UnsavedChangesRegistry,
+ id: UnsavedChangesRegistrationId,
+ message: string | null,
+): void {
+ if (message === null) {
+ registry.delete(id);
+ return;
+ }
+ registry.set(id, message);
+}
+
+export function getUnsavedChangesMessage(registry: UnsavedChangesRegistry): string | null {
+ let active: string | null = null;
+ for (const message of registry.values()) active = message;
+ return active;
+}