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

fix: confirm before the SongBook editor discards unsaved sheet edits (#3902)

[._.]/ Adam Eivyde6a281f585d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 14b829c292..ca90d2a3c9 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -60,3 +60,4 @@
- Deleting or uploading a SongBook attachment no longer crashes when the attachment presence lookup failed on page load. That failure parks the attachment state on a `'failed'` sentinel string so the synced list still renders with presence unknown, but both mutation handlers treated it as an array: the delete handler called `.find()` on it and threw `TypeError: prev.find is not a function`, leaving the row on screen, and the upload handler spread the string into six single-character rows. Both now check for an array first, falling back to the record's own synced list on upload and leaving presence genuinely unknown on delete rather than stamping a false "not on this machine" pill.
- Uploading several SongBook attachments at once no longer stops at the first failure. The upload loop awaited each file without catching, so one rejected read or a single server error broke out of the loop: the remaining files in the selection were never attempted, and the one generic "Upload failed" toast gave no clue which file failed or that anything had been skipped. Each file's read-and-upload now catches on its own, toasting a message that names the file, and the batch continues so the successful files still land.
- Keyboard-shortcut hints across the client now render the right modifier for the machine they're on. `client/src/utils/platform.js` exports a `modKey` (`⌘` / `Ctrl`) label, but only the command palette and the keyboard-help sheet read it — five other hints hardcoded a glyph instead: the 404 page and the Ask composer advertised `⌘K` / `⌘/Ctrl + Enter` to Windows and Linux users, the OpenClaw composer printed both forms side by side, the Writers Room save button's tooltip said `Ctrl/Cmd+S`, and the digital-twin enrichment prompt said `Ctrl+Enter` on a Mac. All five now read `modKey`, which prefers `navigator.userAgentData.platform` over the deprecated `navigator.platform` and degrades to non-Mac when neither exists — behaviour the module now has tests for.
+- Leaving the SongBook editor with unsaved edits now asks first. The editor holds every change — sheet text, practice notes, metadata — in an in-memory draft until an explicit Save, so clicking View, following the "All songs" link, or closing the tab dropped the work silently. The page now compares the draft against the saved song (numerically for capo, since the number input hands back a string and retyping the stored value would otherwise read as an edit) and defers those exits behind an inline "Discard your unsaved changes?" band under the header, with Discard resetting the draft and Keep editing leaving it intact; a tab close or reload arms the browser's own prompt. Saving clears an armed confirm, since the draft is no longer dirty.
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 380b3344de..1798135597 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -21,6 +21,9 @@
* select and live preview. Saves are explicit (single PATCH). The whole
* `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).
*
* Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top.
* For a drum chart the same keys drive the kit transport instead: space
@@ -39,6 +42,7 @@ import toast from '../components/ui/Toast';
import FilePickerButton from '../components/ui/FilePickerButton';
import PageHeader from '../components/PageHeader';
import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';
+import InlineConfirmRow from '../components/ui/InlineConfirmRow';
import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';
import TabPills from '../components/ui/TabPills';
import TabSheetView from '../components/songbook/TabSheetView';
@@ -94,6 +98,14 @@ const toDraft = (song) => ({
const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);
+// Draft-vs-saved comparison for the unsaved-changes guard. Both sides come from
+// toDraft (flat strings), except `capo`: the number input hands back a STRING,
+// so retyping the stored value ('2' vs 2) would otherwise read as an edit. An
+// emptied capo field compares as 0, which is what the save would clamp it to.
+const draftsEqual = (a, b) => Object.keys(a).every((k) => (
+ k === 'capo' ? Number(a.capo || 0) === Number(b.capo || 0) : a[k] === b[k]
+));
+
// Instrument-view toggle tabs (chord-diagram rendering — never mutates the record).
const VIEW_TABS = VOICING_INSTRUMENTS.map((viewId) => ({ id: viewId, label: instrumentLabel(viewId) }));
@@ -314,6 +326,43 @@ export default function SongBookViewer() {
return updated;
}, { errorMessage: 'Failed to save song' });
+ // --- Unsaved-edit guard (#3902)
+ // 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.
+ const isDirty = useMemo(
+ () => !!song && !!draft && !draftsEqual(draft, toDraft(song)),
+ [song, draft],
+ );
+ const [pendingExit, setPendingExit] = useState(null);
+ // A save (or a discard) settles the draft — any armed confirm is now moot.
+ useEffect(() => { if (!isDirty) setPendingExit(null); }, [isDirty]);
+ // Store the exit as a value, not as a state updater (setState(fn) would CALL it).
+ const requestExit = useCallback((run) => {
+ 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.
+ const onLeaveLink = useCallback((e) => {
+ if (!isDirty) return;
+ e.preventDefault();
+ setPendingExit(() => () => navigate('/songbook'));
+ }, [isDirty, navigate]);
+ const discardAndExit = useCallback(() => {
+ setDraft(song ? toDraft(song) : null);
+ setPendingExit(null);
+ pendingExit?.();
+ }, [pendingExit, song]);
+ // Tab close / reload — the browser owns this prompt; preventDefault arms it.
+ useEffect(() => {
+ if (!isDirty) return undefined;
+ const onBeforeUnload = (e) => { e.preventDefault(); };
+ window.addEventListener('beforeunload', onBeforeUnload);
+ return () => window.removeEventListener('beforeunload', onBeforeUnload);
+ }, [isDirty]);
+
const onDeleteSong = useCallback(() => confirmDelete(() =>
deleteSong(id, { silent: true })
.then(() => navigate('/songbook'))
@@ -420,7 +469,7 @@ export default function SongBookViewer() {
subtitle={song.artist || undefined}
actions={(
<>
- <Link to="/songbook" className={btnClass}>
+ <Link to="/songbook" onClick={onLeaveLink} className={btnClass}>
<ArrowLeft size={15} />
<span className="hidden sm:inline">All songs</span>
</Link>
@@ -437,7 +486,7 @@ export default function SongBookViewer() {
</button>
<button
type="button"
- onClick={() => setMode('play')}
+ onClick={() => requestExit(() => setMode('play'))}
className={btnClass}
>
<Eye size={15} />
@@ -479,6 +528,23 @@ export default function SongBookViewer() {
)}
/>
+ {/* Unsaved-edit guard — a full-width band under the header, so the
+ deferred exit is confirmed where the user just clicked. */}
+ {pendingExit && (
+ <InlineConfirmRow
+ className="shrink-0"
+ variant="separator"
+ tone="warning"
+ question="Discard your unsaved changes to this song?"
+ confirmText="Discard"
+ cancelText="Keep editing"
+ onConfirm={discardAndExit}
+ onCancel={() => setPendingExit(null)}
+ autoFocus
+ aria-label={`Discard unsaved changes to ${song.title}`}
+ />
+ )}
+
{editing ? (
/* ============================== EDIT MODE ============================== */
<div className="flex-1 overflow-y-auto p-4">
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index efdf77bbd3..692a01ed37 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -567,4 +567,69 @@ K: o - - - - - o -`;
// attachments is server-managed — never sent.
expect('attachments' in patch).toBe(false);
});
+
+ describe('unsaved-edit guard (#3902)', () => {
+ const editSheet = async (value = 'Edited sheet text') => {
+ const textarea = await screen.findByLabelText('Content');
+ fireEvent.change(textarea, { target: { value } });
+ return textarea;
+ };
+
+ it('switches straight to play mode when the draft is clean', async () => {
+ renderPage('/songbook/abc?mode=edit');
+ fireEvent.click(await screen.findByRole('button', { name: 'View' }));
+ expect(await screen.findByText('Nonsense words here')).toBeTruthy();
+ expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();
+ });
+
+ it('confirms before the View toggle discards unsaved edits', async () => {
+ renderPage('/songbook/abc?mode=edit');
+ await editSheet();
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ // Still in edit mode, with the discard confirm armed.
+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();
+ expect(screen.getByLabelText('Content')).toBeTruthy();
+
+ // Keep editing → stay put, draft intact.
+ fireEvent.click(screen.getByRole('button', { name: 'Keep editing' }));
+ expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();
+ expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');
+
+ // Discard → the exit runs and the draft resets to the saved song.
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'Discard' }));
+ expect(await screen.findByText('Nonsense words here')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }));
+ expect((await screen.findByLabelText('Content')).value).toBe(SHEET);
+ expect(api.updateSong).not.toHaveBeenCalled();
+ });
+
+ it('confirms before the All songs link leaves with unsaved edits', async () => {
+ renderPage('/songbook/abc?mode=edit');
+ await editSheet();
+ fireEvent.click(screen.getByRole('link', { name: /All songs/ }));
+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();
+ // The navigation was swallowed — the editor is still mounted.
+ expect(screen.getByLabelText('Content').value).toBe('Edited sheet text');
+ });
+
+ it('treats a retyped capo value as clean (number input round-trip)', async () => {
+ renderPage('/songbook/abc?mode=edit');
+ const capo = await screen.findByLabelText('Capo');
+ fireEvent.change(capo, { target: { value: '3' } });
+ fireEvent.change(capo, { target: { value: '2' } });
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ expect(await screen.findByText('Nonsense words here')).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');
+ await editSheet();
+ fireEvent.click(screen.getByRole('button', { name: 'View' }));
+ expect(await screen.findByText('Discard your unsaved changes to this song?')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull());
+ });
+ });
});