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: harden SongBook cross-links against duplicate and out-of-bounds synced entries

[._.]/ Adam Eivye7b127520b0d
diff --git a/client/src/components/songbook/SongLinks.jsx b/client/src/components/songbook/SongLinks.jsx
index 10a544cb9f..59dd9b590e 100644
--- a/client/src/components/songbook/SongLinks.jsx
+++ b/client/src/components/songbook/SongLinks.jsx
@@ -28,11 +28,18 @@ import {
// label captured when the link was made, else the raw id (never blank).
const linkText = (link, freshTitle) => freshTitle || link.label || link.id;
+// React list key. The POSITION is part of it because nothing dedupes the stored
+// array: brain records sync raw between installs with no receive-side
+// validation, so a record can legitimately arrive holding the same {type,id}
+// twice, and a pure identity key would collide. Removal is likewise by index,
+// so deleting one duplicate doesn't take its twin with it.
+const rowKey = (link, index) => `${songLinkKey(link)}#${index}`;
+
export function SongLinkChips({ links, className = '' }) {
if (!links?.length) return null;
return (
<div className={`flex flex-wrap items-center gap-2 text-xs ${className}`}>
- {links.map((link) => {
+ {links.map((link, i) => {
const href = songLinkHref(link);
const text = linkText(link);
const inner = (
@@ -46,7 +53,7 @@ export function SongLinkChips({ links, className = '' }) {
// from a newer peer) — render it as a plain chip rather than a dead link.
return href ? (
<Link
- key={songLinkKey(link)}
+ key={rowKey(link, i)}
to={href}
className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-port-accent hover:border-port-accent/50"
>
@@ -54,7 +61,7 @@ export function SongLinkChips({ links, className = '' }) {
</Link>
) : (
<span
- key={songLinkKey(link)}
+ key={rowKey(link, i)}
className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-gray-400"
>
{inner}
@@ -104,7 +111,7 @@ export function SongLinksEditor({ links, onChange }) {
const map = new Map();
for (const [kind, records] of Object.entries(recordsByType)) {
for (const r of records || []) {
- if (r?.id && r.title) map.set(`${kind}:${r.id}`, r.title);
+ if (r?.id && r.title) map.set(songLinkKey({ type: kind, id: r.id }), r.title);
}
}
return map;
@@ -117,7 +124,9 @@ export function SongLinksEditor({ links, onChange }) {
setTargetId('');
};
- const remove = (link) => onChange(links.filter((l) => songLinkKey(l) !== songLinkKey(link)));
+ // By INDEX, not by identity — see rowKey: a synced record can hold the same
+ // {type,id} twice, and filtering on identity would delete both at once.
+ const remove = (index) => onChange(links.filter((_, i) => i !== index));
const loading = recordsByType[type] === null;
@@ -127,19 +136,18 @@ export function SongLinksEditor({ links, onChange }) {
{links.length > 0 && (
<ul className="space-y-1 mb-2">
- {links.map((link) => {
- const key = songLinkKey(link);
- const text = linkText(link, freshTitles.get(key));
+ {links.map((link, i) => {
+ const text = linkText(link, freshTitles.get(songLinkKey(link)));
return (
<li
- key={key}
+ key={rowKey(link, i)}
className="flex items-center gap-2 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm"
>
<span className="shrink-0 text-xs text-gray-500">{songLinkTypeLabel(link.type)}</span>
<span className="flex-1 min-w-0 truncate text-gray-200">{text}</span>
<button
type="button"
- onClick={() => remove(link)}
+ onClick={() => remove(i)}
className="p-1 shrink-0 text-gray-500 hover:text-port-error"
aria-label={`Remove link to ${text}`}
>
diff --git a/client/src/components/songbook/SongLinks.test.jsx b/client/src/components/songbook/SongLinks.test.jsx
index b45844806a..f3ca0ebbbe 100644
--- a/client/src/components/songbook/SongLinks.test.jsx
+++ b/client/src/components/songbook/SongLinks.test.jsx
@@ -92,6 +92,22 @@ describe('SongLinksEditor', () => {
expect(links).toHaveLength(1);
});
+ // Nothing dedupes the stored array — brain records sync raw with no
+ // receive-side validation, so a record can arrive holding the same {type,id}
+ // twice. Removing one must not take its twin with it.
+ it('removes only the clicked row when the record holds a duplicate link', async () => {
+ const dupe = [
+ { type: 'round', id: 'r1', label: 'Example Round' },
+ { type: 'round', id: 'r1', label: 'Example Round' },
+ { type: 'track', id: 't1', label: 'Example Track' },
+ ];
+ const onChange = renderEditor(dupe);
+ const buttons = await screen.findAllByRole('button', { name: 'Remove link to Example Round' });
+ expect(buttons).toHaveLength(2);
+ fireEvent.click(buttons[0]);
+ expect(onChange).toHaveBeenCalledWith([dupe[1], dupe[2]]);
+ });
+
it('disables Add until a record is picked', async () => {
const onChange = renderEditor([]);
const add = await screen.findByRole('button', { name: 'Add link' });
diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsx
index 3dab273549..8d62c23803 100644
--- a/client/src/pages/SongBookViewer.jsx
+++ b/client/src/pages/SongBookViewer.jsx
@@ -60,7 +60,7 @@ import PracticeLogger from '../components/songbook/PracticeLogger';
import { SongLinkChips, SongLinksEditor } from '../components/songbook/SongLinks';
import {
SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT,
- DRUM_INSTRUMENT, withStoredOption, songLinks, songLinkKey,
+ DRUM_INSTRUMENT, withStoredOption, songLinks,
inputClass, labelClass, btnClass, instrumentLabel,
} from '../components/songbook/constants';
import { useAsyncAction } from '../hooks/useAsyncAction';
@@ -145,7 +145,14 @@ const normalizeDraftField = (draft, k) => {
// 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.
- if (k === 'links') return (draft.links || []).map((l) => `${songLinkKey(l)}|${l.label || ''}`).join('\n');
+ //
+ // 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.
@@ -391,6 +398,16 @@ export default function SongBookViewer() {
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,
@@ -402,9 +419,7 @@ export default function SongBookViewer() {
tuning: draft.tuning.trim(),
tags: parseTags(draft.tags),
sourceUrl: draft.sourceUrl.trim(),
- // Always sent, including as an empty array — removing the last link has to
- // clear the stored list, and an omitted key would preserve it instead.
- links: draft.links,
+ ...(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.
diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsx
index 67f0662b5c..96a4389256 100644
--- a/client/src/pages/SongBookViewer.test.jsx
+++ b/client/src/pages/SongBookViewer.test.jsx
@@ -650,6 +650,56 @@ K: o - - - - - o -`;
expect(api.updateSong.mock.calls[0][1].links).toEqual([]);
});
+ // Re-validating an untouched array on every save would 400 the WHOLE save
+ // for a song synced from a newer peer whose links exceed this version's
+ // bounds — a field the user never touched. Omitting the key takes the
+ // schema's absent-preserves branch instead.
+ it('omits links from the PATCH when the user edited something else', async () => {
+ api.getSong.mockResolvedValue(song({ links: [{ type: 'round', id: 'r1', label: 'Example Round' }] }));
+ api.updateSong.mockImplementation((_id, patch) => Promise.resolve(song({ ...patch })));
+ renderPage('/songbook/abc?mode=edit');
+ const titleInput = await screen.findByLabelText('Title');
+ fireEvent.change(titleInput, { target: { value: 'Renamed Song' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));
+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());
+ const [, patch] = api.updateSong.mock.calls[0];
+ expect(patch.title).toBe('Renamed Song');
+ expect('links' in patch).toBe(false);
+ });
+
+ // A label is free text — it is another record's title, captured at link
+ // time — so a delimiter-joined comparison lets two DIFFERENT link lists
+ // serialize identically and hides a real edit from the unsaved-changes
+ // guard. Reachable: two links stored, the first target later renamed to a
+ // title that happens to contain the separators, then the user replaces the
+ // two links with just that one. Both lists join to the same string.
+ it('sees a link edit that a delimiter-joined comparison would miss', async () => {
+ api.getSong.mockResolvedValue(song({
+ links: [
+ { type: 'round', id: 'r1', label: 'A' },
+ { type: 'round', id: 'r2', label: 'B' },
+ ],
+ }));
+ api.listRounds.mockResolvedValue({
+ rounds: [{ id: 'r1', title: 'A\nround:r2|B' }, { id: 'r2', title: 'B' }],
+ });
+ const { router } = renderPage('/songbook/abc?mode=edit', { history: ['/songbook'] });
+
+ // Drop both links, then re-add the renamed one → a single link whose label
+ // is the two old rows run together.
+ const removals = await screen.findAllByRole('button', { name: /^Remove link to/ });
+ expect(removals).toHaveLength(2);
+ fireEvent.click(removals[1]);
+ fireEvent.click(screen.getAllByRole('button', { name: /^Remove link to/ })[0]);
+ fireEvent.change(screen.getByLabelText('Record to link'), { target: { value: 'r1' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Add link' }));
+
+ await navigate(router, '/songbook');
+ // Blocked: the discard prompt is up and we're still on the song.
+ expect(screen.queryByText('All songs index')).toBeNull();
+ expect(screen.getByText('Discard your unsaved changes to this song?')).toBeTruthy();
+ });
+
it('keeps editing usable when the picker lists fail to load', async () => {
api.listRounds.mockRejectedValue(new Error('boom'));
api.listTracks.mockRejectedValue(new Error('boom'));