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

address review (codex): route melody proposals to the base score; clear segments with removed audio

Adam Eivy2e5eea3f6818
diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsx
index aaa4fd8742..f803b9d01d 100644
--- a/client/src/components/songs/ReferenceAnalysis.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.jsx
@@ -142,7 +142,12 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {
<audio controls preload="none" src={getUploadUrl(reference.audioFilename)} className="h-8 max-w-[180px]" />
<button
type="button"
- onClick={() => onUpdate('audioFilename', '')}
+ onClick={() => {
+ // Segments are offsets into THIS audio — clear them with it so
+ // stale ranges can't resurrect against a different recording.
+ onUpdate('segments', []);
+ onUpdate('audioFilename', '');
+ }}
className="flex items-center gap-1 px-2 py-1 text-xs rounded-lg border border-port-border text-gray-400 hover:text-port-error"
>
<X size={13} /> Remove audio
@@ -246,8 +251,13 @@ function Waveform({ samples, durationMs, segments, playheadMs, onSeek }) {
// --- Analysis view -----------------------------------------------------------
+// Sentinel compare/apply target for the round's BASE melody (song.score).
+// A melody-layer proposal must update the base score, not grow a duplicate
+// "Melody" entry in scoreParts (which the parts editor deliberately excludes).
+const BASE_TARGET = '__base__';
+
export default function ReferenceAnalysis({
- reference, layers = [], scoreParts = [], tempo = null, songKey = '',
+ reference, layers = [], scoreParts = [], baseScore = '', tempo = null, songKey = '',
onUpdateReference, onApplyPart, onClose,
}) {
const audioRef = useRef(null);
@@ -361,20 +371,28 @@ export default function ReferenceAnalysis({
return;
}
setProposal({ layerId: seg.layerId, text });
- // Default the comparison to the stored part whose role matches the
- // segment's layer (layer ids double as harmony-part roles). Only when
- // the segment actually HAS a layer and the part a non-empty role — an
- // unassigned segment ('' layerId) must not silently preselect a
- // role-less hand-added part as the overwrite target.
- const match = seg.layerId ? scoreParts.find((p) => p.role && p.role === seg.layerId) : null;
- setCompareId(match?.id || '');
+ // Default the comparison target. A melody segment targets the BASE
+ // score (song.score) — the round's melody lives there, not in
+ // scoreParts. Other layers match the stored part whose role equals the
+ // segment's layer (layer ids double as harmony-part roles) — only when
+ // the segment actually HAS a layer and the part a non-empty role, so an
+ // unassigned segment ('' layerId) can't silently preselect a role-less
+ // hand-added part as the overwrite target.
+ if (seg.layerId === 'melody') {
+ setCompareId(BASE_TARGET);
+ } else {
+ const match = seg.layerId ? scoreParts.find((p) => p.role && p.role === seg.layerId) : null;
+ setCompareId(match?.id || '');
+ }
}, 30);
}, [decoded, tempo, songKey, scoreParts]);
- const comparePart = useMemo(
- () => scoreParts.find((p) => p.id === compareId) || null,
- [scoreParts, compareId],
- );
+ const comparePart = useMemo(() => {
+ if (compareId === BASE_TARGET) {
+ return { id: BASE_TARGET, label: 'Melody (base score)', role: 'melody', score: baseScore, isBase: true };
+ }
+ return scoreParts.find((p) => p.id === compareId) || null;
+ }, [scoreParts, compareId, baseScore]);
const diffRows = useMemo(() => {
if (!proposal?.text || !comparePart?.score) return null;
@@ -388,13 +406,20 @@ export default function ReferenceAnalysis({
toast.error('The proposed part has no parseable notes to apply.');
return;
}
+ if (comparePart?.isBase) {
+ // Melody proposals write the BASE score, never a scoreParts entry.
+ onApplyPart?.({ base: true, score: proposal.text });
+ return;
+ }
onApplyPart?.({
id: comparePart?.id || '',
// Prefer the harmony-part vocabulary label; a custom layer id falls back
// to the layer's own label (harmonyPartLabel returns '' for unknown ids).
label: comparePart?.label
|| (proposal.layerId ? (harmonyPartLabel(proposal.layerId) || layerLabel(proposal.layerId)) : 'Extracted part'),
- role: comparePart?.role ?? (proposal.layerId || ''),
+ // A melody-layer proposal explicitly applied as a NEW part must not mint
+ // a pseudo-"melody" role in scoreParts (the parts editor excludes it).
+ role: comparePart?.role ?? (proposal.layerId === 'melody' ? '' : proposal.layerId || ''),
score: proposal.text,
});
}, [proposal, comparePart, onApplyPart, layerLabel]);
@@ -558,6 +583,7 @@ export default function ReferenceAnalysis({
className="bg-port-bg border border-port-border rounded-lg px-2 py-1.5 text-xs text-white focus:border-port-accent focus:outline-none"
>
<option value="">New part</option>
+ <option value={BASE_TARGET}>Melody (base score)</option>
{scoreParts.map((p) => <option key={p.id} value={p.id}>{p.label || p.role || p.id}</option>)}
</select>
</div>
@@ -620,7 +646,7 @@ export default function ReferenceAnalysis({
onClick={applyProposal}
className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"
>
- {comparePart ? 'Apply to current part' : 'Add as new part'}
+ {comparePart?.isBase ? 'Apply to base melody' : comparePart ? 'Apply to current part' : 'Add as new part'}
</button>
<button
type="button"
diff --git a/client/src/components/songs/ReferenceAnalysis.test.jsx b/client/src/components/songs/ReferenceAnalysis.test.jsx
index f4677003b4..202876e0c5 100644
--- a/client/src/components/songs/ReferenceAnalysis.test.jsx
+++ b/client/src/components/songs/ReferenceAnalysis.test.jsx
@@ -181,6 +181,35 @@ describe('ReferenceAnalysis — extract → review → apply (solo segment)', ()
expect(part.id).toBe('part-bass');
expect(part.role).toBe('bass');
});
+
+ it('routes a melody-layer proposal to the base score, not scoreParts', async () => {
+ installFakeAudio();
+ const onApplyPart = vi.fn();
+ render(
+ <ReferenceAnalysis
+ reference={{ ...baseRef, segments: [{ layerId: 'melody', startMs: 0, endMs: 1000 }] }}
+ layers={layers}
+ scoreParts={[]}
+ baseScore="| A3q |"
+ tempo={60}
+ songKey="C"
+ onUpdateReference={vi.fn()}
+ onApplyPart={onApplyPart}
+ onClose={vi.fn()}
+ />,
+ );
+ const extract = screen.getByRole('button', { name: /extract part/i });
+ await waitFor(() => expect(extract.disabled).toBe(false));
+ fireEvent.click(extract);
+ await waitFor(() => expect(screen.getAllByTestId('scoresheet').length).toBeGreaterThan(0), { timeout: 3000 });
+
+ // Melody defaults to the base-score target and applies as { base: true }.
+ expect(screen.getByLabelText(/compare \/ apply to/i).value).toBe('__base__');
+ fireEvent.click(screen.getByRole('button', { name: /apply to base melody/i }));
+ const applied = onApplyPart.mock.calls[0][0];
+ expect(applied.base).toBe(true);
+ expect(applied.score).toMatch(/A3/);
+ });
});
describe('ReferenceAudioAttach', () => {
@@ -190,11 +219,14 @@ describe('ReferenceAudioAttach', () => {
expect(screen.getByRole('button', { name: /capture from mic/i })).toBeTruthy();
});
- it('shows the attached state and clears via Remove audio', () => {
+ it('shows the attached state and clears audio AND segments via Remove audio', () => {
const onUpdate = vi.fn();
render(<ReferenceAudioAttach reference={{ id: 'r', url: 'https://x.com', audioFilename: 'a.wav' }} onUpdate={onUpdate} />);
expect(screen.getByText(/audio attached/i)).toBeTruthy();
fireEvent.click(screen.getByRole('button', { name: /remove audio/i }));
expect(onUpdate).toHaveBeenCalledWith('audioFilename', '');
+ // Segments are offsets into the removed audio — cleared with it so stale
+ // ranges can't resurrect against a later, different recording.
+ expect(onUpdate).toHaveBeenCalledWith('segments', []);
});
});
diff --git a/client/src/pages/RoundEditor.jsx b/client/src/pages/RoundEditor.jsx
index ec23c9676c..89911a522e 100644
--- a/client/src/pages/RoundEditor.jsx
+++ b/client/src/pages/RoundEditor.jsx
@@ -319,11 +319,17 @@ export default function RoundEditor() {
...prev, references: prev.references.filter((r) => r.id !== rid),
}));
- // Apply an extracted reference part into the scoreParts DRAFT (#2106). An
- // `id` targeting an existing part replaces its score; otherwise the part is
- // appended with a temp id (stripped on save). Nothing persists until the
- // header Save — the same explicit-save model as recordings and AI derive.
+ // Apply an extracted reference part into the DRAFT (#2106). `base: true`
+ // updates the round's base melody (song.score); otherwise an `id` targeting
+ // an existing part replaces its score, and anything else is appended with a
+ // temp id (stripped on save). Nothing persists until the header Save — the
+ // same explicit-save model as recordings and AI derive.
const applyProposedPart = useCallback((part) => {
+ if (part.base) {
+ setSong((prev) => (prev ? { ...prev, score: part.score } : prev));
+ toast.success('Base melody updated in the draft — Save the song to keep it');
+ return;
+ }
const parts = song?.scoreParts || [];
const exists = part.id && parts.some((p) => p.id === part.id);
if (!exists && parts.length >= SCORE_PARTS_MAX) {
@@ -429,6 +435,7 @@ export default function RoundEditor() {
reference={(song.references || []).find((r) => r.id === analyzeId) || null}
layers={song.layers || []}
scoreParts={song.scoreParts || []}
+ baseScore={song.score || ''}
tempo={song.tempo ?? null}
songKey={song.key || ''}
onUpdateReference={updateReference}
diff --git a/server/services/rounds.js b/server/services/rounds.js
index 0cf1bc7959..fb62499570 100644
--- a/server/services/rounds.js
+++ b/server/services/rounds.js
@@ -294,9 +294,15 @@ const sanitizeReference = (r) => {
note: trimField(r.note, FIELD_MAX_LENGTH),
};
const audioFilename = trimField(r.audioFilename, URL_MAX_LENGTH);
- if (audioFilename) ref.audioFilename = audioFilename;
- const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);
- if (segments.length) ref.segments = segments;
+ if (audioFilename) {
+ ref.audioFilename = audioFilename;
+ // Segments are time ranges INTO the attached audio — meaningless without
+ // it. Persisting them only alongside an audioFilename makes the invariant
+ // structural: removing the audio clears them, so stale ranges can't
+ // resurrect against a later, different recording.
+ const segments = sanitizeList(r.segments, sanitizeRefSegment, REF_SEGMENTS_MAX);
+ if (segments.length) ref.segments = segments;
+ }
return ref;
};
diff --git a/server/services/rounds.test.js b/server/services/rounds.test.js
index 184bdbd0e1..c0f63c27e9 100644
--- a/server/services/rounds.test.js
+++ b/server/services/rounds.test.js
@@ -396,6 +396,7 @@ describe('rounds service', () => {
id: 'x',
references: [{
url: 'https://example.com',
+ audioFilename: 'ref.wav',
segments: [
{ layerId: 'a', startMs: 5000, endMs: 5000 }, // zero-length → dropped
{ layerId: 'b', startMs: 9000, endMs: 1000 }, // inverted → dropped
@@ -411,7 +412,7 @@ describe('rounds service', () => {
// An all-invalid list leaves the key absent (no empty-array husk).
const empty = svc.sanitizeRound({
id: 'y',
- references: [{ url: 'https://example.com', segments: [{ startMs: 1, endMs: 1 }] }],
+ references: [{ url: 'https://example.com', audioFilename: 'ref.wav', segments: [{ startMs: 1, endMs: 1 }] }],
});
expect('segments' in empty.references[0]).toBe(false);
// Bound: more than REF_SEGMENTS_MAX spans are truncated.
@@ -419,6 +420,7 @@ describe('rounds service', () => {
id: 'z',
references: [{
url: 'https://example.com',
+ audioFilename: 'ref.wav',
segments: Array.from({ length: svc.REF_SEGMENTS_MAX + 5 }, (_, i) => ({
layerId: `l${i}`, startMs: i * 1000, endMs: i * 1000 + 500,
})),
@@ -427,6 +429,21 @@ describe('rounds service', () => {
expect(many.references[0].segments).toHaveLength(svc.REF_SEGMENTS_MAX);
});
+ it('drops reference segments when no audio is attached (#2106)', () => {
+ // Segments are offsets into the attached audio — without an audioFilename
+ // they are stale ranges from a removed recording and must not persist
+ // (removing the audio clears them structurally).
+ const song = svc.sanitizeRound({
+ id: 'x',
+ references: [{
+ url: 'https://example.com',
+ segments: [{ layerId: 'bass', startMs: 0, endMs: 2000 }],
+ }],
+ });
+ expect('segments' in song.references[0]).toBe(false);
+ expect('audioFilename' in song.references[0]).toBe(false);
+ });
+
it('refreshes a built-in from template, preserving recordings + learned', async () => {
await svc.listRounds(); // seed
const seedId = [...svc.BUILTIN_ROUND_IDS][0];