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: keep the Music Designer's drawn wave sketch on the track (#8376)
[._.]/ Adam Eivy5ba2200451d9
diff --git a/client/src/components/music/TrackWaveformHost.jsx b/client/src/components/music/TrackWaveformHost.jsxnew file mode 100644index 0000000000..ba920923ba--- /dev/null+++ b/client/src/components/music/TrackWaveformHost.jsx@@ -0,0 +1,51 @@+/**+ * TrackWaveformHost — the Tracks editor's "Drawn waveform" mode (#8376).+ *+ * Hosts the Music Designer's `WaveformPanel` on a saved track so a drawn take+ * can be revised and re-rendered where the track lives: the panel opens on the+ * track's stored `waveSketch`, and draws from the editor's prompt/lyrics. The+ * designer owns its provider picker; this host supplies its own.+ */++import { useState } from 'react';+import useProviderModels from '../../hooks/useProviderModels';+import ProviderModelSelector from '../ProviderModelSelector';+import WaveformPanel from './WaveformPanel';++export default function TrackWaveformHost({ track, description, lyrics, title, onTrackUpdate }) {+ const [effort, setEffort] = useState('');+ const {+ providers, selectedProviderId, selectedModel, availableModels,+ setSelectedProviderId, setSelectedModel, loading: providersLoading,+ } = useProviderModels({ silent: true, withEffort: true });++ return (+ <WaveformPanel+ key={track.id}+ trackId={track.id}+ track={track}+ description={description}+ lyrics={lyrics}+ title={title}+ providerId={selectedProviderId}+ model={selectedModel}+ effort={effort}+ providerPicker={(+ <ProviderModelSelector+ providers={providers}+ selectedProviderId={selectedProviderId}+ selectedModel={selectedModel}+ availableModels={availableModels}+ onProviderChange={(pid) => { setSelectedProviderId(pid); setEffort(''); }}+ onModelChange={setSelectedModel}+ effort={effort}+ onEffortChange={setEffort}+ disabled={providersLoading}+ layout="stacked"+ />+ )}+ onTrackUpdate={onTrackUpdate}+ onRendered={onTrackUpdate}+ />+ );+}diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsxindex 632854a3d9..8b0d582348 100644--- a/client/src/components/music/TracksManager.jsx+++ b/client/src/components/music/TracksManager.jsx@@ -6,7 +6,8 @@* and an audio file. Audio is stored in the shared music library; the editor* uploads a file or attaches an existing library track, and plays it inline.*- * The editor hosts both on-device audio generation and LLM-composed chiptunes.+ * The editor hosts on-device audio generation, LLM-composed chiptunes, and —+ * for a track that carries one — the Music Designer's LLM-drawn wave sketch.* It can also save the open form and hand the same persisted track to the* stepped MusicDesigner workflow. Mirrors the Authors/Artists master-detail* pattern.@@ -26,6 +27,7 @@ import { withUnlistedOption } from '../../lib/withUnlistedOption';import ArtistPicker from './ArtistPicker';import MusicGenPanel from './MusicGenPanel';import ChiptunePanel from './ChiptunePanel';+import TrackWaveformHost from './TrackWaveformHost';import TrackRenderCard from './TrackRenderCard';import TrackRenderModal from './TrackRenderModal';import MidiVisualization from '../songs/MidiVisualization.jsx';@@ -55,6 +57,13 @@ const formFromTrack = (t) => ({audioFilename: t.audioFilename || '',});+// The generator a freshly selected track opens on: its drawing when the active+// take was drawn from it, else its chiptune score, else the audio models.+const initialGenMode = (track) => {+ if (track.engine === 'waveform' && track.waveSketch) return 'drawn';+ return track.chiptuneScore ? 'chiptune' : 'audio';+};+export default function TracksManager() {const navigate = useNavigate();// Selection lives in the URL (`/music/tracks/:id`, `/music/tracks/new`) so it's@@ -79,9 +88,11 @@ export default function TracksManager() {// Music Video projects, for the MIDI read-through: MuScriptor transcriptions// are stored on the MV project that links a track, not on the track itself.const [mvProjects, setMvProjects] = useState([]);- // Which generator the editor shows: the on-device audio models or the- // LLM-composed chiptune score (#2911). Seeded per selection below — a track- // that already carries a score opens on the chiptune panel.+ // Which generator the editor shows: the on-device audio models, the+ // LLM-composed chiptune score (#2911), or the LLM-drawn wave sketch (#8376,+ // offered only for a track that already carries one). Seeded per selection+ // below — a track whose active take is drawn opens on its drawing, and one+ // that carries a score opens on the chiptune panel.const [genMode, setGenMode] = useState('audio');const remixNonceRef = useRef(0);// Mirrors `selectedId` so async audio handlers can detect a selection change@@ -161,7 +172,7 @@ export default function TracksManager() {// Skip the derivation exactly once for the track `handleSave` just made,// so the pre-save choice survives the create → navigate hydration.if (justCreatedIdRef.current === selectionKey) justCreatedIdRef.current = null;- else setGenMode(selected.chiptuneScore ? 'chiptune' : 'audio');+ else setGenMode(initialGenMode(selected));}}, [selectionKey, isCreate, selected, loading]);@@ -172,6 +183,22 @@ export default function TracksManager() {});};+ // A chiptune/drawn generator updated the persisted track (score, drawing, or+ // a new take): refresh the list and mirror the active audio pointer onto the+ // open form without touching the user's unsaved edits.+ const applyGeneratorUpdate = (updated) => {+ upsertLocal(updated); // list update is id-keyed → always safe+ if (selectedIdRef.current === updated.id) {+ setForm((f) => ({ ...f, audioFilename: updated.audioFilename || f.audioFilename }));+ }+ };++ const genModes = [+ ['audio', 'Audio model'],+ ['chiptune', 'Chiptune score'],+ ...(persisted?.waveSketch ? [['drawn', 'Drawn waveform']] : []),+ ];+const persistForm = async () => {const title = form.title.trim();if (!title) { toast.error('Track title is required'); return null; }@@ -348,8 +375,15 @@ 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.+ // A drawn-waveform take remixes in the editor's drawn mode, on the track's+ // stored sketch, seeded with the description the take was rendered from.+ if (render.engine === 'waveform' && persisted?.waveSketch) {+ setGenMode('drawn');+ if (render.prompt) setForm((f) => ({ ...f, prompt: render.prompt }));+ return;+ }+ // A drawn take from before the sketch was stored on the track (#8376) has+ // nothing to reopen here — send it to the Music Designer's drawn engine.if (render.engine === 'waveform' && persisted) {navigate(`/music/generate/render?trackId=${encodeURIComponent(persisted.id)}&engine=drawn`);return;@@ -517,15 +551,16 @@ export default function TracksManager() {/></Field>- {/* Generation — two modes: the on-device audio models- (MusicGen/AudioLDM2/ACE-Step) and the LLM-composed looping- chiptune score (#2911).+ {/* Generation — the on-device audio models (MusicGen/AudioLDM2/+ ACE-Step), the LLM-composed looping chiptune score (#2911),+ and, for a track drawn in the Music Designer, its stored wave+ sketch (#8376) to revise and re-render.Audio-model generation can create a standalone track directly;chiptune composition still needs a persisted score record. */}<div className="space-y-2"><div className="inline-flex rounded-lg border border-port-border overflow-hidden text-sm" role="group" aria-label="Generation mode">- {[['audio', 'Audio model'], ['chiptune', 'Chiptune score']].map(([mode, label]) => (+ {genModes.map(([mode, label]) => (<buttonkey={mode}type="button"@@ -541,18 +576,21 @@ export default function TracksManager() {<p className="text-xs text-gray-500">Save the track first, then generate a chiptune score.</p>+ ) : genMode === 'drawn' && persisted?.waveSketch ? (+ <TrackWaveformHost+ track={persisted}+ description={form.prompt}+ lyrics={form.lyrics}+ title={form.title}+ onTrackUpdate={applyGeneratorUpdate}+ />) : genMode === 'chiptune' ? (<ChiptunePaneltrack={persisted}sourcePrompt={form.prompt}sourceLyrics={form.lyrics}remix={chiptuneRemix}- onTrackUpdate={(updated) => {- upsertLocal(updated); // list update is id-keyed → always safe- if (selectedIdRef.current === updated.id) {- setForm((f) => ({ ...f, audioFilename: updated.audioFilename || f.audioFilename }));- }- }}+ onTrackUpdate={applyGeneratorUpdate}/>) : (<MusicGenPaneldiff --git a/client/src/components/music/TracksManager.test.jsx b/client/src/components/music/TracksManager.test.jsxindex c2a1402f50..e3c043b6db 100644--- a/client/src/components/music/TracksManager.test.jsx+++ b/client/src/components/music/TracksManager.test.jsx@@ -4,6 +4,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const musicGenProps = vi.hoisted(() => ({ current: null }));const chiptuneProps = vi.hoisted(() => ({ current: null }));+const waveformProps = vi.hoisted(() => ({ current: null }));// Stub the heavy children — this suite pins the MIDI read-through wiring// (#2477 follow-up), not the editor/generation internals.@@ -16,6 +17,10 @@ vi.mock('./ChiptunePanel', () => ({ default: (props) => {chiptuneProps.current = props;return <div data-testid="chiptune-panel" />;} }));+vi.mock('./TrackWaveformHost', () => ({ default: (props) => {+ waveformProps.current = props;+ return <div data-testid="waveform-panel" />;+} }));vi.mock('./TrackRenderCard', () => ({ default: ({ render: item, onRemix, onSendToVideo }) => (<><button type="button" data-testid="render-card" onClick={() => onRemix(item)}>Remix {item.id}</button>@@ -261,7 +266,34 @@ describe('<TracksManager> generative workflow hand-off', () => {expect(musicGenProps.current.remix).not.toHaveProperty('instrumentalOnly');});- it('remixes a drawn-waveform take in the designer\'s drawn engine', async () => {+ it('remixes a drawn take on the track\'s stored sketch, seeded with the take\'s description', async () => {+ const waveSketch = { version: 1, title: 'Glass Tide' };+ listTracks.mockResolvedValue([{+ ...TRACK,+ prompt: 'Current source',+ waveSketch,+ renders: [{ id: 'render-drawn', audioFilename: 'drawn.wav', engine: 'waveform', prompt: 'Glassy', createdAt: '2026-01-02T00:00:00Z' }],+ }]);+ renderAt('track-1');+ await screen.findByDisplayValue('Current source');+ // An unrelated active take opens on the audio panel; the drawn mode is offered.+ expect(screen.getByTestId('gen-panel')).toBeInTheDocument();+ fireEvent.click(await screen.findByRole('button', { name: 'Remix render-drawn' }));++ expect(await screen.findByTestId('waveform-panel')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'Drawn waveform' })).toHaveAttribute('aria-pressed', 'true');+ expect(waveformProps.current.track.waveSketch).toBe(waveSketch);+ expect(waveformProps.current.description).toBe('Glassy');+ expect(screen.queryByTestId('location')).toBeNull();+ });++ it('opens a track whose active take was drawn on its drawing', async () => {+ listTracks.mockResolvedValue([{ ...TRACK, engine: 'waveform', waveSketch: { version: 1 } }]);+ renderAt('track-1');+ expect(await screen.findByTestId('waveform-panel')).toBeInTheDocument();+ });++ it('sends a drawn take with no stored sketch to 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' }],diff --git a/client/src/components/music/WaveformPanel.jsx b/client/src/components/music/WaveformPanel.jsxindex a1fad9a9e2..6c150dd6e6 100644--- a/client/src/components/music/WaveformPanel.jsx+++ b/client/src/components/music/WaveformPanel.jsx@@ -10,8 +10,12 @@* is exactly what gets saved.** The LLM call fires only from the Draw/Revise buttons (no cold-bootstrap LLM- * calls). The latest drawing is remembered per viewer in localStorage so a- * reload doesn't lose it; saving renders it into the track's render history.+ * calls). Every drawing is stored on the track (`waveSketch`, #8376), so it+ * survives reloads, syncs to the user's other machines, and reopens for+ * revision from either host: the Music Designer's drawn engine (which passes+ * only `trackId`, so the panel loads the track) or the Tracks editor's "Drawn+ * waveform" mode (which passes the loaded `track`). Saving renders the stored+ * drawing into the track's render history.*/import { memo, useEffect, useMemo, useRef, useState } from 'react';@@ -19,17 +23,18 @@ import { Brush, Loader2, Play, Save, Square, Wand2 } from 'lucide-react';import toast from '../ui/Toast';import useMounted from '../../hooks/useMounted';import useAudioSessionClaim from '../../hooks/useAudioSessionClaim';-import { getAudioContext, resumeAudioContext } from '../../lib/audioContext.js';-import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage.js';+import { createWaveSketchPlayer } from '../../lib/waveSketchPlayback.js';+import { safeRemoveStorage } from '../../lib/safeStorage.js';import { clamp, formatTimecode } from '../../utils/formatters';import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';-import { drawWaveform, renderTrackWaveform } from '../../services/api';+import { drawTrackWaveform, getTrack, renderTrackWaveform } from '../../services/api';import {- WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE,- normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,+ WAVE_SKETCH_LIMITS, normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,} from '../../../../server/lib/waveSketch.js';-const SKETCH_KEY = 'portos.musicDesigner.waveSketch';+// Before #8376 the latest drawing lived only in this per-viewer key; the track+// is now the store, so the stale key is just cleared.+const LEGACY_SKETCH_KEY = 'portos.musicDesigner.waveSketch';const DEFAULT_LENGTH_SEC = 20;const MIN_LENGTH_SEC = 4;const PEAK_COLUMNS = 600;@@ -39,13 +44,6 @@ const VOICE_COLORS = ['rgb(var(--port-accent))', 'rgb(var(--port-accent-2))', 'rconst voiceColor = (index) => VOICE_COLORS[index % VOICE_COLORS.length];const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;-// Only the most recent drawing is kept (one key, tagged with its draft track),-// re-validated on read so a stale or hand-edited entry can't break the panel.-const readStoredSketch = (trackId) => {- const stored = safeReadJsonStorage(SKETCH_KEY);- return trackId && stored?.trackId === trackId ? normalizeWaveSketch(stored.sketch) : null;-};-/** One drawn cycle, shown twice so the loop seam is visible. */function ShapeDrawing({ name, points, color, usedBy }) {const cycle = [...points, points[0]];@@ -146,11 +144,12 @@ const SketchDrawing = memo(function SketchDrawing({ sketch, peaksPath, playheadR});export default function WaveformPanel({- trackId, disabled = false, description = '', lyrics = '', title = '',- providerId, model, effort, providerPicker, onRendered,+ trackId, track, disabled = false, description = '', lyrics = '', title = '',+ providerId, model, effort, providerPicker, onRendered, onTrackUpdate,}) {const mountedRef = useMounted();- const [sketch, setSketch] = useState(() => readStoredSketch(trackId));+ // Seeded from the host's track once; hosts key the panel by track id.+ const [sketch, setSketch] = useState(() => normalizeWaveSketch(track?.waveSketch));const [guidance, setGuidance] = useState('');// Raw field text — clamped only when used, so typing "12" isn't snapped to// the minimum after its first digit.@@ -159,8 +158,7 @@ export default function WaveformPanel({const [saving, setSaving] = useState(false);const [playing, setPlaying] = useState(false);const { claim, release } = useAudioSessionClaim('playback');- const sourceRef = useRef(null);- const startedAtRef = useRef(0);+ const playerRef = useRef(null);const playheadRef = useRef(null);const elapsedRef = useRef(null);@@ -169,14 +167,19 @@ export default function WaveformPanel({? pcmPeaks(pcm, PEAK_COLUMNS).map(([min, max], x) => `M${x + 0.5} ${(50 - max * 48).toFixed(1)}V${(50 - min * 48 + 0.5).toFixed(1)}`).join(''): ''), [pcm]);+ // The Music Designer passes only the draft's id: load its stored drawing+ // (unless a draw already landed first).+ useEffect(() => {+ safeRemoveStorage(LEGACY_SKETCH_KEY);+ if (track || !trackId) return;+ getTrack(trackId, { silent: true }).then((loaded) => {+ const stored = normalizeWaveSketch(loaded?.waveSketch);+ if (stored && mountedRef.current) setSketch((current) => current ?? stored);+ }).catch(() => {});+ }, [trackId, track]);+const stop = () => {- const source = sourceRef.current;- sourceRef.current = null;- if (source) {- source.onended = null;- try { source.stop(); } catch { /* already ended */ }- source.disconnect();- }+ playerRef.current?.stop();release();if (mountedRef.current) setPlaying(false);};@@ -187,22 +190,15 @@ export default function WaveformPanel({const play = async () => {if (!pcm) return;stop();- const ctx = getAudioContext();+ playerRef.current ??= createWaveSketchPlayer({+ onEnded: () => { release(); if (mountedRef.current) setPlaying(false); },+ });claim();- const started = await resumeAudioContext(ctx).then(() => true).catch((err) => {+ const started = await playerRef.current.play(pcm).catch((err) => {console.error(`〰️ Waveform preview failed to start: ${err.message}`);return false;});- if (!started || !mountedRef.current) { release(); return; }- const buffer = ctx.createBuffer(1, pcm.length, WAVE_SKETCH_SAMPLE_RATE);- buffer.getChannelData(0).set(pcm);- const source = ctx.createBufferSource();- source.buffer = buffer;- source.connect(ctx.destination);- source.onended = () => { if (sourceRef.current === source) stop(); };- sourceRef.current = source;- startedAtRef.current = ctx.currentTime;- source.start();+ if (!started || !mountedRef.current) { playerRef.current.stop(); release(); return; }setPlaying(true);};@@ -217,7 +213,7 @@ export default function WaveformPanel({if (!playing) { paint(0); return undefined; }let raf = 0;const loop = () => {- paint(Math.max(0, getAudioContext().currentTime - startedAtRef.current));+ paint(playerRef.current?.position() ?? 0);raf = requestAnimationFrame(loop);};raf = requestAnimationFrame(loop);@@ -226,13 +222,14 @@ export default function WaveformPanel({const draw = async (mode) => {if (!description.trim()) { toast.error('Write the musical description first'); return; }+ if (!trackId) return;setDrawing(mode);- const res = await drawWaveform({+ const res = await drawTrackWaveform(trackId, {description: description.trim(),lyrics: lyrics.trim() || undefined,guidance: guidance.trim() || undefined,durationSec: clamp(Number(lengthInput) || DEFAULT_LENGTH_SEC, MIN_LENGTH_SEC, WAVE_SKETCH_LIMITS.DURATION_MAX_SEC),- ...(mode === 'revise' && sketch ? { current: sketch } : {}),+ ...(mode === 'revise' ? { revise: true } : {}),providerId: providerId || undefined,model: model || undefined,effort: effort || undefined,@@ -241,14 +238,13 @@ export default function WaveformPanel({setDrawing(null);if (!res?.sketch) return;setSketch(res.sketch);- safeWriteJsonStorage(SKETCH_KEY, { trackId, sketch: res.sketch });+ if (res.track) onTrackUpdate?.(res.track);};const save = async () => {if (!sketch || !trackId) return;setSaving(true);const res = await renderTrackWaveform(trackId, {- sketch,prompt: description.trim() || undefined,title: title.trim() || sketch.title || undefined,}, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not save the take'); return null; });@@ -301,12 +297,12 @@ export default function WaveformPanel({</div><div className="flex flex-wrap gap-2">- <button type="button" onClick={() => draw('fresh')} disabled={disabled || busy || !description.trim()} className={sketch ? GHOST_BTN : PRIMARY_BTN}>+ <button type="button" onClick={() => draw('fresh')} disabled={disabled || busy || !trackId || !description.trim()} className={sketch ? GHOST_BTN : PRIMARY_BTN}>{drawing === 'fresh' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Brush className="h-4 w-4" />}<span>{drawing === 'fresh' ? 'Drawing…' : sketch ? 'Draw from scratch' : 'Draw it'}</span></button>{sketch && (- <button type="button" onClick={() => draw('revise')} disabled={disabled || busy || !description.trim()} className={PRIMARY_BTN}>+ <button type="button" onClick={() => draw('revise')} disabled={disabled || busy || !trackId || !description.trim()} className={PRIMARY_BTN}>{drawing === 'revise' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />}<span>{drawing === 'revise' ? 'Revising…' : 'Revise drawing'}</span></button>diff --git a/client/src/components/music/WaveformPanel.test.jsx b/client/src/components/music/WaveformPanel.test.jsxindex b39a9256cc..f5058e5d84 100644--- a/client/src/components/music/WaveformPanel.test.jsx+++ b/client/src/components/music/WaveformPanel.test.jsx@@ -4,7 +4,8 @@ import WaveformPanel from './WaveformPanel';import * as api from '../../services/api';vi.mock('../../services/api', () => ({- drawWaveform: vi.fn(),+ drawTrackWaveform: vi.fn(),+ getTrack: vi.fn(),renderTrackWaveform: vi.fn(),}));@@ -57,20 +58,27 @@ describe('<WaveformPanel>', () => {window.localStorage.clear();audio.sources = [];vi.stubGlobal('AudioContext', FakeAudioContext);- api.drawWaveform.mockResolvedValue({ sketch: drawn, llm: { provider: 'provider-a', model: 'model-a' } });+ // The server stores what it drew; getTrack serves it back (a reload).+ const stored = new Map();+ api.drawTrackWaveform.mockImplementation(async (trackId) => {+ stored.set(trackId, drawn);+ return { sketch: drawn, llm: { provider: 'provider-a', model: 'model-a' }, track: { id: trackId, waveSketch: drawn } };+ });+ api.getTrack.mockImplementation(async (trackId) => ({ id: trackId, waveSketch: stored.get(trackId) ?? null }));api.renderTrackWaveform.mockResolvedValue({ track: { id: 'track-1' }, filename: 'music-x.wav', durationSec: 1 });});afterEach(() => { cleanup(); vi.unstubAllGlobals(); });- it('draws from the description with the chosen provider, shows the drawing, and remembers it', async () => {- renderPanel();+ it('draws from the description with the chosen provider, stores it on the track, and reloads it', async () => {+ const onTrackUpdate = vi.fn();+ renderPanel({ onTrackUpdate });expect(screen.getByText(/Nothing drawn yet/)).toBeTruthy();fireEvent.change(screen.getByLabelText('Drawing guidance (optional)'), { target: { value: 'lots of glide' } });fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));await screen.findByText('Glass Tide');- expect(api.drawWaveform).toHaveBeenCalledWith({+ expect(api.drawTrackWaveform).toHaveBeenCalledWith('track-1', {description: 'glassy tidal ambient',lyrics: undefined,guidance: 'lots of glide',@@ -81,40 +89,51 @@ describe('<WaveformPanel>', () => {}, { silent: true });expect(screen.getByTestId('waveform-shapes').textContent).toContain('glass');expect(screen.getByText(/2 voices · 2 strokes/)).toBeTruthy();+ expect(onTrackUpdate).toHaveBeenCalledWith({ id: 'track-1', waveSketch: drawn });- // A remount (reload) of the same draft restores the drawing without a call.+ // A remount (reload) of the same draft loads the stored drawing — no LLM call.cleanup();renderPanel();- expect(screen.getByText('Glass Tide')).toBeTruthy();- expect(api.drawWaveform).toHaveBeenCalledTimes(1);+ await screen.findByText('Glass Tide');+ expect(api.drawTrackWaveform).toHaveBeenCalledTimes(1);// …but a different draft starts blank.cleanup();renderPanel({ trackId: 'track-2' });+ await waitFor(() => expect(api.getTrack).toHaveBeenCalledWith('track-2', { silent: true }));expect(screen.getByText(/Nothing drawn yet/)).toBeTruthy();});+ it('opens on the host track\'s stored drawing without fetching', () => {+ renderPanel({ track: { id: 'track-1', waveSketch: drawn } });+ expect(screen.getByText('Glass Tide')).toBeTruthy();+ expect(screen.getByRole('button', { name: /Revise drawing/ })).toBeTruthy();+ expect(api.getTrack).not.toHaveBeenCalled();+ });+it('sends the typed length, clamped to the supported range', async () => {renderPanel();const length = screen.getByLabelText('Length (sec)');fireEvent.change(length, { target: { value: '1' } });fireEvent.change(length, { target: { value: '12' } });fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));- await waitFor(() => expect(api.drawWaveform).toHaveBeenCalledTimes(1));- expect(api.drawWaveform.mock.calls[0][0].durationSec).toBe(12);+ await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(1));+ expect(api.drawTrackWaveform.mock.calls[0][1].durationSec).toBe(12);fireEvent.change(length, { target: { value: '999' } });fireEvent.click(await screen.findByRole('button', { name: /Draw from scratch/ }));- await waitFor(() => expect(api.drawWaveform).toHaveBeenCalledTimes(2));- expect(api.drawWaveform.mock.calls[1][0].durationSec).toBe(60);+ await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(2));+ expect(api.drawTrackWaveform.mock.calls[1][1].durationSec).toBe(60);});- it('revises by sending the current drawing back', async () => {+ it('revises the stored drawing (the server holds it, so only the intent is sent)', async () => {renderPanel();fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));fireEvent.click(await screen.findByRole('button', { name: /Revise drawing/ }));- await waitFor(() => expect(api.drawWaveform).toHaveBeenCalledTimes(2));- expect(api.drawWaveform.mock.calls[1][0].current).toEqual(drawn);+ await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(2));+ expect(api.drawTrackWaveform.mock.calls[0][1].revise).toBeUndefined();+ expect(api.drawTrackWaveform.mock.calls[1][1]).toMatchObject({ revise: true });+ expect(api.drawTrackWaveform.mock.calls[1][1].current).toBeUndefined();});it('plays and stops the synthesized drawing', async () => {@@ -132,7 +151,7 @@ describe('<WaveformPanel>', () => {expect(screen.getByRole('button', { name: /Play drawing/ })).toBeTruthy();});- it('saves the drawing as a take, titled from the drawing when the user gave none', async () => {+ it('saves the stored drawing as a take, titled from the drawing when the user gave none', async () => {const onRendered = vi.fn();renderPanel({ onRendered });fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));@@ -140,7 +159,7 @@ describe('<WaveformPanel>', () => {await waitFor(() => expect(onRendered).toHaveBeenCalledWith({ id: 'track-1' }));expect(api.renderTrackWaveform).toHaveBeenCalledWith('track-1', {- sketch: drawn, prompt: 'glassy tidal ambient', title: 'Glass Tide',+ prompt: 'glassy tidal ambient', title: 'Glass Tide',}, { silent: true });});});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3e0fcabde3..3ee1b714d6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -199,6 +199,7 @@ grep -i "what you want to do" client/src/lib/README.md| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. || `wireframeCore.js` | The Kestrel Neon "core assembly": icosahedron geometry (`ICOSAHEDRON_VERTICES` / `ICOSAHEDRON_EDGES`, 12 vertices, 30 edges), `rotatePoint` / `projectIcosahedron` (Y-then-X rotation + perspective), and `drawWireframeCore(ctx, frame)` — one 2D-canvas frame of the depth-shaded wireframe with its orbit rings, vertex dots, and corner angle readout. Every color is an `[r, g, b]` triple so the caller sources them from `AGENT_STATES` and resolved theme tokens; no DOM reads. Consumed by `cos/CoreCoSAvatar.jsx`. || `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing `position()` (monotonic across loop passes) + `loopSec()` for playhead UIs. No React — `ChiptunePanel` drives it. |+| `waveSketchPlayback.js` | One-shot WebAudio preview for the Music Designer's LLM-drawn wave sketches (#8376) — `createWaveSketchPlayer({ onEnded })` → `{ play(pcm), stop(), position() }` over the shared `audioContext.js` context. Plays PCM from `synthesizeWaveSketch` (`server/lib/waveSketch.js`, the same deterministic synth the server renders the saved take with); a `stop()` during the resume makes `play` resolve false instead of sounding late. No React — `WaveformPanel` drives it in both the Music Designer and the Tracks editor. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 17160d1d55..9ab51bcd4e 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -157,6 +157,7 @@ export * from './audioContext.js';export * from './canvasRoll.js';export * from './wireframeCore.js';export * from './chiptunePlayback.js';+export * from './waveSketchPlayback.js';export * from './chordPlayback.js';export * from './chordShapes.js';export * from './colorMatch.js';diff --git a/client/src/lib/waveSketchPlayback.js b/client/src/lib/waveSketchPlayback.jsnew file mode 100644index 0000000000..55288502cf--- /dev/null+++ b/client/src/lib/waveSketchPlayback.js@@ -0,0 +1,64 @@+// One-shot WebAudio preview for the Music Designer's LLM-drawn wave sketches+// (#8376). The PCM comes from `synthesizeWaveSketch` in+// server/lib/waveSketch.js — the same deterministic synth the server renders a+// saved take with — so what plays here is exactly what gets saved.+//+// No React: `WaveformPanel` drives it, whichever host mounts the panel (the+// Music Designer's drawn engine or the Tracks editor's "Drawn waveform" mode).+// The host owns the iOS audio-session claim (`useAudioSessionClaim`).++import { getAudioContext, resumeAudioContext } from './audioContext.js';+import { WAVE_SKETCH_SAMPLE_RATE } from '../../../server/lib/waveSketch.js';++/**+ * A single-source player for synthesized sketch PCM.+ *+ * - `play(pcm)` → Promise<boolean>: stops any current playback, resumes the+ * shared context, and starts the buffer. Resolves false when a `stop()` (or+ * a newer `play`) landed while the context was resuming, so a stale start+ * never sounds. Rejects when the context cannot resume.+ * - `stop()` silences and releases the current source (idempotent).+ * - `position()` → seconds since the current playback started (0 when idle).+ * - `onEnded` fires when a buffer plays through to its end (not on `stop()`).+ */+export function createWaveSketchPlayer({ onEnded } = {}) {+ let source = null;+ let startedAt = 0;+ let generation = 0;++ const stop = () => {+ generation += 1;+ const current = source;+ source = null;+ if (!current) return;+ current.onended = null;+ try { current.stop(); } catch { /* already ended */ }+ current.disconnect();+ };++ const play = async (pcm) => {+ stop();+ const token = generation;+ const ctx = getAudioContext();+ await resumeAudioContext(ctx);+ if (token !== generation) return false;+ const buffer = ctx.createBuffer(1, pcm.length, WAVE_SKETCH_SAMPLE_RATE);+ buffer.getChannelData(0).set(pcm);+ const node = ctx.createBufferSource();+ node.buffer = buffer;+ node.connect(ctx.destination);+ node.onended = () => {+ if (source !== node) return;+ stop();+ onEnded?.();+ };+ source = node;+ startedAt = ctx.currentTime;+ node.start();+ return true;+ };++ const position = () => (source ? Math.max(0, getAudioContext().currentTime - startedAt) : 0);++ return { play, stop, position };+}diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.jsindex bafc4871ec..879486c511 100644--- a/client/src/services/apiMusic.js+++ b/client/src/services/apiMusic.js@@ -46,17 +46,6 @@ export const generateLyrics = (body, requestOptions = {}) => request('/music/lyr...requestOptions,});-// Have the LLM DRAW the music as a wave sketch (server/lib/waveSketch.js):-// single-cycle waveforms + timed strokes the browser synthesizes directly.-// body: { description, lyrics?, guidance?, durationSec?, current? (sketch to-// revise), providerId?, model?, effort? }-// → { sketch, llm: { provider, model } }-export const drawWaveform = (body, requestOptions = {}) => request('/music/waveform', {- method: 'POST',- body: JSON.stringify(body),- ...requestOptions,-});-// Have the LLM write the piece as Strudel code (the Music Designer's code// engine). Nothing runs server-side; the browser plays it in a sandboxed frame.// body: { description, lyrics?, guidance?, current? (code to revise),diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.jsindex b32ae1e98e..5cab9b3bc6 100644--- a/client/src/services/apiTracks.js+++ b/client/src/services/apiTracks.js@@ -104,9 +104,18 @@ export const publishTrackChiptune = (id, body, requestOptions = {}) => request(`...requestOptions,});-// Render a drawn-waveform sketch (the Music Designer's LLM-drawn engine) into-// the shared music library as the track's active take.-// `body`: { sketch, prompt?, title? } → { track, filename, durationSec }.+// Have the LLM DRAW the music as a wave sketch (server/lib/waveSketch.js) and+// store it on the track (`waveSketch`/`waveSketchPrompt`, #8376).+// `body`: { description, lyrics?, guidance?, durationSec?, revise? (redraw the+// stored sketch), providerId?, model?, effort? } → { sketch, llm, track }.+export const drawTrackWaveform = (id, body, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/waveform/draw`, {+ method: 'POST',+ body: JSON.stringify(body),+ ...requestOptions,+});++// Render the track's STORED wave sketch into the shared music library as the+// track's active take. `body`: { prompt?, title? } → { track, filename, durationSec }.export const renderTrackWaveform = (id, body, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/waveform/render`, {method: 'POST',body: JSON.stringify(body),diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex a6d47bfd84..2b21048d88 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -126,9 +126,12 @@ const HASH_FIELDS = Object.freeze({// cares about, and vice versa).// v4: concept, the user-authored creative brief used by resumable music// designer drafts.+ // v7 (#8376): waveSketch/waveSketchPrompt, the Music Designer's drawn wave+ // sketch — hashed only for bases stamped at v7+.track: Object.freeze({3: Object.freeze(['chiptuneScore', 'chiptunePrompt']),4: Object.freeze(['concept']),+ 7: Object.freeze(['waveSketch', 'waveSketchPrompt']),}),});@@ -504,8 +507,9 @@ export const RESTORABLE_FIELDS = Object.freeze({// `chiptuneScore`/`chiptunePrompt` (#2911) are also restorable and, as of// #2912, DO participate in the content hash via the version-gated HASH_FIELDS// mechanism (see above) — a base hash predating the field just compares at- // its own stored version until the next sync re-stamps it.- track: ['title', 'albumId', 'artistId', 'artist', 'concept', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders', 'chiptuneScore', 'chiptunePrompt'],+ // its own stored version until the next sync re-stamps it. Same for+ // `waveSketch`/`waveSketchPrompt` (#8376, hashed from v7).+ track: ['title', 'albumId', 'artistId', 'artist', 'concept', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders', 'chiptuneScore', 'chiptunePrompt', 'waveSketch', 'waveSketchPrompt'],// Issue: the user-authored content the merge can restore. `stages` carries// the bulk of the work (prose, comic pages, render metadata). Server-owned /// structural fields are excluded deliberately — `number` is renumber-managed,diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 5ced5c43a7..bdb275b299 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -287,7 +287,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// the ambiguous render back and make a later remix silently change vocal mode.// tracks v6 = render history entries preserve the effective generation// executionProfile. Older peers would strip the measured placement on sync.- tracks: 6,+ // tracks v7 = `track.waveSketch`/`waveSketchPrompt` (#8376, the Music+ // Designer's LLM-drawn wave sketch). Same strip-and-push-back reason as v3:+ // a <=v6 peer's sketch-unaware sanitizer would drop the drawing and LWW the+ // loss back. The accepted sender-behind direction is covered by the+ // absent-key carry in services/tracks/logic.js mergeTrackRecord.+ tracks: 7,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index thediff --git a/server/routes/music.js b/server/routes/music.jsindex f2780968af..b4f041de22 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -368,8 +368,9 @@ const waveformSchema = z.object({...designerPickerShape,}).omit({ template: true });-// POST /api/music/waveform — have the LLM DRAW the music: single-cycle-// waveforms plus timed strokes, previewed and rendered by lib/waveSketch.js.+// POST /api/music/waveform — stateless: have the LLM DRAW the music (single-cycle+// waveforms plus timed strokes, lib/waveSketch.js) without storing it. The+// designer draws via POST /api/tracks/:id/waveform/draw, which persists it.// One explicit user action per call.router.post('/waveform', asyncHandler(async (req, res) => {const body = validateRequest(waveformSchema, req.body ?? {});diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex c74491d5cd..88ff5743f1 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -15,6 +15,7 @@* POST /api/tracks/:id/audio/upload → Track (multipart 'track' file)* POST /api/tracks/:id/audio/attach → Track (attach a library filename)* DELETE /api/tracks/:id/audio → Track (clear the audio pointer)+ * POST /api/tracks/:id/waveform/draw → { sketch, llm, track } (LLM-drawn sketch, stored on the track)* POST /api/tracks/:id/waveform/render → { track, filename, durationSec } (drawn-waveform take)* POST /api/tracks/:id/code/render → { track, filename, durationSec } (multipart 'track' WAV recorded from code)*@@ -46,7 +47,8 @@ import {} from '../services/trackYoutubeImport.js';import { YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE } from '../lib/youtubeUrl.js';import { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack } from '../services/chiptune.js';-import { renderWaveSketchToTrack } from '../services/musicWaveform.js';+import { drawWaveSketchForTrack, renderWaveSketchToTrack } from '../services/musicWaveform.js';+import { WAVE_SKETCH_LIMITS } from '../lib/waveSketch.js';import { saveCodeTakeToTrack } from '../services/musicCode.js';const router = Router();@@ -291,15 +293,33 @@ router.post('/:id/chiptune/publish', asyncHandler(async (req, res) => {}));// --- Drawn waveform takes — the Music Designer's LLM-drawn sketch-// (server/lib/waveSketch.js), rendered with the same deterministic synth the-// browser previewed. The sketch travels in the body; it is not stored on the-// track.+// (server/lib/waveSketch.js). `draw` persists the sketch on the track+// (`waveSketch`/`waveSketchPrompt`, #8376); `render` renders that STORED sketch+// with the same deterministic synth the browser previewed. Drawing is one+// explicit user action per call (AI Provider Usage Policy).+const optionalPick = (max) => z.string().max(max).optional().transform((v) => v?.trim() || undefined);+const waveformDrawSchema = z.object({+ description: z.string().trim().min(1, 'description is required').max(tracks.PROMPT_MAX),+ lyrics: z.string().trim().max(tracks.LYRICS_MAX).optional(),+ guidance: z.string().trim().max(4000).optional(),+ durationSec: z.number().min(WAVE_SKETCH_LIMITS.DURATION_MIN_SEC).max(WAVE_SKETCH_LIMITS.DURATION_MAX_SEC).optional(),+ // true = revise the track's stored drawing instead of drawing from scratch.+ revise: z.boolean().optional(),+ providerId: optionalPick(128),+ model: optionalPick(256),+ effort: optionalPick(64),+});+const waveformRenderSchema = z.object({- sketch: z.record(z.string(), z.unknown()),prompt: z.string().trim().max(tracks.PROMPT_MAX).optional(),title: z.string().trim().max(200).optional(),});+router.post('/:id/waveform/draw', asyncHandler(async (req, res) => {+ const body = validateRequest(waveformDrawSchema, req.body ?? {});+ res.json(await drawWaveSketchForTrack({ trackId: req.params.id, ...body }));+}));+router.post('/:id/waveform/render', asyncHandler(async (req, res) => {const body = validateRequest(waveformRenderSchema, req.body ?? {});res.json(await renderWaveSketchToTrack({ trackId: req.params.id, ...body }));diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex f413f1c2ce..dec6ffe8df 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -15,6 +15,12 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const actual = await importOriginal();return { ...actual, PATHS: { ...actual.PATHS, music: musicDir } };});+// The drawn-waveform draw route runs one LLM call — stub the provider seam.+vi.mock('../services/promptRunner.js', async () => ({+ ...(await vi.importActual('../services/promptRunner.js')),+ resolveProviderAndModel: vi.fn(async () => ({ provider: { id: 'prov-1', type: 'api' }, selectedModel: 'model-x' })),+ runPromptThroughProvider: vi.fn(),+}));vi.mock('../lib/ffmpeg.js', () => ({findFfmpeg: vi.fn().mockResolvedValue(null),runFfmpegProcess: vi.fn(),@@ -85,6 +91,7 @@ import * as albums from '../services/albums/index.js';import { TRACK_IDS_MAX } from '../services/albums/logic.js';import * as ytImport from '../services/trackYoutubeImport.js';import { errorMiddleware } from '../lib/errorHandler.js';+import * as promptRunner from '../services/promptRunner.js';import tracksRoutes from './tracks.js';function makeApp() {@@ -416,4 +423,39 @@ describe('tracks routes', () => {expect(r.status).toBe(404);});});++ describe('drawn waveform (#8376)', () => {+ const sketch = {+ version: 1, title: 'Glass Tide', durationSec: 2,+ shapes: { glass: [0, 0.8, 1, 0.3, 0, -0.5, -1, -0.2] },+ voices: [{ name: 'lead', shape: 'glass', notes: [{ t: 0, d: 1, pitch: 'A4' }] }],+ };++ it('POST /:id/waveform/draw persists the drawing on the track', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(sketch) });+ const r = await request(app).post('/api/tracks/track-1/waveform/draw')+ .send({ description: 'glassy tidal ambient', durationSec: 12, revise: true, providerId: '' });+ expect(r.status).toBe(200);+ expect(r.body.sketch).toMatchObject({ title: 'Glass Tide' });+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({+ waveSketch: expect.objectContaining({ title: 'Glass Tide' }), waveSketchPrompt: 'glassy tidal ambient',+ }));+ expect(r.body.track.waveSketchPrompt).toBe('glassy tidal ambient');+ });++ it('POST /:id/waveform/draw requires a description', async () => {+ const r = await request(app).post('/api/tracks/track-1/waveform/draw').send({});+ expect(r.status).toBe(400);+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('POST /:id/waveform/render renders the stored drawing, never a client-supplied one', async () => {+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [], waveSketch: null });+ const r = await request(app).post('/api/tracks/track-1/waveform/render').send({ sketch });+ expect(r.status).toBe(400);+ expect(r.body.code).toBe('WAVEFORM_EMPTY');+ expect(tracks.appendActiveTake).not.toHaveBeenCalled();+ });+ });});diff --git a/server/services/musicWaveform.js b/server/services/musicWaveform.jsindex 9c6b5be6db..67ec101fc3 100644--- a/server/services/musicWaveform.js+++ b/server/services/musicWaveform.js@@ -3,9 +3,14 @@** drawWaveSketch() musical description → a wave sketch the LLM drew* point by point (lib/waveSketch.js contract).- * renderWaveSketchToTrack() a (client round-tripped) sketch → WAV/OGG in the- * shared music library, appended to the track's- * render history as an `engine: 'waveform'` take.+ * Stateless (POST /api/music/waveform).+ * drawWaveSketchForTrack() the same, persisted on the track as+ * `waveSketch`/`waveSketchPrompt` (#8376) so the+ * drawing survives reloads, syncs to the user's+ * other machines, and can be revised later.+ * renderWaveSketchToTrack() the track's STORED sketch → WAV in the shared+ * music library, appended to the track's render+ * history as an `engine: 'waveform'` take.** The browser previews the same sketch with the same deterministic synth* (`synthesizeWaveSketch`), so the saved take is exactly what was auditioned.@@ -118,23 +123,43 @@ export async function drawWaveSketch({ description, lyrics, guidance, durationSereturn { sketch, llm: { provider: run.provider?.id || provider.id, model: ranModel } };}+const requireTrack = async (trackId) => {+ const track = await tracks.getTrack(trackId);+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });+ return track;+};+/**- * Render a sketch into the shared music library and make it the track's active- * take (same render-history contract as the chiptune and diffusion engines).+ * Draw (or, with `revise`, redraw the track's stored sketch) and persist the+ * result on the track. The description it was drawn from is kept alongside as+ * `waveSketchPrompt` so a remix reopens with the same brief.*/-export async function renderWaveSketchToTrack({ trackId, sketch, prompt, title }) {- const normalized = normalizeWaveSketch(sketch);+export async function drawWaveSketchForTrack({ trackId, revise = false, ...params }) {+ const track = await requireTrack(trackId);+ const current = revise ? track.waveSketch : null;+ const { sketch, llm } = await drawWaveSketch({ ...params, current });+ const updated = await tracks.updateTrack(trackId, { waveSketch: sketch, waveSketchPrompt: trimTo(params.description, MAX_DESCRIPTION) });+ return { sketch: updated.waveSketch, llm, track: updated };+}++/**+ * Render the track's stored sketch into the shared music library and make it+ * the track's active take (same render-history contract as the chiptune and+ * diffusion engines). The server renders what it stored, never a+ * client-supplied drawing, so the take always matches the persisted sketch.+ */+export async function renderWaveSketchToTrack({ trackId, prompt, title }) {+ const track = await requireTrack(trackId);+ const normalized = track.waveSketch;if (!normalized) {- throw new ServerError('That waveform drawing has nothing playable in it', { status: 400, code: 'WAVEFORM_EMPTY' });+ throw new ServerError('This track has no drawing to render yet — draw one first', { status: 400, code: 'WAVEFORM_EMPTY' });}- const track = await tracks.getTrack(trackId);- if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });const wav = pcmToWavBuffer(synthesizeWaveSketch(normalized), { sampleRate: WAVE_SKETCH_SAMPLE_RATE });const filename = await writeWavAudioFile(wav, PATHS.music, `music-${randomUUID()}`);const durationSec = Math.max(1, Math.round(normalized.durationSec));const updated = await tracks.appendActiveTake(trackId, {- audioFilename: filename, prompt: prompt || track.prompt, engine: WAVEFORM_ENGINE, durationSec,+ audioFilename: filename, prompt: prompt || track.waveSketchPrompt || 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 take (${durationSec}s)`);diff --git a/server/services/musicWaveform.test.js b/server/services/musicWaveform.test.jsindex e529f3b1a8..27e8d231f8 100644--- a/server/services/musicWaveform.test.js+++ b/server/services/musicWaveform.test.js@@ -7,6 +7,7 @@ const musicDir = await mkdtemp(join(tmpdir(), 'waveform-music-'));vi.mock('./tracks/index.js', () => ({getTrack: vi.fn(),+ updateTrack: vi.fn(async (id, patch) => ({ id, ...patch })),appendActiveTake: vi.fn(async (id, take, patch) => ({ id, ...take, ...patch })),}));@@ -29,7 +30,8 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const tracks = await import('./tracks/index.js');const promptRunner = await import('./promptRunner.js');-const { drawWaveSketch, renderWaveSketchToTrack } = await import('./musicWaveform.js');+const { drawWaveSketch, drawWaveSketchForTrack, renderWaveSketchToTrack } = await import('./musicWaveform.js');+const { normalizeWaveSketch } = await import('../lib/waveSketch.js');const drawnSketch = () => ({version: 1,@@ -81,11 +83,44 @@ describe('drawWaveSketch', () => {});});-describe('renderWaveSketchToTrack', () => {- it('renders the drawing into the music library as the active waveform take', async () => {+describe('drawWaveSketchForTrack', () => {+ it('persists the drawing and its description on the track', async () => {tracks.getTrack.mockResolvedValue(baseTrack());+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()), model: 'model-x' });++ const result = await drawWaveSketchForTrack({ trackId: 'track-1', description: 'glassy tidal ambient', revise: true });++ // No stored drawing yet, so "revise" still draws fresh.+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).not.toContain('CURRENT SKETCH');+ expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', {+ waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'glassy tidal ambient',+ });+ expect(result.sketch).toEqual(normalizeWaveSketch(drawnSketch()));+ expect(result.track).toMatchObject({ id: 'track-1', waveSketchPrompt: 'glassy tidal ambient' });+ });++ it('revises the STORED drawing, and only when asked', async () => {+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()) }));+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()) });++ await drawWaveSketchForTrack({ trackId: 'track-1', description: 'x', revise: true });+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('CURRENT SKETCH');+ await drawWaveSketchForTrack({ trackId: 'track-1', description: 'x' });+ expect(promptRunner.runPromptThroughProvider.mock.calls[1][0].prompt).not.toContain('CURRENT SKETCH');+ });- const result = await renderWaveSketchToTrack({ trackId: 'track-1', sketch: drawnSketch(), prompt: 'glassy', title: 'Glass Tide' });+ it('404s on a missing track without calling the provider', async () => {+ tracks.getTrack.mockResolvedValue(null);+ await expect(drawWaveSketchForTrack({ trackId: 'gone', description: 'x' })).rejects.toMatchObject({ status: 404 });+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();+ });+});++describe('renderWaveSketchToTrack', () => {+ it('renders the stored drawing into the music library as the active waveform take', async () => {+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'drawn from this' }));++ const result = await renderWaveSketchToTrack({ trackId: 'track-1', prompt: 'glassy', title: 'Glass Tide' });expect(result.filename).toMatch(/^music-.+\.wav$/);expect(await readdir(musicDir)).toContain(result.filename);@@ -97,12 +132,18 @@ describe('renderWaveSketchToTrack', () => {expect(result.track).toMatchObject({ engine: 'waveform', title: 'Glass Tide' });});- it('400s on an empty drawing and 404s on a missing track', async () => {- tracks.getTrack.mockResolvedValue(baseTrack());- await expect(renderWaveSketchToTrack({ trackId: 'track-1', sketch: { voices: [] } }))+ it('defaults the take prompt to the description the drawing came from', async () => {+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'drawn from this' }));+ await renderWaveSketchToTrack({ trackId: 'track-1' });+ expect(tracks.appendActiveTake.mock.calls[0][1]).toMatchObject({ prompt: 'drawn from this' });+ });++ it('400s when the track has no drawing and 404s on a missing track', async () => {+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: null }));+ await expect(renderWaveSketchToTrack({ trackId: 'track-1' })).rejects.toMatchObject({ status: 400, code: 'WAVEFORM_EMPTY' });tracks.getTrack.mockResolvedValue(null);- await expect(renderWaveSketchToTrack({ trackId: 'gone', sketch: drawnSketch() }))+ await expect(renderWaveSketchToTrack({ trackId: 'gone' })).rejects.toMatchObject({ status: 404 });expect(tracks.appendActiveTake).not.toHaveBeenCalled();});diff --git a/server/services/tracks/file.test.js b/server/services/tracks/file.test.jsindex 438448f086..191f517b33 100644--- a/server/services/tracks/file.test.js+++ b/server/services/tracks/file.test.js@@ -30,14 +30,14 @@ function reset() {const journalEntries = () => cj.conflictJournalStore().loadAll();-// chiptuneScore/chiptunePrompt default to sanitizeTrack's own untouched shape+// chiptuneScore/chiptunePrompt/waveSketch/waveSketchPrompt default to sanitizeTrack's own untouched shape// (null/'') so a fixture that omits them hashes identically to what// mergeTracksFromSync actually persists (the fields participate in the// content hash as of #2912 — see conflictJournal.js HASH_FIELDS).const track = (id, extra = {}) => ({id, title: id, albumId: '', artistId: '', artist: '', concept: '', lyrics: '', prompt: '',engine: '', modelId: '', durationSec: null, audioFilename: '',- chiptuneScore: null, chiptunePrompt: '',+ chiptuneScore: null, chiptunePrompt: '', waveSketch: null, waveSketchPrompt: '',createdAt: '2026-01-01T00:00:00.000Z', updatedAt: '2026-01-01T00:00:00.000Z',deleted: false, deletedAt: null, ...extra,});diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 794a75ba37..59ff0a0fc4 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -29,6 +29,11 @@* modelId, executionProfile, durationSec, createdAt }`. The* top-level `audioFilename`/`engine`/`modelId`/`durationSec`* point at whichever render is currently ACTIVE (selected).+ * - chiptuneScore / chiptunePrompt — the LLM-composed looping 8-bit score+ * and the brief it was composed from (#2911), or null / ''+ * - waveSketch / waveSketchPrompt — the Music Designer's LLM-drawn wave+ * sketch (lib/waveSketch.js) and the description it was+ * drawn from (#8376), or null / ''** Tracks are `db-primary` (PostgreSQL `tracks` table). The audio bytes live in* the shared music library (services/pipeline/musicLibrary.js, `data/music/`);@@ -40,6 +45,7 @@import { compareNewerWins } from '../../lib/lwwTimestamp.js';import { sanitizeChiptuneScore } from '../../lib/chiptuneScore.js';+import { normalizeWaveSketch } from '../../lib/waveSketch.js';import { isStr, trimTo } from '../../lib/textUtils.js';export const TRACK_ID_RE = /^track-[A-Za-z0-9-]{1,64}$/;@@ -188,6 +194,11 @@ export function sanitizeTrack(raw) {// "no score", never to a half-valid object the renderer would trip on).chiptuneScore: sanitizeChiptuneScore(raw.chiptuneScore),chiptunePrompt: trimTo(raw.chiptunePrompt, PROMPT_MAX),+ // Drawn wave sketch (#8376): same sentinel rule — null = no drawing, and an+ // invalid stored/synced value normalizes to null rather than a sketch the+ // synth would trip on.+ waveSketch: normalizeWaveSketch(raw.waveSketch),+ waveSketchPrompt: trimTo(raw.waveSketchPrompt, PROMPT_MAX),createdAt,updatedAt,deleted,@@ -286,7 +297,7 @@ export function deleteRenderPatch(current, renderId) {// generic create/patch route schemas omit it so a client can't inject history.const PATCHABLE = ['title', 'albumId', 'artistId', 'artist', 'concept', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename', 'renders',- 'chiptuneScore', 'chiptunePrompt',+ 'chiptuneScore', 'chiptunePrompt', 'waveSketch', 'waveSketchPrompt',];/**@@ -311,6 +322,9 @@ export function mergeTrackRecord(local, remoteRaw) {if (!('concept' in remoteRaw) && local.concept) carry.concept = local.concept;if (!('chiptuneScore' in remoteRaw) && local.chiptuneScore) carry.chiptuneScore = local.chiptuneScore;if (!('chiptunePrompt' in remoteRaw) && local.chiptunePrompt) carry.chiptunePrompt = local.chiptunePrompt;+ // Same for the drawn wave sketch (#8376): a ≤v6 peer's payload lacks the keys.+ if (!('waveSketch' in remoteRaw) && local.waveSketch) carry.waveSketch = local.waveSketch;+ if (!('waveSketchPrompt' in remoteRaw) && local.waveSketchPrompt) carry.waveSketchPrompt = local.waveSketchPrompt;if (Object.keys(carry).length) next = { ...remote, ...carry };}const changed = JSON.stringify(next) !== JSON.stringify(local);diff --git a/server/services/tracks/logic.test.js b/server/services/tracks/logic.test.jsindex f1a4d0e50a..833eddae00 100644--- a/server/services/tracks/logic.test.js+++ b/server/services/tracks/logic.test.js@@ -247,4 +247,40 @@ describe('tracks logic', () => {expect(merged.next.chiptunePrompt).toBe('');});});++ describe('drawn wave sketch fields (#8376)', () => {+ const sketch = {+ version: 1, title: 'Glass Tide', durationSec: 2,+ shapes: { glass: [0, 0.8, 1, 0.3, 0, -0.5, -1, -0.2] },+ voices: [{ name: 'lead', shape: 'glass', notes: [{ t: 0, d: 1, pitch: 'A4' }] }],+ };+ const local = () => sanitizeTrack({+ id: 'track-1', title: 'X', waveSketch: sketch, waveSketchPrompt: 'glassy', updatedAt: '2026-01-01T00:00:00.000Z',+ });++ it('normalizes a stored sketch and sanitizes an invalid one to null', () => {+ expect(local().waveSketch).toMatchObject({ title: 'Glass Tide', voices: [{ notes: [{ hz: 440 }] }] });+ expect(local().waveSketchPrompt).toBe('glassy');+ // Nothing playable (unknown shape) and a non-object both collapse to null.+ expect(sanitizeTrack({ id: 'track-1', title: 'X', waveSketch: { voices: [{ shape: 'nope', notes: [] }] } }).waveSketch).toBeNull();+ expect(sanitizeTrack({ id: 'track-1', title: 'X', waveSketch: 'draw me' }).waveSketch).toBeNull();+ expect(sanitizeTrack({ id: 'track-1', title: 'X' })).toMatchObject({ waveSketch: null, waveSketchPrompt: '' });+ });++ it('merge keeps the local drawing when a winning v6 peer payload lacks the keys', () => {+ const merged = mergeTrackRecord(local(), { id: 'track-1', title: 'Renamed', updatedAt: '2026-02-01T00:00:00.000Z' });+ expect(merged.remoteWins).toBe(true);+ expect(merged.next.title).toBe('Renamed');+ expect(merged.next.waveSketch).toEqual(local().waveSketch);+ expect(merged.next.waveSketchPrompt).toBe('glassy');+ });++ it('merge applies an explicit remote clear', () => {+ const merged = mergeTrackRecord(local(), {+ id: 'track-1', title: 'X', waveSketch: null, waveSketchPrompt: '', updatedAt: '2026-02-01T00:00:00.000Z',+ });+ expect(merged.next.waveSketch).toBeNull();+ expect(merged.next.waveSketchPrompt).toBe('');+ });+ });});