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 drawn-waveform takes against races, oversized input, and dead remix

[._.]/ Adam Eivy5febf5cbbcd5
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index 218cf1182b..a5ef65a31a 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -348,6 +348,12 @@ export default function TracksManager() {
setChiptuneRemix({ prompt: render.prompt || '', nonce: remixNonceRef.current });
return;
}
+ // A drawn-waveform take has no audio-model engine to seed — reopen it in the
+ // Music Designer's drawn engine on this track, where its drawing lives.
+ if (render.engine === 'waveform' && persisted) {
+ navigate(`/music/generate/render?trackId=${encodeURIComponent(persisted.id)}&engine=drawn`);
+ return;
+ }
setGenMode('audio');
setForm((f) => ({
...f,
diff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsx
index b5ba2e7df6..c2a1402f50 100644
--- a/client/src/components/music/TracksManager.test.jsx
+++ b/client/src/components/music/TracksManager.test.jsx
@@ -260,6 +260,16 @@ describe('<TracksManager> generative workflow hand-off', () => {
await waitFor(() => expect(musicGenProps.current?.remix?.nonce).toBe(2));
expect(musicGenProps.current.remix).not.toHaveProperty('instrumentalOnly');
});
+
+ it('remixes a drawn-waveform take in the designer\'s drawn engine', async () => {
+ listTracks.mockResolvedValue([{
+ ...TRACK,
+ renders: [{ id: 'render-drawn', audioFilename: 'drawn.wav', engine: 'waveform', prompt: 'Glassy', createdAt: '2026-01-02T00:00:00Z' }],
+ }]);
+ renderAt('track-1');
+ fireEvent.click(await screen.findByRole('button', { name: 'Remix render-drawn' }));
+ expect(await screen.findByTestId('location')).toHaveTextContent('/music/generate/render?trackId=track-1&engine=drawn');
+ });
});
describe('<TracksManager> Audio-to-Video hand-off', () => {
diff --git a/server/lib/waveSketch.js b/server/lib/waveSketch.js
index a8d3c583f7..58cf192203 100644
--- a/server/lib/waveSketch.js
+++ b/server/lib/waveSketch.js
@@ -75,7 +75,8 @@ const round = (n, places = 4) => Math.round(n * 10 ** places) / 10 ** places;
function normalizePoints(raw, { min, max, lo, hi }) {
const list = Array.isArray(raw) ? raw : Array.isArray(raw?.points) ? raw.points : null;
if (!list) return null;
- const points = list.filter(isNum).slice(0, max).map((n) => round(clamp(n, lo, hi)));
+ // Slice BEFORE scanning so an oversized array costs O(cap), not O(length).
+ const points = list.slice(0, max).filter(isNum).map((n) => round(clamp(n, lo, hi)));
return points.length >= min ? points : null;
}
@@ -114,8 +115,11 @@ export function normalizeWaveSketch(raw) {
const shapes = {};
const rawShapes = raw.shapes && typeof raw.shapes === 'object' && !Array.isArray(raw.shapes) ? raw.shapes : {};
- for (const [name, points] of Object.entries(rawShapes)) {
- if (Object.keys(shapes).length >= L.SHAPES_MAX) break;
+ let shapeBudget = L.SHAPES_MAX * 4; // bounded scan of a hostile key count
+ for (const name in rawShapes) {
+ if (!Object.hasOwn(rawShapes, name)) continue;
+ if (Object.keys(shapes).length >= L.SHAPES_MAX || (shapeBudget -= 1) < 0) break;
+ const points = rawShapes[name];
if (!NAME_RE.test(name) || name === WAVE_SKETCH_NOISE) continue;
const normalized = normalizePoints(points, { min: L.SHAPE_POINTS_MIN, max: L.SHAPE_POINTS_MAX, lo: -1, hi: 1 });
if (normalized) shapes[name] = normalized;
@@ -124,7 +128,7 @@ export function normalizeWaveSketch(raw) {
const rawVoices = Array.isArray(raw.voices) ? raw.voices.slice(0, L.VOICES_MAX) : [];
// An absent/invalid duration is derived from the strokes themselves.
- const lastEnd = rawVoices.flatMap((v) => (Array.isArray(v?.notes) ? v.notes : []))
+ const lastEnd = rawVoices.flatMap((v) => (Array.isArray(v?.notes) ? v.notes.slice(0, L.NOTES_PER_VOICE_MAX) : []))
.reduce((end, n) => (isNum(n?.t) && isNum(n?.d) ? Math.max(end, n.t + n.d) : end), 0);
const durationSec = round(clamp(isNum(raw.durationSec) ? raw.durationSec : lastEnd, L.DURATION_MIN_SEC, L.DURATION_MAX_SEC), 3);
@@ -136,7 +140,7 @@ export function normalizeWaveSketch(raw) {
const isNoise = shape === WAVE_SKETCH_NOISE;
if (!isNoise && !shapeNames.has(shape)) continue;
const notes = [];
- for (const rawNote of (Array.isArray(rawVoice.notes) ? rawVoice.notes : [])) {
+ for (const rawNote of (Array.isArray(rawVoice.notes) ? rawVoice.notes.slice(0, L.NOTES_PER_VOICE_MAX * 2) : [])) {
if (notes.length >= L.NOTES_PER_VOICE_MAX || noteBudget <= 0) break;
const note = normalizeNote(rawNote, { durationSec, isNoise, shapeNames });
if (!note || note.d > secondsBudget) continue;
diff --git a/server/lib/waveSketch.test.js b/server/lib/waveSketch.test.js
index 736a2bbf13..88e538f55a 100644
--- a/server/lib/waveSketch.test.js
+++ b/server/lib/waveSketch.test.js
@@ -74,6 +74,13 @@ describe('normalizeWaveSketch', () => {
expect(voiced).toBeLessThanOrEqual(WAVE_SKETCH_LIMITS.NOTE_SECONDS_MAX);
});
+ it('bounds its work by the caps, not by the size of an oversized input', () => {
+ const huge = new Array(2_000_000).fill(0.5);
+ const sketch = normalizeWaveSketch(sketchOf([{ shape: 'sine', notes: [{ t: 0, d: 1, pitch: 'A4', env: huge }] }], { shapes: { sine: huge } }));
+ expect(sketch.shapes.sine).toHaveLength(WAVE_SKETCH_LIMITS.SHAPE_POINTS_MAX);
+ expect(sketch.voices[0].notes[0].env).toHaveLength(WAVE_SKETCH_LIMITS.ENV_POINTS_MAX);
+ });
+
it('is idempotent, so a sketch round-trips through the client unchanged', () => {
const once = normalizeWaveSketch(sketchOf([
{ name: 'lead', shape: 'sine', notes: [{ t: 0.1234567, d: 0.5, pitch: 'F#4', glideTo: 'B4', env: [0, 1, 0.3, 0] }] },
diff --git a/server/services/musicWaveform.js b/server/services/musicWaveform.js
index 0b452afe63..9c6b5be6db 100644
--- a/server/services/musicWaveform.js
+++ b/server/services/musicWaveform.js
@@ -137,6 +137,6 @@ export async function renderWaveSketchToTrack({ trackId, sketch, prompt, title }
audioFilename: filename, prompt: prompt || track.prompt, engine: WAVEFORM_ENGINE, durationSec,
}, title ? { title } : {});
if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
- console.log(`〰️ Rendered drawn waveform for track ${trackId} → ${filename} (${durationSec}s)`);
+ console.log(`〰️ Rendered drawn waveform take (${durationSec}s)`);
return { track: updated, filename, durationSec };
}
diff --git a/server/services/tracks/index.js b/server/services/tracks/index.js
index 3b2caa2dc3..4783c70ac3 100644
--- a/server/services/tracks/index.js
+++ b/server/services/tracks/index.js
@@ -57,6 +57,9 @@ export function buildRenderAppend(track, renderInput) {
return { render, renders: [...(track?.renders || []), render] };
}
+// Per-track tail of in-flight take appends (see appendActiveTake).
+const takeTails = new Map();
+
/**
* Record a freshly rendered audio file as the track's ACTIVE take: re-read the
* track (so the append lands on the freshest history), append the render, and
@@ -64,11 +67,18 @@ export function buildRenderAppend(track, renderInput) {
* engine updates alongside (e.g. a title). Resolves to the updated track, or
* null when the track is gone. Shared by the offline LLM-music renderers.
*/
-export async function appendActiveTake(trackId, { audioFilename, engine, prompt, durationSec }, patch = {}) {
- const current = await getTrack(trackId);
- if (!current) return null;
- const { renders } = buildRenderAppend(current, { audioFilename, prompt, engine, durationSec });
- return updateTrack(trackId, { ...patch, audioFilename, engine, modelId: '', durationSec, renders });
+export function appendActiveTake(trackId, { audioFilename, engine, prompt, durationSec }, patch = {}) {
+ // Serialized per track: two renders finishing together would otherwise both
+ // read the same history and the later write would drop the other's take.
+ const run = (takeTails.get(trackId) || Promise.resolve()).catch(() => null).then(async () => {
+ const current = await getTrack(trackId);
+ if (!current) return null;
+ const { renders } = buildRenderAppend(current, { audioFilename, prompt, engine, durationSec });
+ return updateTrack(trackId, { ...patch, audioFilename, engine, modelId: '', durationSec, renders });
+ });
+ takeTails.set(trackId, run);
+ run.finally(() => { if (takeTails.get(trackId) === run) takeTails.delete(trackId); }).catch(() => {});
+ return run;
}
/** Name of the active backend, or null before first call (for diagnostics/tests). */
diff --git a/server/services/tracks/index.test.js b/server/services/tracks/index.test.js
new file mode 100644
index 0000000000..04ec163e2e
--- /dev/null
+++ b/server/services/tracks/index.test.js
@@ -0,0 +1,33 @@
+import { describe, it, expect, vi } from 'vitest';
+
+// In-memory backend whose reads and writes yield, so two appends interleave
+// exactly the way two renders finishing together would.
+const store = vi.hoisted(() => ({ track: null }));
+const tick = () => new Promise((resolve) => setTimeout(resolve, 5));
+vi.mock('./file.js', () => ({
+ getTrack: async () => { await tick(); return store.track && structuredClone(store.track); },
+ updateTrack: async (id, patch) => { await tick(); store.track = { ...store.track, ...patch }; return structuredClone(store.track); },
+}));
+vi.mock('../sharing/recordEvents.js', () => ({
+ emitRecordUpdated: () => {},
+ autoSubscribeRecordToAllPeers: async () => {},
+}));
+
+const { appendActiveTake } = await import('./index.js');
+
+describe('appendActiveTake', () => {
+ it('keeps both takes when two renders of one track finish together', async () => {
+ store.track = { id: 'track-1', renders: [] };
+ await Promise.all([
+ appendActiveTake('track-1', { audioFilename: 'a.wav', engine: 'waveform', prompt: 'a', durationSec: 2 }),
+ appendActiveTake('track-1', { audioFilename: 'b.wav', engine: 'chiptune', prompt: 'b', durationSec: 3 }),
+ ]);
+ expect(store.track.renders.map((r) => r.audioFilename)).toEqual(['a.wav', 'b.wav']);
+ expect(store.track).toMatchObject({ audioFilename: 'b.wav', engine: 'chiptune', modelId: '', durationSec: 3 });
+ });
+
+ it('resolves null for a missing track', async () => {
+ store.track = null;
+ await expect(appendActiveTake('gone', { audioFilename: 'a.wav', engine: 'waveform', durationSec: 1 })).resolves.toBeNull();
+ });
+});