Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: share the unsaved-changes confirm row and take a scopePath instead of a predicate

[._.]/ Adam Eivybb559d1adf79
diff --git a/client/src/components/ui/UnsavedChangesConfirm.jsx b/client/src/components/ui/UnsavedChangesConfirm.jsx
new file mode 100644
index 0000000000..75b58a0f34
--- /dev/null
+++ b/client/src/components/ui/UnsavedChangesConfirm.jsx
@@ -0,0 +1,51 @@
+import InlineConfirmRow from './InlineConfirmRow';
+
+// The discard confirm every `useUnsavedChangesGuard` consumer renders from
+// `blocked` (#3958/#3995) — one styling contract instead of a copy per editor.
+// Pass the guard straight through; it renders nothing unless a navigation is
+// actually parked.
+//
+// <UnsavedChangesConfirm
+// guard={routeGuard}
+// when={!saving}
+// question="Discard your unsaved changes to this song?"
+// label={`Discard unsaved changes to ${song.title}`}
+// onDiscard={discardAndExit}
+// />
+//
+// A page that ALSO defers a non-router exit of its own (SongBookViewer parks
+// its View toggle, which only flips a search param) needs its own `blocked ||
+// pendingExit` condition and its own cancel handler, so it drives
+// `InlineConfirmRow` directly rather than going through here.
+//
+// `when` (default true) is the caller's extra render gate — pass `!saving` when
+// a save is in flight. The navigation stays PARKED either way; suppressing the
+// row just avoids flashing a confirm for a draft that is about to settle clean
+// and auto-proceed on its own. Discarding is the caller's job (only it knows
+// how to reset its draft), so `onDiscard` resets state and then calls
+// `guard.proceed()`.
+export default function UnsavedChangesConfirm({
+ guard,
+ question,
+ label,
+ onDiscard,
+ when = true,
+ confirmText = 'Discard',
+ cancelText = 'Keep editing',
+}) {
+ if (!guard.blocked || !when) return null;
+ return (
+ <InlineConfirmRow
+ className="shrink-0"
+ variant="separator"
+ tone="warning"
+ question={question}
+ confirmText={confirmText}
+ cancelText={cancelText}
+ onConfirm={onDiscard}
+ onCancel={guard.reset}
+ autoFocus
+ aria-label={label}
+ />
+ );
+}
diff --git a/client/src/components/ui/UnsavedChangesConfirm.test.jsx b/client/src/components/ui/UnsavedChangesConfirm.test.jsx
new file mode 100644
index 0000000000..6e9fadbf6c
--- /dev/null
+++ b/client/src/components/ui/UnsavedChangesConfirm.test.jsx
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi } from 'vitest';
+import { render, screen, fireEvent } from '@testing-library/react';
+import UnsavedChangesConfirm from './UnsavedChangesConfirm';
+
+const guard = (blocked, reset = vi.fn()) => ({ blocked, proceed: vi.fn(), reset });
+
+const renderRow = (props) => render(
+ <UnsavedChangesConfirm
+ question="Discard your unsaved changes?"
+ label="Discard unsaved changes to Example Work"
+ onDiscard={() => {}}
+ {...props}
+ />,
+);
+
+describe('UnsavedChangesConfirm', () => {
+ it('renders nothing while no navigation is parked', () => {
+ renderRow({ guard: guard(false) });
+ expect(screen.queryByText('Discard your unsaved changes?')).toBeNull();
+ });
+
+ it('renders the confirm once the guard blocks', () => {
+ renderRow({ guard: guard(true) });
+ expect(screen.getByText('Discard your unsaved changes?')).toBeInTheDocument();
+ expect(screen.getByText('Discard')).toBeInTheDocument();
+ expect(screen.getByText('Keep editing')).toBeInTheDocument();
+ });
+
+ it('stays down while the caller gate is closed (a save in flight)', () => {
+ renderRow({ guard: guard(true), when: false });
+ expect(screen.queryByText('Discard your unsaved changes?')).toBeNull();
+ });
+
+ it('wires Discard to onDiscard and Keep editing to the guard reset', () => {
+ const onDiscard = vi.fn();
+ const reset = vi.fn();
+ renderRow({ guard: guard(true, reset), onDiscard });
+
+ fireEvent.click(screen.getByText('Discard'));
+ expect(onDiscard).toHaveBeenCalledTimes(1);
+ fireEvent.click(screen.getByText('Keep editing'));
+ expect(reset).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsx
index b8d608a0ef..9eee4a3cd7 100644
--- a/client/src/components/writers-room/WorkEditor.jsx
+++ b/client/src/components/writers-room/WorkEditor.jsx
@@ -28,7 +28,7 @@ import {
import toast from '../ui/Toast';
import ProseEditor from '../ui/ProseEditor';
import Drawer from '../Drawer';
-import InlineConfirmRow from '../ui/InlineConfirmRow';
+import UnsavedChangesConfirm from '../ui/UnsavedChangesConfirm';
import useMounted from '../../hooks/useMounted';
import useUnsavedChangesGuard from '../../hooks/useUnsavedChangesGuard';
import useClickOutside from '../../hooks/useClickOutside';
@@ -335,10 +335,11 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
// `ui_navigate`, browser Back) — otherwise the body reset in the effect above
// silently discards them. The confirm renders below the header banners.
const routeGuard = useUnsavedChangesGuard(dirty);
+ const { proceed: proceedExit } = routeGuard;
const discardAndExit = useCallback(() => {
setBody(savedBody);
- routeGuard.proceed();
- }, [routeGuard, savedBody]);
+ proceedExit();
+ }, [proceedExit, savedBody]);
useClickOutside(overflowRef, overflowOpen, () => setOverflowOpen(false));
@@ -859,20 +860,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseO
</div>
</div>
- {routeGuard.blocked && (
- <InlineConfirmRow
- className="shrink-0"
- variant="separator"
- tone="warning"
- question="Discard your unsaved changes to this work?"
- confirmText="Discard"
- cancelText="Keep editing"
- onConfirm={discardAndExit}
- onCancel={routeGuard.reset}
- autoFocus
- aria-label={`Discard unsaved changes to ${title || 'this work'}`}
- />
- )}
+ {/* A save in flight is about to settle the draft clean, and the guard
+ releases the parked navigation on its own — no confirm to flash. */}
+ <UnsavedChangesConfirm
+ guard={routeGuard}
+ when={!saving}
+ question="Discard your unsaved changes to this work?"
+ label={`Discard unsaved changes to ${title || 'this work'}`}
+ onDiscard={discardAndExit}
+ />
{runningKind && (
<AnalysisRunBanner
diff --git a/client/src/components/writers-room/WorkEditor.test.jsx b/client/src/components/writers-room/WorkEditor.test.jsx
index aac50a4023..90ba8f52b3 100644
--- a/client/src/components/writers-room/WorkEditor.test.jsx
+++ b/client/src/components/writers-room/WorkEditor.test.jsx
@@ -171,7 +171,6 @@ describe('WorkEditor unsaved-changes route guard (#3995)', () => {
const typeUnsaved = async (container, next) => {
const area = container.querySelector('textarea');
await act(async () => { fireEvent.change(area, { target: { value: next } }); });
- return area;
};
it('blocks an in-app navigation while the draft is dirty', async () => {
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 38f9282478..f906d55b1e 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -117,7 +117,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSidebarResize` | Drag-to-resize split-pane width persisted to `localStorage`; returns `{ containerRef, width, onMouseDown, reset }` and caps the drag at `maxFraction` of the measured container. | A desktop sidebar/split pane with a draggable divider (WorkEditor's storyboard sidebar). |
| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. |
| `useTokenPopover` | Hover/click/pin state machine for an anchored token popover (200ms open, 150ms grace close) plus the `hotRef` cross-link highlight; returns `{ pop, hotRef, onTokenEnter/Leave/Click, onPopoverEnter/Leave, closePopover }`. | Prose (or any) tokens that open a detail popover on hover and pin on click (WorkEditor ↔ ProseTokenPopover). |
-| `useUnsavedChangesGuard` | `useUnsavedChangesGuard(isDirty, { beforeUnload, isSameView })` → `{ blocked, proceed, reset }` — parks router navigation (sidebar link, ⌘K, voice nav, browser Back) behind react-router's `useBlocker` while a draft is dirty, and arms `beforeunload` for tab close/reload. Auto-proceeds once the draft goes clean. `isSameView(from, to)` exempts an editor's own pathname-changing in-page moves (a splat route's tab switch). Requires the data router in `main.jsx`; tests must mount `createMemoryRouter` + `<RouterProvider>`. | Any editor holding an unsaved draft (SongBookViewer, PipelineManuscriptEditor, writers-room WorkEditor) — render your own `InlineConfirmRow` from `blocked`, never `window.confirm`. |
+| `useUnsavedChangesGuard` | `useUnsavedChangesGuard(isDirty, { beforeUnload, scopePath })` → `{ blocked, proceed, reset }` — parks router navigation (sidebar link, ⌘K, voice nav, browser Back) behind react-router's `useBlocker` while a draft is dirty, and arms `beforeunload` for tab close/reload. Auto-proceeds once the draft goes clean. `scopePath` is the path prefix the editor owns, exempting its own pathname-changing in-page moves (a splat route's tab switch). Requires the data router in `main.jsx`; tests must mount `createMemoryRouter` + `<RouterProvider>`. | Any editor holding an unsaved draft (SongBookViewer, PipelineManuscriptEditor, writers-room WorkEditor) — render the confirm with `<UnsavedChangesConfirm guard={…} when={!saving}>`, never `window.confirm`. |
| `useUrlParams` | `[searchParams, updateParams]` — `updateParams(patch, { replace })` merges a patch into the query string and deletes keys set to `null`/`undefined`/`''` so a cleared filter leaves the URL clean. Reads the live params off a ref (react-router's functional updater is closure-stale) and is referentially stable. | Any page whose filter/sort/selection state lives in the URL (Catalog, MediaCollections, Media3D) — don't re-roll the merge-and-prune loop. |
| `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. |
| `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |
diff --git a/client/src/hooks/useUnsavedChangesGuard.js b/client/src/hooks/useUnsavedChangesGuard.js
index f6a3bc172a..56047c2075 100644
--- a/client/src/hooks/useUnsavedChangesGuard.js
+++ b/client/src/hooks/useUnsavedChangesGuard.js
@@ -1,4 +1,4 @@
-import { useCallback, useEffect } from 'react';
+import { useCallback, useEffect, useMemo } from 'react';
import { useBlocker } from 'react-router';
// Guards an editor's unsaved draft against BOTH exit doors (#3958):
@@ -23,13 +23,15 @@ import { useBlocker } from 'react-router';
//
// Discarding is the CALLER's job — only it knows how to reset its draft — so a
// discard handler resets local state and then calls `proceed()`.
-// `isSameView(currentPathname, nextPathname)` — optional escape hatch for an
-// editor whose OWN in-page moves change the pathname. A splat route like
+// `scopePath` — the path prefix this editor OWNS, for an editor whose own
+// in-page moves change the pathname. A splat route like
// `/pipeline/series/:id/manuscript/*` swaps the issue segment without leaving
// (or remounting) the editor, so the default pathname comparison would raise a
-// discard confirm on every issue tab click. Return true for a navigation that
-// stays inside the editor and it passes through unguarded.
-export default function useUnsavedChangesGuard(isDirty, { beforeUnload = true, isSameView } = {}) {
+// discard confirm on every issue tab click. A navigation that stays under the
+// prefix is an in-editor move and passes through unguarded; leaving it is a
+// real exit and still parks. A plain string (not a predicate) so a caller can't
+// re-register the blocker every render with an unmemoized inline function.
+export default function useUnsavedChangesGuard(isDirty, { beforeUnload = true, scopePath } = {}) {
// Same-location navigations (a re-click on the link you're already on, a
// search-param tweak on the current page) don't unmount the editor, so
// there's nothing to guard — let them through rather than raising a confirm
@@ -37,8 +39,8 @@ export default function useUnsavedChangesGuard(isDirty, { beforeUnload = true, i
const shouldBlock = useCallback(({ currentLocation, nextLocation }) => {
if (!isDirty) return false;
if (currentLocation.pathname === nextLocation.pathname) return false;
- return !isSameView?.(currentLocation.pathname, nextLocation.pathname);
- }, [isDirty, isSameView]);
+ return !(scopePath && nextLocation.pathname.startsWith(scopePath));
+ }, [isDirty, scopePath]);
const blocker = useBlocker(shouldBlock);
const blocked = blocker.state === 'blocked';
@@ -65,5 +67,8 @@ export default function useUnsavedChangesGuard(isDirty, { beforeUnload = true, i
const proceed = useCallback(() => blocker.proceed?.(), [blocker]);
const reset = useCallback(() => blocker.reset?.(), [blocker]);
- return { blocked, proceed, reset };
+ // Memoized: callers pass this object to `<UnsavedChangesConfirm guard>` and
+ // name its members in dep arrays, so a fresh literal per render would be a
+ // guaranteed miss on every editor's hot typing path.
+ return useMemo(() => ({ blocked, proceed, reset }), [blocked, proceed, reset]);
}
diff --git a/client/src/hooks/useUnsavedChangesGuard.test.jsx b/client/src/hooks/useUnsavedChangesGuard.test.jsx
index 4718180673..a836bc99f8 100644
--- a/client/src/hooks/useUnsavedChangesGuard.test.jsx
+++ b/client/src/hooks/useUnsavedChangesGuard.test.jsx
@@ -103,17 +103,15 @@ describe('useUnsavedChangesGuard', () => {
expect(await screen.findByText('keep')).toBeTruthy();
});
- it('lets an in-editor move through when isSameView claims it (splat route tab switch)', async () => {
- const isSameView = (from, to) => from.startsWith('/edit') && to.startsWith('/edit');
- const router = renderEditor({ options: { isSameView } });
+ it('lets an in-editor move through when it stays under scopePath (splat route tab switch)', async () => {
+ const router = renderEditor({ options: { scopePath: '/edit' } });
await navigate(router, '/edit/deeper');
await waitFor(() => expect(router.state.location.pathname).toBe('/edit/deeper'));
expect(screen.queryByText('keep')).toBeNull();
});
- it('still blocks a real exit when isSameView is supplied', async () => {
- const isSameView = (from, to) => from.startsWith('/edit') && to.startsWith('/edit');
- const router = renderEditor({ options: { isSameView } });
+ it('still blocks a navigation that leaves scopePath', async () => {
+ const router = renderEditor({ options: { scopePath: '/edit' } });
await navigate(router, '/away');
expect(await screen.findByText('keep')).toBeTruthy();
expect(screen.queryByText('away')).toBeNull();
diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsx
index 9940109a14..242f0cfca3 100644
--- a/client/src/pages/PipelineManuscriptEditor.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.jsx
@@ -34,7 +34,7 @@ import {
} from 'lucide-react';
import { formatManuscript } from '../lib/manuscriptFormat';
import toast from '../components/ui/Toast';
-import InlineConfirmRow from '../components/ui/InlineConfirmRow';
+import UnsavedChangesConfirm from '../components/ui/UnsavedChangesConfirm';
import { useAsyncAction } from '../hooks/useAsyncAction';
import { usePipelineProgress } from '../hooks/usePipelineProgress';
import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';
@@ -157,32 +157,32 @@ export default function PipelineManuscriptEditor() {
liveSectionsRef.current = sections;
const liveContentFor = (issueId) => liveSectionsRef.current.find((s) => s.issueId === issueId)?.content ?? '';
- // Sections only persist onBlur, so leaving right after typing (before the
- // field blurs) would silently drop the edit. Reactive mirror of the ref-based
- // dirty check above, so the route guard re-evaluates as sections/baselines
- // change (`baselineRef` is for handlers reading outside the render cycle).
- const isDirty = useMemo(
- () => sections.some((s) => isSectionDirty(baselines, s)),
- [sections, baselines],
- );
+ // Issue numbers holding an unsaved edit, for the tab dirty dots. Sections save
+ // onBlur, so tabbing away from a pending edit leaves it unsaved with no cue
+ // unless the tab itself carries one (#3399). Also the route guard's reactive
+ // dirty signal (#3995) — `baselineRef` is for handlers that read outside the
+ // render cycle, and can't drive a re-evaluation on its own.
+ const dirtyNumbers = useMemo(() => {
+ const set = new Set();
+ sections.forEach((s) => { if (isSectionDirty(baselines, s)) set.add(s.number); });
+ return set;
+ }, [sections, baselines]);
// Guards BOTH exit doors (#3958/#3995): tab close/reload, and any in-app
// navigation — a sidebar link, ⌘K, voice `ui_navigate`, the browser Back
// button. This is a splat route, so switching issue tabs changes the pathname
- // WITHOUT leaving the editor; `isSameView` lets those through unguarded.
- const manuscriptPath = `/pipeline/series/${seriesId}/manuscript`;
- const isSameView = useCallback(
- (from, to) => from.startsWith(manuscriptPath) && to.startsWith(manuscriptPath),
- [manuscriptPath],
- );
- const routeGuard = useUnsavedChangesGuard(isDirty, { isSameView });
- const discardAndExit = () => {
+ // WITHOUT leaving the editor; `scopePath` lets those through unguarded.
+ const savingAny = Object.values(saveState).some((s) => s === 'saving');
+ const routeGuard = useUnsavedChangesGuard(dirtyNumbers.size > 0, {
+ scopePath: `/pipeline/series/${seriesId}/manuscript`,
+ });
+ const discardAndExit = useCallback(() => {
setSections((prev) => prev.map((s) => {
const key = baselineKey(s);
- return baselineRef.current.has(key) ? { ...s, content: baselineRef.current.get(key) } : s;
+ return baselines.has(key) ? { ...s, content: baselines.get(key) } : s;
}));
routeGuard.proceed();
- };
+ }, [baselines, routeGuard]);
useEffect(() => {
safeWriteStorage(VIEW_MODE_KEY, viewMode);
@@ -661,15 +661,6 @@ export default function PipelineManuscriptEditor() {
return set;
}, [sectionSpans]);
- // Issue numbers holding an unsaved edit, for the tab dirty dots. Sections save
- // onBlur, so tabbing away from a pending edit leaves it unsaved with no cue
- // unless the tab itself carries one (#3399).
- const dirtyNumbers = useMemo(() => {
- const set = new Set();
- sections.forEach((s) => { if (isSectionDirty(baselines, s)) set.add(s.number); });
- return set;
- }, [sections, baselines]);
-
// Open-note count per issue, for the tab badges.
const openCountByNumber = useMemo(() => {
const map = new Map();
@@ -746,21 +737,17 @@ export default function PipelineManuscriptEditor() {
<div className="flex flex-col h-full overflow-y-auto lg:overflow-hidden">
{/* Parked navigation away from unsaved section edits (#3995). Sections
persist onBlur, so "unsaved" here means the user typed and left
- without the field blurring. */}
- {routeGuard.blocked && (
- <InlineConfirmRow
- className="shrink-0"
- variant="separator"
- tone="warning"
- question="Discard your unsaved manuscript edits?"
- confirmText="Discard"
- cancelText="Keep editing"
- onConfirm={discardAndExit}
- onCancel={routeGuard.reset}
- autoFocus
- aria-label={`Discard unsaved manuscript edits to ${series?.name || 'this series'}`}
- />
- )}
+ without the field blurring — and clicking a sidebar link blurs the
+ textarea, firing that save. While one is in flight the confirm stays
+ down: the save is about to settle these very edits clean, and the
+ guard then releases the parked navigation on its own. */}
+ <UnsavedChangesConfirm
+ guard={routeGuard}
+ when={!savingAny}
+ question="Discard your unsaved manuscript edits?"
+ label={`Discard unsaved manuscript edits to ${series?.name || 'this series'}`}
+ onDiscard={discardAndExit}
+ />
<div className="flex-1 flex flex-col lg:grid min-h-0" style={{ gridTemplateColumns: 'minmax(0, 1fr) 380px' }}>
{/* Manuscript pane */}
<section className="flex flex-col min-h-0 lg:overflow-y-auto p-4 md:p-6 space-y-5">
diff --git a/client/src/pages/PipelineManuscriptEditor.test.jsx b/client/src/pages/PipelineManuscriptEditor.test.jsx
index f64976e7da..256e12e98b 100644
--- a/client/src/pages/PipelineManuscriptEditor.test.jsx
+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx
@@ -664,6 +664,26 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {
expect(screen.queryByText('dashboard')).not.toBeInTheDocument();
});
+ it('keeps the confirm down while the onBlur save of those edits is in flight', async () => {
+ // Clicking a sidebar link blurs the textarea first, so the PATCH that
+ // persists the edit is already running when the navigation parks.
+ let resolveSave;
+ api.savePipelineManuscriptSection.mockReturnValue(new Promise((res) => { resolveSave = res; }));
+ const { router } = renderEditor('/pipeline/series/ser-1/manuscript/1');
+ const area = await typeUnsaved('The hero walked in. She left.', 'Edited, then blurred.');
+ fireEvent.blur(area);
+
+ await act(async () => { await router.navigate('/dashboard'); });
+ expect(screen.queryByText(CONFIRM)).not.toBeInTheDocument();
+ expect(screen.queryByText('dashboard')).not.toBeInTheDocument();
+
+ // The save lands, the draft settles clean, and the parked navigation runs.
+ await act(async () => {
+ resolveSave({ section: { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'Edited, then blurred.' } });
+ });
+ expect(await screen.findByText('dashboard')).toBeInTheDocument();
+ });
+
it('does not block an issue switch inside the editor (same splat route)', async () => {
api.getPipelineManuscript.mockResolvedValue(twoIssues);
renderEditor('/pipeline/series/ser-1/manuscript/1');