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

feat: let the AI draw the waveform in the Music Designer

[._.]/ Adam Eivy79003744b228
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsx
index f2203c4816..b13b302162 100644
--- a/client/src/components/music/MusicDesigner.jsx
+++ b/client/src/components/music/MusicDesigner.jsx
@@ -7,7 +7,9 @@
* The user starts from a short reference/vibe ("a cross between X and Y"), an
* AI provider of their choosing expands it into a rich, genre-dense musical
* description, they optionally generate lyrics from that description plus their
- * own extra guidance, and the existing `MusicGenPanel` renders the track. Every
+ * own extra guidance, and the render step either hands it to an audio model
+ * (`MusicGenPanel`) or asks the AI to DRAW the waveform itself (`WaveformPanel`,
+ * `?engine=drawn`) and plays that drawing back in the browser. Every
* step's output lands in an editable textarea — **the AI drafts, the human owns
* the text** — and every step stays revisitable from the step bar.
*
@@ -26,9 +28,11 @@
import { useEffect, useRef, useState } from 'react';
import { Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
import {
- AudioLines, ChevronDown, ChevronUp, FileText, Lightbulb, Loader2, Mic2, Sparkles, Wand2,
+ AudioLines, AudioWaveform, Brush, ChevronDown, ChevronUp, FileText, Lightbulb, Loader2, Mic2, Sparkles, Wand2,
} from 'lucide-react';
import MusicGenPanel from './MusicGenPanel';
+import WaveformPanel from './WaveformPanel';
+import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';
import ProviderModelSelector from '../ProviderModelSelector';
import TabPills from '../ui/TabPills';
import toast from '../ui/Toast';
@@ -46,6 +50,13 @@ const STEPS = [
{ id: 'render', label: 'Render', icon: AudioLines },
];
const STEP_IDS = STEPS.map((s) => s.id);
+// How the render step turns the description into sound: an on-device/remote
+// audio model, or a waveform the AI draws point by point. Rides in `?engine=`.
+const RENDER_ENGINES = [
+ { id: 'model', label: 'Audio model', icon: AudioWaveform },
+ { id: 'drawn', label: 'Drawn waveform', icon: Brush },
+];
+const DRAWN_ENGINE = 'drawn';
const FIRST_STEP = STEP_IDS[0];
const DRAFT_TITLE = 'Untitled music draft';
const ACTIVE_DRAFT_KEY = 'portos.musicDesigner.activeDraft';
@@ -56,17 +67,14 @@ const ACTIVE_DRAFT_KEY = 'portos.musicDesigner.activeDraft';
const DESCRIBE_PLACEHOLDER = 'Rewrite the musical reference into a detailed, generation-oriented structured caption in English. Preserve explicit requirements and exclusions while developing genre and subgenres, emotional arc, imagery, sonics, production character, core instruments, and spatial feel. Describe approximate tempo, meter or time signature, rhythmic subdivision, and groove when they matter. Use exact BPM, key, scale, or time signature only when deliberately requested. State the vocal plan explicitly; for instrumental music, rule out vocals and name the lead melodic instrument. Treat the arrangement as a continuous section-by-section timeline with plausible entrances, exits, changes, and transitions. Keep lyric words out of the caption.';
const LYRICS_PLACEHOLDER = 'Write original, singable song lyrics that fit the musical description. Put every bracketed section tag alone on its own line, using useful tags such as [intro], [verse], [pre-chorus], [chorus], [post-chorus], [bridge], [instrumental], [solo], and [outro], with words beginning on the following line. Build enough sections for the intended song length. Keep tempo, meter, key, arrangement, and production instructions in the separate musical description.';
-const FIELD_CLASS = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white';
-const LABEL_CLASS = 'mb-1 block text-xs uppercase tracking-wider text-gray-500';
-const PRIMARY_BTN = 'inline-flex items-center justify-center gap-1.5 rounded-lg bg-port-accent px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:opacity-50 min-h-[40px]';
-const GHOST_BTN = 'inline-flex items-center justify-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 transition-colors hover:border-port-accent hover:text-white disabled:opacity-50 min-h-[40px]';
export default function MusicDesigner() {
const navigate = useNavigate();
const { id } = useParams();
- const [searchParams] = useSearchParams();
+ const [searchParams, setSearchParams] = useSearchParams();
const mountedRef = useMounted();
const requestedTrackId = searchParams.get('trackId') || '';
+ const renderEngine = searchParams.get('engine') === DRAWN_ENGINE ? DRAWN_ENGINE : 'model';
const storedDraftId = requestedTrackId || safeReadStorage(ACTIVE_DRAFT_KEY) || '';
// Wizard text — lifted here so MusicGenPanel (which never writes back to
@@ -205,9 +213,21 @@ export default function MusicDesigner() {
return draftSaveTailRef.current;
};
+ // Step changes keep the query (the draft's trackId and the render engine).
const goTo = (stepId) => {
- const suffix = trackId ? `?trackId=${encodeURIComponent(trackId)}` : '';
- navigate(`/music/generate/${stepId}${suffix}`);
+ const params = new URLSearchParams(searchParams);
+ if (trackId) params.set('trackId', trackId);
+ const query = params.toString();
+ navigate(`/music/generate/${stepId}${query ? `?${query}` : ''}`);
+ };
+
+ const setRenderEngine = (engineId) => {
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ if (engineId === DRAWN_ENGINE) next.set('engine', DRAWN_ENGINE);
+ else next.delete('engine');
+ return next;
+ }, { replace: true });
};
const runDescribe = async ({ advance }) => {
@@ -251,6 +271,8 @@ export default function MusicDesigner() {
persistDesignerPrefs({ providerId: selectedProviderId || '', model: selectedModel || '', effort: effort || '' });
};
+ const openTrack = (track) => navigate(`/music/tracks/${encodeURIComponent(track.id)}`);
+
const busy = describing || writing;
const draftReady = !!trackId && !draftLoading;
@@ -535,6 +557,15 @@ export default function MusicDesigner() {
{step === 'render' && (
<div className="space-y-4">
+ <TabPills
+ tabs={RENDER_ENGINES}
+ activeTab={renderEngine}
+ onChange={setRenderEngine}
+ variant="pills"
+ size="sm"
+ mobileCompact
+ ariaLabel="Render engine"
+ />
<label htmlFor="music-designer-render-prompt" className="block">
<span className={LABEL_CLASS}>Prompt for this render</span>
<textarea
@@ -550,7 +581,9 @@ export default function MusicDesigner() {
className={FIELD_CLASS}
/>
<span id="music-designer-render-prompt-hint" className="mt-1 block text-xs text-gray-500">
- Required. This editable description is the prompt sent to the selected audio engine.
+ {renderEngine === DRAWN_ENGINE
+ ? 'Required. The AI draws the waveform from this editable description.'
+ : 'Required. This editable description is the prompt sent to the selected audio engine.'}
</span>
</label>
<label htmlFor="music-designer-title" className="block">
@@ -571,13 +604,29 @@ export default function MusicDesigner() {
className={FIELD_CLASS}
/>
</label>
- <MusicGenPanel
- track={trackId ? { id: trackId } : undefined}
- title={title}
- prompt={description}
- lyrics={lyrics}
- onGenerated={(track) => navigate(`/music/tracks/${encodeURIComponent(track.id)}`)}
- />
+ {renderEngine === DRAWN_ENGINE ? (
+ <WaveformPanel
+ key={trackId}
+ trackId={trackId}
+ disabled={!draftReady || busy}
+ description={description}
+ lyrics={lyrics}
+ title={title}
+ providerId={selectedProviderId}
+ model={selectedModel}
+ effort={effort}
+ providerPicker={providerPicker}
+ onRendered={openTrack}
+ />
+ ) : (
+ <MusicGenPanel
+ track={trackId ? { id: trackId } : undefined}
+ title={title}
+ prompt={description}
+ lyrics={lyrics}
+ onGenerated={openTrack}
+ />
+ )}
</div>
)}
</section>
diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsx
index 97e9f40539..4a82248e30 100644
--- a/client/src/components/music/MusicDesigner.test.jsx
+++ b/client/src/components/music/MusicDesigner.test.jsx
@@ -24,6 +24,12 @@ vi.mock('./MusicGenPanel', () => ({
),
}));
+vi.mock('./WaveformPanel', () => ({
+ default: ({ trackId, description, providerId }) => (
+ <div data-testid="waveform-panel" data-track={trackId} data-description={description} data-provider={providerId} />
+ ),
+}));
+
// Stateful stub of useProviderModels: the pin-restore effect calls its setters,
// so they have to actually move the returned selection for the restore path to
// be observable.
@@ -180,6 +186,28 @@ describe('<MusicDesigner>', () => {
});
});
+ describe('the render engine', () => {
+ it('swaps to the drawn-waveform engine and keeps it across step navigation', async () => {
+ api.getTrack.mockResolvedValue({
+ id: 'track-saved', title: 'Named Track', concept: 'x', prompt: 'Glassy tidal ambient.', lyrics: '',
+ });
+ renderAt('/music/generate/render?trackId=track-saved');
+ await findEnabledByLabelText(/prompt for this render/i);
+ expect(screen.getByTestId('gen-panel')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('tab', { name: /drawn waveform/i }));
+ const panel = await screen.findByTestId('waveform-panel');
+ expect(panel).toHaveAttribute('data-track', 'track-saved');
+ expect(panel).toHaveAttribute('data-description', 'Glassy tidal ambient.');
+ expect(panel).toHaveAttribute('data-provider', 'provider-a');
+ expect(screen.queryByTestId('gen-panel')).toBeNull();
+
+ fireEvent.click(screen.getByRole('tab', { name: /^lyrics$/i }));
+ fireEvent.click(await screen.findByRole('tab', { name: /^render$/i }));
+ expect(await screen.findByTestId('waveform-panel')).toBeInTheDocument();
+ });
+ });
+
describe('the describe step', () => {
it('fires no LLM call on mount — both provider calls need an explicit press', async () => {
renderAt('/music/generate/concept');
diff --git a/client/src/components/music/WaveformPanel.jsx b/client/src/components/music/WaveformPanel.jsx
new file mode 100644
index 0000000000..dab5db92c4
--- /dev/null
+++ b/client/src/components/music/WaveformPanel.jsx
@@ -0,0 +1,338 @@
+/**
+ * WaveformPanel — the Music Designer's "Drawn waveform" engine.
+ *
+ * Instead of prompting an audio model (MusicGenPanel) or writing a score, the
+ * chosen AI provider DRAWS the music: single-cycle waveform shapes, point by
+ * point, played by voices as timed strokes (server/lib/waveSketch.js). The
+ * panel shows the drawing — each shape, the stroke map, and the resulting
+ * waveform — and plays it straight from the browser with the same
+ * deterministic synth the server uses to save it as a take, so what you hear
+ * 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.
+ */
+
+import { memo, useEffect, useMemo, useRef, useState } from 'react';
+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 { clamp, formatTimecode } from '../../utils/formatters';
+import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';
+import { drawWaveform, renderTrackWaveform } from '../../services/api';
+import {
+ WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE,
+ normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,
+} from '../../../../server/lib/waveSketch.js';
+
+const SKETCH_KEY = 'portos.musicDesigner.waveSketch';
+const DEFAULT_LENGTH_SEC = 20;
+const PEAK_COLUMNS = 600;
+const LANE_HEIGHT = 14;
+// Theme tokens (RGB triplets), so the drawing follows the active PortOS theme.
+const VOICE_COLORS = ['rgb(var(--port-accent))', 'rgb(var(--port-accent-2))', 'rgb(var(--port-success))', 'rgb(var(--port-warning))', 'rgb(var(--port-error))', 'rgb(var(--port-text-muted))'];
+const 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]];
+ const coords = [...cycle, ...cycle.slice(1)].map((p, i, all) => `${((i / (all.length - 1)) * 100).toFixed(2)},${(20 - p * 17).toFixed(2)}`).join(' ');
+ return (
+ <figure className="rounded border border-port-border bg-port-bg p-2">
+ <svg viewBox="0 0 100 40" className="h-16 w-full" preserveAspectRatio="none" aria-hidden="true">
+ <line x1="0" y1="20" x2="100" y2="20" stroke="rgb(var(--port-border))" strokeDasharray="2 2" vectorEffect="non-scaling-stroke" />
+ <line x1="50" y1="0" x2="50" y2="40" stroke="rgb(var(--port-border))" vectorEffect="non-scaling-stroke" />
+ <polyline points={coords} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
+ </svg>
+ <figcaption className="mt-1 truncate text-xs text-gray-400">
+ <span className="text-gray-200">{name}</span>
+ {' · '}{points.length} pts{usedBy.length ? ` · ${usedBy.join(', ')}` : ''}
+ </figcaption>
+ </figure>
+ );
+}
+
+/**
+ * The drawing itself: every shape, the rendered waveform (with the drawn
+ * contour), the per-voice stroke map, and a legend. Memoized on the sketch so
+ * typing in the panel's inputs doesn't rebuild hundreds of SVG nodes.
+ */
+const SketchDrawing = memo(function SketchDrawing({ sketch, peaksPath, playheadRef }) {
+ const noteCount = sketch.voices.reduce((sum, v) => sum + v.notes.length, 0);
+ // Each shape is coloured after the first voice that plays it.
+ const shapes = Object.entries(sketch.shapes).map(([name, points]) => {
+ const users = sketch.voices.filter((v) => v.shape === name);
+ return {
+ name,
+ points,
+ color: voiceColor(Math.max(0, sketch.voices.indexOf(users[0]))),
+ usedBy: users.map((v) => v.name),
+ };
+ });
+ return (
+ <>
+ <div className="text-xs text-gray-400">
+ <span className="text-white">{sketch.title || 'Untitled drawing'}</span>
+ {' — '}{sketch.durationSec}s · {plural(shapes.length, 'drawn shape')} · {plural(sketch.voices.length, 'voice')} · {plural(noteCount, 'stroke')}
+ </div>
+
+ {shapes.length > 0 && (
+ <div className="grid grid-cols-2 gap-2 sm:grid-cols-3 lg:grid-cols-4" data-testid="waveform-shapes">
+ {shapes.map((shape) => <ShapeDrawing key={shape.name} {...shape} />)}
+ </div>
+ )}
+
+ <div className="rounded border border-port-border bg-port-bg p-2">
+ <div className="relative">
+ <svg viewBox={`0 0 ${PEAK_COLUMNS} 100`} className="h-28 w-full" preserveAspectRatio="none" aria-hidden="true">
+ <line x1="0" y1="50" x2={PEAK_COLUMNS} y2="50" stroke="rgb(var(--port-border))" vectorEffect="non-scaling-stroke" />
+ <path d={peaksPath} stroke="rgb(var(--port-accent))" strokeWidth="1" vectorEffect="non-scaling-stroke" />
+ {sketch.contour && (
+ <polyline
+ points={sketch.contour.map((c, i, all) => `${(i / (all.length - 1)) * PEAK_COLUMNS},${100 - c * 96}`).join(' ')}
+ fill="none"
+ stroke="rgb(var(--port-text-muted))"
+ strokeDasharray="4 3"
+ vectorEffect="non-scaling-stroke"
+ />
+ )}
+ </svg>
+ <svg
+ viewBox={`0 0 1000 ${sketch.voices.length * LANE_HEIGHT}`}
+ className="mt-2 w-full"
+ style={{ height: `${sketch.voices.length * 12}px` }}
+ preserveAspectRatio="none"
+ aria-hidden="true"
+ >
+ {sketch.voices.map((voice, lane) => voice.notes.map((note, i) => (
+ <rect
+ key={`${lane}-${i}`}
+ x={(note.t / sketch.durationSec) * 1000}
+ y={lane * LANE_HEIGHT + 2}
+ width={Math.max(1.5, (note.d / sketch.durationSec) * 1000)}
+ height={LANE_HEIGHT - 4}
+ fill={voiceColor(lane)}
+ opacity={0.35 + note.v * 0.65}
+ />
+ )))}
+ </svg>
+ <div ref={playheadRef} className="pointer-events-none absolute inset-y-0 w-0.5 bg-port-text" style={{ left: '0%' }} aria-hidden="true" />
+ </div>
+ </div>
+
+ <ul className="flex flex-wrap gap-x-4 gap-y-1 text-xs text-gray-400">
+ {sketch.voices.map((voice, lane) => (
+ <li key={`${voice.name}-${lane}`} className="inline-flex items-center gap-1.5">
+ <span className="inline-block h-2.5 w-2.5 rounded-sm" style={{ background: voiceColor(lane) }} aria-hidden="true" />
+ {voice.name} <span className="text-gray-500">({voice.shape}, {voice.notes.length})</span>
+ </li>
+ ))}
+ </ul>
+ </>
+ );
+});
+
+export default function WaveformPanel({
+ trackId, disabled = false, description = '', lyrics = '', title = '',
+ providerId, model, effort, providerPicker, onRendered,
+}) {
+ const mountedRef = useMounted();
+ const [sketch, setSketch] = useState(() => readStoredSketch(trackId));
+ const [guidance, setGuidance] = useState('');
+ const [lengthSec, setLengthSec] = useState(DEFAULT_LENGTH_SEC);
+ const [drawing, setDrawing] = useState(null); // 'fresh' | 'revise' | null
+ const [saving, setSaving] = useState(false);
+ const [playing, setPlaying] = useState(false);
+ const { claim, release } = useAudioSessionClaim('playback');
+ const sourceRef = useRef(null);
+ const startedAtRef = useRef(0);
+ const playheadRef = useRef(null);
+ const elapsedRef = useRef(null);
+
+ const pcm = useMemo(() => (sketch ? synthesizeWaveSketch(sketch) : null), [sketch]);
+ const peaksPath = useMemo(() => (pcm
+ ? 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]);
+
+ const stop = () => {
+ const source = sourceRef.current;
+ sourceRef.current = null;
+ if (source) {
+ source.onended = null;
+ try { source.stop(); } catch { /* already ended */ }
+ source.disconnect();
+ }
+ release();
+ if (mountedRef.current) setPlaying(false);
+ };
+
+ // A new drawing (or leaving the panel) silences the old one.
+ useEffect(() => stop, [sketch]);
+
+ const play = async () => {
+ if (!pcm) return;
+ stop();
+ const ctx = getAudioContext();
+ claim();
+ const started = await resumeAudioContext(ctx).then(() => true).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();
+ setPlaying(true);
+ };
+
+ // Playhead painted straight into the DOM at frame rate (ChiptunePanel's
+ // pattern) rather than re-rendering the drawing 60x a second.
+ useEffect(() => {
+ const paint = (sec) => {
+ const fraction = sketch ? Math.min(1, sec / sketch.durationSec) : 0;
+ if (playheadRef.current) playheadRef.current.style.left = `${fraction * 100}%`;
+ if (elapsedRef.current) elapsedRef.current.textContent = formatTimecode(sec);
+ };
+ if (!playing) { paint(0); return undefined; }
+ let raf = 0;
+ const loop = () => {
+ paint(Math.max(0, getAudioContext().currentTime - startedAtRef.current));
+ raf = requestAnimationFrame(loop);
+ };
+ raf = requestAnimationFrame(loop);
+ return () => cancelAnimationFrame(raf);
+ }, [playing, sketch]);
+
+ const draw = async (mode) => {
+ if (!description.trim()) { toast.error('Write the musical description first'); return; }
+ setDrawing(mode);
+ const res = await drawWaveform({
+ description: description.trim(),
+ lyrics: lyrics.trim() || undefined,
+ guidance: guidance.trim() || undefined,
+ durationSec: lengthSec,
+ ...(mode === 'revise' && sketch ? { current: sketch } : {}),
+ providerId: providerId || undefined,
+ model: model || undefined,
+ effort: effort || undefined,
+ }, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not draw the waveform'); return null; });
+ if (!mountedRef.current) return;
+ setDrawing(null);
+ if (!res?.sketch) return;
+ setSketch(res.sketch);
+ safeWriteJsonStorage(SKETCH_KEY, { trackId, sketch: res.sketch });
+ };
+
+ 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; });
+ if (!mountedRef.current) return;
+ setSaving(false);
+ if (!res?.track) return;
+ toast.success(`Saved the drawn take (${res.durationSec}s)`);
+ onRendered?.(res.track);
+ };
+
+ const busy = !!drawing || saving;
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-gray-400">
+ No audio model — the AI draws every sound point by point: single-cycle waveforms become timbres, and timed strokes of those drawings become the melody, bass, and drums. Preview it here, then save it as a take.
+ </p>
+
+ <div className="grid gap-3 sm:grid-cols-[1fr_auto]">
+ <label htmlFor="music-waveform-guidance" className="block">
+ <span className={LABEL_CLASS}>Drawing guidance (optional)</span>
+ <input
+ id="music-waveform-guidance"
+ value={guidance}
+ onChange={(event) => setGuidance(event.target.value)}
+ disabled={disabled}
+ maxLength={4000}
+ placeholder={sketch ? 'Make the lead glassier and the kick punchier…' : 'Soft rounded bass, a bell-like lead, lots of glide…'}
+ className={FIELD_CLASS}
+ />
+ </label>
+ <label htmlFor="music-waveform-length" className="block">
+ <span className={LABEL_CLASS}>Length (sec)</span>
+ <input
+ id="music-waveform-length"
+ type="number"
+ min={4}
+ max={WAVE_SKETCH_LIMITS.DURATION_MAX_SEC}
+ value={lengthSec}
+ onChange={(event) => setLengthSec(clamp(Number(event.target.value) || DEFAULT_LENGTH_SEC, 4, WAVE_SKETCH_LIMITS.DURATION_MAX_SEC))}
+ disabled={disabled}
+ className={`${FIELD_CLASS} sm:w-28`}
+ />
+ </label>
+ </div>
+
+ <div className="rounded border border-port-border bg-port-bg/60 p-3">
+ <span className={LABEL_CLASS}>AI provider</span>
+ {providerPicker}
+ </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}>
+ {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}>
+ {drawing === 'revise' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />}
+ <span>{drawing === 'revise' ? 'Revising…' : 'Revise drawing'}</span>
+ </button>
+ )}
+ </div>
+
+ {sketch ? (
+ <div className="space-y-3 border-t border-port-border pt-3">
+ <SketchDrawing sketch={sketch} peaksPath={peaksPath} playheadRef={playheadRef} />
+
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={playing ? stop : play} className={GHOST_BTN}>
+ {playing ? <Square className="h-4 w-4" /> : <Play className="h-4 w-4" />}
+ <span>{playing ? 'Stop' : 'Play drawing'}</span>
+ </button>
+ <button type="button" onClick={save} disabled={disabled || busy || !trackId} className={PRIMARY_BTN}>
+ {saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ <span>{saving ? 'Saving…' : 'Save as take'}</span>
+ </button>
+ <span className="text-xs font-mono tabular-nums text-gray-500">
+ <span ref={elapsedRef}>{formatTimecode(0)}</span>{' / '}{formatTimecode(sketch.durationSec)}
+ </span>
+ </div>
+ </div>
+ ) : (
+ <p className="text-xs text-gray-500">
+ Nothing drawn yet. The drawing uses the description (and lyrics, for mood) from the earlier steps.
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/music/WaveformPanel.test.jsx b/client/src/components/music/WaveformPanel.test.jsx
new file mode 100644
index 0000000000..485df9168a
--- /dev/null
+++ b/client/src/components/music/WaveformPanel.test.jsx
@@ -0,0 +1,131 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, cleanup } from '@testing-library/react';
+import WaveformPanel from './WaveformPanel';
+import * as api from '../../services/api';
+
+vi.mock('../../services/api', () => ({
+ drawWaveform: vi.fn(),
+ renderTrackWaveform: vi.fn(),
+}));
+
+const drawn = {
+ version: 1,
+ title: 'Glass Tide',
+ durationSec: 1,
+ shapes: { glass: [0, 0.8, 1, 0.3, 0, -0.5, -1, -0.2] },
+ voices: [
+ { name: 'lead', shape: 'glass', gain: 0.6, notes: [{ t: 0, d: 0.5, hz: 440, pitch: 'A4', v: 0.8 }] },
+ { name: 'hats', shape: 'noise', gain: 0.6, notes: [{ t: 0.5, d: 0.05, hz: 12000, v: 0.8 }] },
+ ],
+};
+
+// Minimal Web Audio double: the panel plays the synthesized PCM through one
+// AudioBufferSourceNode on the shared context.
+const audio = vi.hoisted(() => ({ sources: [] }));
+function FakeAudioContext() {
+ this.state = 'running';
+ this.currentTime = 0;
+ this.destination = {};
+ this.createBuffer = (_channels, length, sampleRate) => {
+ const data = new Float32Array(length);
+ return { length, sampleRate, getChannelData: () => data };
+ };
+ this.createBufferSource = () => {
+ const source = { connect: vi.fn(), disconnect: vi.fn(), start: vi.fn(), stop: vi.fn(), onended: null };
+ audio.sources.push(source);
+ return source;
+ };
+}
+
+const renderPanel = (props = {}) => render(
+ <WaveformPanel
+ trackId="track-1"
+ description="glassy tidal ambient"
+ lyrics=""
+ title=""
+ providerId="provider-a"
+ model="model-a"
+ effort=""
+ providerPicker={<div data-testid="picker" />}
+ {...props}
+ />,
+);
+
+describe('<WaveformPanel>', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ window.localStorage.clear();
+ audio.sources = [];
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ api.drawWaveform.mockResolvedValue({ sketch: drawn, llm: { provider: 'provider-a', model: 'model-a' } });
+ 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();
+ 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({
+ description: 'glassy tidal ambient',
+ lyrics: undefined,
+ guidance: 'lots of glide',
+ durationSec: 20,
+ providerId: 'provider-a',
+ model: 'model-a',
+ effort: undefined,
+ }, { silent: true });
+ expect(screen.getByTestId('waveform-shapes').textContent).toContain('glass');
+ expect(screen.getByText(/2 voices · 2 strokes/)).toBeTruthy();
+
+ // A remount (reload) of the same draft restores the drawing without a call.
+ cleanup();
+ renderPanel();
+ expect(screen.getByText('Glass Tide')).toBeTruthy();
+ expect(api.drawWaveform).toHaveBeenCalledTimes(1);
+
+ // …but a different draft starts blank.
+ cleanup();
+ renderPanel({ trackId: 'track-2' });
+ expect(screen.getByText(/Nothing drawn yet/)).toBeTruthy();
+ });
+
+ it('revises by sending the current drawing back', 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);
+ });
+
+ it('plays and stops the synthesized drawing', async () => {
+ renderPanel();
+ fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));
+ fireEvent.click(await screen.findByRole('button', { name: /Play drawing/ }));
+
+ await screen.findByRole('button', { name: /Stop/ });
+ const [source] = audio.sources;
+ expect(source.start).toHaveBeenCalled();
+ expect(source.buffer.length).toBe(44100);
+
+ fireEvent.click(screen.getByRole('button', { name: /Stop/ }));
+ expect(source.stop).toHaveBeenCalled();
+ 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 () => {
+ const onRendered = vi.fn();
+ renderPanel({ onRendered });
+ fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));
+ fireEvent.click(await screen.findByRole('button', { name: /Save as take/ }));
+
+ await waitFor(() => expect(onRendered).toHaveBeenCalledWith({ id: 'track-1' }));
+ expect(api.renderTrackWaveform).toHaveBeenCalledWith('track-1', {
+ sketch: drawn, prompt: 'glassy tidal ambient', title: 'Glass Tide',
+ }, { silent: true });
+ });
+});
diff --git a/client/src/components/music/designerStyles.js b/client/src/components/music/designerStyles.js
new file mode 100644
index 0000000000..088ea21d2e
--- /dev/null
+++ b/client/src/components/music/designerStyles.js
@@ -0,0 +1,5 @@
+// Field/button styling shared by the Music Designer and the panels it hosts.
+export const FIELD_CLASS = 'w-full rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-white';
+export const LABEL_CLASS = 'mb-1 block text-xs uppercase tracking-wider text-gray-500';
+export const PRIMARY_BTN = 'inline-flex items-center justify-center gap-1.5 rounded-lg bg-port-accent px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-port-accent/80 disabled:opacity-50 min-h-[40px]';
+export const GHOST_BTN = 'inline-flex items-center justify-center gap-1.5 rounded-lg border border-port-border px-3 py-2 text-sm text-gray-300 transition-colors hover:border-port-accent hover:text-white disabled:opacity-50 min-h-[40px]';
diff --git a/client/src/lib/chiptunePlayback.js b/client/src/lib/chiptunePlayback.js
index f658069b1c..b3ad3f480c 100644
--- a/client/src/lib/chiptunePlayback.js
+++ b/client/src/lib/chiptunePlayback.js
@@ -14,24 +14,19 @@
import { getAudioContext as ctx, getNoiseBuffer } from './audioContext.js';
import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
import { midiToFreq, makeSafeCall } from './scorePlayback.js';
+import { pitchToMidi } from '../../../server/lib/pitchMath.js';
const { SCHEDULE_AHEAD } = SYNTH_TIMING;
const safeCall = makeSafeCall('chiptune playback');
// --- Pure schedule build (mirrors server buildScoreEvents) ------------------
-const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
-const PITCH_RE = /^([A-Ga-g])(#{1,2}|b{1,2})?(-?\d)$/;
export const CHIPTUNE_NOISE_PRESETS = ['kick', 'snare', 'hat', 'open-hat'];
-// MIDI number for a scientific-pitch STRING ("C4" = 60), or null. Differs from
-// scorePlayback.pitchToMidi, which takes a parsed { letter, accidental, octave }.
-export function parseChiptunePitch(pitch) {
- const m = PITCH_RE.exec(String(pitch || '').trim());
- if (!m) return null;
- const shift = m[2] ? (m[2][0] === '#' ? m[2].length : -m[2].length) : 0;
- return (Number(m[3]) + 1) * 12 + PITCH_CLASS[m[1].toUpperCase()] + shift;
-}
+// MIDI number for a scientific-pitch STRING ("C4" = 60), or null — the shared
+// server/lib/pitchMath.js parser. Differs from scorePlayback.pitchToMidi, which
+// takes a parsed { letter, accidental, octave }.
+export const parseChiptunePitch = pitchToMidi;
/**
* Flatten a chiptune score into absolute-time events + the exact loop length.
diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.js
index cd2f32e74c..e62f33fec0 100644
--- a/client/src/lib/scorePlayback.js
+++ b/client/src/lib/scorePlayback.js
@@ -13,6 +13,7 @@
import { getAudioContext as ctx } from './audioContext.js';
import { createLookaheadTransport, SYNTH_TIMING } from './lookaheadTransport.js';
+import { midiToFreq } from '../../../server/lib/pitchMath.js';
// --- Pitch → frequency ------------------------------------------------------
// Equal-tempered, A4 = 440 Hz. MIDI 69 == A4, so f = 440 · 2^((midi−69)/12).
@@ -29,8 +30,9 @@ export const pitchToMidi = (pitch) => {
return (pitch.octave + 1) * 12 + pc + shift;
};
-// Frequency (Hz) for a MIDI note number. A4 (69) → 440.
-export const midiToFreq = (midi) => (Number.isFinite(midi) ? 440 * Math.pow(2, (midi - 69) / 12) : null);
+// Frequency (Hz) for a MIDI note number. A4 (69) → 440. The shared
+// server/lib/pitchMath.js math, re-exported for the client playback stack.
+export { midiToFreq };
// Frequency (Hz) for a parsed pitch, or null when it isn't a pitch.
export const noteToFrequency = (pitch) => {
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
index cbebbf3489..3afd4129e0 100644
--- a/client/src/services/apiMusic.js
+++ b/client/src/services/apiMusic.js
@@ -46,6 +46,17 @@ 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,
+});
+
// De-register a user-installed model (id is the HF repo id) → { removed }.
export const removeAudioModel = (engine, id, requestOptions = {}) =>
request(`/music/models/${encodeURIComponent(engine)}/${id.split('/').map(encodeURIComponent).join('/')}`, {
diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.js
index a9ed36c1b2..5b2c1de249 100644
--- a/client/src/services/apiTracks.js
+++ b/client/src/services/apiTracks.js
@@ -104,6 +104,15 @@ 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 }.
+export const renderTrackWaveform = (id, body, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/waveform/render`, {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...requestOptions,
+});
+
// Mirror server caps in server/services/tracks/logic.js — bump both sides.
export const TRACK_TITLE_MAX = 200;
export const TRACK_LYRICS_MAX = 20000;
diff --git a/server/lib/README.md b/server/lib/README.md
index 1aa0818c56..a39d92487d 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -511,7 +511,10 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `capabilityMap.js` | Pure row builders for Setup & Capabilities, including strict network/provider first-run readiness and optional-integration health rollups; fed by `routes/capabilities.js`. |
| `claimFlowTaskTypes.js` | `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. Imports nothing. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
-| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, pitch math (`pitchToMidi`/`midiToFreq`), and `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
+| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
+| `pitchMath.js` | Dependency-free scientific-pitch math shared by the LLM-authored music formats on both runtimes: `pitchToMidi("C4")` → 60 (null when unparseable) and `midiToFreq(69)` → 440. |
+| `wavAudioFile.js` | `writeWavAudioFile(wav, dir, basename)` — land a synthesized WAV Buffer as `<basename>.ogg` via the system ffmpeg, falling back to `<basename>.wav` (and dropping a stale `.ogg`) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers. |
+| `waveSketch.js` | Drawn-waveform music contract (browser-safe): the LLM draws single-cycle `shapes` (point polylines in [-1, 1]) played by `voices` as timed strokes with optional glide, shape morph, and drawn envelope, plus a whole-piece `contour`. `normalizeWaveSketch(raw)` is the one lenient, idempotent validator (null when nothing playable survives); `synthesizeWaveSketch(sketch)` → deterministic mono PCM (seeded noise), so the client preview and server render match; `pcmPeaks(pcm, columns)` for drawing it; `WAVE_SKETCH_LIMITS`. |
| `civitai.js` | Civitai URL parsing + API client. |
| `huggingfaceLora.js` | HuggingFace LoRA import helpers: parse HF ref → `{repo,revision,file}`, fetch `/api/models` metadata, select an exact or family-matching `.safetensors`, detect the image or video LoRA family (`flux2` / `ltx-video` / …), build the sidecar + `resolve` download URL. The HF analogue of `civitai.js`. Pure. |
| `huggingfaceModel.js` | HuggingFace base-model (image/video) classifier for the self-service "add a model" flow (#2124): inspect repo siblings + card → decide the loadable runtime/runner, STRICTLY refuse GGUF-only / wan / hunyuan / unclassifiable repos (so a bad add can't wedge the picker), build the `media-models.json` entry (`source:'user'`), + a `searchHuggingfaceModels` Hub-search helper. Pure. |
diff --git a/server/lib/chiptuneScore.js b/server/lib/chiptuneScore.js
index 6b72179c7f..7576b7b6a8 100644
--- a/server/lib/chiptuneScore.js
+++ b/server/lib/chiptuneScore.js
@@ -18,6 +18,7 @@
*/
import { z } from 'zod';
+import { pitchToMidi, midiToFreq } from './pitchMath.js';
export const CHIPTUNE_SCORE_VERSION = 1;
@@ -201,23 +202,6 @@ export function sanitizeChiptuneScore(raw) {
return parsed.success ? parsed.data : null;
}
-// --- Pitch → frequency (mirrors client/src/lib/scorePlayback.js math) -------
-const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
-const PITCH_RE = /^([A-Ga-g])(#{1,2}|b{1,2})?(-?\d)$/;
-
-/** MIDI number for a scientific-pitch string ("C4" = 60, "A4" = 69), or null. */
-export function pitchToMidi(pitch) {
- const m = PITCH_RE.exec(String(pitch || '').trim());
- if (!m) return null;
- const pc = PITCH_CLASS[m[1].toUpperCase()];
- const shift = m[2] ? (m[2][0] === '#' ? m[2].length : -m[2].length) : 0;
- const octave = Number(m[3]);
- return (octave + 1) * 12 + pc + shift;
-}
-
-/** Frequency (Hz) for a MIDI note number, A4 (69) = 440. */
-export const midiToFreq = (midi) => (Number.isFinite(midi) ? 440 * Math.pow(2, (midi - 69) / 12) : null);
-
/** Seconds per sequencer step. */
export const scoreStepSec = (score) => 60 / (score.bpm * score.stepsPerBeat);
diff --git a/server/lib/chiptuneScore.test.js b/server/lib/chiptuneScore.test.js
index 0fe2d8b704..51fa4f1e4a 100644
--- a/server/lib/chiptuneScore.test.js
+++ b/server/lib/chiptuneScore.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
+import { pitchToMidi, midiToFreq } from './pitchMath.js';
import {
- chiptuneScoreSchema, sanitizeChiptuneScore, pitchToMidi, midiToFreq,
+ chiptuneScoreSchema, sanitizeChiptuneScore,
buildScoreEvents, scoreDurationSec, scoreTotalSteps, CHIPTUNE_LIMITS,
} from './chiptuneScore.js';
diff --git a/server/lib/index.js b/server/lib/index.js
index cda8238296..83e3ce5bc0 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -471,6 +471,9 @@ export * from './capabilityMap.js';
export * from './claimFlowTaskTypes.js';
export * from './chiptuneRender.js';
export * from './chiptuneScore.js';
+export * from './pitchMath.js';
+export * from './wavAudioFile.js';
+export * from './waveSketch.js';
export * from './civitai.js';
export * from './huggingfaceLora.js';
export * from './huggingfaceModel.js';
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index e05a0b0c9c..0716c0b134 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -83,7 +83,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.create.rounds', path: '/rounds', label: 'Rounds', section: 'Create', aliases: ['rounds', 'round', 'songs', 'song', 'a-cappella', 'acappella', 'sing'], keywords: ['round', 'song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', 'quodlibet', '500 miles'] },
{ id: 'nav.create.rounds-guide', path: '/rounds/guide', label: 'Rounds Guide', section: 'Create', aliases: ['rounds-guide', 'round-guide', 'songs-guide', 'song-guide', 'singing-guide', 'round-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn round', 'learn song', 'a cappella', 'singing help'] },
{ id: 'nav.create.music', path: '/music', label: 'Music', section: 'Create', aliases: ['music', 'music-studio', 'generate-music'], keywords: ['music generation', 'ace-step', 'acestep', 'musicgen', 'audioldm', 'album', 'track', 'single', 'album art', 'artist', 'song generation', 'audio', 'beat', 'producer'] },
- { id: 'nav.create.music-generate', path: '/music/generate', label: 'Music Designer', section: 'Create', tabGroup: 'music', tabId: 'generate', tabLabel: 'Generate', aliases: ['music-generate', 'music-designer', 'design-music', 'write-a-song', 'make-music'], keywords: ['generate music', 'music designer', 'describe music', 'enrich prompt', 'write lyrics', 'lyrics', 'ace-step', 'reference track', 'vibe', 'step by step', 'wizard'] },
+ { id: 'nav.create.music-generate', path: '/music/generate', label: 'Music Designer', section: 'Create', tabGroup: 'music', tabId: 'generate', tabLabel: 'Generate', aliases: ['music-generate', 'music-designer', 'design-music', 'write-a-song', 'make-music'], keywords: ['generate music', 'music designer', 'describe music', 'enrich prompt', 'write lyrics', 'lyrics', 'ace-step', 'reference track', 'vibe', 'step by step', 'wizard', 'draw waveform', 'drawn waveform', 'wavetable'] },
{ id: 'nav.create.music-artists', path: '/music/artists', label: 'Music Artists', section: 'Create', tabGroup: 'music', tabId: 'artists', tabLabel: 'Artists', aliases: ['music-artists', 'artists', 'artist', 'artist-persona', 'musician', 'band'], keywords: ['artist persona', 'musician', 'band', 'byline', 'portrait', 'genre', 'musical style', 'stage name'] },
{ id: 'nav.create.music-albums', path: '/music/albums', label: 'Music Albums', section: 'Create', tabGroup: 'music', tabId: 'albums', tabLabel: 'Albums', aliases: ['albums', 'album', 'music-albums', 'discography', 'lp', 'ep'], keywords: ['album', 'cover art', 'tracklist', 'release', 'discography', 'record'] },
{ id: 'nav.create.music-tracks', path: '/music/tracks', label: 'Music Tracks', section: 'Create', tabGroup: 'music', tabId: 'tracks', tabLabel: 'Tracks', aliases: ['tracks', 'track', 'music-tracks', 'singles', 'songs-audio'], keywords: ['track', 'single', 'audio', 'recording', 'lyrics', 'mp3', 'wav', 'generate track'] },
diff --git a/server/lib/pitchMath.js b/server/lib/pitchMath.js
new file mode 100644
index 0000000000..c7e366ad97
--- /dev/null
+++ b/server/lib/pitchMath.js
@@ -0,0 +1,21 @@
+/**
+ * Scientific-pitch math shared by the LLM-authored music formats (chiptune
+ * scores, drawn waveform sketches) on both runtimes. Pure and dependency-free,
+ * so the client imports it directly (see client/src/lib/README.md).
+ */
+
+const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
+const PITCH_RE = /^([A-Ga-g])(#{1,2}|b{1,2})?(-?\d)$/;
+
+/** MIDI number for a scientific-pitch string ("C4" = 60, "A4" = 69), or null. */
+export function pitchToMidi(pitch) {
+ const m = PITCH_RE.exec(String(pitch || '').trim());
+ if (!m) return null;
+ const pc = PITCH_CLASS[m[1].toUpperCase()];
+ const shift = m[2] ? (m[2][0] === '#' ? m[2].length : -m[2].length) : 0;
+ const octave = Number(m[3]);
+ return (octave + 1) * 12 + pc + shift;
+}
+
+/** Frequency (Hz) for a MIDI note number, A4 (69) = 440. */
+export const midiToFreq = (midi) => (Number.isFinite(midi) ? 440 * Math.pow(2, (midi - 69) / 12) : null);
diff --git a/server/lib/wavAudioFile.js b/server/lib/wavAudioFile.js
new file mode 100644
index 0000000000..0a83b70185
--- /dev/null
+++ b/server/lib/wavAudioFile.js
@@ -0,0 +1,33 @@
+/**
+ * Land a synthesized 16-bit WAV on disk as game/library-ready audio:
+ * `<dir>/<basename>.ogg` (Vorbis via the system ffmpeg) or, when ffmpeg is
+ * missing or the encode fails, `<dir>/<basename>.wav`. Shared by the offline
+ * renderers of LLM-authored music (chiptune scores, drawn wave sketches).
+ */
+
+import { join } from 'path';
+import { atomicWrite, unlinkGuarded } from './fileUtils.js';
+import { findFfmpeg, runFfmpegProcess } from './ffmpeg.js';
+
+/** Write `wav` (a WAV Buffer) into `dir`; resolves to the filename used. */
+export async function writeWavAudioFile(wav, dir, basename) {
+ const wavPath = join(dir, `${basename}.wav`);
+ const oggPath = join(dir, `${basename}.ogg`);
+ await atomicWrite(wavPath, wav); // ensureDir + temp-rename
+ const bin = await findFfmpeg();
+ if (!bin) {
+ // WAV fallback: drop any stale <basename>.ogg from an earlier
+ // ffmpeg-equipped write, or a consumer still referencing it would play the
+ // old audio while the source says otherwise.
+ await unlinkGuarded(oggPath).catch(() => {});
+ return `${basename}.wav`;
+ }
+ const result = await runFfmpegProcess({ bin, args: ['-y', '-i', wavPath, '-c:a', 'libvorbis', '-q:a', '5', oggPath] });
+ if (!result.ok) {
+ console.error(`❌ OGG encode failed (keeping WAV): ${result.reason}`);
+ await unlinkGuarded(oggPath).catch(() => {}); // stale or partial encode output
+ return `${basename}.wav`;
+ }
+ await unlinkGuarded(wavPath).catch(() => {});
+ return `${basename}.ogg`;
+}
diff --git a/server/lib/waveSketch.js b/server/lib/waveSketch.js
new file mode 100644
index 0000000000..a8d3c583f7
--- /dev/null
+++ b/server/lib/waveSketch.js
@@ -0,0 +1,302 @@
+/**
+ * Wave sketch contract — music an LLM *draws* instead of scores.
+ *
+ * Rather than naming instruments or writing Tone.js/Strudel code, the model
+ * draws the sound itself:
+ *
+ * - `shapes` — single-cycle waveforms, each a polyline of 4–256 amplitude
+ * points in [-1, 1]. Looping one at a pitch turns the drawing
+ * into a timbre (a drawn wavetable).
+ * - `voices` — lanes that play one drawn shape (or `noise`) as timed
+ * strokes: onset/length in seconds, a pitch, an optional glide,
+ * an optional morph into a second drawn shape, and an optional
+ * drawn amplitude envelope.
+ * - `contour` — an optional drawn loudness curve over the whole piece.
+ *
+ * `normalizeWaveSketch` is the ONE validator (lenient: clamps what it can,
+ * drops what it can't, null when nothing playable survives) and is idempotent,
+ * so a normalized sketch round-trips through the client unchanged.
+ * `synthesizeWaveSketch` turns a normalized sketch into mono PCM
+ * deterministically (noise is seeded per stroke), so the browser preview and
+ * the server-rendered WAV are the same samples.
+ *
+ * Pure and dependency-free: imported by the client (MusicDesigner's drawn
+ * waveform engine) as well as server/services/musicWaveform.js.
+ */
+
+import { pitchToMidi, midiToFreq } from './pitchMath.js';
+
+export const WAVE_SKETCH_VERSION = 1;
+export const WAVE_SKETCH_SAMPLE_RATE = 44100;
+export const WAVE_SKETCH_NOISE = 'noise';
+
+export const WAVE_SKETCH_LIMITS = Object.freeze({
+ DURATION_MIN_SEC: 1,
+ DURATION_MAX_SEC: 60,
+ SHAPES_MAX: 12,
+ SHAPE_POINTS_MIN: 4,
+ SHAPE_POINTS_MAX: 256,
+ VOICES_MAX: 8,
+ NOTES_PER_VOICE_MAX: 512,
+ NOTES_MAX: 1536,
+ // Aggregate voiced time — the per-sample synth loop runs once per voiced
+ // sample, so this (not the duration) bounds the render work. 8 voices fully
+ // voiced for the longest piece.
+ NOTE_SECONDS_MAX: 480,
+ ENV_POINTS_MIN: 2,
+ ENV_POINTS_MAX: 32,
+ CONTOUR_POINTS_MAX: 256,
+ NOTE_MIN_SEC: 0.005,
+ HZ_MIN: 20,
+ HZ_MAX: 8000,
+ // Noise strokes read `hz` as a sample-and-hold rate, which may run faster
+ // than any tonal pitch (crisp hats) — up to Nyquist.
+ NOISE_HZ_MAX: WAVE_SKETCH_SAMPLE_RATE / 2,
+ TITLE_MAX: 120,
+ NAME_MAX: 24,
+});
+
+const L = WAVE_SKETCH_LIMITS;
+const NAME_RE = new RegExp(`^[A-Za-z0-9_-]{1,${L.NAME_MAX}}$`);
+const MASTER_GAIN = 0.5;
+const CLIP_CEILING = 0.98;
+const DEFAULT_GAIN = 0.6;
+const DEFAULT_VELOCITY = 0.8;
+const DEFAULT_ATTACK_SEC = 0.005;
+const DEFAULT_RELEASE_SEC = 0.04;
+const DECLICK_SEC = 0.002;
+
+const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
+const isNum = (n) => typeof n === 'number' && Number.isFinite(n);
+// Keep stored numbers short — the sketch is sent back to the LLM on revision.
+const round = (n, places = 4) => Math.round(n * 10 ** places) / 10 ** places;
+
+/** A drawn polyline of `min`..`max` finite points, clamped to [lo, hi], or null. */
+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)));
+ return points.length >= min ? points : null;
+}
+
+/** Hz for a stroke pitch: a number of Hz, or a scientific-pitch string ("C4"). */
+function resolveHz(value, maxHz) {
+ const hz = isNum(value) ? value : midiToFreq(pitchToMidi(value));
+ return isNum(hz) && hz >= L.HZ_MIN ? round(Math.min(hz, maxHz), 3) : null;
+}
+
+function normalizeNote(raw, { durationSec, isNoise, shapeNames }) {
+ if (!raw || typeof raw !== 'object' || !isNum(raw.t) || !isNum(raw.d)) return null;
+ const t = round(clamp(raw.t, 0, durationSec));
+ const d = round(Math.min(raw.d, durationSec - t));
+ if (!(d >= L.NOTE_MIN_SEC)) return null;
+ const maxHz = isNoise ? L.NOISE_HZ_MAX : L.HZ_MAX;
+ // `hz` wins over `pitch` so a normalized note (which carries both) is stable.
+ const hz = resolveHz(raw.hz ?? raw.pitch, maxHz);
+ // A tonal stroke needs a pitch; a noise stroke without one is white noise.
+ if (hz == null && !isNoise) return null;
+ const note = { t, d, hz, v: round(isNum(raw.v) ? clamp(raw.v, 0, 1) : DEFAULT_VELOCITY) };
+ if (typeof raw.pitch === 'string' && pitchToMidi(raw.pitch) != null) note.pitch = raw.pitch.trim();
+ const toHz = hz == null ? null : resolveHz(raw.toHz ?? raw.glideTo, maxHz);
+ if (toHz != null && toHz !== hz) note.toHz = toHz;
+ if (!isNoise && typeof raw.morphTo === 'string' && shapeNames.has(raw.morphTo)) note.morphTo = raw.morphTo;
+ const env = normalizePoints(raw.env, { min: L.ENV_POINTS_MIN, max: L.ENV_POINTS_MAX, lo: 0, hi: 1 });
+ if (env) note.env = env;
+ return note;
+}
+
+/**
+ * Validate + canonicalize an LLM (or client round-tripped) wave sketch.
+ * Returns the normalized sketch, or null when nothing playable survives.
+ */
+export function normalizeWaveSketch(raw) {
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;
+
+ 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;
+ 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;
+ }
+ const shapeNames = new Set(Object.keys(shapes));
+
+ 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 : []))
+ .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);
+
+ let noteBudget = L.NOTES_MAX;
+ let secondsBudget = L.NOTE_SECONDS_MAX;
+ const voices = [];
+ for (const [index, rawVoice] of rawVoices.entries()) {
+ const shape = rawVoice?.shape;
+ const isNoise = shape === WAVE_SKETCH_NOISE;
+ if (!isNoise && !shapeNames.has(shape)) continue;
+ const notes = [];
+ for (const rawNote of (Array.isArray(rawVoice.notes) ? rawVoice.notes : [])) {
+ if (notes.length >= L.NOTES_PER_VOICE_MAX || noteBudget <= 0) break;
+ const note = normalizeNote(rawNote, { durationSec, isNoise, shapeNames });
+ if (!note || note.d > secondsBudget) continue;
+ notes.push(note);
+ noteBudget -= 1;
+ secondsBudget -= note.d;
+ }
+ if (!notes.length) continue;
+ const name = typeof rawVoice.name === 'string' && rawVoice.name.trim()
+ ? rawVoice.name.trim().slice(0, L.NAME_MAX)
+ : `voice${index + 1}`;
+ voices.push({
+ name,
+ shape,
+ gain: round(isNum(rawVoice.gain) ? clamp(rawVoice.gain, 0, 1) : DEFAULT_GAIN),
+ notes: notes.sort((a, b) => a.t - b.t),
+ });
+ }
+ if (!voices.length) return null;
+
+ const sketch = { version: WAVE_SKETCH_VERSION, title: '', durationSec, shapes, voices };
+ if (typeof raw.title === 'string') sketch.title = raw.title.trim().slice(0, L.TITLE_MAX);
+ // Only the shapes a voice actually plays (or morphs into) are kept, so the
+ // drawings shown to the user are exactly the ones they hear.
+ const used = new Set(voices.flatMap((v) => [v.shape, ...v.notes.map((n) => n.morphTo)]));
+ for (const name of Object.keys(shapes)) if (!used.has(name)) delete shapes[name];
+ const contour = normalizePoints(raw.contour, { min: 2, max: L.CONTOUR_POINTS_MAX, lo: 0, hi: 1 });
+ if (contour) sketch.contour = contour;
+ return sketch;
+}
+
+/** Linear interpolation across evenly spaced points at progress u ∈ [0, 1]. */
+function samplePolyline(points, u) {
+ const x = clamp(u, 0, 1) * (points.length - 1);
+ const i = Math.floor(x);
+ if (i >= points.length - 1) return points[points.length - 1];
+ return points[i] + (points[i + 1] - points[i]) * (x - i);
+}
+
+// One drawn cycle as a looping wavetable, DC-centred so a lopsided drawing
+// can't push the mix off zero.
+function buildTable(points) {
+ const mean = points.reduce((sum, p) => sum + p, 0) / points.length;
+ return Float32Array.from(points, (p) => p - mean);
+}
+
+// Cyclic read: phase ∈ [0, 1) wraps from the last point back to the first.
+function readTable(table, phase) {
+ const x = phase * table.length;
+ const i = Math.floor(x);
+ const j = i + 1 === table.length ? 0 : i + 1;
+ return table[i] + (table[j] - table[i]) * (x - i);
+}
+
+// mulberry32 — tiny deterministic PRNG so noise renders identically everywhere.
+function seededRandom(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6D2B79F5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// Amplitude at progress u of a note: its drawn envelope (declicked at both
+// ends) or the default quick attack/release. `releaseSec` is per-note, hoisted
+// out of the per-sample loop.
+function envelopeAt(note, u, elapsedSec, releaseSec) {
+ const remainingSec = note.d - elapsedSec;
+ if (note.env) {
+ const declick = Math.min(1, elapsedSec / DECLICK_SEC, remainingSec / DECLICK_SEC);
+ return samplePolyline(note.env, u) * Math.max(0, declick);
+ }
+ return Math.max(0, Math.min(1, elapsedSec / DEFAULT_ATTACK_SEC, remainingSec / releaseSec));
+}
+
+/**
+ * Render a NORMALIZED sketch to mono PCM (Float32Array in [-1, 1]).
+ * Deterministic: the same sketch always yields the same samples.
+ */
+export function synthesizeWaveSketch(sketch, { sampleRate = WAVE_SKETCH_SAMPLE_RATE } = {}) {
+ const total = Math.max(1, Math.round(sketch.durationSec * sampleRate));
+ const out = new Float32Array(total);
+ const tables = Object.fromEntries(Object.entries(sketch.shapes).map(([name, points]) => [name, buildTable(points)]));
+
+ sketch.voices.forEach((voice, voiceIndex) => {
+ const isNoise = voice.shape === WAVE_SKETCH_NOISE;
+ const table = tables[voice.shape];
+ voice.notes.forEach((note, noteIndex) => {
+ const start = Math.floor(note.t * sampleRate);
+ const length = Math.max(1, Math.round(note.d * sampleRate));
+ const end = Math.min(total, start + length);
+ const fromHz = note.hz;
+ // Exponential glide (equal cents per second — a musical slide), applied
+ // as a constant per-sample multiplier rather than a pow() per sample.
+ const glideStep = note.toHz ? (note.toHz / fromHz) ** (1 / length) : 1;
+ const releaseSec = Math.min(DEFAULT_RELEASE_SEC, note.d / 3);
+ const morph = note.morphTo ? tables[note.morphTo] : null;
+ const random = isNoise ? seededRandom((voiceIndex + 1) * 100003 + noteIndex) : null;
+ const level = voice.gain * note.v;
+ let phase = 0;
+ let hz = fromHz;
+ let held = random ? random() * 2 - 1 : 0;
+ for (let s = start; s < end; s += 1, hz = hz == null ? null : hz * glideStep) {
+ const i = s - start;
+ const u = i / length;
+ let sample;
+ if (isNoise) {
+ if (hz == null) {
+ sample = random() * 2 - 1;
+ } else {
+ phase += hz / sampleRate;
+ if (phase >= 1) { phase -= Math.floor(phase); held = random() * 2 - 1; }
+ sample = held;
+ }
+ } else {
+ phase += hz / sampleRate;
+ phase -= Math.floor(phase);
+ sample = readTable(table, phase);
+ if (morph) sample += (readTable(morph, phase) - sample) * u;
+ }
+ out[s] += sample * level * envelopeAt(note, u, i / sampleRate, releaseSec);
+ }
+ });
+ });
+
+ let peak = 0;
+ for (let s = 0; s < total; s += 1) {
+ const contour = sketch.contour ? samplePolyline(sketch.contour, s / total) : 1;
+ out[s] *= MASTER_GAIN * contour;
+ peak = Math.max(peak, Math.abs(out[s]));
+ }
+ // Scale down (never up) so a dense drawing can't clip — deterministic,
+ // unlike a compressor, so preview and render stay identical.
+ if (peak > CLIP_CEILING) {
+ const scale = CLIP_CEILING / peak;
+ for (let s = 0; s < total; s += 1) out[s] *= scale;
+ }
+ return out;
+}
+
+/**
+ * Downsample PCM into `columns` [min, max] pairs for drawing the rendered
+ * waveform. Each column covers an equal slice of the buffer.
+ */
+export function pcmPeaks(pcm, columns) {
+ const count = Math.max(1, Math.floor(columns));
+ const peaks = [];
+ for (let c = 0; c < count; c += 1) {
+ const from = Math.floor((c / count) * pcm.length);
+ const to = Math.max(from + 1, Math.floor(((c + 1) / count) * pcm.length));
+ let min = 0;
+ let max = 0;
+ for (let s = from; s < to && s < pcm.length; s += 1) {
+ if (pcm[s] < min) min = pcm[s];
+ if (pcm[s] > max) max = pcm[s];
+ }
+ peaks.push([min, max]);
+ }
+ return peaks;
+}
diff --git a/server/lib/waveSketch.test.js b/server/lib/waveSketch.test.js
new file mode 100644
index 0000000000..736a2bbf13
--- /dev/null
+++ b/server/lib/waveSketch.test.js
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+import {
+ WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE, normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,
+} from './waveSketch.js';
+
+// One drawn sine cycle — 16 points, the example the LLM prompt teaches.
+const SINE = [0, 0.38, 0.71, 0.92, 1, 0.92, 0.71, 0.38, 0, -0.38, -0.71, -0.92, -1, -0.92, -0.71, -0.38];
+
+const sketchOf = (voices, extra = {}) => ({ version: 1, durationSec: 2, shapes: { sine: SINE }, voices, ...extra });
+
+// Rising zero crossings per second ≈ the fundamental of a periodic signal.
+const risingCrossings = (pcm, from, to) => {
+ let count = 0;
+ for (let i = from + 1; i < to; i += 1) if (pcm[i - 1] < 0 && pcm[i] >= 0) count += 1;
+ return count;
+};
+
+describe('normalizeWaveSketch', () => {
+ it('returns null when nothing playable survives', () => {
+ expect(normalizeWaveSketch(null)).toBeNull();
+ expect(normalizeWaveSketch([])).toBeNull();
+ expect(normalizeWaveSketch({ shapes: { sine: SINE }, voices: [] })).toBeNull();
+ // A voice naming an undeclared shape, and a tonal note without a pitch.
+ expect(normalizeWaveSketch(sketchOf([{ shape: 'nope', notes: [{ t: 0, d: 1, pitch: 'A4' }] }]))).toBeNull();
+ expect(normalizeWaveSketch(sketchOf([{ shape: 'sine', notes: [{ t: 0, d: 1, pitch: 'kick' }] }]))).toBeNull();
+ });
+
+ it('resolves pitches, clamps values, and clips strokes to the piece', () => {
+ const sketch = normalizeWaveSketch(sketchOf([{
+ shape: 'sine',
+ gain: 3,
+ notes: [
+ { t: 1.5, d: 5, pitch: 'A4', glideTo: 'A5', v: -1, env: [0, 2, 0.5] },
+ { t: 0, d: 0.5, hz: 99999 },
+ ],
+ }], { shapes: { sine: [...SINE.slice(0, -1), 7] } }));
+
+ expect(sketch.shapes.sine.at(-1)).toBe(1);
+ const [voice] = sketch.voices;
+ expect(voice).toMatchObject({ name: 'voice1', gain: 1 });
+ // Sorted by onset; the overlong stroke is clipped at durationSec.
+ expect(voice.notes[0]).toEqual({ t: 0, d: 0.5, hz: WAVE_SKETCH_LIMITS.HZ_MAX, v: 0.8 });
+ expect(voice.notes[1]).toEqual({ t: 1.5, d: 0.5, hz: 440, pitch: 'A4', toHz: 880, v: 0, env: [0, 1, 0.5] });
+ });
+
+ it('lets noise strokes skip a pitch and keeps morph targets only on tonal voices', () => {
+ const sketch = normalizeWaveSketch(sketchOf([
+ { shape: 'noise', notes: [{ t: 0, d: 0.1 }, { t: 0.5, d: 0.05, hz: 12000, morphTo: 'saw' }] },
+ { shape: 'sine', notes: [{ t: 0, d: 1, pitch: 'C4', morphTo: 'saw' }, { t: 1, d: 1, pitch: 'C4', morphTo: 'missing' }] },
+ ], { shapes: { sine: SINE, saw: [-1, -0.5, 0, 0.5, 1], unused: [0, 1, 0, -1] } }));
+
+ expect(sketch.voices[0].notes).toEqual([{ t: 0, d: 0.1, hz: null, v: 0.8 }, { t: 0.5, d: 0.05, hz: 12000, v: 0.8 }]);
+ expect(sketch.voices[1].notes.map((n) => n.morphTo)).toEqual(['saw', undefined]);
+ // A drawing nothing plays is dropped, so what is shown is what is heard.
+ expect(Object.keys(sketch.shapes).sort()).toEqual(['saw', 'sine']);
+ });
+
+ it('derives the duration from the strokes when none is given', () => {
+ const sketch = normalizeWaveSketch({ shapes: { sine: SINE }, voices: [{ shape: 'sine', notes: [{ t: 2, d: 1.5, pitch: 'E3' }] }] });
+ expect(sketch.durationSec).toBe(3.5);
+ });
+
+ it('enforces the aggregate stroke caps', () => {
+ const notes = Array.from({ length: WAVE_SKETCH_LIMITS.NOTES_PER_VOICE_MAX + 50 }, (_, i) => ({ t: i * 0.01, d: 0.01, pitch: 'A4' }));
+ const sketch = normalizeWaveSketch(sketchOf([{ shape: 'sine', notes }], { durationSec: 60 }));
+ expect(sketch.voices[0].notes).toHaveLength(WAVE_SKETCH_LIMITS.NOTES_PER_VOICE_MAX);
+
+ // Voiced seconds: 8 voices × 60s fills the budget; a 9th voice (over the
+ // voice cap anyway) and further full-length notes are refused.
+ const full = Array.from({ length: 12 }, () => ({ shape: 'sine', notes: [{ t: 0, d: 60, pitch: 'A2' }, { t: 0, d: 60, pitch: 'A3' }] }));
+ const capped = normalizeWaveSketch(sketchOf(full, { durationSec: 60 }));
+ const voiced = capped.voices.flatMap((v) => v.notes).reduce((sum, n) => sum + n.d, 0);
+ expect(capped.voices.length).toBeLessThanOrEqual(WAVE_SKETCH_LIMITS.VOICES_MAX);
+ expect(voiced).toBeLessThanOrEqual(WAVE_SKETCH_LIMITS.NOTE_SECONDS_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] }] },
+ { shape: 'noise', notes: [{ t: 1, d: 0.2 }] },
+ ], { title: ' Glass Tide ', contour: [0.2, 1, 0.4] }));
+ expect(once.title).toBe('Glass Tide');
+ expect(normalizeWaveSketch(JSON.parse(JSON.stringify(once)))).toEqual(once);
+ });
+});
+
+describe('synthesizeWaveSketch', () => {
+ it('plays a drawn cycle at the requested pitch for the whole piece length', () => {
+ const sketch = normalizeWaveSketch(sketchOf([{ shape: 'sine', notes: [{ t: 0, d: 1, pitch: 'A4' }] }]));
+ const pcm = synthesizeWaveSketch(sketch);
+ expect(pcm).toHaveLength(2 * WAVE_SKETCH_SAMPLE_RATE);
+ // Mid-note second: ~440 cycles. Second half is silent (the note ended).
+ expect(risingCrossings(pcm, 0, WAVE_SKETCH_SAMPLE_RATE)).toBeGreaterThanOrEqual(438);
+ expect(risingCrossings(pcm, 0, WAVE_SKETCH_SAMPLE_RATE)).toBeLessThanOrEqual(441);
+ expect(Math.max(...pcm.subarray(WAVE_SKETCH_SAMPLE_RATE + 10).map(Math.abs))).toBe(0);
+ });
+
+ it('glides exponentially from pitch to glideTo', () => {
+ const sketch = normalizeWaveSketch(sketchOf([{ shape: 'sine', notes: [{ t: 0, d: 2, hz: 200, glideTo: 800 }] }]));
+ const pcm = synthesizeWaveSketch(sketch);
+ const quarter = WAVE_SKETCH_SAMPLE_RATE / 4;
+ // First and last quarter-second windows centre on ~224 Hz and ~713 Hz.
+ expect(risingCrossings(pcm, 0, quarter) * 4).toBeLessThan(260);
+ expect(risingCrossings(pcm, pcm.length - quarter, pcm.length) * 4).toBeGreaterThan(650);
+ });
+
+ it('is deterministic — noise included — so preview and saved take match', () => {
+ const sketch = normalizeWaveSketch(sketchOf([
+ { shape: 'noise', notes: [{ t: 0, d: 0.5 }, { t: 0.5, d: 0.5, hz: 3000 }] },
+ { shape: 'sine', notes: [{ t: 0, d: 2, pitch: 'C3', env: [0, 1, 0] }] },
+ ]));
+ expect(synthesizeWaveSketch(sketch)).toEqual(synthesizeWaveSketch(sketch));
+ });
+
+ it('never clips a dense drawing and applies the drawn contour', () => {
+ const loud = Array.from({ length: 8 }, () => ({ shape: 'sine', gain: 1, notes: [{ t: 0, d: 2, pitch: 'A3', v: 1 }] }));
+ const pcm = synthesizeWaveSketch(normalizeWaveSketch(sketchOf(loud)));
+ expect(Math.max(...pcm.map(Math.abs))).toBeLessThanOrEqual(0.98 + 1e-6);
+
+ const faded = synthesizeWaveSketch(normalizeWaveSketch(sketchOf(loud.slice(0, 1), { contour: [1, 0] })));
+ expect(Math.abs(faded.at(-1))).toBeLessThan(0.001);
+ });
+});
+
+describe('drawing helpers', () => {
+ it('pcmPeaks reduces a buffer to per-column [min, max]', () => {
+ expect(pcmPeaks(Float32Array.from([0.5, -0.25, 0, 1]), 2)).toEqual([[-0.25, 0.5], [0, 1]]);
+ });
+});
diff --git a/server/routes/music.js b/server/routes/music.js
index 79d4d6a504..3a9d73c370 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -4,12 +4,15 @@
* GET /api/music/engines → { engines, defaultEngine }
* POST /api/music/describe → { description, llm }
* POST /api/music/lyrics → { lyrics, llm }
+ * POST /api/music/waveform → { sketch, llm }
* POST /api/music/generate → { jobId, position, status }
*
* `describe`/`lyrics` are the Generate tab's stepped designer (#4305): an LLM
* expands a short reference/vibe into a rich conditioning prompt, then writes
* lyrics from it. Both are one-shot, user-triggered calls — the studio never
- * fires them on its own (AI Provider Usage Policy).
+ * fires them on its own (AI Provider Usage Policy). `waveform` is the same
+ * designer's "Drawn waveform" engine: the LLM draws single-cycle waveforms and
+ * timed strokes (server/lib/waveSketch.js) that the browser plays directly.
*
* Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/
* musicGen.js) through the unified audio media-job lane. The completion hook
@@ -36,6 +39,8 @@ import {
import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from '../services/audioModels.js';
import { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';
import { describeMusic, writeLyrics } from '../services/musicDesigner.js';
+import { drawWaveSketch } from '../services/musicWaveform.js';
+import { WAVE_SKETCH_LIMITS } from '../lib/waveSketch.js';
import { startHfDownloadStream } from '../services/hfDownloadStream.js';
import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
import { createInstallLogger } from '../lib/installLogger.js';
@@ -349,6 +354,24 @@ router.post('/lyrics', asyncHandler(async (req, res) => {
res.json({ lyrics, llm });
}));
+const waveformSchema = z.object({
+ description: z.string().trim().min(1, 'description is required').max(8000),
+ lyrics: z.string().trim().max(20000).optional(),
+ durationSec: z.number().min(WAVE_SKETCH_LIMITS.DURATION_MIN_SEC).max(WAVE_SKETCH_LIMITS.DURATION_MAX_SEC).optional(),
+ // The drawing to revise — normalized (and size-bounded) by the service.
+ current: z.record(z.string(), z.unknown()).optional(),
+ // The drawing contract is fixed (no meta-prompt override like describe/lyrics).
+ ...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.
+// One explicit user action per call.
+router.post('/waveform', asyncHandler(async (req, res) => {
+ const body = validateRequest(waveformSchema, req.body ?? {});
+ res.json(await drawWaveSketch(body));
+}));
+
const generateSchema = z.object({
prompt: z.string().trim().min(1, 'prompt is required').max(8000),
// No default: distinguish ABSENT (don't touch the track's lyrics) from a
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index ac801488f4..b1709ba17e 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/render → { track, filename, durationSec } (drawn-waveform take)
*
* Tracks store only a pointer (`audioFilename`) into the shared music library
* (services/pipeline/musicLibrary.js, `data/music/`); the bytes are uploaded /
@@ -43,6 +44,7 @@ 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';
const router = Router();
@@ -285,6 +287,21 @@ router.post('/:id/chiptune/publish', asyncHandler(async (req, res) => {
res.json(await publishChiptuneTrack({ trackId: req.params.id, ...body }));
}));
+// --- 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.
+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/render', asyncHandler(async (req, res) => {
+ const body = validateRequest(waveformRenderSchema, req.body ?? {});
+ res.json(await renderWaveSketchToTrack({ trackId: req.params.id, ...body }));
+}));
+
// Make a past render the active one (re-point the player + gen-metadata badges
// at it). The user-authored prompt/lyrics are left untouched — they drive the
// NEXT generation, independent of which take is selected for playback.
diff --git a/server/services/chiptune.js b/server/services/chiptune.js
index 06d43f0b1e..d738e00001 100644
--- a/server/services/chiptune.js
+++ b/server/services/chiptune.js
@@ -18,8 +18,8 @@ import { stat } from 'fs/promises';
import { randomUUID } from 'crypto';
import { join, resolve, isAbsolute } from 'path';
import { ServerError } from '../lib/errorHandler.js';
-import { PATHS, atomicWrite, isPathInsideDir, unlinkGuarded } from '../lib/fileUtils.js';
-import { findFfmpeg, runFfmpegProcess } from '../lib/ffmpeg.js';
+import { PATHS, atomicWrite, isPathInsideDir } from '../lib/fileUtils.js';
+import { writeWavAudioFile } from '../lib/wavAudioFile.js';
import { chiptuneScoreSchema, CHIPTUNE_LIMITS, CHIPTUNE_NOISE_PRESETS, scoreDurationSec } from '../lib/chiptuneScore.js';
import { renderScoreToWav } from '../lib/chiptuneRender.js';
import { resolveProviderAndModel, assertProvider, runPromptThroughProvider } from './promptRunner.js';
@@ -117,29 +117,7 @@ export async function generateChiptuneScore({ trackId, prompt, providerId, model
return { track: updated, providerId: run.provider?.id || provider.id, model: run.model ?? selectedModel ?? null };
}
-// Render the score to an audio file in `dir` as `<basename>.ogg` (via ffmpeg)
-// or `<basename>.wav` when ffmpeg isn't installed. Returns the filename used.
-async function renderScoreToFile(score, dir, basename) {
- const wavPath = join(dir, `${basename}.wav`);
- const oggPath = join(dir, `${basename}.ogg`);
- await atomicWrite(wavPath, renderScoreToWav(score)); // ensureDir + temp-rename
- const bin = await findFfmpeg();
- if (!bin) {
- // WAV fallback: drop any stale <slug>.ogg from an earlier ffmpeg-equipped
- // publish, or a game still referencing it would play the old composition
- // while the score JSON says otherwise.
- await unlinkGuarded(oggPath).catch(() => {});
- return `${basename}.wav`;
- }
- const result = await runFfmpegProcess({ bin, args: ['-y', '-i', wavPath, '-c:a', 'libvorbis', '-q:a', '5', oggPath] });
- if (!result.ok) {
- console.error(`❌ Chiptune OGG encode failed (keeping WAV): ${result.reason}`);
- await unlinkGuarded(oggPath).catch(() => {}); // stale or partial encode output
- return `${basename}.wav`;
- }
- await unlinkGuarded(wavPath).catch(() => {});
- return `${basename}.ogg`;
-}
+const renderScoreToFile = (score, dir, basename) => writeWavAudioFile(renderScoreToWav(score), dir, basename);
/**
* Render the track's current score into the shared music library and append
@@ -151,20 +129,8 @@ export async function renderChiptuneTrack({ trackId }) {
const filename = await renderScoreToFile(score, PATHS.music, `music-${randomUUID()}`);
const durationSec = Math.max(1, Math.round(scoreDurationSec(score)));
- // Re-read so the append lands on the freshest history (musicGen route pattern).
- const current = (await tracks.getTrack(trackId)) ?? track;
- const { renders } = tracks.buildRenderAppend(current, {
- audioFilename: filename,
- prompt: track.chiptunePrompt,
- engine: 'chiptune',
- durationSec,
- });
- const updated = await tracks.updateTrack(trackId, {
- audioFilename: filename,
- engine: 'chiptune',
- modelId: '',
- durationSec,
- renders,
+ const updated = await tracks.appendActiveTake(trackId, {
+ audioFilename: filename, prompt: track.chiptunePrompt, engine: 'chiptune', durationSec,
});
return { track: updated, filename, durationSec };
}
diff --git a/server/services/chiptune.test.js b/server/services/chiptune.test.js
index 0381913b10..38adba2581 100644
--- a/server/services/chiptune.test.js
+++ b/server/services/chiptune.test.js
@@ -14,10 +14,7 @@ const musicDir = await makeTmp('chiptune-music-');
vi.mock('./tracks/index.js', () => ({
getTrack: vi.fn(),
updateTrack: vi.fn(),
- buildRenderAppend: vi.fn((track, input) => {
- const render = { id: 'render-test', ...input, createdAt: '2026-01-01T00:00:00.000Z' };
- return { render, renders: [...(track?.renders || []), render] };
- }),
+ appendActiveTake: vi.fn(async (id, take) => ({ id, ...take })),
}));
vi.mock('./promptRunner.js', () => ({
@@ -150,17 +147,12 @@ describe('renderChiptuneTrack', () => {
const files = await readdir(musicDir);
expect(files).toContain(result.filename);
expect(result.durationSec).toBe(2); // 16 steps · 0.125s = 2s
- expect(tracks.buildRenderAppend).toHaveBeenCalledWith(expect.objectContaining({ id: 'track-1' }), {
+ expect(tracks.appendActiveTake).toHaveBeenCalledWith('track-1', {
audioFilename: result.filename,
prompt: 'farm loop',
engine: 'chiptune',
durationSec: result.durationSec,
});
- expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({
- audioFilename: result.filename,
- engine: 'chiptune',
- modelId: '',
- }));
});
});
diff --git a/server/services/musicWaveform.js b/server/services/musicWaveform.js
new file mode 100644
index 0000000000..0b452afe63
--- /dev/null
+++ b/server/services/musicWaveform.js
@@ -0,0 +1,142 @@
+/**
+ * Drawn-waveform music — the Music Designer's "Drawn waveform" engine.
+ *
+ * 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.
+ *
+ * The browser previews the same sketch with the same deterministic synth
+ * (`synthesizeWaveSketch`), so the saved take is exactly what was auditioned.
+ *
+ * Nothing here runs on its own: every call is driven by an explicit button
+ * press in the same request (AI Provider Usage Policy — no cold bootstrap).
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { trimTo } from '../lib/textUtils.js';
+import { pcmToWavBuffer } from '../lib/chiptuneRender.js';
+import { writeWavAudioFile } from '../lib/wavAudioFile.js';
+import {
+ WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE, normalizeWaveSketch, synthesizeWaveSketch,
+} from '../lib/waveSketch.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
+import * as tracks from './tracks/index.js';
+
+const WAVEFORM_ENGINE = 'waveform';
+const DEFAULT_SKETCH_SEC = 20;
+
+const MAX_DESCRIPTION = 8000;
+const MAX_LYRICS = 20000;
+const MAX_GUIDANCE = 4000;
+const L = WAVE_SKETCH_LIMITS;
+
+const section = (label, body) => (body ? `\n\n${label}:\n${body}` : '');
+
+/** The drawing contract sent to the LLM. */
+function buildWaveSketchPrompt({ description, lyrics, guidance, durationSec = DEFAULT_SKETCH_SEC, current } = {}) {
+ const target = Math.min(L.DURATION_MAX_SEC, Math.max(L.DURATION_MIN_SEC, Math.round(durationSec)));
+ return `You are a sound designer and composer who makes music by DRAWING WAVEFORMS. There are no instruments, samples, synth presets, or code: every sound in the piece comes from single-cycle waveforms you draw point by point, played back as timed strokes.${
+ section('MUSIC TO DRAW', trimTo(description, MAX_DESCRIPTION) || '(none given)')
+ }${
+ section('LYRICS / THEME (mood only — nothing is sung; drawn sounds carry the melody)', trimTo(lyrics, MAX_LYRICS))
+ }${
+ section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE))
+ }${
+ current ? section('CURRENT SKETCH (revise it per the request above — keep what works, change what is asked)', JSON.stringify(current)) : ''
+ }
+
+TARGET LENGTH: about ${target} seconds.
+
+Return ONLY a JSON object (no prose, no code fence) in exactly this shape:
+{
+ "version": 1,
+ "title": "<short title>",
+ "durationSec": <number ${L.DURATION_MIN_SEC}-${L.DURATION_MAX_SEC}>,
+ "shapes": {
+ "<shapeName>": [<${L.SHAPE_POINTS_MIN}-${L.SHAPE_POINTS_MAX} numbers in -1..1 — ONE cycle of the waveform, evenly spaced left to right; it loops, so the last point flows back into the first>]
+ },
+ "voices": [
+ {"name": "<lane name>", "shape": "<a shapeName, or \\"noise\\">", "gain": <0-1>,
+ "notes": [{"t": <start seconds>, "d": <length seconds>, "pitch": "<scientific pitch like A3 or F#4 — or use \\"hz\\": <number> instead>",
+ "glideTo": "<optional pitch the note slides to across its length>",
+ "morphTo": "<optional shapeName the timbre crossfades into across the note>",
+ "env": [<optional ${L.ENV_POINTS_MIN}-${L.ENV_POINTS_MAX} numbers 0..1 — the note's loudness drawn left to right>],
+ "v": <0-1 velocity>}]}
+ ],
+ "contour": [<optional 2-${L.CONTOUR_POINTS_MAX} numbers 0..1 — the whole piece's loudness drawn left to right>]
+}
+
+How your drawing becomes sound:
+- A shape's outline IS its timbre. Smooth round curves sound pure and soft (a sine drawn in 16 points: 0, 0.38, 0.71, 0.92, 1, 0.92, 0.71, 0.38, 0, -0.38, -0.71, -0.92, -1, -0.92, -0.71, -0.38). Straight ramps (saw) sound bright and buzzy; flat tops with sharp jumps (square) sound hollow and reedy; small ripples riding on a curve add upper harmonics — glassy, bell-like, stringy, or gritty. Most shapes need 16-64 points; spend more only on fine detail.
+- Draw a distinct shape for each role (bass, lead, pad, percussion body). Up to ${L.SHAPES_MAX} shapes and ${L.VOICES_MAX} voices; a voice plays one shape.
+- "noise" voices are unpitched: without "hz" they hiss (snares, breath, wind); with "hz" the noise is resampled at that rate (6000-16000 for crisp hats, 200-1500 for rumble and crunch).
+- Percussion is drawable too: a kick is a round shape gliding down fast ("hz": 150, "glideTo": "B0") over ~0.25s with "env": [1, 0.6, 0.2, 0]; a snare is a short noise stroke with "env": [1, 0.4, 0.1, 0]; hats are 0.03-0.08s high-hz noise strokes.
+- Without "env" a note holds full level with a quick fade in and out. Draw "env" for plucks [1, 0.5, 0.2, 0.05, 0], swells [0, 0.4, 1, 0.8], or tremolo [1, 0.4, 1, 0.4, 1, 0.4].
+- Times are absolute seconds. Choose a tempo and place notes on its grid (at 120 BPM a beat is 0.5s, a sixteenth 0.125s) so the rhythm grooves. Every note must end by durationSec. At most ${L.NOTES_MAX} notes in total.
+
+Compose real music: a memorable melody on a lead voice, a bassline that moves, harmony (pads or arpeggios), and percussion that grooves unless the description asks otherwise. Stay in key, repeat and vary motifs, and shape an arc with "contour" and velocity.`;
+}
+
+// The runner validates/coerces the response against this predicate (it strips
+// fences/prose and re-requests on an off-shape reply), so "parses into a
+// playable sketch" is the schema.
+const isPlayableSketch = (value) => normalizeWaveSketch(value) !== null;
+
+/**
+ * Ask the chosen provider to draw a wave sketch for the description. `current`
+ * (a normalized sketch) turns the call into a revision of that drawing.
+ */
+export async function drawWaveSketch({ description, lyrics, guidance, durationSec, current, providerId, model, effort } = {}) {
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, { message: 'No AI provider available to draw the waveform', code: 'NO_PROVIDER' });
+
+ const revising = normalizeWaveSketch(current);
+ const run = await runPromptThroughProvider({
+ provider,
+ model: selectedModel ?? undefined,
+ effort,
+ prompt: buildWaveSketchPrompt({ description, lyrics, guidance, durationSec, current: revising }),
+ source: 'music-waveform',
+ responseSchema: isPlayableSketch,
+ });
+
+ let parsed = null;
+ try { parsed = JSON.parse(run.text); } catch { /* handled below */ }
+ const sketch = normalizeWaveSketch(parsed);
+ if (!sketch) {
+ throw new ServerError('The AI did not return a playable waveform drawing. Try rerunning or picking a stronger model.', {
+ status: 502, code: 'WAVEFORM_BAD_RESPONSE',
+ });
+ }
+ const ranModel = run.model ?? selectedModel ?? null;
+ const noteCount = sketch.voices.reduce((sum, v) => sum + v.notes.length, 0);
+ console.log(`〰️ Drew waveform via ${provider.id}/${ranModel || 'default'} (${Object.keys(sketch.shapes).length} shapes, ${noteCount} notes, ${sketch.durationSec}s)`);
+ return { sketch, llm: { provider: run.provider?.id || provider.id, model: ranModel } };
+}
+
+/**
+ * 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).
+ */
+export async function renderWaveSketchToTrack({ trackId, sketch, prompt, title }) {
+ const normalized = normalizeWaveSketch(sketch);
+ if (!normalized) {
+ throw new ServerError('That waveform drawing has nothing playable in it', { 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,
+ }, 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)`);
+ return { track: updated, filename, durationSec };
+}
diff --git a/server/services/musicWaveform.test.js b/server/services/musicWaveform.test.js
new file mode 100644
index 0000000000..e529f3b1a8
--- /dev/null
+++ b/server/services/musicWaveform.test.js
@@ -0,0 +1,109 @@
+import { mkdtemp, readdir, readFile, rm } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const musicDir = await mkdtemp(join(tmpdir(), 'waveform-music-'));
+
+vi.mock('./tracks/index.js', () => ({
+ getTrack: vi.fn(),
+ appendActiveTake: vi.fn(async (id, take, patch) => ({ id, ...take, ...patch })),
+}));
+
+vi.mock('./promptRunner.js', async () => ({
+ ...(await vi.importActual('./promptRunner.js')),
+ resolveProviderAndModel: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+}));
+
+// No ffmpeg in tests — the render keeps the deterministic WAV output.
+vi.mock('../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn().mockResolvedValue(null),
+ runFfmpegProcess: vi.fn(),
+}));
+
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, music: musicDir } };
+});
+
+const tracks = await import('./tracks/index.js');
+const promptRunner = await import('./promptRunner.js');
+const { drawWaveSketch, renderWaveSketchToTrack } = await import('./musicWaveform.js');
+
+const drawnSketch = () => ({
+ 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' }, { t: 1, d: 1, pitch: 'E5' }] }],
+});
+
+const baseTrack = (extra = {}) => ({ id: 'track-1', title: 'Untitled music draft', prompt: 'saved prompt', renders: [], ...extra });
+
+afterAll(async () => { await rm(musicDir, { recursive: true, force: true }); });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: { id: 'prov-1', type: 'api' }, selectedModel: 'model-x' });
+});
+
+describe('drawWaveSketch', () => {
+ it('asks for a drawing and returns the normalized sketch', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()), model: 'model-x' });
+
+ const result = await drawWaveSketch({ description: 'glassy tidal ambient', lyrics: '[verse]\nsalt', durationSec: 12, providerId: 'prov-1' });
+
+ const args = promptRunner.runPromptThroughProvider.mock.calls[0][0];
+ expect(args).toMatchObject({ source: 'music-waveform', model: 'model-x' });
+ expect(args.prompt).toContain('glassy tidal ambient');
+ expect(args.prompt).toContain('about 12 seconds');
+ expect(args.prompt).not.toContain('CURRENT SKETCH');
+ // The runner's schema is "normalizes to something playable".
+ expect(args.responseSchema(drawnSketch())).toBe(true);
+ expect(args.responseSchema({ voices: [] })).toBe(false);
+ expect(result.sketch.voices[0].notes[0]).toMatchObject({ hz: 440, pitch: 'A4' });
+ expect(result.llm).toEqual({ provider: 'prov-1', model: 'model-x' });
+ });
+
+ it('sends the current drawing back when revising', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()) });
+ await drawWaveSketch({ description: 'x', guidance: 'punchier kick', current: drawnSketch() });
+ const { prompt } = promptRunner.runPromptThroughProvider.mock.calls[0][0];
+ expect(prompt).toContain('CURRENT SKETCH');
+ expect(prompt).toContain('"glass"');
+ expect(prompt).toContain('punchier kick');
+ });
+
+ it('502s when the reply has nothing playable', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'I drew you a lovely picture!' });
+ await expect(drawWaveSketch({ description: 'x' })).rejects.toMatchObject({ status: 502, code: 'WAVEFORM_BAD_RESPONSE' });
+ });
+});
+
+describe('renderWaveSketchToTrack', () => {
+ it('renders the drawing into the music library as the active waveform take', async () => {
+ tracks.getTrack.mockResolvedValue(baseTrack());
+
+ const result = await renderWaveSketchToTrack({ trackId: 'track-1', sketch: drawnSketch(), prompt: 'glassy', title: 'Glass Tide' });
+
+ expect(result.filename).toMatch(/^music-.+\.wav$/);
+ expect(await readdir(musicDir)).toContain(result.filename);
+ // 2s of 16-bit mono at 44.1 kHz behind a 44-byte header.
+ expect((await readFile(join(musicDir, result.filename))).length).toBe(44 + 2 * 44100 * 2);
+ expect(tracks.appendActiveTake).toHaveBeenCalledWith('track-1', {
+ audioFilename: result.filename, prompt: 'glassy', engine: 'waveform', durationSec: 2,
+ }, { title: 'Glass Tide' });
+ 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: [] } }))
+ .rejects.toMatchObject({ status: 400, code: 'WAVEFORM_EMPTY' });
+ tracks.getTrack.mockResolvedValue(null);
+ await expect(renderWaveSketchToTrack({ trackId: 'gone', sketch: drawnSketch() }))
+ .rejects.toMatchObject({ status: 404 });
+ expect(tracks.appendActiveTake).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/tracks/index.js b/server/services/tracks/index.js
index 4a0229d729..3b2caa2dc3 100644
--- a/server/services/tracks/index.js
+++ b/server/services/tracks/index.js
@@ -57,6 +57,20 @@ export function buildRenderAppend(track, renderInput) {
return { render, renders: [...(track?.renders || []), render] };
}
+/**
+ * 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
+ * point the top-level audio fields at it. `patch` carries any extra fields the
+ * 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 });
+}
+
/** Name of the active backend, or null before first call (for diagnostics/tests). */
export function getTracksBackendName() {
return getBackendName();