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
feat: link SongBook songs to related music records (#4103)
[._.]/ Adam Eivy1dc765ec038b
diff --git a/client/src/components/songbook/SongLinks.jsx b/client/src/components/songbook/SongLinks.jsxnew file mode 100644index 0000000000..d082ba1687--- /dev/null+++ b/client/src/components/songbook/SongLinks.jsx@@ -0,0 +1,191 @@+/**+ * SongBook cross-links to the other music record kinds in PortOS (#4103) —+ * Rounds (`/rounds/:id`) and music Tracks (`/music/tracks/:id`).+ *+ * Two surfaces over the same `links: [{ type, id, label }]` array stored on the+ * song record (schema: `songLinkSchema` in server/lib/brainValidation.js):+ *+ * - <SongLinkChips> — play mode. Read-only chips that navigate to the target.+ * - <SongLinksEditor> — edit mode. Type select + record select + Add, over the+ * draft array; removal is inline per row.+ *+ * `label` is denormalized at link time on purpose: Rounds and Tracks are NOT+ * brain records and do not necessarily exist on every federated machine, so a+ * link whose target is missing here still renders a name rather than a bare id.+ * The editor prefers the FRESH title when the target is present locally (a+ * renamed round shouldn't read stale), and falls back to the stored label.+ */++import { useState, useEffect, useMemo } from 'react';+import { Link } from 'react-router';+import { Link2, Plus, X } from 'lucide-react';+import { listRounds, listTracks } from '../../services/api';+import {+ SONG_LINK_TYPES, songLinkHref, songLinkKey, songLinkTypeLabel, inputClass, labelClass,+} from './constants';++// What a chip/row shows: the target's current title when we can see it, else the+// label captured when the link was made, else the raw id (never blank).+const linkText = (link, freshTitle) => freshTitle || link.label || link.id;++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) => {+ const href = songLinkHref(link);+ const text = linkText(link);+ const inner = (+ <>+ <Link2 size={12} className="shrink-0" />+ <span className="text-gray-500">{songLinkTypeLabel(link.type)}</span>+ <span className="truncate max-w-[14rem]">{text}</span>+ </>+ );+ // An unknown link type has no route to send the user to (a song synced+ // from a newer peer) — render it as a plain chip rather than a dead link.+ return href ? (+ <Link+ key={songLinkKey(link)}+ 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"+ >+ {inner}+ </Link>+ ) : (+ <span+ key={songLinkKey(link)}+ className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-gray-400"+ >+ {inner}+ </span>+ );+ })}+ </div>+ );+}++export function SongLinksEditor({ links, onChange }) {+ // null = not fetched yet (or the fetch failed) vs [] = fetched and this+ // install genuinely has no records of that kind — the two must not collapse,+ // or an empty install reads as "still loading" forever.+ const [rounds, setRounds] = useState(null);+ const [tracks, setTracks] = useState(null);+ const [type, setType] = useState(SONG_LINK_TYPES[0].id);+ const [targetId, setTargetId] = useState('');++ // Both lists load once when the editor mounts. `.catch` swallows the failure+ // on purpose — a rounds/tracks outage must not block editing the SONG, and+ // request() already toasted, so `{ silent: true }` keeps it to one toast.+ useEffect(() => {+ let alive = true;+ listRounds({ silent: true })+ .then((res) => { if (alive) setRounds(Array.isArray(res?.rounds) ? res.rounds : []); })+ .catch(() => { if (alive) setRounds([]); });+ listTracks({ silent: true })+ .then((res) => { if (alive) setTracks(Array.isArray(res) ? res : []); })+ .catch(() => { if (alive) setTracks([]); });+ return () => { alive = false; };+ }, []);++ const recordsByType = useMemo(() => ({ round: rounds, track: tracks }), [rounds, tracks]);++ // Options for the currently selected type, minus anything already linked.+ const linked = useMemo(() => new Set(links.map(songLinkKey)), [links]);+ const options = useMemo(() => (+ (recordsByType[type] || [])+ .filter((r) => r?.id && !linked.has(`${type}:${r.id}`))+ .map((r) => ({ id: r.id, title: r.title || r.id }))+ ), [recordsByType, type, linked]);++ // Titles for rows whose target IS present locally, so a renamed record shows+ // its current name instead of the label frozen at link time.+ const freshTitles = useMemo(() => {+ 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);+ }+ }+ return map;+ }, [recordsByType]);++ const add = () => {+ if (!targetId) return;+ const label = options.find((o) => o.id === targetId)?.title || '';+ onChange([...links, { type, id: targetId, label }]);+ setTargetId('');+ };++ const remove = (link) => onChange(links.filter((l) => songLinkKey(l) !== songLinkKey(link)));++ const loading = recordsByType[type] === null;++ return (+ <div>+ <span className={labelClass}>Linked records</span>++ {links.length > 0 && (+ <ul className="space-y-1 mb-2">+ {links.map((link) => (+ <li+ key={songLinkKey(link)}+ 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">+ {linkText(link, freshTitles.get(songLinkKey(link)))}+ </span>+ <button+ type="button"+ onClick={() => remove(link)}+ className="p-1 shrink-0 text-gray-500 hover:text-port-error"+ aria-label={`Remove link to ${linkText(link, freshTitles.get(songLinkKey(link)))}`}+ >+ <X size={14} />+ </button>+ </li>+ ))}+ </ul>+ )}++ <div className="flex flex-col sm:flex-row gap-2">+ <div className="sm:w-32">+ <label htmlFor="song-link-type" className="sr-only">Link type</label>+ <select+ id="song-link-type"+ value={type}+ onChange={(e) => { setType(e.target.value); setTargetId(''); }}+ className={inputClass}+ >+ {SONG_LINK_TYPES.map((t) => <option key={t.id} value={t.id}>{t.label}</option>)}+ </select>+ </div>+ <div className="flex-1 min-w-0">+ <label htmlFor="song-link-target" className="sr-only">Record to link</label>+ <select+ id="song-link-target"+ value={targetId}+ onChange={(e) => setTargetId(e.target.value)}+ disabled={loading || options.length === 0}+ className={inputClass}+ >+ <option value="">+ {loading ? 'Loading…' : options.length === 0 ? `No ${songLinkTypeLabel(type).toLowerCase()}s available` : 'Select…'}+ </option>+ {options.map((o) => <option key={o.id} value={o.id}>{o.title}</option>)}+ </select>+ </div>+ <button+ type="button"+ onClick={add}+ disabled={!targetId}+ className="flex items-center justify-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Plus size={14} />+ Add link+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsindex 0769d8a974..66fb15e9a7 100644--- a/client/src/components/songbook/constants.js+++ b/client/src/components/songbook/constants.js@@ -75,6 +75,43 @@ export const instrumentLabel = (id) => INSTRUMENTS.find((i) => i.id === id)?.labexport const SONG_FORMATS = ['chordpro', 'tab', 'plain', 'drum'];+// =============================================================================+// CROSS-LINKS to other music records (#4103)+// =============================================================================++// The record kinds a song can link to. Mirrors `songLinkTypeEnum` in+// server/lib/brainValidation.js; `path` is the detail route the chip navigates+// to (`${path}/${id}`), and `listAll` names the api.js helper the edit-mode+// picker loads its options from. Parity with the server enum is asserted in+// constants.test.js.+export const SONG_LINK_TYPES = [+ { id: 'round', label: 'Round', path: '/rounds', listAll: 'listRounds' },+ { id: 'track', label: 'Track', path: '/music/tracks', listAll: 'listTracks' },+];++// Display label for a stored link type. A type this client doesn't know (a song+// synced from a newer peer — the server accepts any short slug) renders as-is+// rather than vanishing.+export const songLinkTypeLabel = (type) => (+ SONG_LINK_TYPES.find((t) => t.id === type)?.label || type+);++// In-app route for a link, or null when the type is unknown to this client —+// there is no route to send the user to, so the caller renders a plain (unlinked)+// chip instead of a dead <Link>.+export const songLinkHref = (link) => {+ const path = SONG_LINK_TYPES.find((t) => t.id === link?.type)?.path;+ return path && link?.id ? `${path}/${encodeURIComponent(link.id)}` : null;+};++// A link's identity for dedupe/removal — type+id, since the same id could in+// principle exist under two record kinds.+export const songLinkKey = (link) => `${link?.type}:${link?.id}`;++// The song's links as an array. Absent (a song predating the field, or one+// synced from an older peer) reads the same as none — but never as a crash.+export const songLinks = (song) => (Array.isArray(song?.links) ? song.links : []);+// The content format whose renderer is <DrumSheetView> (kit grid) rather than// <TabSheetView>. Named so the viewer/import branches read intent, not a string.export const DRUM_FORMAT = 'drum';diff --git a/client/src/components/songbook/constants.test.js b/client/src/components/songbook/constants.test.jsindex bcebb33a48..2a8c5032da 100644--- a/client/src/components/songbook/constants.test.js+++ b/client/src/components/songbook/constants.test.js@@ -3,6 +3,7 @@ import {INSTRUMENTS, SONG_FORMATS, DRUM_FORMAT, DRUM_INSTRUMENT, SONG_STAGES,SONG_PRACTICE_RATINGS, instrumentLabel, withStoredOption,isSongDue, songNextReviewAt, songPracticeSessions,+ SONG_LINK_TYPES, songLinkTypeLabel, songLinkHref, songLinkKey, songLinks,} from './constants.js';describe('SongBook constants', () => {@@ -115,3 +116,37 @@ describe('withStoredOption', () => {}});});++describe('cross-links to other music records (#4103)', () => {+ it('mirrors the server songLinkTypeEnum (server/lib/brainValidation.js)', () => {+ expect(SONG_LINK_TYPES.map((t) => t.id)).toEqual(['round', 'track']);+ });++ it('builds the in-app detail route for each known type', () => {+ expect(songLinkHref({ type: 'round', id: 'r1' })).toBe('/rounds/r1');+ expect(songLinkHref({ type: 'track', id: 't1' })).toBe('/music/tracks/t1');+ expect(songLinkHref({ type: 'round', id: 'a/b' })).toBe('/rounds/a%2Fb');+ });++ // A song synced from a NEWER peer can carry a link type this client has no+ // route for. It must degrade to "no href" (the caller renders a plain chip)+ // rather than fabricating a dead route — and still show a readable label.+ it('degrades an unknown or incomplete link to no href, keeping the raw type as its label', () => {+ expect(songLinkHref({ type: 'stem-pack', id: 'x1' })).toBe(null);+ expect(songLinkHref({ type: 'round' })).toBe(null);+ expect(songLinkHref(null)).toBe(null);+ expect(songLinkTypeLabel('stem-pack')).toBe('stem-pack');+ expect(songLinkTypeLabel('round')).toBe('Round');+ });++ it('keys a link on type+id so the same id under two kinds stays distinct', () => {+ expect(songLinkKey({ type: 'round', id: 'x' })).not.toBe(songLinkKey({ type: 'track', id: 'x' }));+ });++ it('reads an absent links field as none, never as a crash', () => {+ expect(songLinks(undefined)).toEqual([]);+ expect(songLinks({})).toEqual([]);+ expect(songLinks({ links: 'nope' })).toEqual([]);+ expect(songLinks({ links: [{ type: 'round', id: 'r1' }] })).toEqual([{ type: 'round', id: 'r1' }]);+ });+});diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 98c87e2dd1..3dab273549 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -18,7 +18,8 @@* persisted per song via safeStorage), font size ±, an instrument-view* toggle (?view=guitar|ukulele|piano — chord diagrams only, render-only,* defaults to the song's instrument), stage select, capo/key/tuning badges,- * source link — plus the attachments section (synced meta, machine-local+ * source link, cross-link chips to the related Round / music Track (#4103) —+ * plus the attachments section (synced meta, machine-local* bytes → "not on this machine" when absent).* - EDIT (?mode=edit): metadata form + font-mono content textarea with format* select and live preview. Saves are explicit (single PATCH). The whole@@ -56,9 +57,10 @@ import DrumSheetView from '../components/songbook/DrumSheetView';import DrumPreview from '../components/songbook/DrumPreview';import DrumTransportBar from '../components/songbook/DrumTransportBar';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,+ DRUM_INSTRUMENT, withStoredOption, songLinks, songLinkKey,inputClass, labelClass, btnClass, instrumentLabel,} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';@@ -115,6 +117,10 @@ const toDraft = (song) => ({tuning: song.tuning || '',tags: Array.isArray(song.tags) ? song.tags.join(', ') : '',sourceUrl: song.sourceUrl || '',+ // Cross-links to Rounds / music Tracks (#4103). Copied, not aliased — the+ // editor replaces the array wholesale, so the draft must never share identity+ // with the stored record or the dirty check compares a value against itself.+ links: songLinks(song).map((l) => ({ ...l })),notes: song.notes || '',// '' is the form's "no target" — the record stores null (or has no key at all// on a song written before the field existed / synced from an older peer).@@ -135,6 +141,11 @@ const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);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.+ if (k === 'links') return (draft.links || []).map((l) => `${songLinkKey(l)}|${l.label || ''}`).join('\n');// 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 +402,9 @@ 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,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.@@ -692,6 +706,14 @@ export default function SongBookViewer() {<label htmlFor="song-edit-source" className={labelClass}>Source URL</label><input id="song-edit-source" type="text" value={draft.sourceUrl} onChange={(e) => setDraft({ ...draft, sourceUrl: e.target.value })} placeholder="https://…" className={inputClass} /></div>+ <div className="sm:col-span-2">+ {/* Cross-links to Rounds / music Tracks (#4103) — edits the draft+ array; the save sends it whole (empty = clear). */}+ <SongLinksEditor+ links={draft.links}+ onChange={(links) => setDraft({ ...draft, links })}+ />+ </div><div className="sm:col-span-2"><label htmlFor="song-edit-notes" className={labelClass}>Notes</label><AutoSizeTextarea@@ -907,6 +929,11 @@ export default function SongBookViewer() {</div><div ref={scrollRef} className="flex-1 overflow-y-auto px-3 py-3 sm:px-4 sm:py-4">+ {/* Cross-links to the Round / music Track this song relates to+ (#4103). Above the sheet so they're reachable without scrolling;+ inside the scroller so they don't crowd the controls bar. */}+ <SongLinkChips links={songLinks(song)} className="mb-3 max-w-4xl" />+{song.content?.text && isDrum ? (// Full width, not max-w-4xl: the kit strip IS the horizontal// scroller, so capping it just shortens the window you readdiff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex 0b4616a365..67f0662b5c 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -12,6 +12,9 @@ const api = vi.hoisted(() => ({deleteSongAttachment: vi.fn(),practiceSong: vi.fn(),songAttachmentUrl: (id, filename) => `/api/brain/songbook/${id}/attachments/${filename}`,+ // Cross-link picker options (#4103) — the editor loads both lists on mount.+ listRounds: vi.fn(),+ listTracks: vi.fn(),}));vi.mock('../services/api', () => api);vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));@@ -66,6 +69,8 @@ describe('SongBookViewer', () => {api.updateSong.mockReset();api.deleteSong.mockReset();api.practiceSong.mockReset();+ api.listRounds.mockReset().mockResolvedValue({ rounds: [{ id: 'r1', title: 'Example Round' }] });+ api.listTracks.mockReset().mockResolvedValue([{ id: 't1', title: 'Example Track' }]);globalThis.localStorage?.clear?.();});@@ -595,6 +600,76 @@ K: o - - - - - o -`;expect('attachments' in patch).toBe(false);});+ // Cross-links to the other music record kinds — Rounds and music Tracks.+ describe('cross-links to Rounds / Tracks (#4103)', () => {+ it('renders stored links as chips pointing at the target routes in play mode', async () => {+ api.getSong.mockResolvedValue(song({+ links: [+ { type: 'round', id: 'r1', label: 'Example Round' },+ { type: 'track', id: 't1', label: 'Example Track' },+ ],+ }));+ renderPage();+ const round = await screen.findByRole('link', { name: /Example Round/ });+ expect(round.getAttribute('href')).toBe('/rounds/r1');+ expect(screen.getByRole('link', { name: /Example Track/ }).getAttribute('href')).toBe('/music/tracks/t1');+ });++ // A song synced from a NEWER peer can carry a link type this client has no+ // route for — it must still render its name, not a dead link.+ it('renders an unknown link type as a plain chip, not a link', async () => {+ api.getSong.mockResolvedValue(song({ links: [{ type: 'stem-pack', id: 'x1', label: 'Future Record' }] }));+ renderPage();+ expect(await screen.findByText('Future Record')).toBeTruthy();+ expect(screen.queryByRole('link', { name: /Future Record/ })).toBeNull();+ });++ it('adds a link from the picker and sends it on save with the target title', async () => {+ api.updateSong.mockImplementation((_id, patch) => Promise.resolve(song({ ...patch })));+ renderPage('/songbook/abc?mode=edit');+ const target = await screen.findByLabelText('Record to link');+ await waitFor(() => expect(within(target).getAllByRole('option').length).toBe(2));+ fireEvent.change(target, { target: { value: 'r1' } });+ fireEvent.click(screen.getByRole('button', { name: 'Add link' }));++ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());+ const [, patch] = api.updateSong.mock.calls[0];+ expect(patch.links).toEqual([{ type: 'round', id: 'r1', label: 'Example Round' }]);+ });++ // Absent vs. intentionally-empty: removing the last link must SEND [] so the+ // stored list is cleared, not omit the key (which would preserve it).+ it('sends an explicit empty array when the last link is removed', 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');+ fireEvent.click(await screen.findByRole('button', { name: 'Remove link to Example Round' }));+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());+ expect(api.updateSong.mock.calls[0][1].links).toEqual([]);+ });++ it('keeps editing usable when the picker lists fail to load', async () => {+ api.listRounds.mockRejectedValue(new Error('boom'));+ api.listTracks.mockRejectedValue(new Error('boom'));+ renderPage('/songbook/abc?mode=edit');+ const target = await screen.findByLabelText('Record to link');+ await waitFor(() => expect(target.disabled).toBe(true));+ expect(screen.getByLabelText('Title').value).toBe('Example Song');+ });++ // Opening Edit must not read as dirty just because `links` is an array —+ // a by-reference compare would flag every open (#3902 guard).+ it('does not treat an untouched links array as an unsaved edit', async () => {+ api.getSong.mockResolvedValue(song({ links: [{ type: 'round', id: 'r1', label: 'Example Round' }] }));+ const { router } = renderPage('/songbook/abc?mode=edit', { history: ['/songbook'] });+ await screen.findByLabelText('Title');+ await navigate(router, '/songbook');+ expect(await screen.findByText('All songs index')).toBeTruthy();+ });+ });+describe('fit-to-duration autoscroll preset (#4100)', () => {// jsdom lays nothing out, so the scroll container reports 0/0 — stub the two// metrics the preset measures. 2000 tall in a 500 viewport = 1500px of travel.diff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.mdindex ecd45fd429..e4a062d674 100644--- a/docs/plans/2026-07-15-songbook.md+++ b/docs/plans/2026-07-15-songbook.md@@ -214,7 +214,17 @@ invent fixture tabs (e.g. "Example Song" by "The Placeholders").schema key, like `attachments`) and derived on READ for songs predating thefeature — no backfill migration, so the `data.reference/` seeds staybyte-identical across installs.-- Linking a song to existing Rounds/Tracks/MIDI records (cross-links field).+- ~~Linking a song to existing Rounds/Tracks/MIDI records (cross-links field).~~+ **Shipped in #4103** — songs carry `links: [{ type, id, label }]`+ (`songLinkSchema` in `brainValidation.js`, ≤20 entries). `type` is+ `round | track`, accepted as enum-OR-short-slug like `instrument`/`format` so+ a link kind from a newer peer stays editable. There is deliberately no `midi`+ type: MIDI is a *file* (already a songbook attachment) or+ `referenceAudio.midiFilename` on a Round, which the `round` link reaches.+ `label` is the target's title denormalized at link time, because Rounds and+ Tracks are not brain records and may be absent on a given machine. No+ `PORTOS_SCHEMA_VERSIONS` bump — `brain` has no entry (records sync raw, no+ receive-side re-sanitize), so no peer can strip the field and LWW the loss back.- Chord diagrams / fretboard rendering; MIDI/score preview embedding in the viewer.- Voice/palette actions (nav entry alone gives ⌘K + voice nav).- Brain memory-bridge/graph enrollment for songs.diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 43415dc0f7..999e42bcf4 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -626,6 +626,31 @@ const songForwardCompatSlug = z.string().trim().regex(/^[a-z0-9][a-z0-9_-]{0,31}const songInstrumentValue = z.union([songInstrumentEnum, songForwardCompatSlug]);const songContentFormatValue = z.union([songContentFormatEnum, songForwardCompatSlug]);+// Cross-links from a song to the OTHER music record kinds in PortOS (#4103):+// a Round (`/rounds/:id`) or a generated/imported music Track+// (`/music/tracks/:id`). MIDI is deliberately absent — there is no MIDI record+// in PortOS; MIDI is a file (already a songbook attachment, see+// SONGBOOK_ATTACHMENT_EXTENSIONS) or `referenceAudio.midiFilename` on a Round,+// which the `round` link already reaches.+export const songLinkTypeEnum = z.enum(['round', 'track']);++// Same enum-OR-slug acceptance boundary as instrument/format above, for the+// same reason: brain records sync raw (LWW, no Zod on receive), so a song+// arriving from a NEWER peer can carry a link type this install has never heard+// of. Rejecting it would make that song uneditable — every save 400ing on a+// field the user never touched.+const songLinkTypeValue = z.union([songLinkTypeEnum, songForwardCompatSlug]);++// One cross-link. `label` is the target's title DENORMALIZED at link time:+// Rounds and Tracks are not brain records and do not necessarily exist on every+// federated machine, so a link that resolves to nothing locally still renders a+// name instead of a bare id.+const songLinkSchema = z.object({+ type: songLinkTypeValue,+ id: z.string().trim().min(1).max(200),+ label: z.string().trim().max(300).optional().default(''),+});+// Nested content object — named so the update schema below can rebuild it// defaults-free (partialWithoutDefaults only strips TOP-LEVEL field defaults).const songContentSchema = z.object({@@ -647,6 +672,10 @@ export const songInputSchema = z.object({capo: z.number().int().min(0).max(12).optional().default(0),tuning: z.string().trim().max(40).optional().default(''),sourceUrl: z.string().trim().max(2000).optional().default(''),+ // Cross-links to Rounds / music Tracks (#4103). On a PATCH the top-level+ // default is stripped, so an OMITTED key preserves the stored links while an+ // explicit `[]` clears them (the absent-vs-empty rule).+ links: z.array(songLinkSchema).max(20).optional().default([]),content: songContentSchema.optional().default({ format: 'tab', text: '' }),notes: z.string().max(5000).optional().default(''),// "Fit to duration" autoscroll target: how many seconds the play view shoulddiff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.jsindex 7ea44ac979..6bbda779f6 100644--- a/server/lib/brainValidation.test.js+++ b/server/lib/brainValidation.test.js@@ -888,4 +888,73 @@ describe('brainValidation.js', () => {expect(songUpdateSchema.safeParse({ scrollDurationSec: 7200 }).success).toBe(false);});});++ // Cross-links to the other music record kinds — Rounds and music Tracks (#4103).+ describe('songbook links (#4103)', () => {+ it('accepts links to a round and a track, defaulting the label', () => {+ const result = songInputSchema.safeParse({+ title: 'T',+ links: [+ { type: 'round', id: 'round-1', label: 'Example Round' },+ { type: 'track', id: 'track-1' },+ ],+ });+ expect(result.success).toBe(true);+ expect(result.data.links).toEqual([+ { type: 'round', id: 'round-1', label: 'Example Round' },+ { type: 'track', id: 'track-1', label: '' },+ ]);+ });++ it('defaults to an empty list when the key is absent on create', () => {+ const result = songInputSchema.safeParse({ title: 'T' });+ expect(result.success).toBe(true);+ expect(result.data.links).toEqual([]);+ });++ it('rejects malformed entries and an over-long list', () => {+ const bad = [+ [{ id: 'round-1' }], // no type+ [{ type: 'round' }], // no id+ [{ type: 'round', id: '' }], // empty id+ [{ type: 'Round', id: 'round-1' }], // uppercase — not a valid slug+ [{ type: 'round', id: 'round-1', label: 'x'.repeat(301) }],+ ['round-1'], // not an object+ ];+ for (const links of bad) {+ expect(songInputSchema.safeParse({ title: 'T', links }).success, JSON.stringify(links)).toBe(false);+ }+ const tooMany = Array.from({ length: 21 }, (_, i) => ({ type: 'round', id: `round-${i}` }));+ expect(songInputSchema.safeParse({ title: 'T', links: tooMany }).success).toBe(false);+ });++ // Same forward-compat contract as instrument/content.format: a song synced+ // from a NEWER peer can carry a link type this install doesn't know, and+ // rejecting it would make the song uneditable.+ it('accepts an unknown short-slug link type from a newer peer', () => {+ const result = songInputSchema.safeParse({+ title: 'T',+ links: [{ type: 'stem-pack', id: 'x1' }],+ });+ expect(result.success).toBe(true);+ expect(result.data.links[0].type).toBe('stem-pack');+ // …but not free text.+ expect(songInputSchema.safeParse({+ title: 'T',+ links: [{ type: 'a totally free form value', id: 'x1' }],+ }).success).toBe(false);+ });++ // Absent vs. intentionally-empty: an omitted key preserves the stored links+ // through the PATCH merge, while an explicit [] clears them.+ it('separates "not sent" from an explicit empty list on update', () => {+ const untouched = songUpdateSchema.safeParse({ title: 'T' });+ expect(untouched.success).toBe(true);+ expect('links' in untouched.data).toBe(false);++ const cleared = songUpdateSchema.safeParse({ links: [] });+ expect(cleared.success).toBe(true);+ expect(cleared.data.links).toEqual([]);+ });+ });});diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsindex 9c9aeb07bb..4f9587701a 100644--- a/server/routes/brainSongbook.test.js+++ b/server/routes/brainSongbook.test.js@@ -233,6 +233,35 @@ describe('Brain SongBook routes', () => {.send({ title: 'X' });expect(res.status).toBe(404);});++ // Cross-links (#4103): absent preserves, explicit [] clears.+ it('preserves stored links when the key is absent, and clears them on []', async () => {+ const links = [{ type: 'round', id: 'round-1', label: 'Example Round' }];++ const untouched = mockUpdateWith(baseSong({ links }));+ const kept = await request(app)+ .patch(`/api/brain/songbook/${SONG_ID}`)+ .send({ title: 'New Title' });+ expect(kept.status).toBe(200);+ expect('links' in untouched.updates).toBe(false);+ expect(kept.body.links).toEqual(links);++ const emptied = mockUpdateWith(baseSong({ links }));+ const cleared = await request(app)+ .patch(`/api/brain/songbook/${SONG_ID}`)+ .send({ links: [] });+ expect(cleared.status).toBe(200);+ expect(emptied.updates).toEqual({ links: [] });+ expect(cleared.body.links).toEqual([]);+ });++ it('400s on a malformed link entry', async () => {+ const res = await request(app)+ .patch(`/api/brain/songbook/${SONG_ID}`)+ .send({ links: [{ type: 'round' }] });+ expect(res.status).toBe(400);+ expect(brainStorage.updateWith).not.toHaveBeenCalled();+ });});describe('DELETE /api/brain/songbook/:id', () => {