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: share SongBook save normalization with unsaved edit guards
[._.]/ Adam Eivy0220bca97bfa
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex adb8973b26..c21d11a5a7 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -210,6 +210,7 @@ grep -i "what you want to do" client/src/lib/README.md| `singToScore.js` | Sing-to-score transcription for the song system — turns a sung pitch track into lead-sheet notation. `segmentPitchTrack(track, opts)` groups `[{ tMs, hz, clarity }]` frames into note/rest segments (median pitch per stable span, rests where clarity drops, sub-threshold note/rest filtering); `quantizeSegments(segments, { bpm, beatValue })` snaps each duration to the nearest grid value (w/h/q/e/s) at the song tempo; `segmentsToScoreDsl(quantized, { keySig, beatsPerBar, beatValue })` spells notes enharmonically from the key signature and emits measure-grouped `\| … \|` body text; `transcribePitchTrack(track, { bpm, key, beatsPerBar, beatValue })` runs all three. Round-trips cleanly back through `parseScore`. Reuses `frequencyToNote` (pitchDetect) + the duration/key tables (scoreNotation) — no DSP/notation library. || `singToVerify.js` | Pure strict-1:1 score verification: `alignSingToVerify(score, track, { bpm, startBar, captureEndMs })` aligns clear sung-pitch frames to `buildColorMatchTimeline` windows, preserves detected octave and key-aware spelling, and returns written→sung rows with raw cents, grade, source note, and explicit acceptance state. Reached silent windows are `missed`; notes after Stop remain `pending`. || `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. |+| `songBookDraft.js` | SongBook editor save/dirty boundary: `buildSongBookPatch(draft, savedDraft)` preserves unchanged-link omission; `songBookDraftsEqual(a, b)` compares the same serialized values. Exports `SCROLL_DURATION_MIN/MAX` for the form. Page owns defaults and lifecycle; add save normalization here so the navigation guard follows. || `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `songProgress.js` | Pure training-progress core for the song system's memorize/learn/track mode. `deriveTrainingSections(score, lyricSections?)` slices a lead-sheet score into blank-line-separated trainable sections (each a self-contained header+block score, positional stable id, lyric-matched label); `recordAttempt(progress, scope, summary)` appends a graded take to a scope's bounded rolling history (drops zero-note takes); `scopeStats(progress, scope)`/`wholeSongStats` derive `{ attempts, best, average, last, streak, learned }` (learned = streak of ≥`LEARNED_PERCENT` takes ≥`LEARNED_STREAK`); `weakestSections(progress, sections)` ranks weak/un-attempted sections for spaced-repetition; `memorizationPercent` is the learned-section share; `hideLevelFor(average)` maps a rolling average to a progressive lyric/note-hiding level (`show`/`dim`/`hide`/`blind`). No React/audio — `useSongTraining` drives it. || `powersBreakdown.js` | Pure, DOM-free Powers mental-math lessons — maps supported base/exponent pairs to named techniques and deterministic worked steps for drill misses and historical review. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 2c8490a527..de31576171 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -208,3 +208,4 @@ export * from './qrCode.js';export * from './riggingReasons.js';export * from './usdzExport.js';export * from './eidoverseFrame.js';+export * from './songBookDraft.js';diff --git a/client/src/lib/songBookDraft.js b/client/src/lib/songBookDraft.jsnew file mode 100644index 0000000000..71b9ec2d25--- /dev/null+++ b/client/src/lib/songBookDraft.js@@ -0,0 +1,59 @@+// SongBook editor serialization. Save and the unsaved-changes guard share this+// boundary so a field has exactly one definition of its persisted value.+// Pure: the page owns record-to-form defaults, requests, and navigation.++// "Fit to duration" target bounds — client mirror of `scrollDurationSec` in+// server/lib/brainValidation.js (songInputSchema). Keep the two in step: a value+// the input accepts but the schema rejects 400s the whole save.+export const SCROLL_DURATION_MIN = 15;+export const SCROLL_DURATION_MAX = 3600;++// Scroll-duration input (a string, like every number input) → what a save sends:+// null for "no target" (blank, or anything non-numeric), otherwise a whole+// second count inside the schema bounds. null is a real value here — it CLEARS a+// stored target on PATCH — so it must never collapse into "field absent".+const parseScrollDurationSec = (raw) => {+ if (raw === '' || raw === null || raw === undefined) return null;+ const n = Number(raw);+ if (!Number.isFinite(n)) return null;+ return Math.max(SCROLL_DURATION_MIN, Math.min(SCROLL_DURATION_MAX, Math.trunc(n)));+};++const serializeDraft = (draft) => ({+ title: draft.title.trim(),+ artist: draft.artist.trim(),+ instrument: draft.instrument,+ stage: draft.stage,+ key: draft.key.trim(),+ capo: Math.max(0, Math.min(12, Math.trunc(Number(draft.capo) || 0))),+ tuning: draft.tuning.trim(),+ tags: draft.tags.split(',').map((tag) => tag.trim()).filter(Boolean),+ sourceUrl: draft.sourceUrl.trim(),+ links: draft.links,+ notes: draft.notes,+ // null explicitly clears a stored target; omission would preserve it.+ scrollDurationSec: parseScrollDurationSec(draft.scrollDurationSec),+ // Preserve the editor contract: format and text are saved together.+ content: { format: draft.format, text: draft.text },+});++// Compare known link fields by value, independently of object key order from+// sync peers. Tuples avoid collisions with delimiters inside free-text labels.+const comparableLinks = (links) => (links || []).map((link) => [link.type, link.id, link.label || '']);+const comparableDraft = (draft) => {+ const fields = serializeDraft(draft);+ return JSON.stringify({ ...fields, links: comparableLinks(fields.links) });+};++export const songBookDraftsEqual = (a, b) => comparableDraft(a) === comparableDraft(b);++export const buildSongBookPatch = (draft, savedDraft) => {+ const patch = serializeDraft(draft);+ // Untouched links must bypass this client's validation bounds: a newer peer+ // may have stored more links or longer labels. Changed lists are sent whole,+ // including [] to clear the last link, preserving the existing PATCH contract.+ if (JSON.stringify(comparableLinks(draft.links)) === JSON.stringify(comparableLinks(savedDraft.links))) {+ delete patch.links;+ }+ return patch;+};diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex ed592562cf..ba7499450a 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -90,6 +90,7 @@ import useDrumPlayer from '../hooks/useDrumPlayer';import useChordPlayer from '../hooks/useChordPlayer';import useWakeLock from '../hooks/useWakeLock';import useUnsavedChangesGuard from '../hooks/useUnsavedChangesGuard';+import { buildSongBookPatch, songBookDraftsEqual, SCROLL_DURATION_MIN, SCROLL_DURATION_MAX } from '../lib/songBookDraft.js';import { transposeText } from '../lib/tabNotation.js';import { VOICING_INSTRUMENTS, toVoicingInstrument } from '../lib/chordShapes.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';@@ -109,23 +110,6 @@ const FONT_MAX = 1.75;const FONT_STEP = 0.125;const SPEED_MIN = 5;const SPEED_MAX = 150;-// "Fit to duration" target bounds — client mirror of `scrollDurationSec` in-// server/lib/brainValidation.js (songInputSchema). Keep the two in step: a value-// the input accepts but the schema rejects 400s the whole save.-const SCROLL_DURATION_MIN = 15;-const SCROLL_DURATION_MAX = 3600;--// Scroll-duration input (a string, like every number input) → what a save sends:-// null for "no target" (blank, or anything non-numeric), otherwise a whole-// second count inside the schema bounds. null is a real value here — it CLEARS a-// stored target on PATCH — so it must never collapse into "field absent".-const parseScrollDurationSec = (raw) => {- if (raw === '' || raw === null || raw === undefined) return null;- const n = Number(raw);- if (!Number.isFinite(n)) return null;- return Math.max(SCROLL_DURATION_MIN, Math.min(SCROLL_DURATION_MAX, Math.trunc(n)));-};-// Song record → flat editable draft (tags joined for the text input).const toDraft = (song) => ({title: song.title || '',@@ -149,44 +133,6 @@ const toDraft = (song) => ({text: song.content?.text || '',});-const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);--// Draft-vs-saved comparison for the unsaved-changes guard. It compares what a-// SAVE would send, not the raw form text — otherwise edits the save normalizes-// away read as unsaved work and prompt for nothing. Each field is normalized-// exactly as `save` normalizes it: trimmed strings, `parseTags` for the tag-// input ('a,b' and 'a, b,' both save as ['a','b']), and a numeric capo (the-// number input hands back a STRING, and an emptied field clamps to 0).-// `notes`/`text` go to the server verbatim, so they compare verbatim.-const TRIMMED_DRAFT_FIELDS = ['title', 'artist', 'key', 'tuning', 'sourceUrl'];-const normalizeDraftField = (draft, k) => {- if (k === 'capo') return Number(draft.capo || 0);- // The one array field: compare by VALUE, not by reference (`===` on two equal- // arrays is always false, so every open of Edit would read as dirty). Order- // matters (adding a link is an edit), and the label rides along because it is- // stored on the record — swapping it is a real change to save.- //- // Serialized as JSON over per-link ARRAYS, not by joining on a delimiter: a- // label is free text (it comes from another record's title), so any separator- // could appear inside one and let two different link lists collapse to the- // same string — an unsaved edit the guard would never see. Arrays rather than- // the objects themselves because JSON.stringify is key-ORDER sensitive, and a- // record synced from a peer can carry the same keys in a different order.- if (k === 'links') return JSON.stringify((draft.links || []).map((l) => [l.type, l.id, l.label || '']));- // Compare the SAVED value, not the raw text: '210' and '0210' (and '' vs a- // sub-minimum '3', which clamps) both save the same, so retyping one isn't- // unsaved work. Null (no target) compares equal to itself.- if (k === 'scrollDurationSec') return parseScrollDurationSec(draft.scrollDurationSec);- // Joined on a comma — the one character parseTags strips from every tag, so- // two different tag lists can never normalize to the same string.- if (k === 'tags') return parseTags(draft.tags).join(',');- if (TRIMMED_DRAFT_FIELDS.includes(k)) return (draft[k] || '').trim();- return draft[k];-};-const draftsEqual = (a, b) => Object.keys(a).every(- (k) => normalizeDraftField(a, k) === normalizeDraftField(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) }));@@ -462,35 +408,7 @@ export default function SongBookViewer() {const [save, saving] = useAsyncAction(async () => {const title = draft.title.trim();if (!title) { toast.error('Title is required'); return null; }- const capo = Math.max(0, Math.min(12, Math.trunc(Number(draft.capo) || 0)));- // `links` is sent only when the user actually CHANGED it. An untouched array- // would otherwise be re-validated against this version's bounds on every- // save, so a song synced from a NEWER peer (a raised link cap, a longer- // label than this version allows) would 400 the whole save on a field the- // user never touched — the same forward-compat hazard the link-type slug- // guards, applied to the bounds. Omitting the key takes the schema's- // absent-preserves branch instead. When it IS changed the array always goes- // whole, including as an empty one: clearing the last link must clear the- // stored list, and an omitted key would preserve it.- const linksChanged = normalizeDraftField(draft, 'links') !== normalizeDraftField(toDraft(song), 'links');- // Always the WHOLE content object — a partial { text } would reset format.- const updated = await updateSong(id, {- title,- artist: draft.artist.trim(),- instrument: draft.instrument,- stage: draft.stage,- key: draft.key.trim(),- capo,- tuning: draft.tuning.trim(),- tags: parseTags(draft.tags),- sourceUrl: draft.sourceUrl.trim(),- ...(linksChanged ? { links: draft.links } : {}),- notes: draft.notes,- // Always sent, including as an explicit null — clearing the input has to- // clear the stored target, and an omitted key would preserve it instead.- scrollDurationSec: parseScrollDurationSec(draft.scrollDurationSec),- content: { format: draft.format, text: draft.text },- }, { silent: true });+ const updated = await updateSong(id, buildSongBookPatch(draft, toDraft(song)), { silent: true });setSong(updated);setDraft(toDraft(updated));toast.success('Song saved');@@ -503,7 +421,7 @@ export default function SongBookViewer() {// 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 && !songBookDraftsEqual(draft, toDraft(song)),[song, draft],);const [pendingExit, setPendingExit] = useState(null);diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 246c8a2474..9d30a5d371 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -1010,6 +1010,15 @@ K: o - - - - - o -`;expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();});+ it('uses the saved capo normalization when deciding whether View needs confirmation', async () => {+ await renderEditPage();+ fireEvent.change(screen.getByLabelText('Capo'), { target: { value: '2.9' } });+ fireEvent.click(screen.getByRole('button', { name: 'View' }));+ await waitFor(() => expect(screen.queryByLabelText('Content')).toBeNull());+ expect(screen.queryByText(/Discard your unsaved changes/)).toBeNull();+ expect(api.updateSong).not.toHaveBeenCalled();+ });+it('treats tag whitespace and a trailing comma as clean (parseTags round-trip)', async () => {api.getSong.mockResolvedValue(song({ tags: ['campfire', 'fingerstyle'] }));await renderEditPage();