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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: guard unsaved manuscript and writers-room edits against in-app navigation (#3995)
[._.]/ Adam Eivy093cc5710805
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1b5440c427..153c44df8d 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -84,3 +84,4 @@- Saving an ingredient no longer issues one or two database queries per tag. `normalizeTags` mapped each raw label to its canonical `catalog_tags` row inside a `for` loop — an `INSERT … ON CONFLICT DO NOTHING RETURNING label` per label, plus a follow-up `SELECT` whenever the row already existed, which is the common case — so an ingredient carrying M tags cost between M and 2M round-trips on every create, every tag-touching update, and every committed scrap. The whole list is now resolved in at most two statements: one `SELECT id, label … WHERE id = ANY($1)` to read every pre-existing row, then a single multi-row insert for whatever is missing, skipped entirely when nothing is. The canonical rules are unchanged — blank tags dropped, casing/whitespace variants collapsed to one row, order of first appearance preserved, and a stored label still beating the incoming casing (`Noir` wins over a later `NOIR`) — and passing `{ client }` still runs both statements on the caller's transaction.- A failed quota read on an already-loaded Quota Burn page now says so. Once a plan was on screen, a "Refresh quota" that never landed — or a background poll for a still-pending provider scrape — left the numbers exactly as they were, so a read that failed was indistinguishable from one that came back unchanged. Any failed read now raises a warning banner above the page header naming the cause, with its own Retry button, and clears itself on the next successful read (including the poll's). The banner is the page's single error surface: the manual refresh no longer toasts the same failure on top of it, and the stale plan stays rendered throughout rather than being blanked.- Unsaved SongBook editor drafts survive a sidebar click, a ⌘K jump, voice nav and the browser Back button. The editor already deferred its own exits — the View toggle and the "All songs" link — behind an inline discard confirm, but anything that left through the router without touching those controls unmounted the editor and dropped the sheet text and practice notes silently, which is the same data loss through a different door. The client now mounts a react-router data router (the existing route tree hangs unchanged under one splat route, so no page needed rewriting), which makes `useBlocker` available, and the guard ships as a shared `useUnsavedChangesGuard(isDirty)` hook: it parks the navigation, hands the page `blocked` / `proceed()` / `reset()` so the page renders its own inline confirm rather than a `window.confirm`, and arms `beforeunload` for tab close and reload. A parked navigation that settles clean — the user hits Save with the confirm up — runs instead of being swallowed, a navigation that only changes search params on the same page is never blocked, and a ⌘-click that opens a second tab still leaves the editor standing untouched.+- Unsaved edits in the pipeline manuscript editor and the writers-room work editor now survive an in-app navigation. Both carried a `beforeunload`-only guard, so a tab close or reload asked before dropping the draft but a sidebar link, a ⌘K jump, a voice `ui_navigate` or the browser Back button unmounted the editor and discarded the work silently — manuscript sections only persist onBlur, so a section typed into and left without blurring was gone. Both now adopt the shared `useUnsavedChangesGuard` hook and render an inline Discard / Keep editing confirm (never a `window.confirm`), with the local `beforeunload` effects dropped in favour of the hook's. The manuscript editor is a splat route where switching issue tabs changes the pathname without leaving the editor, so the hook grew an `isSameView(from, to)` option that exempts an editor's own in-page moves: switching between issues with unsaved text raises nothing, while leaving the manuscript entirely still parks the navigation behind the confirm, and discarding restores each section to its last server-confirmed content before the navigation runs.diff --git a/client/src/components/writers-room/WorkEditor.jsx b/client/src/components/writers-room/WorkEditor.jsxindex 1db702cdd0..b8d608a0ef 100644--- a/client/src/components/writers-room/WorkEditor.jsx+++ b/client/src/components/writers-room/WorkEditor.jsx@@ -28,7 +28,9 @@ import {import toast from '../ui/Toast';import ProseEditor from '../ui/ProseEditor';import Drawer from '../Drawer';+import InlineConfirmRow from '../ui/InlineConfirmRow';import useMounted from '../../hooks/useMounted';+import useUnsavedChangesGuard from '../../hooks/useUnsavedChangesGuard';import useClickOutside from '../../hooks/useClickOutside';import {saveWritersRoomDraft,@@ -328,14 +330,15 @@ export default function WorkEditor({ work, onChange, onToggleExercise, exerciseOreturn () => window.removeEventListener('keydown', onKey);}, []);- // Warn on tab close/navigation away while there are unsaved draft edits —- // otherwise the body reset in the effect above silently discards them.- useEffect(() => {- if (!dirty) return undefined;- const onBeforeUnload = (e) => { e.preventDefault(); };- window.addEventListener('beforeunload', onBeforeUnload);- return () => window.removeEventListener('beforeunload', onBeforeUnload);- }, [dirty]);+ // Guard unsaved draft edits at BOTH exit doors (#3958/#3995) — tab+ // close/reload, and any in-app navigation (sidebar link, ⌘K, voice+ // `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 discardAndExit = useCallback(() => {+ setBody(savedBody);+ routeGuard.proceed();+ }, [routeGuard, savedBody]);useClickOutside(overflowRef, overflowOpen, () => setOverflowOpen(false));@@ -856,6 +859,21 @@ 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'}`}+ />+ )}+{runningKind && (<AnalysisRunBannerkind={runningKind}diff --git a/client/src/components/writers-room/WorkEditor.perf.test.jsx b/client/src/components/writers-room/WorkEditor.perf.test.jsxindex 9f0fb58bb3..64eb680720 100644--- a/client/src/components/writers-room/WorkEditor.perf.test.jsx+++ b/client/src/components/writers-room/WorkEditor.perf.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, render } from '@testing-library/react';import { fireEvent } from '@testing-library/dom';-import { MemoryRouter } from 'react-router';+import { createMemoryRouter, RouterProvider } from 'react-router';// Regression guard for #3387: typing in the WorkEditor body must NOT re-render// the <StoryboardPanel> sidebar. The panel is a heavy tree (bibles, boards,@@ -64,12 +64,14 @@ const work = {drafts: [{ id: 'wr-draft-1', label: 'v1', wordCount: 3 }],};+// A DATA router: WorkEditor's unsaved-changes guard uses `useBlocker`, which+// throws under a plain <MemoryRouter> (#3995).+const editorRouter = () => createMemoryRouter([+ { path: '/writers-room', element: <WorkEditor work={work} onChange={() => {}} /> },+], { initialEntries: ['/writers-room'] });+async function renderEditor() {- const view = render(- <MemoryRouter>- <WorkEditor work={work} onChange={() => {}} />- </MemoryRouter>- );+ const view = render(<RouterProvider router={editorRouter()} />);// Settle the mount-effect bible fetches before asserting render counts.await act(async () => {});return view;diff --git a/client/src/components/writers-room/WorkEditor.test.jsx b/client/src/components/writers-room/WorkEditor.test.jsxindex 575c40f593..aac50a4023 100644--- a/client/src/components/writers-room/WorkEditor.test.jsx+++ b/client/src/components/writers-room/WorkEditor.test.jsx@@ -1,7 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import { act, render, screen, within } from '@testing-library/react';import { fireEvent } from '@testing-library/dom';-import { MemoryRouter } from 'react-router';+import { createMemoryRouter, RouterProvider } from 'react-router';// Header layout contract for #3568: on a ~375px phone the WorkEditor header// used to wrap into 4-5 rows and push the prose textarea below the fold. The@@ -44,14 +44,18 @@ const work = {drafts: [{ id: 'wr-draft-1', label: 'v1', wordCount: 3 }],};+// A DATA router: WorkEditor's unsaved-changes guard uses `useBlocker`, which+// throws under a plain <MemoryRouter> (#3995).+const editorRouter = () => createMemoryRouter([+ { path: '/writers-room', element: <WorkEditor work={work} onChange={() => {}} /> },+ { path: '/dashboard', element: <div>dashboard</div> },+], { initialEntries: ['/writers-room'] });+async function renderEditor() {- const view = render(- <MemoryRouter>- <WorkEditor work={work} onChange={() => {}} />- </MemoryRouter>- );+ const router = editorRouter();+ const view = render(<RouterProvider router={router} />);await act(async () => {});- return view;+ return { ...view, router };}function headerControls() {@@ -161,3 +165,47 @@ describe('WorkEditor header layout (#3568)', () => {expect(container.querySelector('textarea')).toBeNull();});});++describe('WorkEditor unsaved-changes route guard (#3995)', () => {+ const CONFIRM = 'Discard your unsaved changes to this work?';+ 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 () => {+ const { container, router } = await renderEditor();+ await typeUnsaved(container, 'The hero wakes, then hesitates.');++ await act(async () => { await router.navigate('/dashboard'); });+ expect(screen.getByText(CONFIRM)).toBeInTheDocument();+ expect(screen.queryByText('dashboard')).not.toBeInTheDocument();+ });++ it('discards the draft and runs the parked navigation', async () => {+ const { container, router } = await renderEditor();+ await typeUnsaved(container, 'The hero wakes, then hesitates.');+ await act(async () => { await router.navigate('/dashboard'); });++ await act(async () => { fireEvent.click(screen.getByText('Discard')); });+ expect(screen.getByText('dashboard')).toBeInTheDocument();+ });++ it('keeps the editor and the draft on cancel', async () => {+ const { container, router } = await renderEditor();+ await typeUnsaved(container, 'The hero wakes, then hesitates.');+ await act(async () => { await router.navigate('/dashboard'); });++ await act(async () => { fireEvent.click(screen.getByText('Keep editing')); });+ expect(screen.queryByText(CONFIRM)).not.toBeInTheDocument();+ expect(container.querySelector('textarea').value).toBe('The hero wakes, then hesitates.');+ expect(screen.queryByText('dashboard')).not.toBeInTheDocument();+ });++ it('lets a navigation through while the draft is clean', async () => {+ const { router } = await renderEditor();+ await act(async () => { await router.navigate('/dashboard'); });+ expect(screen.getByText('dashboard')).toBeInTheDocument();+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ade6121fa2..38f9282478 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 })` → `{ 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. Requires the data router in `main.jsx`; tests must mount `createMemoryRouter` + `<RouterProvider>`. | Any editor holding an unsaved draft (SongBookViewer) — render your own `InlineConfirmRow` from `blocked`, never `window.confirm`. |+| `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`. || `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.jsindex 1812269ce1..f6a3bc172a 100644--- a/client/src/hooks/useUnsavedChangesGuard.js+++ b/client/src/hooks/useUnsavedChangesGuard.js@@ -23,14 +23,22 @@ 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()`.-export default function useUnsavedChangesGuard(isDirty, { beforeUnload = true } = {}) {+// `isSameView(currentPathname, nextPathname)` — optional escape hatch 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 } = {}) {// 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// the user can't explain.- const shouldBlock = useCallback(({ currentLocation, nextLocation }) => (- !!isDirty && currentLocation.pathname !== nextLocation.pathname- ), [isDirty]);+ const shouldBlock = useCallback(({ currentLocation, nextLocation }) => {+ if (!isDirty) return false;+ if (currentLocation.pathname === nextLocation.pathname) return false;+ return !isSameView?.(currentLocation.pathname, nextLocation.pathname);+ }, [isDirty, isSameView]);const blocker = useBlocker(shouldBlock);const blocked = blocker.state === 'blocked';diff --git a/client/src/hooks/useUnsavedChangesGuard.test.jsx b/client/src/hooks/useUnsavedChangesGuard.test.jsxindex eb3404e972..4718180673 100644--- a/client/src/hooks/useUnsavedChangesGuard.test.jsx+++ b/client/src/hooks/useUnsavedChangesGuard.test.jsx@@ -103,6 +103,22 @@ 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 } });+ 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 } });+ await navigate(router, '/away');+ expect(await screen.findByText('keep')).toBeTruthy();+ expect(screen.queryByText('away')).toBeNull();+ });+it('arms beforeunload while dirty and disarms once clean', async () => {const add = vi.spyOn(window, 'addEventListener');const remove = vi.spyOn(window, 'removeEventListener');diff --git a/client/src/pages/PipelineManuscriptEditor.jsx b/client/src/pages/PipelineManuscriptEditor.jsxindex 6333922fa6..9940109a14 100644--- a/client/src/pages/PipelineManuscriptEditor.jsx+++ b/client/src/pages/PipelineManuscriptEditor.jsx@@ -27,15 +27,17 @@* docs/plans/2026-06-06-manuscript-editor-inline-feedback.md.*/-import { useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { Link, useParams, useNavigate, useSearchParams } from 'react-router';import {ArrowLeft, Loader2, Sparkles, FileText, Star, ClipboardCheck, Layers, PencilLine, BookOpen, GitCompare, Volume2, X,} from 'lucide-react';import { formatManuscript } from '../lib/manuscriptFormat';import toast from '../components/ui/Toast';+import InlineConfirmRow from '../components/ui/InlineConfirmRow';import { useAsyncAction } from '../hooks/useAsyncAction';import { usePipelineProgress } from '../hooks/usePipelineProgress';+import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';import { filterGenerationModels, mergeModelLists, localBackendForProvider, modelOptionLabel } from '../utils/providers';import useLocalModels from '../hooks/useLocalModels';import { locateAnchors } from '../lib/manuscriptAnchors';@@ -155,17 +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 a tab close/navigation right after typing- // (before the field blurs) would silently drop the edit. Warn on unload- // whenever any section's live content has drifted from its saved baseline.- useEffect(() => {- const onBeforeUnload = (e) => {- const dirty = liveSectionsRef.current.some((s) => isSectionDirty(baselineRef.current, s));- if (dirty) e.preventDefault();- };- window.addEventListener('beforeunload', onBeforeUnload);- return () => window.removeEventListener('beforeunload', onBeforeUnload);- }, []);+ // 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],+ );++ // 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 = () => {+ setSections((prev) => prev.map((s) => {+ const key = baselineKey(s);+ return baselineRef.current.has(key) ? { ...s, content: baselineRef.current.get(key) } : s;+ }));+ routeGuard.proceed();+ };useEffect(() => {safeWriteStorage(VIEW_MODE_KEY, viewMode);@@ -727,6 +744,23 @@ export default function PipelineManuscriptEditor() {// manuscript and review controls stack on mobile, so the page needs one// shared scroll region until the desktop panes take over at lg.<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'}`}+ />+ )}<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.jsxindex 48e3179492..f64976e7da 100644--- a/client/src/pages/PipelineManuscriptEditor.test.jsx+++ b/client/src/pages/PipelineManuscriptEditor.test.jsx@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, waitFor, fireEvent, within, act } from '@testing-library/react';-import { MemoryRouter, Routes, Route } from 'react-router';+import { createMemoryRouter, RouterProvider } from 'react-router';import { MockEventSource, lastEventSource as lastEs } from '../test/mockEventSource';const api = vi.hoisted(() => ({@@ -32,14 +32,16 @@ const comment = {status: 'open', fix: null, createdAt: 't', updatedAt: 't',};-const renderEditor = (path = '/pipeline/series/ser-1/manuscript') => render(- <MemoryRouter initialEntries={[path]}>- <Routes>- <Route path="/pipeline/series/:seriesId/manuscript/*" element={<PipelineManuscriptEditor />} />- <Route path="/pipeline/series/:seriesId" element={<div>series page</div>} />- </Routes>- </MemoryRouter>,-);+// A DATA router: the editor's unsaved-changes guard uses `useBlocker`, which+// throws under a plain <MemoryRouter> (#3995).+const renderEditor = (path = '/pipeline/series/ser-1/manuscript') => {+ const router = createMemoryRouter([+ { path: '/pipeline/series/:seriesId/manuscript/*', element: <PipelineManuscriptEditor /> },+ { path: '/pipeline/series/:seriesId', element: <div>series page</div> },+ { path: '/dashboard', element: <div>dashboard</div> },+ ], { initialEntries: [path] });+ return { ...render(<RouterProvider router={router} />), router };+};// Reveal a comment in context by clicking its sidebar index row.const revealFromIndex = (problem) => fireEvent.click(screen.getByText(problem));@@ -615,4 +617,61 @@ describe('PipelineManuscriptEditor — generate-edits streamed review', () => {expect(await screen.findByText('Run editorial review')).toBeInTheDocument();await waitFor(() => expect(api.getPipelineManuscriptReview).toHaveBeenCalledTimes(2));});++ describe('unsaved-changes route guard (#3995)', () => {+ const twoIssues = {+ sections: [+ { issueId: 'iss-1', number: 1, title: 'One', stageId: 'prose', content: 'Issue one body.' },+ { issueId: 'iss-2', number: 2, title: 'Two', stageId: 'prose', content: 'Issue two body.' },+ ],+ viewType: 'prose', primaryStageId: 'prose', pinnedPrimary: 'prose', availableTypes: ['prose'],+ };+ // Sections persist onBlur, so typing WITHOUT blurring is exactly the state+ // the guard exists to protect.+ const typeUnsaved = async (current, next) => {+ const area = await screen.findByDisplayValue(current);+ fireEvent.change(area, { target: { value: next } });+ return area;+ };+ const CONFIRM = 'Discard your unsaved manuscript edits?';++ it('blocks leaving the editor while a section has unsaved edits', async () => {+ const { router } = renderEditor('/pipeline/series/ser-1/manuscript/1');+ await typeUnsaved('The hero walked in. She left.', 'Edited but not blurred.');++ await act(async () => { await router.navigate('/dashboard'); });+ expect(await screen.findByText(CONFIRM)).toBeInTheDocument();+ expect(screen.queryByText('dashboard')).not.toBeInTheDocument();+ });++ it('discards the edits and runs the parked navigation', async () => {+ const { router } = renderEditor('/pipeline/series/ser-1/manuscript/1');+ await typeUnsaved('The hero walked in. She left.', 'Edited but not blurred.');+ await act(async () => { await router.navigate('/dashboard'); });++ fireEvent.click(await screen.findByText('Discard'));+ expect(await screen.findByText('dashboard')).toBeInTheDocument();+ });++ it('keeps the editor (and the edits) on cancel', async () => {+ const { router } = renderEditor('/pipeline/series/ser-1/manuscript/1');+ await typeUnsaved('The hero walked in. She left.', 'Edited but not blurred.');+ await act(async () => { await router.navigate('/dashboard'); });++ fireEvent.click(await screen.findByText('Keep editing'));+ await waitFor(() => expect(screen.queryByText(CONFIRM)).not.toBeInTheDocument());+ expect(screen.getByDisplayValue('Edited but not blurred.')).toBeInTheDocument();+ expect(screen.queryByText('dashboard')).not.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');+ await typeUnsaved('Issue one body.', 'Issue one, edited.');++ fireEvent.click(within(screen.getByRole('navigation', { name: 'Issues' })).getByRole('link', { name: /Issue 2/ }));+ expect(await screen.findByDisplayValue('Issue two body.')).toBeInTheDocument();+ expect(screen.queryByText(CONFIRM)).not.toBeInTheDocument();+ });+ });});