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 SongBook drafts against router navigation via a data router (#3958)
[._.]/ Adam Eivy0d17c7ee1fa6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 72aa37d640..1b5440c427 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -83,3 +83,4 @@- Unsaved job-skill edits in the Prompt Manager are no longer thrown away when you click another skill. Selecting a skill replaced the Markdown editor's contents outright, so a half-written template vanished with no warning and no undo the moment the user reached for a neighbouring skill in the sidebar list. The editor now tracks the last server-confirmed text (a full copy, not a flag, so typing an edit and undoing it back to the original stops counting as dirty) and marks itself with an "Unsaved changes" note in the header and an "Unsaved" badge on the list row. Clicking a different skill while dirty parks that click and takes over its list slot with an inline confirm row — "Discard unsaved changes to …?" with Discard / Keep editing — so cancelling leaves the selection, the URL, and the typed text untouched, and the next skill is only fetched once the discard is confirmed. Saving snapshots exactly what was sent — and which skill it was sent for — as the new clean baseline, so a save that lands after the user has already moved on cannot mark the freshly loaded skill dirty; a preview that resolves late is dropped for the same reason rather than rendered under the wrong skill's heading.- 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.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 8397354492..ade6121fa2 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -117,6 +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`. || `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/index.js b/client/src/hooks/index.jsindex 7674d69ee4..eb0dece8ad 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -67,6 +67,7 @@ export { default as useRowDraft } from './useRowDraft.js';export { default as useTheme } from './useTheme.js';export { default as useThreejsModelFamilies } from './useThreejsModelFamilies.js';export { default as useUniverse } from './useUniverse.js';+export { default as useUnsavedChangesGuard } from './useUnsavedChangesGuard.js';export { default as useUniverseAction } from './useUniverseAction.js';export { default as useUniverseBucketActions } from './useUniverseBucketActions.js';export { default as useUniverseDraft } from './useUniverseDraft.js';diff --git a/client/src/hooks/useUnsavedChangesGuard.js b/client/src/hooks/useUnsavedChangesGuard.jsnew file mode 100644index 0000000000..1812269ce1--- /dev/null+++ b/client/src/hooks/useUnsavedChangesGuard.js@@ -0,0 +1,61 @@+import { useCallback, useEffect } from 'react';+import { useBlocker } from 'react-router';++// Guards an editor's unsaved draft against BOTH exit doors (#3958):+//+// 1. In-app router navigation — a sidebar link, a ⌘K palette jump, a voice+// `ui_navigate`, or the browser Back button. These never touch the page's+// own controls, so a page-local handler can't see them; react-router's+// `useBlocker` parks the navigation instead and hands back `proceed()` /+// `reset()`.+// 2. Tab close / reload — `beforeunload`, which the browser owns.+//+// REQUIRES a data router (`createBrowserRouter` + `<RouterProvider>`, wired in+// `client/src/main.jsx`); `useBlocker` throws under a plain `<BrowserRouter>`.+// Tests rendering a page that uses this hook must mount it under+// `createMemoryRouter` + `<RouterProvider>`, not `<MemoryRouter>`.+//+// The caller renders its OWN confirm UI from `blocked` — an `InlineConfirmRow`,+// never `window.confirm` (see client/src/CLAUDE.md).+//+// const { blocked, proceed, reset } = useUnsavedChangesGuard(isDirty);+// {blocked && <InlineConfirmRow onConfirm={discardAndProceed} onCancel={reset} … />}+//+// 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 } = {}) {+ // 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 blocker = useBlocker(shouldBlock);+ const blocked = blocker.state === 'blocked';++ // Once the draft settles while a navigation is parked — the user hit Save+ // with the confirm up, or typed the value back to what's stored — the+ // navigation they asked for RUNS. Dropping it would swallow the click: the+ // confirm hides and nothing ever navigates.+ useEffect(() => {+ if (!isDirty && blocker.state === 'blocked') blocker.proceed();+ }, [isDirty, blocker]);++ // Tab close / reload — the browser owns this prompt; preventDefault arms it.+ // `returnValue` is the legacy signal, still what some browsers actually read,+ // so set both or the tab can close without asking.+ useEffect(() => {+ if (!beforeUnload || !isDirty) return undefined;+ const onBeforeUnload = (e) => { e.preventDefault(); e.returnValue = ''; };+ window.addEventListener('beforeunload', onBeforeUnload);+ return () => window.removeEventListener('beforeunload', onBeforeUnload);+ }, [beforeUnload, isDirty]);++ // `proceed` / `reset` exist only while blocked — the optional call keeps a+ // stale confirm's button from throwing after the blocker went idle.+ const proceed = useCallback(() => blocker.proceed?.(), [blocker]);+ const reset = useCallback(() => blocker.reset?.(), [blocker]);++ return { blocked, proceed, reset };+}diff --git a/client/src/hooks/useUnsavedChangesGuard.test.jsx b/client/src/hooks/useUnsavedChangesGuard.test.jsxnew file mode 100644index 0000000000..eb3404e972--- /dev/null+++ b/client/src/hooks/useUnsavedChangesGuard.test.jsx@@ -0,0 +1,120 @@+import { describe, it, expect, beforeEach, vi } from 'vitest';+import { useState } from 'react';+import { render, screen, fireEvent, waitFor, act } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router';+import useUnsavedChangesGuard from './useUnsavedChangesGuard.js';++// Minimal editor standing in for a real page: a dirty flag it can clear, plus+// the caller-owned confirm the hook expects (never window.confirm).+function Editor({ options }) {+ const [dirty, setDirty] = useState(true);+ const { blocked, proceed, reset } = useUnsavedChangesGuard(dirty, options);+ return (+ <div>+ <span>editor</span>+ <button type="button" onClick={() => setDirty(false)}>save</button>+ {blocked && (+ <>+ <button type="button" onClick={() => { setDirty(false); proceed(); }}>discard</button>+ <button type="button" onClick={reset}>keep</button>+ </>+ )}+ </div>+ );+}++// router.navigate resolves asynchronously — settle it inside act() or the+// suite's strict act-warning guard fails the test (src/test/setup.js).+const navigate = (router, to) => act(async () => { await router.navigate(to); });++const renderEditor = ({ options, history = [] } = {}) => {+ const router = createMemoryRouter([+ { path: '/away', element: <div>away</div> },+ { path: '/edit', element: <Editor options={options} /> },+ { path: '/edit/deeper', element: <Editor options={options} /> },+ ], { initialEntries: [...history, '/edit'], initialIndex: history.length });+ render(<RouterProvider router={router} />);+ return router;+};++describe('useUnsavedChangesGuard', () => {+ beforeEach(() => {+ vi.restoreAllMocks();+ });++ it('blocks a router navigation while the draft is dirty', async () => {+ const router = renderEditor();+ await navigate(router, '/away');+ expect(await screen.findByText('keep')).toBeTruthy();+ expect(screen.getByText('editor')).toBeTruthy();+ expect(screen.queryByText('away')).toBeNull();+ });++ it('runs the parked navigation on proceed', async () => {+ const router = renderEditor();+ await navigate(router, '/away');+ fireEvent.click(await screen.findByText('discard'));+ expect(await screen.findByText('away')).toBeTruthy();+ });++ it('drops the parked navigation on reset', async () => {+ const router = renderEditor();+ await navigate(router, '/away');+ fireEvent.click(await screen.findByText('keep'));+ await waitFor(() => expect(screen.queryByText('keep')).toBeNull());+ expect(screen.getByText('editor')).toBeTruthy();+ expect(screen.queryByText('away')).toBeNull();+ });++ it('blocks a POP navigation (browser Back)', async () => {+ const router = renderEditor({ history: ['/away'] });+ await navigate(router, -1);+ expect(await screen.findByText('keep')).toBeTruthy();+ expect(screen.queryByText('away')).toBeNull();+ });++ it('lets a navigation through once the draft goes clean', async () => {+ const router = renderEditor();+ fireEvent.click(screen.getByText('save'));+ await navigate(router, '/away');+ expect(await screen.findByText('away')).toBeTruthy();+ });++ it('auto-proceeds a parked navigation when the draft settles', async () => {+ const router = renderEditor();+ await navigate(router, '/away');+ expect(await screen.findByText('keep')).toBeTruthy();+ // Saving clears the dirty flag with the confirm still up — the navigation+ // the user asked for RUNS instead of being swallowed.+ fireEvent.click(screen.getByText('save'));+ expect(await screen.findByText('away')).toBeTruthy();+ });++ it('does not block a same-pathname navigation (search-param change)', async () => {+ const router = renderEditor();+ await navigate(router, '/edit?tab=notes');+ await waitFor(() => expect(router.state.location.search).toBe('?tab=notes'));+ expect(screen.queryByText('keep')).toBeNull();+ });++ it('blocks a navigation to a different pathname under the same page', async () => {+ const router = renderEditor();+ await navigate(router, '/edit/deeper');+ expect(await screen.findByText('keep')).toBeTruthy();+ });++ it('arms beforeunload while dirty and disarms once clean', async () => {+ const add = vi.spyOn(window, 'addEventListener');+ const remove = vi.spyOn(window, 'removeEventListener');+ renderEditor();+ expect(add.mock.calls.some(([type]) => type === 'beforeunload')).toBe(true);+ fireEvent.click(screen.getByText('save'));+ await waitFor(() => expect(remove.mock.calls.some(([type]) => type === 'beforeunload')).toBe(true));+ });++ it('skips beforeunload when the caller opts out', () => {+ const add = vi.spyOn(window, 'addEventListener');+ renderEditor({ options: { beforeUnload: false } });+ expect(add.mock.calls.some(([type]) => type === 'beforeunload')).toBe(false);+ });+});diff --git a/client/src/main.jsx b/client/src/main.jsxindex ecd0f1178e..3649bf8aa0 100644--- a/client/src/main.jsx+++ b/client/src/main.jsx@@ -1,7 +1,7 @@import './lib/consoleFilters';import React from 'react';import ReactDOM from 'react-dom/client';-import { BrowserRouter } from 'react-router';+import { createBrowserRouter, RouterProvider } from 'react-router';import { Toaster } from './components/ui/Toast';import ErrorBoundary from './components/ErrorBoundary';import { ThemeProvider } from './components/ThemeContext';@@ -51,26 +51,41 @@ window.addEventListener('error', (event) => {});});+// Data router (not a plain <BrowserRouter>) so `useBlocker` is available —+// it is the only way an editor can stop a sidebar link, a ⌘K jump, a voice+// `ui_navigate`, or the browser Back button from dropping an unsaved draft+// (#3958, see hooks/useUnsavedChangesGuard). The whole existing <Routes> tree+// stays mounted under one splat route, so no page needed rewriting; new pages+// keep adding a <Route> in App.jsx exactly as before.+const router = createBrowserRouter([+ {+ path: '*',+ element: (+ <>+ <App />+ <Toaster+ position="bottom-right"+ toastOptions={{+ style: {+ background: 'rgb(var(--port-card) / var(--port-card-alpha, 1))',+ color: 'rgb(var(--port-text))',+ border: '1px solid rgb(var(--port-border) / var(--port-border-alpha, 1))',+ borderRadius: 'var(--port-radius-lg)',+ backdropFilter: 'var(--port-backdrop-filter)',+ boxShadow: 'var(--port-shadow-elevated)'+ }+ }}+ />+ </>+ ),+ },+]);+ReactDOM.createRoot(document.getElementById('root')).render(<React.StrictMode><ErrorBoundary><ThemeProvider>- <BrowserRouter>- <App />- <Toaster- position="bottom-right"- toastOptions={{- style: {- background: 'rgb(var(--port-card) / var(--port-card-alpha, 1))',- color: 'rgb(var(--port-text))',- border: '1px solid rgb(var(--port-border) / var(--port-border-alpha, 1))',- borderRadius: 'var(--port-radius-lg)',- backdropFilter: 'var(--port-backdrop-filter)',- boxShadow: 'var(--port-shadow-elevated)'- }- }}- />- </BrowserRouter>+ <RouterProvider router={router} /></ThemeProvider></ErrorBoundary></React.StrictMode>diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex dae65f834f..82362fb7a7 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -22,8 +22,10 @@* `content` object is always sent — the server fills nested content* defaults, so `{ content: { text } }` alone would reset format to 'tab'.* Because the draft only reaches the server on Save, every exit out of edit- * mode (View toggle, "All songs", tab close) goes through an unsaved-changes- * guard rather than dropping the draft silently (#3902).+ * mode goes through an unsaved-changes guard rather than dropping the draft+ * silently — the View toggle in-page (#3902), and every route exit (the+ * "All songs" link, a sidebar link, ⌘K, voice nav, Back, tab close) via+ * useUnsavedChangesGuard (#3958).** Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top.* For a drum chart the same keys drive the kit transport instead: space@@ -61,6 +63,7 @@ import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';import useAutoscroll from '../hooks/useAutoscroll';import useDrumPlayer from '../hooks/useDrumPlayer';import useWakeLock from '../hooks/useWakeLock';+import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';import { transposeText } from '../lib/tabNotation.js';import { VOICING_INSTRUMENTS, toVoicingInstrument } from '../lib/chordShapes.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';@@ -338,11 +341,11 @@ export default function SongBookViewer() {return updated;}, { errorMessage: 'Failed to save song' });- // --- Unsaved-edit guard (#3902)+ // --- Unsaved-edit guard (#3902, #3958)// The editor holds everything in `draft` until an explicit Save, so leaving- // edit mode (View toggle, "All songs", a tab close) would drop sheet text and- // practice notes silently. `pendingExit` holds the deferred navigation while- // the inline discard confirm is up.+ // edit mode would drop sheet text and practice notes silently. `pendingExit`+ // holds a deferred IN-PAGE exit (the View toggle) while the inline discard+ // confirm is up; `routeGuard` below parks anything that leaves the route.const isDirty = useMemo(() => !!song && !!draft && !draftsEqual(draft, toDraft(song)),[song, draft],@@ -363,29 +366,21 @@ export default function SongBookViewer() {if (isDirty) setPendingExit(() => run);else run();}, [isDirty]);- // Route-link clicks can't be deferred by returning false — swallow the default- // navigation and re-run it from the confirm instead. A modified click- // (⌘/Ctrl/Shift/Alt, or a middle button) opens a second tab and LEAVES the- // editor standing, so there's nothing to guard: let the browser have it.- const onLeaveLink = useCallback((e) => {- if (!isDirty || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;- e.preventDefault();- setPendingExit(() => () => navigate('/songbook'));- }, [isDirty, navigate]);+ // Everything that leaves this ROUTE — the "All songs" link, a sidebar link, a+ // ⌘K palette jump, a voice `ui_navigate`, the browser Back button — plus tab+ // close / reload (#3958). `requestExit` above still covers the one exit that+ // isn't a navigation: the View toggle, which only flips the `?mode` param.+ const routeGuard = useUnsavedChangesGuard(isDirty);const discardAndExit = useCallback(() => {setDraft(song ? toDraft(song) : null);setPendingExit(null);pendingExit?.();- }, [pendingExit, song]);- // Tab close / reload — the browser owns this prompt; preventDefault arms it.- // `returnValue` is the legacy signal, still what some browsers actually read,- // so set both or the tab can close without asking.- useEffect(() => {- if (!isDirty) return undefined;- const onBeforeUnload = (e) => { e.preventDefault(); e.returnValue = ''; };- window.addEventListener('beforeunload', onBeforeUnload);- return () => window.removeEventListener('beforeunload', onBeforeUnload);- }, [isDirty]);+ routeGuard.proceed();+ }, [pendingExit, routeGuard, song]);+ const keepEditing = useCallback(() => {+ setPendingExit(null);+ routeGuard.reset();+ }, [routeGuard]);const onDeleteSong = useCallback(() => confirmDelete(() =>deleteSong(id, { silent: true })@@ -493,7 +488,7 @@ export default function SongBookViewer() {subtitle={song.artist || undefined}actions={(<>- <Link to="/songbook" onClick={onLeaveLink} className={btnClass}>+ <Link to="/songbook" className={btnClass}><ArrowLeft size={15} /><span className="hidden sm:inline">All songs</span></Link>@@ -557,7 +552,7 @@ export default function SongBookViewer() {while a save is in flight: discarding then would reset the draftunder a PATCH that is still persisting those very edits. A failedsave leaves the draft dirty, so the band comes back. */}- {pendingExit && !saving && (+ {(pendingExit || routeGuard.blocked) && !saving && (<InlineConfirmRowclassName="shrink-0"variant="separator"@@ -566,7 +561,7 @@ export default function SongBookViewer() {confirmText="Discard"cancelText="Keep editing"onConfirm={discardAndExit}- onCancel={() => setPendingExit(null)}+ onCancel={keepEditing}autoFocusaria-label={`Discard unsaved changes to ${song.title}`}/>diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex f5cba6f50a..c50dfa54a3 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { render, screen, fireEvent, waitFor, within } from '@testing-library/react';-import { MemoryRouter, Routes, Route } from 'react-router';+import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react';+import { createMemoryRouter, RouterProvider } from 'react-router';// Mock the api barrel (RoundEditor.test.jsx harness style).const api = vi.hoisted(() => ({@@ -42,11 +42,21 @@ const song = (extra = {}) => ({...extra,});-const renderPage = (path = '/songbook/abc') => render(- <MemoryRouter initialEntries={[path]}>- <Routes><Route path="/songbook/:id" element={<SongBookViewer />} /></Routes>- </MemoryRouter>,-);+// Data router (not <MemoryRouter>) — SongBookViewer's unsaved-draft guard uses+// react-router's `useBlocker`, which only exists under one, matching how+// main.jsx mounts the app (#3958). The index route stands in for anywhere else+// the user might navigate (sidebar link, ⌘K, Back).+// router.navigate resolves asynchronously — settle it inside act() or the+// suite's strict act-warning guard fails the test (src/test/setup.js).+const navigate = (router, to) => act(async () => { await router.navigate(to); });++const renderPage = (path = '/songbook/abc', { history = [] } = {}) => {+ const router = createMemoryRouter([+ { path: '/songbook', element: <div>All songs index</div> },+ { path: '/songbook/:id', element: <SongBookViewer /> },+ ], { initialEntries: [...history, path], initialIndex: history.length });+ return { ...render(<RouterProvider router={router} />), router };+};describe('SongBookViewer', () => {beforeEach(() => {@@ -669,6 +679,53 @@ K: o - - - - - o -`;expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');});+ // Exits that never touch a control on this page — a sidebar link, a ⌘K+ // palette jump, a voice ui_navigate, the browser Back button. They all+ // reach the router the same way, so driving router.navigate covers them.+ it('confirms before a sidebar/⌘K navigation leaves with unsaved edits', async () => {+ const { router } = renderPage('/songbook/abc?mode=edit');+ await editSheet();+ await navigate(router, '/songbook');+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();+ // Parked, not run — the editor is still mounted with the draft intact.+ expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');+ expect(screen.queryByText('All songs index')).toBeNull();++ // Keep editing → the navigation is dropped and the draft survives.+ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));+ await waitFor(() => expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull());+ expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');+ });++ it('discards and completes the parked navigation on confirm', async () => {+ const { router } = renderPage('/songbook/abc?mode=edit');+ await editSheet();+ await navigate(router, '/songbook');+ fireEvent.click(await screen.findByRole('button', { name: 'Discard' }));+ expect(await screen.findByText('All songs index')).toBeTruthy();+ expect(api.updateSong).not.toHaveBeenCalled();+ });++ it('confirms before the browser Back button leaves with unsaved edits', async () => {+ const { router } = renderPage('/songbook/abc?mode=edit', { history: ['/songbook'] });+ await editSheet();+ await navigate(router, -1);+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();+ expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');+ });++ it('lets a navigation through once the draft is saved clean', async () => {+ api.updateSong.mockImplementation((_id, patch) => Promise.resolve(song({ ...patch })));+ const { router } = renderPage('/songbook/abc?mode=edit');+ await editSheet();+ await navigate(router, '/songbook');+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();+ // Saving settles the draft, so the parked navigation RUNS rather than+ // being swallowed with the confirm row.+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ expect(await screen.findByText('All songs index')).toBeTruthy();+ });+it('drops the armed confirm once a save settles the draft', async () => {api.updateSong.mockImplementation((_id, patch) => Promise.resolve(song({ ...patch })));renderPage('/songbook/abc?mode=edit');