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

songs: add read/edit view modes, built-in defaults with refresh-from-template, and reference videos

[._.]/ Adam Eivy6b7b81c27ea4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 7d1560e2c1..416ebb9711 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -10,6 +10,7 @@
- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.
- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.
- **Manuscript editor: editorial feedback is now shown in-context, not just in a sidebar** — instead of scrolling a disconnected list of notes, each editorial comment is highlighted directly on the text it points to. A header toggle switches between two modes: **Live** (Grammarly-style — the manuscript stays fully editable and each anchored note shows as a severity-toned underline; click the underlined text or its tag to pop the note's card right there with Generate-fix / Accept / Dismiss) and **Review** (a read-through where the prose is annotated and clicking a highlight expands the note inline, with a per-section Edit toggle to drop into free editing). The right sidebar becomes a filterable index (by severity, with open / accepted / dismissed groups and a "located in text" count) that scrolls to and opens any note. The editor now focuses **one issue at a time** with a deep-linkable tab strip (`…/manuscript/<issueNumber>`, each tab badged with its open-note count) instead of one page-length scroll of every issue. Suggested edits can be reviewed as a **side-by-side before/after diff** (default) or the prior stacked inline diff, and a new **Impact preview** shows, per affected issue, how accepting the selected fixes changes the whole manuscript before you commit to them (a single fix can span multiple issues). Notes whose anchor text no longer matches the draft degrade gracefully — they stay listed in the sidebar with no in-text highlight rather than disappearing.
+- **Songs: a read/perform view, built-in defaults, and reference videos** — the song page now has a **View / Edit** toggle (mode lives in the URL, so each view is linkable). **View** is a clean, desktop-wide performance layout — lyrics rendered in full with no cramped sub-scrolling boxes, sections laid out side-by-side to use the screen and cut vertical scrolling, with the recorder kept front-and-centre for playing/recording; **Edit** is the existing workbench, now wider with a two-column lyric grid. Shipped example songs are tagged **Built-in default** (a badge in the Songs list and a banner in the editor) with a **Refresh from template** button that restores the latest bundled lyrics, arrangement, and references while preserving your own recordings and learned progress — so an install that already has an older copy of a default song can renew it on demand. Songs can also carry **reference material**: paste a link to a performance or tutorial, and TikTok video links play inline as embeds in the View tab (other links render as link cards). The built-in "500 Miles" ships with two TikTok reference performances and its full set of lyrics.
## Changed
diff --git a/client/src/lib/songCraft.js b/client/src/lib/songCraft.js
index 8f5dac00e7..2266c1d2a3 100644
--- a/client/src/lib/songCraft.js
+++ b/client/src/lib/songCraft.js
@@ -70,6 +70,16 @@ export const RHYTHM_SHAPES = [
},
];
+// Human-readable label for a rhythm shape id — `Slow 4/4 ballad · dirge
+// (56–76 BPM)`. Shared by the editor's <select> options and the read-only
+// performance view so the format lives in one place. Empty string for an
+// unknown id.
+export const rhythmShapeLabel = (id) => {
+ const shape = RHYTHM_SHAPES.find((s) => s.id === id);
+ if (!shape) return '';
+ return `${shape.label}${shape.dirge ? ' · dirge' : ''} (${shape.bpm.label})`;
+};
+
// --- Voice layers ----------------------------------------------------------
// The order singers stack parts when arranging a cappella, foundation-first.
// `order` is the recommended build sequence; `voices` names the typical
diff --git a/client/src/pages/SongEditor.jsx b/client/src/pages/SongEditor.jsx
index ed0a3c549c..da5bf77a0f 100644
--- a/client/src/pages/SongEditor.jsx
+++ b/client/src/pages/SongEditor.jsx
@@ -1,31 +1,51 @@
/**
* Song editor — /songs/:id.
*
- * Edit one a cappella song: metadata (title/artist/key/tempo/rhythm shape),
- * lyric sections, the voice layers being stacked, and free-text notation +
- * arrangement notes. Full-width route (Layout.jsx isFullWidth matches
- * `/songs/`) so this page owns its own vertical scroll, mirroring
- * WritersRoomGuide's column layout.
+ * Two URL-param-driven modes (`?mode=read` default, `?mode=edit`):
+ * - READ: a clean, desktop-wide performance view — lyrics rendered in full
+ * (no sub-scrollable textareas), sections laid out in a responsive grid to
+ * use horizontal real-estate and cut vertical scrolling, with the recorder
+ * front-and-centre for playing/recording.
+ * - EDIT: the editing workbench — metadata, lyric sections, voice layers, and
+ * free-text notation + arrangement notes.
+ *
+ * Full-width route (Layout.jsx isFullWidth matches `/songs/`) so this page owns
+ * its own vertical scroll, mirroring WritersRoomGuide's column layout. The mode
+ * lives in the URL (not local state) so a view is linkable — per the project's
+ * "linkable routes for all views" convention.
*
* Saves are explicit (a Save button) rather than per-keystroke — the workbench
- * is a focused editing surface, and a single PUT keeps the merge simple. The
- * "Add layer from ladder" picker seeds a layer pre-filled from songCraft's
+ * is a focused editing surface, and a single PUT keeps the merge simple. Save
+ * stays available in READ mode too, because recording a take mutates the draft.
+ * The "Add layer from ladder" picker seeds a layer pre-filled from songCraft's
* foundation-first VOICE_LAYERS so the user can build harmony in the
* recommended order.
*/
import { useState, useEffect, useCallback, useMemo } from 'react';
-import { useParams, useNavigate, Link } from 'react-router-dom';
+import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';
import {
- Music, ArrowLeft, Plus, Trash2, Save, BookOpen, CheckCircle2, Circle, Layers,
+ Music, ArrowLeft, Plus, Trash2, Save, BookOpen, CheckCircle2, Circle, Layers, Eye, Pencil,
+ Sparkles, RefreshCw, Video, ExternalLink,
} from 'lucide-react';
import toast from '../components/ui/Toast';
import { useAsyncAction } from '../hooks/useAsyncAction';
-import { getSong, updateSong } from '../services/api';
-import { RHYTHM_SHAPES, VOICE_LAYERS } from '../lib/songCraft';
+import { getSong, updateSong, refreshSongTemplate } from '../services/api';
+import { RHYTHM_SHAPES, VOICE_LAYERS, rhythmShapeLabel } from '../lib/songCraft';
+import Pill from '../components/ui/Pill';
import SongAiPanel from '../components/songs/SongAiPanel';
import SongRecordings from '../components/songs/SongRecordings';
+// Extract a TikTok video id from a share/watch URL so we can render TikTok's
+// documented iframe Embed Player (https://www.tiktok.com/player/v1/<id>)
+// instead of loading their embed.js. Returns null for anything that isn't a
+// TikTok video URL — those references render as plain links.
+const tiktokVideoId = (url) => {
+ const m = /tiktok\.com\/(?:@[\w.-]+\/video|v|embed(?:\/v2)?|player\/v1)\/(\d+)/.exec(url || '');
+ return m ? m[1] : null;
+};
+const tiktokEmbedSrc = (id) => `https://www.tiktok.com/player/v1/${id}`;
+
// In-session-only id for a freshly-added section/layer, used purely as a React
// key until the row is saved. Counter-based (not Math.random, which is
// unavailable in some harnesses and unnecessary here) — uniqueness only needs
@@ -63,6 +83,16 @@ const clampTempo = (n) => {
export default function SongEditor() {
const { id } = useParams();
const navigate = useNavigate();
+ const [searchParams, setSearchParams] = useSearchParams();
+ const editing = searchParams.get('mode') === 'edit';
+ const setMode = useCallback((mode) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (mode === 'edit') next.set('mode', 'edit');
+ else next.delete('mode');
+ return next;
+ }, { replace: true });
+ }, [setSearchParams]);
const [song, setSong] = useState(null);
const [loading, setLoading] = useState(true);
@@ -90,6 +120,7 @@ export default function SongEditor() {
sections: (song.sections || []).map(stripTempId),
layers: (song.layers || []).map(stripTempId),
recordings: (song.recordings || []).map(stripTempId),
+ references: (song.references || []).map(stripTempId),
};
const data = await updateSong(id, patch, { silent: true });
if (data?.song) setSong(data.song);
@@ -97,6 +128,17 @@ export default function SongEditor() {
return data?.song;
}, { errorMessage: 'Failed to save song' });
+ // Restore a built-in default to its shipped content (lyrics, layers,
+ // references). Persists server-side immediately and preserves the user's
+ // recordings + learned progress; replaces any local unsaved edits, so the
+ // BuiltInBanner gates this behind an inline confirm.
+ const [refreshTemplate, refreshing] = useAsyncAction(async () => {
+ const data = await refreshSongTemplate(id, { silent: true });
+ if (data?.song) setSong(data.song);
+ toast.success('Refreshed from the bundled template');
+ return data?.song;
+ }, { errorMessage: 'Failed to refresh from template' });
+
// Merge an AI-generated draft into the editor. The server returns canonical
// fields with server-assigned ids; we replace the editable content (metadata,
// sections, layers, notation, notes) but PRESERVE the user's recordings and
@@ -151,6 +193,19 @@ export default function SongEditor() {
...prev, layers: prev.layers.filter((l) => l.id !== lid),
}));
+ // --- Reference helpers --------------------------------------------------
+ const addReference = () => setSong((prev) => ({
+ ...prev,
+ references: [...(prev.references || []), { id: localId('ref'), url: '', label: '', note: '' }],
+ }));
+ const updateReference = (rid, key, value) => setSong((prev) => ({
+ ...prev,
+ references: prev.references.map((r) => (r.id === rid ? { ...r, [key]: value } : r)),
+ }));
+ const removeReference = (rid) => setSong((prev) => ({
+ ...prev, references: prev.references.filter((r) => r.id !== rid),
+ }));
+
// Layer presets the user hasn't added yet, in foundation-first order. Match
// on the preset id: preset layers (seed or ladder-added) carry the bare
// preset id like `lead`, so renaming a layer's label can't make its preset
@@ -190,6 +245,25 @@ export default function SongEditor() {
</button>
<Music size={18} className="text-port-accent shrink-0" />
<span className="text-white font-semibold truncate flex-1 min-w-0">{song.title || 'Untitled song'}</span>
+ {/* View / Edit toggle — mode lives in the URL so each view is linkable. */}
+ <div className="flex items-center rounded-lg border border-port-border overflow-hidden shrink-0">
+ <button
+ type="button"
+ onClick={() => setMode('read')}
+ aria-pressed={!editing}
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs transition-colors ${!editing ? 'bg-port-accent text-white' : 'text-gray-300 hover:text-white hover:bg-port-border/50'}`}
+ >
+ <Eye size={14} /> View
+ </button>
+ <button
+ type="button"
+ onClick={() => setMode('edit')}
+ aria-pressed={editing}
+ className={`flex items-center gap-1.5 px-2.5 py-1.5 text-xs transition-colors border-l border-port-border ${editing ? 'bg-port-accent text-white' : 'text-gray-300 hover:text-white hover:bg-port-border/50'}`}
+ >
+ <Pencil size={14} /> Edit
+ </button>
+ </div>
<Link
to="/songs/guide"
className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"
@@ -210,7 +284,18 @@ export default function SongEditor() {
{/* Scrollable body */}
<div className="flex-1 overflow-y-auto p-4 md:p-6">
- <div className="max-w-3xl mx-auto space-y-6">
+ {!editing && (
+ <ReadView
+ song={song}
+ setField={setField}
+ onRefreshTemplate={refreshTemplate}
+ refreshing={refreshing}
+ />
+ )}
+
+ {editing && (
+ <div className="max-w-5xl mx-auto space-y-6">
+ {song.builtIn && <BuiltInBanner onRefresh={refreshTemplate} refreshing={refreshing} />}
{/* Metadata */}
<section className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
@@ -245,7 +330,7 @@ export default function SongEditor() {
<select id="rhythm" value={song.rhythmShapeId} onChange={(e) => setField('rhythmShapeId', e.target.value)} className={inputCls}>
<option value="">— Choose a feel —</option>
{RHYTHM_SHAPES.map((s) => (
- <option key={s.id} value={s.id}>{s.label}{s.dirge ? ' · dirge' : ''} ({s.bpm.label})</option>
+ <option key={s.id} value={s.id}>{rhythmShapeLabel(s.id)}</option>
))}
</select>
</div>
@@ -271,7 +356,7 @@ export default function SongEditor() {
{(song.sections || []).length === 0 ? (
<p className="text-xs text-gray-500">No sections yet. Add a verse, chorus, or bridge.</p>
) : (
- <div className="space-y-3">
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">
{song.sections.map((s) => (
<div key={s.id} className="bg-port-card border border-port-border rounded-lg p-3">
<div className="flex items-center gap-2 mb-2">
@@ -378,6 +463,63 @@ export default function SongEditor() {
onChange={(recordings) => setField('recordings', recordings)}
/>
+ {/* Reference material — links / videos (TikTok embeds in read view) */}
+ <section>
+ <div className="flex items-center justify-between mb-2">
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">
+ <Video size={15} className="text-port-accent" /> Reference material
+ </h2>
+ <button type="button" onClick={addReference} className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50">
+ <Plus size={14} /> Add reference
+ </button>
+ </div>
+ <p className="text-xs text-gray-500 mb-2">
+ Paste a link to a performance, tutorial, or chart. TikTok video links play inline in the View tab.
+ </p>
+ {(song.references || []).length === 0 ? (
+ <p className="text-xs text-gray-500">No references yet. Add a TikTok or other link to study from.</p>
+ ) : (
+ <div className="space-y-3">
+ {song.references.map((r) => (
+ <div key={r.id} className="bg-port-card border border-port-border rounded-lg p-3 space-y-2">
+ <div className="flex items-center gap-2">
+ <input
+ type="url"
+ value={r.url}
+ onChange={(e) => updateReference(r.id, 'url', e.target.value)}
+ placeholder="https://www.tiktok.com/@user/video/…"
+ aria-label="Reference URL"
+ className="flex-1 min-w-0 bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ <button type="button" onClick={() => removeReference(r.id)} className="p-1.5 text-gray-500 hover:text-port-error shrink-0" aria-label="Remove reference">
+ <Trash2 size={15} />
+ </button>
+ </div>
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
+ <input
+ type="text"
+ value={r.label}
+ onChange={(e) => updateReference(r.id, 'label', e.target.value)}
+ placeholder="Label (e.g. TikTok · @user)"
+ aria-label="Reference label"
+ className="bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ <input
+ type="text"
+ value={r.note}
+ onChange={(e) => updateReference(r.id, 'note', e.target.value)}
+ placeholder="Note (what to listen for…)"
+ aria-label="Reference note"
+ className="bg-port-bg border border-port-border rounded-lg px-3 py-1.5 text-sm text-white focus:border-port-accent focus:outline-none"
+ />
+ </div>
+ {tiktokVideoId(r.url) && <p className="text-xs text-port-success">✓ TikTok video — embeds in View</p>}
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
{/* Notation + notes */}
<section className="grid grid-cols-1 gap-4">
<div>
@@ -404,7 +546,208 @@ export default function SongEditor() {
</div>
</section>
</div>
+ )}
+ </div>
+ </div>
+ );
+}
+
+// --- Read-only performance view -------------------------------------------
+// Renders the song for reading / playing / recording: lyrics shown in full
+// (no sub-scrollable textareas) and laid out in a responsive grid so short
+// sections sit side-by-side and use the available desktop width. The recorder
+// stays interactive (recording mutates the draft; the header Save persists it).
+function ReadView({ song, setField, onRefreshTemplate, refreshing }) {
+ const sections = song.sections || [];
+ const layers = song.layers || [];
+ const references = song.references || [];
+ const hasText = (v) => typeof v === 'string' && v.trim().length > 0;
+ const feel = song.rhythmShapeId ? rhythmShapeLabel(song.rhythmShapeId) : '';
+
+ // Label + value badge, two-toned, built on the shared Pill primitive.
+ const metaBadge = (label, value) => (
+ <Pill tone="muted">
+ <span className="text-gray-500">{label}</span>
+ <span className="text-gray-200">{value}</span>
+ </Pill>
+ );
+
+ return (
+ <div className="max-w-6xl mx-auto space-y-6">
+ {song.builtIn && <BuiltInBanner onRefresh={onRefreshTemplate} refreshing={refreshing} />}
+ {/* Compact meta line — no form fields, just the at-a-glance facts. */}
+ <div className="flex flex-wrap items-center gap-2">
+ {hasText(song.artist) && metaBadge('Artist', song.artist)}
+ {hasText(song.key) && metaBadge('Key', song.key)}
+ {song.tempo != null && metaBadge('Tempo', `${song.tempo} BPM`)}
+ {feel && metaBadge('Feel', feel)}
+ <Pill tone={song.learned ? 'success' : 'muted'} icon={song.learned ? CheckCircle2 : Circle}>
+ {song.learned ? 'Learned' : 'Learning'}
+ </Pill>
+ </div>
+
+ <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
+ {/* Lyrics — the main reading surface, given the most width. */}
+ <section className="lg:col-span-2 space-y-3">
+ <h2 className="text-sm font-semibold text-white">Lyrics</h2>
+ {sections.length === 0 ? (
+ <p className="text-xs text-gray-500">No lyrics yet. Switch to Edit to add a verse or chorus.</p>
+ ) : (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
+ {sections.map((s) => (
+ <div key={s.id} className="bg-port-card border border-port-border rounded-lg p-4">
+ <h3 className="text-xs font-semibold uppercase tracking-wide text-port-accent mb-2">{s.label || 'Section'}</h3>
+ {hasText(s.lyrics)
+ ? <p className="text-sm text-gray-100 whitespace-pre-wrap leading-relaxed">{s.lyrics}</p>
+ : <p className="text-xs text-gray-600 italic">No lyrics</p>}
+ </div>
+ ))}
+ </div>
+ )}
+ </section>
+
+ {/* Side rail — notation, layers, and notes. */}
+ <aside className="space-y-6">
+ {hasText(song.notation) && (
+ <section>
+ <h2 className="text-sm font-semibold text-white mb-2">Notation / chords</h2>
+ <p className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-100 whitespace-pre-wrap leading-relaxed font-mono">{song.notation}</p>
+ </section>
+ )}
+
+ {layers.length > 0 && (
+ <section>
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white mb-2">
+ <Layers size={15} className="text-port-accent" /> Voice layers
+ </h2>
+ <ul className="space-y-2">
+ {layers.map((l) => (
+ <li key={l.id} className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-baseline justify-between gap-2">
+ <span className="text-sm text-white">{l.label || 'Layer'}</span>
+ {hasText(l.part) && <span className="text-xs text-gray-500">{l.part}</span>}
+ </div>
+ {hasText(l.notes) && <p className="mt-1 text-xs text-gray-400 whitespace-pre-wrap leading-relaxed">{l.notes}</p>}
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ {hasText(song.notes) && (
+ <section>
+ <h2 className="text-sm font-semibold text-white mb-2">Arrangement & notes</h2>
+ <p className="bg-port-card border border-port-border rounded-lg p-4 text-sm text-gray-200 whitespace-pre-wrap leading-relaxed">{song.notes}</p>
+ </section>
+ )}
+ </aside>
</div>
+
+ {/* Reference material — TikTok videos embed; other links render as cards. */}
+ {references.length > 0 && (
+ <section>
+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white mb-3">
+ <Video size={15} className="text-port-accent" /> Reference material
+ </h2>
+ <div className="flex flex-wrap gap-4">
+ {references.map((r) => <ReferenceCard key={r.id} reference={r} />)}
+ </div>
+ </section>
+ )}
+
+ {/* Vocal takes — recording/playback stays available in read mode. */}
+ <SongRecordings
+ recordings={song.recordings || []}
+ layers={song.layers || []}
+ onChange={(recordings) => setField('recordings', recordings)}
+ />
+ </div>
+ );
+}
+
+// One reference: a TikTok video renders as the official embed iframe; any other
+// URL renders as a link card (label + note + the raw URL).
+function ReferenceCard({ reference }) {
+ const ttId = tiktokVideoId(reference.url);
+ const title = reference.label || reference.url;
+ if (ttId) {
+ return (
+ <div className="w-full sm:w-[325px] space-y-2">
+ <iframe
+ title={title}
+ src={tiktokEmbedSrc(ttId)}
+ className="w-full h-[575px] rounded-lg border border-port-border bg-port-card"
+ loading="lazy"
+ allow="encrypted-media; fullscreen"
+ referrerPolicy="strict-origin-when-cross-origin"
+ />
+ {(reference.label || reference.note) && (
+ <div className="px-1">
+ {reference.label && <p className="text-sm text-white truncate">{reference.label}</p>}
+ {reference.note && <p className="text-xs text-gray-500">{reference.note}</p>}
+ </div>
+ )}
+ </div>
+ );
+ }
+ return (
+ <a
+ href={reference.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="w-full sm:w-[325px] bg-port-card border border-port-border rounded-lg p-4 hover:border-port-accent/50 transition-colors"
+ >
+ <div className="flex items-center gap-2 text-white">
+ <ExternalLink size={15} className="text-port-accent shrink-0" />
+ <span className="text-sm truncate">{title}</span>
+ </div>
+ {reference.note && <p className="mt-1 text-xs text-gray-500">{reference.note}</p>}
+ <p className="mt-1 text-xs text-gray-600 truncate">{reference.url}</p>
+ </a>
+ );
+}
+
+// Built-in default banner — shows the shipped-default label and an inline-
+// confirmed "Refresh from template" action (restores shipped content, keeps the
+// user's recordings + learned progress). Inline confirm rather than a two-click
+// arm so the destructive-of-edits nature is explicit without a hidden re-click.
+function BuiltInBanner({ onRefresh, refreshing }) {
+ const [confirming, setConfirming] = useState(false);
+ return (
+ <div className="flex flex-wrap items-center gap-3 bg-port-accent/5 border border-port-accent/20 rounded-lg px-3 py-2">
+ <Pill tone="accent" icon={Sparkles}>Built-in default</Pill>
+ <span className="text-xs text-gray-400 flex-1 min-w-0">
+ Shipped with PortOS. Refresh to restore the latest bundled lyrics, arrangement & references — your recordings and learned progress are kept.
+ </span>
+ {confirming ? (
+ <span className="flex items-center gap-2">
+ <span className="text-xs text-gray-300">Replace local edits?</span>
+ <button
+ type="button"
+ onClick={() => { onRefresh(); setConfirming(false); }}
+ disabled={refreshing}
+ className="px-2.5 py-1 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"
+ >
+ {refreshing ? 'Refreshing…' : 'Refresh'}
+ </button>
+ <button
+ type="button"
+ onClick={() => setConfirming(false)}
+ className="px-2.5 py-1 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white"
+ >
+ Cancel
+ </button>
+ </span>
+ ) : (
+ <button
+ type="button"
+ onClick={() => setConfirming(true)}
+ disabled={refreshing}
+ className="flex items-center gap-1.5 px-2.5 py-1.5 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50 shrink-0"
+ >
+ <RefreshCw size={14} /> Refresh from template
+ </button>
+ )}
</div>
);
}
diff --git a/client/src/pages/Songs.jsx b/client/src/pages/Songs.jsx
index 7dba414261..204497f49c 100644
--- a/client/src/pages/Songs.jsx
+++ b/client/src/pages/Songs.jsx
@@ -40,7 +40,8 @@ export default function Songs() {
if (!name) { toast.error('Give the song a title'); return null; }
const data = await createSong({ title: name, artist: artist.trim() }, { silent: true });
const song = data?.song;
- if (song) navigate(`/songs/${song.id}`);
+ // A blank new song has nothing to read — open straight into edit mode.
+ if (song) navigate(`/songs/${song.id}?mode=edit`);
return song;
}, { errorMessage: 'Failed to create song' });
@@ -58,6 +59,8 @@ export default function Songs() {
if (!fields) { toast.error('Generation produced nothing — try again'); return null; }
const created = await createSong(fields, { silent: true });
const song = created?.song;
+ // Unlike a blank create, a generated draft already has lyrics — open the
+ // read view so the user sees the result, then toggle to Edit to refine.
if (song) navigate(`/songs/${song.id}`);
return song;
}, { errorMessage: 'Failed to generate song' });
@@ -161,6 +164,11 @@ export default function Songs() {
: <Circle size={16} className="text-gray-600 shrink-0" aria-label="In progress" />}
<span className="text-white font-medium truncate">{song.title}</span>
{song.artist && <span className="text-gray-500 text-sm truncate">· {song.artist}</span>}
+ {song.builtIn && (
+ <span className="shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] uppercase tracking-wide bg-port-accent/10 text-port-accent border border-port-accent/20">
+ Built-in
+ </span>
+ )}
</div>
<div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-gray-500 mt-1 pl-6">
{song.key && <span>Key: {song.key}</span>}
diff --git a/client/src/services/apiSongs.js b/client/src/services/apiSongs.js
index 695fff00bc..b63da1202c 100644
--- a/client/src/services/apiSongs.js
+++ b/client/src/services/apiSongs.js
@@ -20,6 +20,12 @@ export const updateSong = (id, patch, options) =>
export const deleteSong = (id, options) =>
request(`/songs/${enc(id)}`, { method: 'DELETE', ...options });
+// Reset a built-in default song's shipped content (metadata/lyrics/layers/
+// references) to the current bundled template → { song }. Preserves the user's
+// recordings + learned progress. 400 if the song isn't a built-in default.
+export const refreshSongTemplate = (id, options) =>
+ request(`/songs/${enc(id)}/refresh-template`, { method: 'POST', ...options });
+
// AI: draft a brand-new arrangement from a brief (no id, not persisted) →
// { song, llm }. body: { title?, artist?, brief?, mood?, providerId?, model? }.
export const generateSong = (body = {}, options) =>
diff --git a/server/routes/songs.js b/server/routes/songs.js
index f74e20edf7..9ae90358eb 100644
--- a/server/routes/songs.js
+++ b/server/routes/songs.js
@@ -52,6 +52,15 @@ const recordingSchema = z.object({
createdAt: z.string().optional(),
});
+// A reference link/video (e.g. a TikTok performance). `url` is required; the
+// client renders TikTok urls as embeds and everything else as a link.
+const referenceSchema = z.object({
+ id: str(svc.ID_MAX_LENGTH).optional(),
+ url: str(svc.URL_MAX_LENGTH),
+ label: str(svc.LABEL_MAX_LENGTH).optional().default(''),
+ note: str(svc.FIELD_MAX_LENGTH).optional().default(''),
+});
+
// No `.default('')` on these fields: `.partial()` (used for PUT) materializes a
// default for an *omitted* key, which would turn a single-field PUT into a
// wipe of every other field via updateSong's `'key' in patch` merge. Leaving
@@ -70,6 +79,7 @@ const songInputSchema = z.object({
sections: z.array(sectionSchema).max(svc.SECTIONS_MAX).optional(),
layers: z.array(layerSchema).max(svc.LAYERS_MAX).optional(),
recordings: z.array(recordingSchema).max(svc.RECORDINGS_MAX).optional(),
+ references: z.array(referenceSchema).max(svc.REFERENCES_MAX).optional(),
});
// AI generate/evaluate inputs. providerId/model are optional overrides; the
@@ -96,6 +106,7 @@ const evaluateSchema = z.object({
// this, asyncHandler defaults everything to 500.
const mapSongError = (err) => {
if (err?.code === svc.ERR_NOT_FOUND) return new ServerError(err.message, { status: 404, code: err.code });
+ if (err?.code === svc.ERR_NOT_BUILTIN) return new ServerError(err.message, { status: 400, code: err.code });
return err;
};
const rethrowSongError = (err) => { throw mapSongError(err); };
@@ -128,6 +139,14 @@ router.delete('/:id', asyncHandler(async (req, res) => {
res.json(result);
}));
+// POST /api/songs/:id/refresh-template → reset a built-in default song's shipped
+// content (metadata/lyrics/layers/notation) to the current bundled template,
+// preserving the user's own recordings + learned progress. 400 if not built-in.
+router.post('/:id/refresh-template', asyncHandler(async (req, res) => {
+ const song = await svc.refreshSongFromTemplate(req.params.id).catch(rethrowSongError);
+ res.json({ song });
+}));
+
// --- AI generate / evaluate -------------------------------------------------
// POST /api/songs/generate → draft a brand-new arrangement from a brief. Does
// NOT persist — returns { song: <fields>, llm } the client merges/creates from.
diff --git a/server/routes/songs.test.js b/server/routes/songs.test.js
index a90b82248a..6e0cbf0b63 100644
--- a/server/routes/songs.test.js
+++ b/server/routes/songs.test.js
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
createSong: vi.fn(),
updateSong: vi.fn(),
deleteSong: vi.fn(),
+ refreshSongFromTemplate: vi.fn(),
}));
vi.mock('../services/songs.js', async () => {
const actual = await vi.importActual('../services/songs.js');
@@ -127,6 +128,39 @@ describe('songs route', () => {
expect(mocks.updateSong).not.toHaveBeenCalled();
});
+ it('PUT /:id accepts a references array', async () => {
+ mocks.updateSong.mockResolvedValue({ id: 'song-1' });
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ references: [{ url: 'https://www.tiktok.com/@u/video/123', label: 'TikTok' }],
+ });
+ expect(res.status).toBe(200);
+ const [, patch] = mocks.updateSong.mock.calls[0];
+ expect(patch.references[0].url).toBe('https://www.tiktok.com/@u/video/123');
+ });
+
+ it('PUT /:id rejects a reference without a url', async () => {
+ const res = await request(makeApp()).put('/api/songs/song-1').send({
+ references: [{ label: 'no url' }],
+ });
+ expect(res.status).toBe(400);
+ expect(mocks.updateSong).not.toHaveBeenCalled();
+ });
+
+ it('POST /:id/refresh-template returns the refreshed built-in song', async () => {
+ mocks.refreshSongFromTemplate.mockResolvedValue({ id: 'seed-500-miles', title: '500 Miles', builtIn: true });
+ const res = await request(makeApp()).post('/api/songs/seed-500-miles/refresh-template');
+ expect(res.status).toBe(200);
+ expect(res.body.song.builtIn).toBe(true);
+ expect(mocks.refreshSongFromTemplate).toHaveBeenCalledWith('seed-500-miles');
+ });
+
+ it('POST /:id/refresh-template maps NOT_BUILTIN to a 400', async () => {
+ mocks.refreshSongFromTemplate.mockRejectedValue(Object.assign(new Error('nope'), { code: 'NOT_BUILTIN' }));
+ const res = await request(makeApp()).post('/api/songs/song-custom/refresh-template');
+ expect(res.status).toBe(400);
+ expect(res.body.code).toBe('NOT_BUILTIN');
+ });
+
it('POST /generate returns the generated fields (no id needed)', async () => {
aiMocks.generateSong.mockResolvedValue({ song: { title: 'New', sections: [] }, llm: { provider: 'p' } });
const res = await request(makeApp()).post('/api/songs/generate').send({ brief: 'a lament' });
diff --git a/server/services/songs.js b/server/services/songs.js
index f43638fc4d..becaa9c22c 100644
--- a/server/services/songs.js
+++ b/server/services/songs.js
@@ -27,6 +27,9 @@ const STATE_PATH = join(PATHS.data, 'songs.json');
// Service errors carry a `code` field so routes map to HTTP status without
// string-matching on err.message (which breaks on rename).
export const ERR_NOT_FOUND = 'NOT_FOUND';
+// Raised when a refresh-from-template is requested for a song that isn't a
+// bundled built-in default (no shipped template to restore from).
+export const ERR_NOT_BUILTIN = 'NOT_BUILTIN';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
// --- Shape bounds (shared with routes/songs.js#songInputSchema) -------------
@@ -42,6 +45,7 @@ export const TEMPO_MAX = 320;
export const SECTIONS_MAX = 60;
export const LAYERS_MAX = 24;
export const RECORDINGS_MAX = 64; // saved vocal takes for layered playback
+export const REFERENCES_MAX = 12; // reference links/videos (e.g. TikTok)
export const URL_MAX_LENGTH = 512; // uploaded-file path/url
// Trim a string field, returning '' for non-strings. Mirrors the
@@ -111,6 +115,23 @@ const sanitizeRecording = (r) => {
};
};
+// One reference link/video ({ id, url, label, note }) — external study
+// material for the song (a TikTok performance, a tutorial, a chord chart).
+// `url` is required (a reference without a target is meaningless); label/note
+// are free text. The client decides how to render each url (TikTok videos
+// embed; everything else is a link).
+const sanitizeReference = (r) => {
+ if (!r || typeof r !== 'object') return null;
+ const url = trimField(r.url, URL_MAX_LENGTH);
+ if (!url) return null;
+ return {
+ id: trimField(r.id, ID_MAX_LENGTH) || `ref-${randomUUID().slice(0, 8)}`,
+ url,
+ label: trimField(r.label, LABEL_MAX_LENGTH),
+ note: trimField(r.note, FIELD_MAX_LENGTH),
+ };
+};
+
const sanitizeList = (arr, fn, max) =>
(Array.isArray(arr) ? arr : [])
.map(fn)
@@ -136,6 +157,11 @@ export const sanitizeSong = (raw) => {
sections: sanitizeList(raw.sections, sanitizeSection, SECTIONS_MAX),
layers: sanitizeList(raw.layers, sanitizeLayer, LAYERS_MAX),
recordings: sanitizeList(raw.recordings, sanitizeRecording, RECORDINGS_MAX),
+ references: sanitizeList(raw.references, sanitizeReference, REFERENCES_MAX),
+ // Derived from the shipped-seed id set, NOT from `raw` — so the flag can't
+ // be lost on edit or spoofed on a hand-edited custom song. A built-in
+ // default can be restored to its shipped content via refreshSongFromTemplate.
+ builtIn: BUILTIN_SONG_IDS.has(id),
createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : new Date().toISOString(),
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : new Date().toISOString(),
};
@@ -156,8 +182,13 @@ export const SEED_SONGS = [
notes: 'A travelling lament — keep it spacious and mournful. Sustain the vowels on the downbeats. Works beautifully with a soft hummed drone under the verses.',
learned: false,
sections: [
- { id: 'sec-verse-1', label: 'Verse 1', lyrics: 'If you miss the train I\'m on, you will know that I am gone\nYou can hear the whistle blow a hundred miles' },
- { id: 'sec-chorus', label: 'Chorus', lyrics: 'A hundred miles, a hundred miles, a hundred miles, a hundred miles\nYou can hear the whistle blow a hundred miles' },
+ { id: 'sec-verse-1', label: 'Verse 1', lyrics: 'If you miss the train I\'m on\nYou will know that I am gone\nYou can hear the whistle blow\nA hundred miles' },
+ { id: 'sec-chorus-1', label: 'Chorus 1', lyrics: 'A hundred miles\nA hundred miles\nA hundred miles\nA hundred miles\nA hundred miles\nYou can hear the whistle blow a hundred miles' },
+ { id: 'sec-verse-2', label: 'Verse 2', lyrics: 'Lord, I\'m one\nLord, I\'m two\nLord, I\'m three\nLord, I\'m four\nLord, I\'m five hundred miles from my home' },
+ { id: 'sec-chorus-2', label: 'Chorus 2', lyrics: 'Five hundred miles\nFive hundred miles\nFive hundred miles\nFive hundred miles\nLord, I\'m five hundred miles from my home' },
+ { id: 'sec-verse-3', label: 'Verse 3', lyrics: 'Not a shirt on my back\nNot a penny to my name\nLord, I can\'t go home\nThis a-way' },
+ { id: 'sec-chorus-3', label: 'Chorus 3', lyrics: 'This a-way\nThis a-way\nThis a-way\nThis a-way\nThis a-way\nLord, I can\'t go home this a-way' },
+ { id: 'sec-verse-4', label: 'Verse 4 (reprise)', lyrics: 'If you miss the train I\'m on\nYou will know that I am gone\nYou can hear the whistle blow a hundred miles' },
],
layers: [
{ id: 'lead', label: 'Lead melody', part: 'Soprano / Tenor', notes: 'The tune everyone knows. Lock this first, in tune, before stacking anything.' },
@@ -165,11 +196,22 @@ export const SEED_SONGS = [
{ id: 'harmony-3rd', label: 'Harmony (third)', part: 'Alto', notes: 'A third under the melody. The first colour — keep it close and warm.' },
{ id: 'drone', label: 'Drone / pedal', part: 'Bass / Alto', notes: 'Optional held tonic (C) under the verse to make the lament feel ancient.' },
],
+ references: [
+ { id: 'ref-tt-marie', url: 'https://www.tiktok.com/@marie.celestinee/video/7638358831205977376', label: 'TikTok · @marie.celestinee', note: 'Reference performance.' },
+ { id: 'ref-tt-eric', url: 'https://www.tiktok.com/@ericolsith/video/7633158760659176718', label: 'TikTok · @ericolsith', note: 'Reference performance.' },
+ ],
createdAt: '2026-01-01T00:00:00.000Z',
updatedAt: '2026-01-01T00:00:00.000Z',
},
];
+// Ids of the bundled built-in default songs. The sanitizer stamps each read
+// song with `builtIn` from this set, and refreshSongFromTemplate restores a
+// built-in's shipped content from the matching SEED_SONGS entry. A user who
+// already has the song installed (older shipped lyrics) renews it on demand.
+export const BUILTIN_SONG_IDS = new Set(SEED_SONGS.map((s) => s.id));
+const seedTemplate = (id) => SEED_SONGS.find((s) => s.id === id) || null;
+
// Serialize the read-modify-write cycle so two mutations issued back-to-back
// (e.g. a rename PUT followed by a layer edit) each merge against the freshest
// persisted state instead of racing on a stale snapshot. Single-user, so this
@@ -235,7 +277,7 @@ export async function updateSong(id, patch) {
// Merge field-by-field so an absent key preserves the stored value while a
// present key (including empty string / empty array) applies the change.
const merged = { ...songs[idx] };
- for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'notes', 'learned', 'sections', 'layers', 'recordings']) {
+ for (const key of ['title', 'artist', 'key', 'tempo', 'rhythmShapeId', 'notation', 'notes', 'learned', 'sections', 'layers', 'recordings', 'references']) {
if (key in patch) merged[key] = patch[key];
}
merged.id = id;
@@ -249,6 +291,34 @@ export async function updateSong(id, patch) {
});
}
+// Restore a built-in default song's shipped content (metadata, lyrics, layers,
+// notation, notes) to the current bundled template — for installs that seeded
+// an older version of the song and want the newer shipped one. User-owned state
+// is preserved: their recorded takes, their `learned` progress, and the
+// original createdAt. Throws ERR_NOT_BUILTIN for a non-default song.
+export async function refreshSongFromTemplate(id) {
+ return enqueue(async () => {
+ const songs = await readSongs();
+ const idx = songs.findIndex((s) => s.id === id);
+ if (idx === -1) throw makeErr(`Song ${id} not found`, ERR_NOT_FOUND);
+ const template = seedTemplate(id);
+ if (!template) throw makeErr(`Song ${id} is not a built-in default`, ERR_NOT_BUILTIN);
+ const existing = songs[idx];
+ const song = sanitizeSong({
+ ...template,
+ id,
+ learned: existing.learned,
+ recordings: existing.recordings,
+ createdAt: existing.createdAt,
+ updatedAt: new Date().toISOString(),
+ });
+ songs[idx] = song;
+ await atomicWrite(STATE_PATH, { songs });
+ console.log(`🔄 Refreshed built-in song "${song.title}" (${id}) from template`);
+ return song;
+ });
+}
+
export async function deleteSong(id) {
return enqueue(async () => {
const songs = await readSongs();
diff --git a/server/services/songs.test.js b/server/services/songs.test.js
index 034233b5e0..514523d370 100644
--- a/server/services/songs.test.js
+++ b/server/services/songs.test.js
@@ -157,4 +157,65 @@ describe('songs service', () => {
const song = svc.sanitizeSong({ id: 'x', recordings: [{ id: 'rec-keep', filename: 'k.wav' }] });
expect(song.recordings[0].id).toBe('rec-keep');
});
+
+ it('stamps builtIn from the seed-id set, ignoring the raw value', () => {
+ const seedId = [...svc.BUILTIN_SONG_IDS][0];
+ expect(svc.sanitizeSong({ id: seedId }).builtIn).toBe(true);
+ // A custom song can't spoof builtIn even if the raw record claims it.
+ expect(svc.sanitizeSong({ id: 'song-custom', builtIn: true }).builtIn).toBe(false);
+ });
+
+ it('seeds the 500 Miles default as a built-in with reference videos', async () => {
+ const songs = await svc.listSongs();
+ const seed = songs.find((s) => s.title === '500 Miles');
+ expect(seed.builtIn).toBe(true);
+ expect(seed.references.length).toBeGreaterThan(0);
+ expect(seed.references.every((r) => r.url.includes('tiktok.com'))).toBe(true);
+ });
+
+ it('sanitizes references — drops urlless entries, mints ids', () => {
+ const song = svc.sanitizeSong({
+ id: 'x',
+ references: [
+ { url: 'https://www.tiktok.com/@u/video/123', label: 'A' },
+ { label: 'no url' }, // no url → dropped
+ { id: 'ref-keep', url: 'https://example.com' },
+ ],
+ });
+ expect(song.references).toHaveLength(2);
+ expect(song.references[0].id).toMatch(/^ref-/);
+ expect(song.references[1].id).toBe('ref-keep');
+ });
+
+ it('refreshes a built-in from template, preserving recordings + learned', async () => {
+ await svc.listSongs(); // seed
+ const seedId = [...svc.BUILTIN_SONG_IDS][0];
+ // User edits the song and records a take + marks it learned.
+ const edited = await svc.updateSong(seedId, {
+ title: 'My edited title',
+ sections: [{ label: 'Custom', lyrics: 'changed' }],
+ learned: true,
+ recordings: [{ filename: 'my-take.wav', durationMs: 1000 }],
+ references: [{ url: 'https://example.com/mine' }],
+ });
+ expect(edited.title).toBe('My edited title');
+
+ const refreshed = await svc.refreshSongFromTemplate(seedId);
+ // Shipped content restored…
+ expect(refreshed.title).toBe('500 Miles');
+ expect(refreshed.references.every((r) => r.url.includes('tiktok.com'))).toBe(true);
+ expect(refreshed.sections.some((s) => s.lyrics.includes('miss the train'))).toBe(true);
+ // …user-owned state preserved.
+ expect(refreshed.learned).toBe(true);
+ expect(refreshed.recordings).toHaveLength(1);
+ expect(refreshed.recordings[0].filename).toBe('my-take.wav');
+ expect(refreshed.createdAt).toBe(edited.createdAt);
+ expect(refreshed.builtIn).toBe(true);
+ });
+
+ it('refresh throws NOT_BUILTIN for a custom song and NOT_FOUND for a missing one', async () => {
+ const custom = await svc.createSong({ title: 'Mine' });
+ await expect(svc.refreshSongFromTemplate(custom.id)).rejects.toMatchObject({ code: svc.ERR_NOT_BUILTIN });
+ await expect(svc.refreshSongFromTemplate('song-nope')).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
+ });
});