Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: paint drawn-waveform music on a stereo spectrogram canvas (#8464)
[._.]/ Adam Eivy3eb15959e10a
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsxindex 4717b1729f..32b710fd1f 100644--- a/client/src/components/music/MusicDesigner.jsx+++ b/client/src/components/music/MusicDesigner.jsx@@ -54,7 +54,7 @@ const STEPS = [];const STEP_IDS = STEPS.map((s) => s.id);// How the render step turns the description into sound: an on-device/remote-// audio model, a waveform the AI draws point by point, or Strudel code the AI+// audio model, a spectrogram the AI paints stroke by stroke, or Strudel code the AI// writes. Rides in `?engine=` (absent = the audio model).const RENDER_ENGINES = [{ id: 'model', label: 'Audio model', icon: AudioWaveform },@@ -68,7 +68,7 @@ const ENGINE_IDS = RENDER_ENGINES.map((e) => e.id);const LLM_ENGINE_PANELS = { drawn: WaveformPanel, code: CodePanel };const PROMPT_HINTS = {model: 'Required. This editable description is the prompt sent to the selected audio engine.',- drawn: 'Required. The AI draws the waveform from this editable description.',+ drawn: 'Required. The AI paints the music from this editable description.',code: 'Required. The AI writes the Strudel code from this editable description.',};const FIRST_STEP = STEP_IDS[0];diff --git a/client/src/components/music/TrackWaveformHost.jsx b/client/src/components/music/TrackWaveformHost.jsxindex ba920923ba..cf4bf63a45 100644--- a/client/src/components/music/TrackWaveformHost.jsx+++ b/client/src/components/music/TrackWaveformHost.jsx@@ -3,7 +3,7 @@** Hosts the Music Designer's `WaveformPanel` on a saved track so a drawn take* can be revised and re-rendered where the track lives: the panel opens on the- * track's stored `waveSketch`, and draws from the editor's prompt/lyrics. The+ * track's stored `waveSketch`, and paints from the editor's prompt/lyrics. The* designer owns its provider picker; this host supplies its own.*/diff --git a/client/src/components/music/WaveformPanel.jsx b/client/src/components/music/WaveformPanel.jsxindex 79c85d37e5..c2677d619e 100644--- a/client/src/components/music/WaveformPanel.jsx+++ b/client/src/components/music/WaveformPanel.jsx@@ -2,15 +2,17 @@* 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.+ * chosen AI provider PAINTS the music on a stereo spectrogram canvas (#8464,+ * server/lib/paintedCanvas.js): strokes of pitch, level, overtones, noise+ * bands and pan over time. The panel shows the painting as a spectrogram 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. Tracks drawn before #8464 hold a v1 sketch+ * (single-cycle shapes played as strokes, server/lib/waveSketch.js), which+ * still shows, plays and saves as before but is repainted rather than revised.*- * The LLM call fires only from the Draw/Revise buttons (no cold-bootstrap LLM- * calls). Every drawing is stored on the track (`waveSketch`, #8376), so it+ * The LLM call fires only from the Paint/Revise buttons (no cold-bootstrap LLM+ * calls). Every painting is stored on the track (`waveSketch`, #8376), so it* survives reloads, syncs to the user's other machines, and reopens for* revision from either host: the Music Designer's drawn engine (which passes* only `trackId`, so the panel loads the track) or the Tracks editor's "Drawn@@ -29,8 +31,9 @@ import { clamp, formatTimecode } from '../../utils/formatters';import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';import { drawTrackWaveform, getTrack, renderTrackWaveform } from '../../services/api';import {- WAVE_SKETCH_LIMITS, normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,+ isPaintedCanvas, normalizeWaveSketch, pcmPeaks, synthesizeSketchChannels,} from '../../../../server/lib/waveSketch.js';+import { PAINTED_CANVAS_LIMITS, paintedCanvasStats } from '../../../../server/lib/paintedCanvas.js';// Before #8376 the latest drawing lived only in this per-viewer key; the track// is now the store, so the stale key is just cleared.@@ -39,6 +42,9 @@ const DEFAULT_LENGTH_SEC = 20;const MIN_LENGTH_SEC = 4;const PEAK_COLUMNS = 600;const LANE_HEIGHT = 14;+const CANVAS_HEIGHT = 224;+const LOG_SPAN = Math.log(PAINTED_CANVAS_LIMITS.HZ_MAX / PAINTED_CANVAS_LIMITS.HZ_MIN);+const FREQ_GUIDES = [100, 1000, 10000];// 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];@@ -63,8 +69,120 @@ function ShapeDrawing({ name, points, color, usedBy }) {);}+const themeColor = (name, alpha) => {+ const rgb = getComputedStyle(document.documentElement).getPropertyValue(name).trim() || '128 128 128';+ return `rgb(${rgb} / ${alpha})`;+};++/**+ * Paint the canvas onto a <canvas> as a spectrogram: time → x, log frequency+ * → y. Tonal strokes draw every partial segment by segment (so a colour+ * change along a stroke shows), noise strokes fill their band, and passage+ * boundaries are dashed.+ */+function paintSpectrogram(el, canvas) {+ const ctx = el.getContext?.('2d');+ if (!ctx) return;+ const ratio = window.devicePixelRatio || 1;+ const width = el.clientWidth || 600;+ const height = CANVAS_HEIGHT;+ el.width = Math.round(width * ratio);+ el.height = Math.round(height * ratio);+ ctx.setTransform(ratio, 0, 0, ratio, 0, 0);+ ctx.clearRect(0, 0, width, height);+ const x = (t) => (t / canvas.durationSec) * width;+ const y = (hz) => height * (1 - Math.log(Math.max(PAINTED_CANVAS_LIMITS.HZ_MIN, hz) / PAINTED_CANVAS_LIMITS.HZ_MIN) / LOG_SPAN);++ ctx.lineWidth = 1;+ ctx.strokeStyle = themeColor('--port-border', 0.8);+ ctx.fillStyle = themeColor('--port-text-muted', 0.9);+ ctx.font = '10px sans-serif';+ for (const hz of FREQ_GUIDES) {+ ctx.beginPath(); ctx.moveTo(0, y(hz)); ctx.lineTo(width, y(hz)); ctx.stroke();+ ctx.fillText(hz >= 1000 ? `${hz / 1000}k` : String(hz), 2, y(hz) - 2);+ }+ ctx.setLineDash([3, 3]);+ for (const section of canvas.sections?.slice(1) ?? []) {+ ctx.beginPath(); ctx.moveTo(x(section.start), 0); ctx.lineTo(x(section.start), height); ctx.stroke();+ }+ ctx.setLineDash([]);++ const tone = themeColor('--port-accent', 1);+ const noise = themeColor('--port-accent-2', 1);+ for (const stroke of canvas.strokes) {+ const { path } = stroke;+ if (stroke.width) {+ ctx.fillStyle = noise;+ for (let k = 0; k < path.length - 1; k += 1) {+ const [a, b] = [path[k], path[k + 1]];+ const half = stroke.width / 2;+ ctx.globalAlpha = Math.min(0.7, 0.08 + Math.max(a.a, b.a) * 0.5);+ ctx.beginPath();+ ctx.moveTo(x(a.t), y(a.hz + half)); ctx.lineTo(x(b.t), y(b.hz + half));+ ctx.lineTo(x(b.t), y(b.hz - half)); ctx.lineTo(x(a.t), y(a.hz - half));+ ctx.closePath(); ctx.fill();+ }+ continue;+ }+ ctx.strokeStyle = tone;+ let colour = stroke.overtones ?? [];+ for (let k = 0; k < path.length - 1; k += 1) {+ const [a, b] = [path[k], path[k + 1]];+ if (a.overtones) colour = a.overtones;+ const next = b.overtones ?? colour;+ const partials = 1 + Math.max(colour.length, next.length);+ for (let p = 0; p < partials; p += 1) {+ const level = Math.max(a.a * (p ? colour[p - 1] ?? 0 : 1), b.a * (p ? next[p - 1] ?? 0 : 1));+ if (level <= 0 || a.hz * (p + 1) > PAINTED_CANVAS_LIMITS.HZ_MAX) continue;+ ctx.globalAlpha = Math.min(1, 0.15 + level);+ ctx.lineWidth = 0.75 + level * 2.5;+ ctx.beginPath(); ctx.moveTo(x(a.t), y(a.hz * (p + 1))); ctx.lineTo(x(b.t), y(b.hz * (p + 1))); ctx.stroke();+ }+ }+ }+ ctx.globalAlpha = 1;+}++/**+ * A v2 painting: the canvas as a spectrogram, the rendered waveform, and a+ * one-line summary. Memoized on the canvas like SketchDrawing.+ */+const CanvasPainting = memo(function CanvasPainting({ canvas, peaksPath, playheadRef }) {+ const canvasRef = useRef(null);+ const stats = useMemo(() => paintedCanvasStats(canvas), [canvas]);+ useEffect(() => {+ const el = canvasRef.current;+ if (!el) return undefined;+ paintSpectrogram(el, canvas);+ const observer = typeof ResizeObserver === 'function' ? new ResizeObserver(() => paintSpectrogram(el, canvas)) : null;+ observer?.observe(el);+ return () => observer?.disconnect();+ }, [canvas]);+ const passages = canvas.sections?.length || 1;+ return (+ <>+ <div className="text-xs text-gray-400" data-testid="waveform-canvas-summary">+ <span className="text-white">{canvas.title || 'Untitled painting'}</span>+ {' — '}{canvas.durationSec}s · {plural(stats.strokes, 'stroke')}+ {stats.noise ? ` (${stats.noise} noise)` : ''} · {plural(stats.keyframes, 'keyframe')} · {plural(passages, 'passage')}+ {canvas.bpm ? ` · ${canvas.bpm} BPM` : ''}+ </div>+ <div className="rounded border border-port-border bg-port-bg p-2">+ <div className="relative">+ <canvas ref={canvasRef} className="block w-full" style={{ height: `${CANVAS_HEIGHT}px` }} role="img" aria-label={`Spectrogram of the painting: ${plural(stats.strokes, 'stroke')} over ${canvas.durationSec} seconds`} />+ <svg viewBox={`0 0 ${PEAK_COLUMNS} 100`} className="mt-2 h-16 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" />+ </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>+ </>+ );+});+/**- * The drawing itself: every shape, the rendered waveform (with the drawn+ * A v1 drawing: 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.*/@@ -154,6 +272,7 @@ export default function WaveformPanel({// Raw field text — clamped only when used, so typing "12" isn't snapped to// the minimum after its first digit.const [lengthInput, setLengthInput] = useState(String(DEFAULT_LENGTH_SEC));+ const [review, setReview] = useState(false);const [drawing, setDrawing] = useState(null); // 'fresh' | 'revise' | nullconst [saving, setSaving] = useState(false);const [playing, setPlaying] = useState(false);@@ -162,9 +281,11 @@ export default function WaveformPanel({const playheadRef = useRef(null);const elapsedRef = useRef(null);- const pcm = useMemo(() => (sketch ? synthesizeWaveSketch(sketch) : null), [sketch]);+ const painted = isPaintedCanvas(sketch);+ // Channels: [mono] for a v1 drawing, [left, right] for a painting.+ const pcm = useMemo(() => (sketch ? synthesizeSketchChannels(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('')+ ? pcmPeaks(pcm.length === 1 ? pcm[0] : pcm[0].map((v, i) => (v + pcm[1][i]) / 2), PEAK_COLUMNS).map(([min, max], x) => `M${x + 0.5} ${(50 - max * 48).toFixed(1)}V${(50 - min * 48 + 0.5).toFixed(1)}`).join(''): ''), [pcm]);// The Music Designer passes only the draft's id: load its stored drawing@@ -232,12 +353,13 @@ export default function WaveformPanel({description: description.trim(),lyrics: lyrics.trim() || undefined,guidance: guidance.trim() || undefined,- durationSec: clamp(Number(lengthInput) || DEFAULT_LENGTH_SEC, MIN_LENGTH_SEC, WAVE_SKETCH_LIMITS.DURATION_MAX_SEC),+ durationSec: clamp(Number(lengthInput) || DEFAULT_LENGTH_SEC, MIN_LENGTH_SEC, PAINTED_CANVAS_LIMITS.DURATION_MAX_SEC),...(mode === 'revise' ? { revise: true } : {}),+ ...(review ? { review: true } : {}),providerId: providerId || undefined,model: model || undefined,effort: effort || undefined,- }, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not draw the waveform'); return null; });+ }, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not paint the music'); return null; });if (!mountedRef.current) return;setDrawing(null);if (!res?.sketch) return;@@ -255,7 +377,7 @@ export default function WaveformPanel({if (!mountedRef.current) return;setSaving(false);if (!res?.track) return;- toast.success(`Saved the drawn take (${res.durationSec}s)`);+ toast.success(`Saved the ${painted ? 'painted' : 'drawn'} take (${res.durationSec}s)`);onRendered?.(res.track);};@@ -264,19 +386,19 @@ export default function WaveformPanel({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.+ No audio model — the AI paints the sound itself on a stereo spectrogram: every stroke is a pitch, a level, a set of overtones or a band of noise moving through time. Long pieces are painted passage by passage. 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>+ <span className={LABEL_CLASS}>Painting guidance (optional)</span><inputid="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…'}+ placeholder={painted ? 'More air in the chorus, a wider stereo field…' : 'Anything the brief leaves out — texture, space, motion…'}className={FIELD_CLASS}/></label>@@ -286,7 +408,7 @@ export default function WaveformPanel({id="music-waveform-length"type="number"min={MIN_LENGTH_SEC}- max={WAVE_SKETCH_LIMITS.DURATION_MAX_SEC}+ max={PAINTED_CANVAS_LIMITS.DURATION_MAX_SEC}value={lengthInput}onChange={(event) => setLengthInput(event.target.value)}disabled={disabled}@@ -300,27 +422,44 @@ export default function WaveformPanel({{providerPicker}</div>+ <label htmlFor="music-waveform-review" className="flex items-start gap-2 text-sm text-gray-300">+ <input+ id="music-waveform-review"+ type="checkbox"+ checked={review}+ onChange={(event) => setReview(event.target.checked)}+ disabled={disabled}+ className="mt-0.5"+ />+ <span>+ Look and repaint+ <span className="block text-xs text-gray-500">Shows the AI a spectrogram of each painted passage for one more pass. Needs a provider that reads images; roughly doubles the calls.</span>+ </span>+ </label>+<div className="flex flex-wrap gap-2"><button type="button" onClick={() => draw('fresh')} disabled={disabled || busy || !trackId || !description.trim()} className={sketch ? GHOST_BTN : PRIMARY_BTN}>{drawing === 'fresh' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Brush className="h-4 w-4" />}- <span>{drawing === 'fresh' ? 'Drawing…' : sketch ? 'Draw from scratch' : 'Draw it'}</span>+ <span>{drawing === 'fresh' ? 'Painting…' : sketch ? 'Paint from scratch' : 'Paint it'}</span></button>- {sketch && (+ {painted && (<button type="button" onClick={() => draw('revise')} disabled={disabled || busy || !trackId || !description.trim()} className={PRIMARY_BTN}>{drawing === 'revise' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />}- <span>{drawing === 'revise' ? 'Revising…' : 'Revise drawing'}</span>+ <span>{drawing === 'revise' ? 'Revising…' : 'Revise painting'}</span></button>)}</div>{sketch ? (<div className="space-y-3 border-t border-port-border pt-3">- <SketchDrawing sketch={sketch} peaksPath={peaksPath} playheadRef={playheadRef} />+ {painted+ ? <CanvasPainting canvas={sketch} peaksPath={peaksPath} playheadRef={playheadRef} />+ : <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>+ <span>{playing ? 'Stop' : painted ? 'Play painting' : '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" />}@@ -333,7 +472,7 @@ export default function WaveformPanel({</div>) : (<p className="text-xs text-gray-500">- Nothing drawn yet. The drawing uses the description (and lyrics, for mood) from the earlier steps.+ Nothing painted yet. The painting uses the description and lyrics from the earlier steps.</p>)}</div>diff --git a/client/src/components/music/WaveformPanel.test.jsx b/client/src/components/music/WaveformPanel.test.jsxindex ea40784d2e..cabacae6e1 100644--- a/client/src/components/music/WaveformPanel.test.jsx+++ b/client/src/components/music/WaveformPanel.test.jsx@@ -9,6 +9,19 @@ vi.mock('../../services/api', () => ({renderTrackWaveform: vi.fn(),}));+// A v2 painted canvas (#8464): one tonal and one noise stroke.+const painted = {+ version: 2,+ title: 'Glass Tide',+ durationSec: 1,+ sections: [{ start: 0, end: 1 }],+ strokes: [+ { name: 'line', overtones: [0.4], path: [{ t: 0, hz: 440, a: 0.6 }, { t: 0.5, hz: 660, a: 0.4, overtones: [0.1, 0.5] }] },+ { name: 'air', width: 1200, pan: -0.5, path: [{ t: 0.4, hz: 5000, a: 0.2 }, { t: 1, hz: 4000, a: 0 }] },+ ],+};++// A v1 drawing stored before #8464.const drawn = {version: 1,title: 'Glass Tide',@@ -27,9 +40,9 @@ 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.createBuffer = (numberOfChannels, length, sampleRate) => {+ const data = Array.from({ length: numberOfChannels }, () => new Float32Array(length));+ return { numberOfChannels, length, sampleRate, getChannelData: (c) => data[c] };};this.createBufferSource = () => {const source = { connect: vi.fn(), disconnect: vi.fn(), start: vi.fn(), stop: vi.fn(), onended: null };@@ -61,21 +74,21 @@ describe('<WaveformPanel>', () => {// The server stores what it drew; getTrack serves it back (a reload).const stored = new Map();api.drawTrackWaveform.mockImplementation(async (trackId) => {- stored.set(trackId, drawn);- return { sketch: drawn, llm: { provider: 'provider-a', model: 'model-a' }, track: { id: trackId, waveSketch: drawn } };+ stored.set(trackId, painted);+ return { sketch: painted, llm: { provider: 'provider-a', model: 'model-a' }, track: { id: trackId, waveSketch: painted } };});api.getTrack.mockImplementation(async (trackId) => ({ id: trackId, waveSketch: stored.get(trackId) ?? null }));api.renderTrackWaveform.mockResolvedValue({ track: { id: 'track-1' }, filename: 'music-x.wav', durationSec: 1 });});afterEach(() => { cleanup(); vi.unstubAllGlobals(); });- it('draws from the description with the chosen provider, stores it on the track, and reloads it', async () => {+ it('paints from the description with the chosen provider, stores it on the track, and reloads it', async () => {const onTrackUpdate = vi.fn();renderPanel({ onTrackUpdate });- expect(screen.getByText(/Nothing drawn yet/)).toBeTruthy();+ expect(screen.getByText(/Nothing painted yet/)).toBeTruthy();- fireEvent.change(screen.getByLabelText('Drawing guidance (optional)'), { target: { value: 'lots of glide' } });- fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));+ fireEvent.change(screen.getByLabelText('Painting guidance (optional)'), { target: { value: 'lots of glide' } });+ fireEvent.click(screen.getByRole('button', { name: /Paint it/ }));await screen.findByText('Glass Tide');expect(api.drawTrackWaveform).toHaveBeenCalledWith('track-1', {@@ -87,9 +100,9 @@ describe('<WaveformPanel>', () => {model: 'model-a',effort: undefined,}, { silent: true });- expect(screen.getByTestId('waveform-shapes').textContent).toContain('glass');- expect(screen.getByText(/2 voices · 2 strokes/)).toBeTruthy();- expect(onTrackUpdate).toHaveBeenCalledWith({ id: 'track-1', waveSketch: drawn });+ expect(screen.getByTestId('waveform-canvas-summary').textContent).toContain('2 strokes (1 noise) · 4 keyframes · 1 passage');+ expect(screen.getByRole('img', { name: /Spectrogram of the painting: 2 strokes over 1 seconds/ })).toBeTruthy();+ expect(onTrackUpdate).toHaveBeenCalledWith({ id: 'track-1', waveSketch: painted });// A remount (reload) of the same draft loads the stored drawing — no LLM call.cleanup();@@ -101,45 +114,61 @@ describe('<WaveformPanel>', () => {cleanup();renderPanel({ trackId: 'track-2' });await waitFor(() => expect(api.getTrack).toHaveBeenCalledWith('track-2', { silent: true }));- expect(screen.getByText(/Nothing drawn yet/)).toBeTruthy();+ expect(screen.getByText(/Nothing painted yet/)).toBeTruthy();});- it('opens on the host track\'s stored drawing without fetching', () => {- renderPanel({ track: { id: 'track-1', waveSketch: drawn } });+ it('opens on the host track\'s stored painting without fetching', () => {+ renderPanel({ track: { id: 'track-1', waveSketch: painted } });expect(screen.getByText('Glass Tide')).toBeTruthy();- expect(screen.getByRole('button', { name: /Revise drawing/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Revise painting/ })).toBeTruthy();expect(api.getTrack).not.toHaveBeenCalled();});+ it('still shows, plays, and saves a v1 drawing, which is repainted rather than revised', async () => {+ renderPanel({ track: { id: 'track-1', waveSketch: drawn } });+ expect(screen.getByTestId('waveform-shapes').textContent).toContain('glass');+ expect(screen.getByText(/2 voices · 2 strokes/)).toBeTruthy();+ expect(screen.queryByRole('button', { name: /Revise/ })).toBeNull();+ expect(screen.getByRole('button', { name: /Paint from scratch/ })).toBeTruthy();+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: /Play drawing/ }));+ await Promise.resolve();+ });+ await screen.findByRole('button', { name: /Stop/ });+ expect(audio.sources[0].buffer.numberOfChannels).toBe(1);+ });+it('sends the typed length, clamped to the supported range', async () => {renderPanel();const length = screen.getByLabelText('Length (sec)');fireEvent.change(length, { target: { value: '1' } });fireEvent.change(length, { target: { value: '12' } });- fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));+ fireEvent.click(screen.getByRole('button', { name: /Paint it/ }));await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(1));expect(api.drawTrackWaveform.mock.calls[0][1].durationSec).toBe(12);- fireEvent.change(length, { target: { value: '999' } });- fireEvent.click(await screen.findByRole('button', { name: /Draw from scratch/ }));+ fireEvent.change(length, { target: { value: '9999' } });+ fireEvent.click(await screen.findByRole('button', { name: /Paint from scratch/ }));await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(2));- expect(api.drawTrackWaveform.mock.calls[1][1].durationSec).toBe(60);+ expect(api.drawTrackWaveform.mock.calls[1][1].durationSec).toBe(600);});- it('revises the stored drawing (the server holds it, so only the intent is sent)', async () => {+ it('revises the stored painting (the server holds it, so only the intent is sent), with an opt-in look-and-repaint pass', async () => {renderPanel();- fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));- fireEvent.click(await screen.findByRole('button', { name: /Revise drawing/ }));+ fireEvent.click(screen.getByRole('button', { name: /Paint it/ }));+ fireEvent.click(screen.getByLabelText(/Look and repaint/));+ fireEvent.click(await screen.findByRole('button', { name: /Revise painting/ }));await waitFor(() => expect(api.drawTrackWaveform).toHaveBeenCalledTimes(2));expect(api.drawTrackWaveform.mock.calls[0][1].revise).toBeUndefined();- expect(api.drawTrackWaveform.mock.calls[1][1]).toMatchObject({ revise: true });+ expect(api.drawTrackWaveform.mock.calls[0][1].review).toBeUndefined();+ expect(api.drawTrackWaveform.mock.calls[1][1]).toMatchObject({ revise: true, review: true });expect(api.drawTrackWaveform.mock.calls[1][1].current).toBeUndefined();});- it('plays and stops the synthesized drawing', async () => {+ it('plays and stops the synthesized painting in stereo', async () => {renderPanel();- fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));- const playButton = await screen.findByRole('button', { name: /Play drawing/ });+ fireEvent.click(screen.getByRole('button', { name: /Paint it/ }));+ const playButton = await screen.findByRole('button', { name: /Play painting/ });await act(async () => {fireEvent.click(playButton);await Promise.resolve();@@ -149,16 +178,17 @@ describe('<WaveformPanel>', () => {const [source] = audio.sources;expect(source.start).toHaveBeenCalled();expect(source.buffer.length).toBe(44100);+ expect(source.buffer.numberOfChannels).toBe(2);fireEvent.click(screen.getByRole('button', { name: /Stop/ }));expect(source.stop).toHaveBeenCalled();- expect(screen.getByRole('button', { name: /Play drawing/ })).toBeTruthy();+ expect(screen.getByRole('button', { name: /Play painting/ })).toBeTruthy();});- it('saves the stored drawing as a take, titled from the drawing when the user gave none', async () => {+ it('saves the stored painting as a take, titled from the painting when the user gave none', async () => {const onRendered = vi.fn();renderPanel({ onRendered });- fireEvent.click(screen.getByRole('button', { name: /Draw it/ }));+ fireEvent.click(screen.getByRole('button', { name: /Paint it/ }));fireEvent.click(await screen.findByRole('button', { name: /Save as take/ }));await waitFor(() => expect(onRendered).toHaveBeenCalledWith({ id: 'track-1' }));diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 3ee1b714d6..0b1e19df08 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -199,7 +199,7 @@ grep -i "what you want to do" client/src/lib/README.md| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. || `wireframeCore.js` | The Kestrel Neon "core assembly": icosahedron geometry (`ICOSAHEDRON_VERTICES` / `ICOSAHEDRON_EDGES`, 12 vertices, 30 edges), `rotatePoint` / `projectIcosahedron` (Y-then-X rotation + perspective), and `drawWireframeCore(ctx, frame)` — one 2D-canvas frame of the depth-shaded wireframe with its orbit rings, vertex dots, and corner angle readout. Every color is an `[r, g, b]` triple so the caller sources them from `AGENT_STATES` and resolved theme tokens; no DOM reads. Consumed by `cos/CoreCoSAvatar.jsx`. || `chiptunePlayback.js` | Looping WebAudio preview for LLM-generated chiptune scores (#2911) — `buildChiptuneSchedule(score)` (pure pattern/order → absolute-time flatten, MIRRORS `server/lib/chiptuneScore.js` timing semantics), `parseChiptunePitch("C5")` → MIDI, and `createChiptunePlayer(getScore, { onLoop })` — a seamless-loop player over `createLookaheadTransport` (pulse-duty via PeriodicWave, triangle bass, noise-buffer/sine-sweep drums), exposing `position()` (monotonic across loop passes) + `loopSec()` for playhead UIs. No React — `ChiptunePanel` drives it. |-| `waveSketchPlayback.js` | One-shot WebAudio preview for the Music Designer's LLM-drawn wave sketches (#8376) — `createWaveSketchPlayer({ onEnded })` → `{ play(pcm), stop(), position() }` over the shared `audioContext.js` context. Plays PCM from `synthesizeWaveSketch` (`server/lib/waveSketch.js`, the same deterministic synth the server renders the saved take with); a `stop()` during the resume makes `play` resolve false instead of sounding late. No React — `WaveformPanel` drives it in both the Music Designer and the Tracks editor. |+| `waveSketchPlayback.js` | One-shot WebAudio preview for the Music Designer's LLM-made wave sketches (#8376; stereo painted canvases #8464) — `createWaveSketchPlayer({ onEnded })` → `{ play(pcm | channels), stop(), position() }` over the shared `audioContext.js` context. Plays PCM from `synthesizeSketchChannels` (`server/lib/waveSketch.js`, the same deterministic synth the server renders the saved take with); a `stop()` during the resume makes `play` resolve false instead of sounding late. No React — `WaveformPanel` drives it in both the Music Designer and the Tracks editor. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |diff --git a/client/src/lib/waveSketchPlayback.js b/client/src/lib/waveSketchPlayback.jsindex 55288502cf..4f639907e4 100644--- a/client/src/lib/waveSketchPlayback.js+++ b/client/src/lib/waveSketchPlayback.js@@ -1,7 +1,8 @@-// One-shot WebAudio preview for the Music Designer's LLM-drawn wave sketches-// (#8376). The PCM comes from `synthesizeWaveSketch` in-// server/lib/waveSketch.js — the same deterministic synth the server renders a-// saved take with — so what plays here is exactly what gets saved.+// One-shot WebAudio preview for the Music Designer's LLM-made wave sketches+// (#8376): v1 drawings (mono) and v2 painted canvases (stereo, #8464). The PCM+// comes from `synthesizeSketchChannels` in server/lib/waveSketch.js — the same+// deterministic synth the server renders a saved take with — so what plays+// here is exactly what gets saved.//// No React: `WaveformPanel` drives it, whichever host mounts the panel (the// Music Designer's drawn engine or the Tracks editor's "Drawn waveform" mode).@@ -13,7 +14,8 @@ import { WAVE_SKETCH_SAMPLE_RATE } from '../../../server/lib/waveSketch.js';/*** A single-source player for synthesized sketch PCM.*- * - `play(pcm)` → Promise<boolean>: stops any current playback, resumes the+ * - `play(pcm)` → Promise<boolean>: `pcm` is one mono Float32Array or an array+ * of channels (`[left, right]`). Stops any current playback, resumes the* shared context, and starts the buffer. Resolves false when a `stop()` (or* a newer `play`) landed while the context was resuming, so a stale start* never sounds. Rejects when the context cannot resume.@@ -42,8 +44,9 @@ export function createWaveSketchPlayer({ onEnded } = {}) {const ctx = getAudioContext();await resumeAudioContext(ctx);if (token !== generation) return false;- const buffer = ctx.createBuffer(1, pcm.length, WAVE_SKETCH_SAMPLE_RATE);- buffer.getChannelData(0).set(pcm);+ const channels = Array.isArray(pcm) ? pcm : [pcm];+ const buffer = ctx.createBuffer(channels.length, channels[0].length, WAVE_SKETCH_SAMPLE_RATE);+ channels.forEach((data, c) => buffer.getChannelData(c).set(data));const node = ctx.createBufferSource();node.buffer = buffer;node.connect(ctx.destination);diff --git a/server/lib/README.md b/server/lib/README.mdindex 91247a17d2..288b7a586c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -514,7 +514,9 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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 and the code-engine take upload. `wavDurationMs(buffer)` reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). |-| `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`. |+| `waveSketch.js` | Drawn-waveform music contract v1 (browser-safe; new paintings are v2 — see `paintedCanvas.js`): 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`. `normalizeWaveSketch` dispatches a `version: 2` sketch to `normalizePaintedCanvas`; `synthesizeSketchChannels(sketch)` renders either version to its channel list; `isPaintedCanvas(sketch)`. |+| `paintedCanvas.js` | Painted-spectrogram canvas, wave sketch v2 (#8464, browser-safe): stereo time × log-frequency canvas painted with strokes (`path` keyframes `{t, hz, a}`, per-keyframe `overtones`, noise `width`, `pan`), plus optional `sections` and tempo grid. `normalizePaintedCanvas(raw, { durationSec, limits })` is the lenient idempotent validator; `synthesizePaintedCanvas(canvas)` → deterministic `[left, right]` PCM using only IEEE-exact math (series sine table, log2/exp2), so server WAV and browser preview match on any engine; render work bounded by `PAINTED_CANVAS_LIMITS.WORK_MAX_PARTIAL_SEC`; `paintedCanvasStats(canvas)` → stroke/keyframe/noise/work totals. |+| `spectrogramImage.js` | `spectrogramPixels(pcm, { sampleRate, width, height, minHz, maxHz })` → raw RGB pixels of a log-frequency STFT spectrogram (80 dB range) — the picture a model gets of its own painted canvas in the review pass (#8464). Pure; the caller encodes the PNG. || `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/chiptuneRender.js b/server/lib/chiptuneRender.jsindex de8901f191..56904fbd2a 100644--- a/server/lib/chiptuneRender.js+++ b/server/lib/chiptuneRender.js@@ -117,9 +117,16 @@ export function renderScoreToPcm(score, { sampleRate = CHIPTUNE_SAMPLE_RATE } =return out;}-/** Encode mono Float32 PCM as a 16-bit little-endian WAV file buffer. */+/**+ * Encode Float32 PCM as a 16-bit little-endian WAV file buffer. `pcm` is one+ * mono Float32Array, or an array of equal-length channels (interleaved, e.g.+ * `[left, right]` for stereo).+ */export function pcmToWavBuffer(pcm, { sampleRate = CHIPTUNE_SAMPLE_RATE } = {}) {- const dataBytes = pcm.length * 2;+ const channels = Array.isArray(pcm) ? pcm : [pcm];+ const frames = channels[0].length;+ const blockAlign = channels.length * 2;+ const dataBytes = frames * blockAlign;const buf = Buffer.alloc(44 + dataBytes);buf.write('RIFF', 0);buf.writeUInt32LE(36 + dataBytes, 4);@@ -127,15 +134,17 @@ export function pcmToWavBuffer(pcm, { sampleRate = CHIPTUNE_SAMPLE_RATE } = {})buf.write('fmt ', 12);buf.writeUInt32LE(16, 16); // fmt chunk sizebuf.writeUInt16LE(1, 20); // PCM- buf.writeUInt16LE(1, 22); // mono+ buf.writeUInt16LE(channels.length, 22);buf.writeUInt32LE(sampleRate, 24);- buf.writeUInt32LE(sampleRate * 2, 28); // byte rate- buf.writeUInt16LE(2, 32); // block align+ buf.writeUInt32LE(sampleRate * blockAlign, 28); // byte rate+ buf.writeUInt16LE(blockAlign, 32);buf.writeUInt16LE(16, 34); // bits per samplebuf.write('data', 36);buf.writeUInt32LE(dataBytes, 40);- for (let i = 0; i < pcm.length; i += 1) {- buf.writeInt16LE(Math.round(pcm[i] * 32767), 44 + i * 2);+ for (let i = 0; i < frames; i += 1) {+ for (let c = 0; c < channels.length; c += 1) {+ buf.writeInt16LE(Math.round(channels[c][i] * 32767), 44 + i * blockAlign + c * 2);+ }}return buf;}diff --git a/server/lib/index.js b/server/lib/index.jsindex 83e3ce5bc0..b0db6c62a5 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -474,6 +474,8 @@ export * from './chiptuneScore.js';export * from './pitchMath.js';export * from './wavAudioFile.js';export * from './waveSketch.js';+export * from './paintedCanvas.js';+export * from './spectrogramImage.js';export * from './civitai.js';export * from './huggingfaceLora.js';export * from './huggingfaceModel.js';diff --git a/server/lib/paintedCanvas.js b/server/lib/paintedCanvas.jsnew file mode 100644index 0000000000..d3f43cc55a--- /dev/null+++ b/server/lib/paintedCanvas.js@@ -0,0 +1,481 @@+/**+ * Painted-spectrogram canvas — wave sketch `version: 2` (#8464).+ *+ * The model paints sound onto a stereo time × log-frequency canvas with one+ * brush. A stroke is a `path` of keyframes `{t, hz, a}`; between keyframes+ * pitch moves on the log axis and amplitude moves linearly. Optional brush+ * properties:+ *+ * - `overtones` — relative levels of the partials at 2×, 3×… the stroke's+ * pitch. Set on the stroke (a default) or on any keyframe+ * (from that keyframe on), so a stroke's color can change+ * along its length.+ * - `width` — Hz > 0 makes the stroke band-passed noise of that+ * bandwidth centred on its pitch.+ * - `pan` — -1 (left) … 1 (right), equal-power.+ *+ * Nothing else exists: reverb, chorus, voices and drums are whatever the model+ * paints. Long pieces carry `sections` (the passages they were painted in) and+ * an optional tempo grid (`bpm`/`beatsPerBar`).+ *+ * `normalizePaintedCanvas` is the ONE validator — lenient (clamps what it can,+ * drops what it can't, null when no stroke survives) and idempotent.+ * `synthesizePaintedCanvas` renders a normalized canvas to stereo PCM using+ * only IEEE-exact arithmetic (+ − × ÷ √, floor): sines come from a table built+ * by polynomial, log-pitch uses series log2/exp2, and noise is seeded, so the+ * server WAV and the browser preview are the same samples on any JS engine.+ * Render work is bounded by `WORK_MAX_PARTIAL_SEC` (stroke-seconds × partials).+ *+ * Pure and dependency-free: imported by the client (WaveformPanel) and the+ * server (musicWaveform.js) through lib/waveSketch.js.+ */++export const PAINTED_CANVAS_VERSION = 2;+export const PAINTED_CANVAS_SAMPLE_RATE = 44100;++export const PAINTED_CANVAS_LIMITS = Object.freeze({+ DURATION_MIN_SEC: 1,+ DURATION_MAX_SEC: 600,+ HZ_MIN: 20,+ HZ_MAX: 16000,+ STROKES_MAX: 4000,+ KEYFRAMES_PER_STROKE_MAX: 256,+ KEYFRAMES_MAX: 40000,+ OVERTONES_MAX: 16,+ WIDTH_MIN_HZ: 10,+ WIDTH_MAX_HZ: 16000,+ // Render work: Σ over strokes of (length in seconds × partials), where a+ // tonal stroke has 1 + its overtone count partials and a noise stroke costs+ // NOISE_STROKE_COST. At 44.1 kHz the cap is ~1 G partial-samples — a few+ // seconds of render; a dense 3-minute painting uses roughly a third of it.+ WORK_MAX_PARTIAL_SEC: 24000,+ NOISE_STROKE_COST: 3,+ SECTIONS_MAX: 40,+ BPM_MIN: 20,+ BPM_MAX: 300,+ BEATS_PER_BAR_MAX: 16,+ TITLE_MAX: 120,+ NAME_MAX: 24,+});++const L = PAINTED_CANVAS_LIMITS;+// The mix is output at half the summed amplitude, then scaled down (never up)+// only when it would still clip.+export const PAINTED_CANVAS_MASTER_GAIN = 0.5;+const CLIP_CEILING = 0.98;+export const PAINTED_CANVAS_DECLICK_SEC = 0.003;+const BLOCK = 64;+const NYQUIST_GUARD = 0.49; // cycles per sample above which a partial is silent++const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));+const isNum = (n) => typeof n === 'number' && Number.isFinite(n);+const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+// Keep stored numbers short — the painting is sent back to the model on revision.+const round = (n, places = 4) => Math.round(n * 10 ** places) / 10 ** places;+const cleanName = (value) => (typeof value === 'string' ? value.trim().slice(0, L.NAME_MAX) : '');++// ---------------------------------------------------------------------------+// Deterministic math — only correctly-rounded IEEE operations, so every JS+// engine produces identical samples (Math.sin/pow/log are implementation-+// defined and differ in the last bits between engines).++const TWO_PI = 6.283185307179586;+const HALF_PI = 1.5707963267948966;+const LN2 = 0.6931471805599453;++/** sin(x) for x ∈ [-π/2, π/2] by Taylor series (error < 1e-15 there). */+function polySin(x) {+ const x2 = x * x;+ let term = x;+ let sum = x;+ for (let n = 1; n < 12; n += 1) {+ term = (-term * x2) / ((2 * n) * (2 * n + 1));+ sum += term;+ }+ return sum;+}++/** sin(2π·turns) for any finite `turns`, by reduction to [-π/2, π/2]. */+function detSinTurns(turns) {+ let f = turns - Math.floor(turns); // [0, 1)+ if (f > 0.5) f -= 1; // (-0.5, 0.5]+ let x = f * TWO_PI; // (-π, π]+ if (x > HALF_PI) x = Math.PI - x;+ else if (x < -HALF_PI) x = -Math.PI - x;+ return polySin(x);+}++const SINE_TABLE_SIZE = 4096;+const SINE_TABLE = (() => {+ const table = new Float64Array(SINE_TABLE_SIZE + 1);+ for (let i = 0; i <= SINE_TABLE_SIZE; i += 1) table[i] = detSinTurns(i / SINE_TABLE_SIZE);+ return table;+})();++/** log2(x) for x > 0: exact power-of-two split plus an atanh series. */+function detLog2(x) {+ let m = x;+ let e = 0;+ while (m >= 2) { m /= 2; e += 1; }+ while (m < 1) { m *= 2; e -= 1; }+ const s = (m - 1) / (m + 1); // [0, 1/3)+ const s2 = s * s;+ let term = s;+ let sum = 0;+ for (let k = 1; k < 40; k += 2) {+ sum += term / k;+ term *= s2;+ }+ return e + (2 * sum) / LN2;+}++/** 2^y: exact integer part plus a Taylor series for the fraction. */+function detExp2(y) {+ const n = Math.floor(y);+ const z = (y - n) * LN2; // [0, ln2)+ let term = 1;+ let sum = 1;+ for (let k = 1; k < 20; k += 1) {+ term = (term * z) / k;+ sum += term;+ }+ let scale = 1;+ if (n > 0) for (let i = 0; i < n; i += 1) scale *= 2;+ else for (let i = 0; i < -n; i += 1) scale /= 2;+ return sum * scale;+}++// 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;+ };+}++// ---------------------------------------------------------------------------+// Validation++function normalizeOvertones(raw) {+ if (!Array.isArray(raw)) return null;+ const levels = raw.slice(0, L.OVERTONES_MAX).map((n) => (isNum(n) ? round(clamp(n, 0, 1)) : 0));+ while (levels.length && levels[levels.length - 1] === 0) levels.pop();+ return levels;+}++function resolveKeyframeHz(raw) {+ if (!isNum(raw)) return null;+ return raw >= L.HZ_MIN ? round(Math.min(raw, L.HZ_MAX), 3) : null;+}++/** Keyframes in time order: finite t/hz, strictly increasing t, ≥ 2 of them. */+function normalizePath(raw, durationSec, isNoise) {+ if (!Array.isArray(raw)) return null;+ const path = [];+ for (const k of raw.slice(0, L.KEYFRAMES_PER_STROKE_MAX * 2)) {+ if (path.length >= L.KEYFRAMES_PER_STROKE_MAX) break;+ if (!isObj(k) || !isNum(k.t)) continue;+ const hz = resolveKeyframeHz(k.hz);+ if (hz == null) continue;+ const t = round(clamp(k.t, 0, durationSec));+ if (path.length && t <= path[path.length - 1].t) continue;+ const frame = { t, hz, a: round(isNum(k.a) ? clamp(k.a, 0, 1) : 0) };+ const overtones = isNoise ? null : normalizeOvertones(k.overtones);+ if (overtones) frame.overtones = overtones;+ path.push(frame);+ }+ return path.length >= 2 ? path : null;+}++/** Highest partial count the stroke ever reaches (1 = fundamental only). */+function partialCount(stroke) {+ let most = stroke.overtones?.length ?? 0;+ for (const k of stroke.path) if (k.overtones) most = Math.max(most, k.overtones.length);+ return 1 + most;+}++/** Render work of one normalized stroke, in partial-seconds. */+function strokeWork(stroke) {+ const seconds = stroke.path[stroke.path.length - 1].t - stroke.path[0].t;+ return seconds * (stroke.width ? L.NOISE_STROKE_COST : partialCount(stroke));+}++function normalizeStroke(raw, durationSec) {+ if (!isObj(raw)) return null;+ const width = isNum(raw.width) && raw.width > 0 ? round(clamp(raw.width, L.WIDTH_MIN_HZ, L.WIDTH_MAX_HZ), 2) : 0;+ const path = normalizePath(raw.path, durationSec, width > 0);+ if (!path) return null;+ const stroke = {};+ const name = cleanName(raw.name);+ if (name) stroke.name = name;+ const pan = isNum(raw.pan) ? round(clamp(raw.pan, -1, 1), 3) : 0;+ if (pan) stroke.pan = pan;+ if (width) stroke.width = width;+ const overtones = width ? null : normalizeOvertones(raw.overtones);+ if (overtones?.length) stroke.overtones = overtones;+ stroke.path = path;+ return stroke;+}++function normalizeSections(raw, durationSec) {+ if (!Array.isArray(raw)) return [];+ const sections = [];+ for (const s of raw.slice(0, L.SECTIONS_MAX * 2)) {+ if (sections.length >= L.SECTIONS_MAX) break;+ if (!isObj(s) || !isNum(s.start) || !isNum(s.end)) continue;+ const start = round(clamp(s.start, 0, durationSec), 3);+ const end = round(clamp(s.end, 0, durationSec), 3);+ const prevEnd = sections.length ? sections[sections.length - 1].end : 0;+ if (!(end > start) || start < prevEnd) continue;+ const section = { start, end };+ const name = cleanName(s.name);+ if (name) section.name = name;+ sections.push(section);+ }+ return sections;+}++/**+ * Validate + canonicalize a painted canvas (an LLM reply, a stored sketch, or a+ * client round-trip). `limits` narrows the stroke/keyframe/work budgets — the+ * painting service uses it to give each passage its share. Returns the+ * normalized canvas, or null when no stroke survives.+ */+export function normalizePaintedCanvas(raw, { durationSec: fixedDuration, limits = {} } = {}) {+ if (!isObj(raw)) return null;+ const rawStrokes = Array.isArray(raw.strokes) ? raw.strokes.slice(0, L.STROKES_MAX * 2) : [];+ let durationSec = fixedDuration;+ if (!isNum(durationSec)) {+ // An absent/invalid duration is derived from the painting itself.+ const lastT = rawStrokes.reduce((end, s) => (Array.isArray(s?.path)+ ? s.path.slice(0, L.KEYFRAMES_PER_STROKE_MAX).reduce((e, k) => (isNum(k?.t) ? Math.max(e, k.t) : e), end)+ : end), 0);+ durationSec = isNum(raw.durationSec) ? raw.durationSec : lastT;+ }+ durationSec = round(clamp(durationSec, L.DURATION_MIN_SEC, L.DURATION_MAX_SEC), 3);++ let strokeBudget = Math.min(L.STROKES_MAX, limits.strokes ?? L.STROKES_MAX);+ let keyframeBudget = Math.min(L.KEYFRAMES_MAX, limits.keyframes ?? L.KEYFRAMES_MAX);+ let workBudget = Math.min(L.WORK_MAX_PARTIAL_SEC, limits.work ?? L.WORK_MAX_PARTIAL_SEC);+ const strokes = [];+ for (const rawStroke of rawStrokes) {+ if (strokeBudget <= 0) break;+ const stroke = normalizeStroke(rawStroke, durationSec);+ if (!stroke) continue;+ const work = strokeWork(stroke);+ // Over a budget → dropped in the order returned (later strokes go first).+ if (stroke.path.length > keyframeBudget || work > workBudget) continue;+ strokes.push(stroke);+ strokeBudget -= 1;+ keyframeBudget -= stroke.path.length;+ workBudget -= work;+ }+ if (!strokes.length) return null;+ // Stable onset order (the budget pass above already ran in reply order).+ strokes.sort((a, b) => a.path[0].t - b.path[0].t);++ const canvas = { version: PAINTED_CANVAS_VERSION, title: '', durationSec };+ if (typeof raw.title === 'string') canvas.title = raw.title.trim().slice(0, L.TITLE_MAX);+ if (isNum(raw.bpm)) canvas.bpm = round(clamp(raw.bpm, L.BPM_MIN, L.BPM_MAX), 2);+ if (canvas.bpm && isNum(raw.beatsPerBar)) canvas.beatsPerBar = clamp(Math.round(raw.beatsPerBar), 1, L.BEATS_PER_BAR_MAX);+ const sections = normalizeSections(raw.sections, durationSec);+ if (sections.length) canvas.sections = sections;+ canvas.strokes = strokes;+ return canvas;+}++/** Totals used by the UI and logs. */+export function paintedCanvasStats(canvas) {+ let keyframes = 0;+ let work = 0;+ let noise = 0;+ for (const s of canvas.strokes) {+ keyframes += s.path.length;+ work += strokeWork(s);+ if (s.width) noise += 1;+ }+ return { strokes: canvas.strokes.length, keyframes, noise, work: round(work, 2) };+}++// ---------------------------------------------------------------------------+// Rendering++/** Each keyframe's effective overtone levels (a keyframe inherits the last set). */+function resolvedOvertones(stroke) {+ let current = stroke.overtones ?? [];+ return stroke.path.map((k) => {+ if (k.overtones) current = k.overtones;+ return current;+ });+}++/**+ * A cursor over one stroke's keyframes. `at(t)` must be called with+ * non-decreasing t and fills `state` = { hz, amp: [partial levels × a] }.+ */+function strokeCursor(stroke, partials) {+ const { path } = stroke;+ const overtones = resolvedOvertones(stroke);+ const start = path[0].t;+ const end = path[path.length - 1].t;+ const declick = Math.min(PAINTED_CANVAS_DECLICK_SEC, (end - start) / 2);+ let seg = 0;+ let segLog = null;+ const state = { hz: path[0].hz, amp: new Float64Array(partials) };+ const at = (t) => {+ while (seg < path.length - 2 && t > path[seg + 1].t) { seg += 1; segLog = null; }+ const k0 = path[seg];+ const k1 = path[seg + 1];+ const u = clamp((t - k0.t) / (k1.t - k0.t), 0, 1);+ if (k0.hz === k1.hz) state.hz = k0.hz;+ else {+ segLog ??= detLog2(k1.hz / k0.hz);+ state.hz = k0.hz * detExp2(u * segLog);+ }+ const edge = Math.min(1, (t - start) / declick, (end - t) / declick);+ const level = (k0.a + (k1.a - k0.a) * u) * Math.max(0, edge);+ state.amp[0] = level;+ const o0 = overtones[seg];+ const o1 = overtones[seg + 1];+ for (let p = 1; p < partials; p += 1) {+ const r0 = o0[p - 1] ?? 0;+ const r1 = o1[p - 1] ?? 0;+ state.amp[p] = level * (r0 + (r1 - r0) * u);+ }+ return state;+ };+ return { start, end, at };+}++function tonalStrokeInto(stroke, buf, fromSample, sampleRate) {+ const partials = partialCount(stroke);+ const cursor = strokeCursor(stroke, partials);+ const phases = new Float64Array(partials);+ const s0 = Math.max(fromSample, Math.ceil(cursor.start * sampleRate));+ const s1 = Math.min(fromSample + buf.length, Math.floor(cursor.end * sampleRate));+ const ampA = new Float64Array(partials);+ for (let b = s0; b < s1; b += BLOCK) {+ const e = Math.min(s1, b + BLOCK);+ const n = e - b;+ let st = cursor.at(b / sampleRate);+ const hzA = st.hz;+ ampA.set(st.amp);+ st = cursor.at(e / sampleRate);+ const hzB = st.hz;+ for (let p = 0; p < partials; p += 1) {+ const incA = (hzA * (p + 1)) / sampleRate;+ const incB = (hzB * (p + 1)) / sampleRate;+ const a0 = incA < NYQUIST_GUARD ? ampA[p] : 0;+ const a1 = incB < NYQUIST_GUARD ? st.amp[p] : 0;+ if (a0 === 0 && a1 === 0) {+ const advanced = phases[p] + ((incA + incB) / 2) * n;+ phases[p] = advanced - Math.floor(advanced);+ continue;+ }+ const dInc = (incB - incA) / n;+ const dAmp = (a1 - a0) / n;+ let phase = phases[p];+ let inc = incA;+ let amp = a0;+ for (let i = 0, s = b - fromSample; i < n; i += 1, s += 1) {+ phase += inc;+ if (phase >= 1) phase -= 1; // inc < 0.5, so one wrap suffices+ const x = phase * SINE_TABLE_SIZE;+ const j = Math.floor(x);+ buf[s] += (SINE_TABLE[j] + (SINE_TABLE[j + 1] - SINE_TABLE[j]) * (x - j)) * amp;+ inc += dInc;+ amp += dAmp;+ }+ phases[p] = phase;+ }+ }+}++function noiseStrokeInto(stroke, buf, fromSample, sampleRate, seed) {+ const cursor = strokeCursor(stroke, 1);+ const random = seededRandom(seed);+ const nyquist = sampleRate / 2;+ const s0 = Math.max(fromSample, Math.ceil(cursor.start * sampleRate));+ const s1 = Math.min(fromSample + buf.length, Math.floor(cursor.end * sampleRate));+ // Unit-RMS-ish band: white noise (RMS 1/√3) through a 0 dB-peak band-pass of+ // equivalent noise bandwidth ≈ π/2 × width keeps ≈ π·width/fs of its power;+ // scale so a band of amplitude a is about as loud as a sine of amplitude a.+ const bandwidth = Math.min(stroke.width, nyquist);+ const gain = Math.sqrt((3 * sampleRate) / (2 * Math.PI * bandwidth));+ let x1 = 0; let x2 = 0; let y1 = 0; let y2 = 0;+ for (let b = s0; b < s1; b += BLOCK) {+ const e = Math.min(s1, b + BLOCK);+ const n = e - b;+ const a0 = cursor.at(b / sampleRate).amp[0];+ const st = cursor.at(e / sampleRate);+ const a1 = st.amp[0];+ // RBJ band-pass (constant 0 dB peak), retuned once per block.+ const centre = Math.min(st.hz, nyquist * 0.95);+ const q = clamp(centre / bandwidth, 0.05, 200);+ const w = centre / sampleRate; // turns per sample+ const sinW = detSinTurns(w);+ const cosW = detSinTurns(w + 0.25);+ const alpha = sinW / (2 * q);+ const norm = 1 / (1 + alpha);+ const b0 = alpha * norm;+ const fa1 = -2 * cosW * norm;+ const fa2 = (1 - alpha) * norm;+ const dAmp = (a1 - a0) / n;+ let amp = a0;+ for (let i = 0, s = b - fromSample; i < n; i += 1, s += 1) {+ const x0 = random() * 2 - 1;+ const y0 = b0 * x0 - b0 * x2 - fa1 * y1 - fa2 * y2;+ x2 = x1; x1 = x0; y2 = y1; y1 = y0;+ buf[s] += y0 * gain * amp;+ amp += dAmp;+ }+ }+}++/** Equal-power pan gains for pan ∈ [-1, 1]. */+function panGains(pan = 0) {+ const turns = (pan + 1) / 8; // θ = (pan + 1)·π/4+ return [detSinTurns(turns + 0.25), detSinTurns(turns)];+}++/**+ * Render a NORMALIZED canvas to stereo PCM: `[left, right]` Float32Arrays in+ * [-1, 1]. Deterministic across engines (see the module comment).+ */+export function synthesizePaintedCanvas(canvas, { sampleRate = PAINTED_CANVAS_SAMPLE_RATE } = {}) {+ const total = Math.max(1, Math.round(canvas.durationSec * sampleRate));+ const left = new Float64Array(total);+ const right = new Float64Array(total);+ canvas.strokes.forEach((stroke, index) => {+ const from = Math.max(0, Math.ceil(stroke.path[0].t * sampleRate));+ const to = Math.min(total, Math.floor(stroke.path[stroke.path.length - 1].t * sampleRate) + 1);+ if (to <= from) return;+ const buf = new Float64Array(to - from);+ if (stroke.width) noiseStrokeInto(stroke, buf, from, sampleRate, (index + 1) * 100003);+ else tonalStrokeInto(stroke, buf, from, sampleRate);+ const [gl, gr] = panGains(stroke.pan);+ for (let i = 0; i < buf.length; i += 1) {+ left[from + i] += buf[i] * gl;+ right[from + i] += buf[i] * gr;+ }+ });++ let peak = 0;+ for (let s = 0; s < total; s += 1) {+ peak = Math.max(peak, Math.abs(left[s]), Math.abs(right[s]));+ }+ // Scale down (never up) so a dense painting can't clip — deterministic,+ // unlike a compressor, so preview and render stay identical.+ const scale = PAINTED_CANVAS_MASTER_GAIN * (peak * PAINTED_CANVAS_MASTER_GAIN > CLIP_CEILING ? CLIP_CEILING / (peak * PAINTED_CANVAS_MASTER_GAIN) : 1);+ const outL = new Float32Array(total);+ const outR = new Float32Array(total);+ for (let s = 0; s < total; s += 1) {+ outL[s] = left[s] * scale;+ outR[s] = right[s] * scale;+ }+ return [outL, outR];+}diff --git a/server/lib/paintedCanvas.test.js b/server/lib/paintedCanvas.test.jsnew file mode 100644index 0000000000..fa7504c9ae--- /dev/null+++ b/server/lib/paintedCanvas.test.js@@ -0,0 +1,162 @@+import { describe, expect, it } from 'vitest';+import {+ PAINTED_CANVAS_LIMITS, PAINTED_CANVAS_SAMPLE_RATE, normalizePaintedCanvas, paintedCanvasStats, synthesizePaintedCanvas,+} from './paintedCanvas.js';+import { normalizeWaveSketch, synthesizeSketchChannels } from './waveSketch.js';+import { PORTOS_SCHEMA_VERSIONS, compareSchemaVersions } from './schemaVersions.js';++const L = PAINTED_CANVAS_LIMITS;+const SR = PAINTED_CANVAS_SAMPLE_RATE;++const canvasOf = (strokes, extra = {}) => ({ version: 2, durationSec: 2, strokes, ...extra });+const tone = (hz, { from = 0, to = 1, a = 0.8, ...rest } = {}) => ({ path: [{ t: from, hz, a }, { t: to, hz, a }], ...rest });++// Energy of one frequency in a window (Goertzel), normalized per sample.+const levelAt = (pcm, hz, from, to) => {+ const w = (2 * Math.PI * hz) / SR;+ const coeff = 2 * Math.cos(w);+ let s1 = 0;+ let s2 = 0;+ for (let i = from; i < to; i += 1) {+ const s0 = pcm[i] + coeff * s1 - s2;+ s2 = s1;+ s1 = s0;+ }+ return Math.sqrt(s1 * s1 + s2 * s2 - coeff * s1 * s2) / (to - from);+};++describe('normalizePaintedCanvas', () => {+ it('canonicalizes a painting and round-trips it idempotently (including through JSON)', () => {+ const raw = canvasOf([+ { name: ' breath ', width: 900, pan: -2, overtones: [0.5], path: [{ t: 0.5, hz: 3000, a: 0.3 }, { t: 1.5, hz: 2500, a: 2 }] },+ {+ name: 'line',+ pan: 0.25,+ overtones: [0.5, 0.25, 0, 0],+ path: [+ { t: 0, hz: 220, a: 0.5 },+ { t: 0.4, hz: 220, a: 0.6, overtones: [0, 0.8, 7] },+ { t: 0.4, hz: 400, a: 1 }, // same instant — dropped+ { t: 1, hz: 'loud', a: 1 }, // no pitch — dropped+ { t: 1.2, hz: 99999, a: 0.2 },+ ],+ },+ { path: [{ t: 0, hz: 440, a: 1 }] }, // one keyframe cannot sound+ ], { title: ' Tide ', bpm: 92.123, beatsPerBar: 3.4, sections: [{ start: 0, end: 1, name: 'a' }, { start: 0.5, end: 2 }, { start: 1, end: 2 }] });++ const canvas = normalizePaintedCanvas(raw);+ expect(canvas).toEqual({+ version: 2,+ title: 'Tide',+ durationSec: 2,+ bpm: 92.12,+ beatsPerBar: 3,+ // The overlapping section is dropped.+ sections: [{ start: 0, end: 1, name: 'a' }, { start: 1, end: 2 }],+ strokes: [+ {+ name: 'line',+ pan: 0.25,+ overtones: [0.5, 0.25],+ path: [{ t: 0, hz: 220, a: 0.5 }, { t: 0.4, hz: 220, a: 0.6, overtones: [0, 0.8, 1] }, { t: 1.2, hz: L.HZ_MAX, a: 0.2 }],+ },+ // A noise stroke keeps no overtones; pan and level are clamped.+ { name: 'breath', pan: -1, width: 900, path: [{ t: 0.5, hz: 3000, a: 0.3 }, { t: 1.5, hz: 2500, a: 1 }] },+ ],+ });+ expect(normalizePaintedCanvas(canvas)).toEqual(canvas);+ expect(normalizePaintedCanvas(JSON.parse(JSON.stringify(canvas)))).toEqual(canvas);+ // The version-dispatching entry point used by tracks and the client agrees.+ expect(normalizeWaveSketch(JSON.parse(JSON.stringify(canvas)))).toEqual(canvas);+ });++ it('returns null when no stroke survives', () => {+ expect(normalizePaintedCanvas(null)).toBeNull();+ expect(normalizePaintedCanvas(canvasOf([]))).toBeNull();+ expect(normalizePaintedCanvas(canvasOf([{ path: [{ t: 0, hz: 5, a: 1 }, { t: 1, hz: 10, a: 1 }] }]))).toBeNull();+ });++ it('drops strokes past the render-work budget, in reply order, and bounds its own scan', () => {+ // Each stroke: 100 s × 17 partials = 1700 partial-seconds.+ const heavy = Array.from({ length: 30 }, (_, i) => ({+ name: `s${i}`, overtones: Array(16).fill(0.5), path: [{ t: 0, hz: 110, a: 0.2 }, { t: 100, hz: 110, a: 0.2 }],+ }));+ const canvas = normalizePaintedCanvas(canvasOf(heavy, { durationSec: 180 }));+ expect(paintedCanvasStats(canvas).work).toBeLessThanOrEqual(L.WORK_MAX_PARTIAL_SEC);+ expect(canvas.strokes.map((s) => s.name)).toEqual(heavy.slice(0, canvas.strokes.length).map((s) => s.name));++ // A narrower per-passage budget is honoured too.+ expect(normalizePaintedCanvas(canvasOf(heavy, { durationSec: 180 }), { limits: { work: 3500 } }).strokes).toHaveLength(2);++ const huge = { path: Array.from({ length: 1_000_000 }, (_, i) => ({ t: i / 1000, hz: 220, a: 0.1 })) };+ expect(normalizePaintedCanvas(canvasOf([huge], { durationSec: 600 })).strokes[0].path).toHaveLength(L.KEYFRAMES_PER_STROKE_MAX);+ });+});++describe('synthesizePaintedCanvas', () => {+ it('renders stereo deterministically, with pitch, pan, and per-keyframe color as painted', () => {+ const canvas = normalizePaintedCanvas(canvasOf([+ // Hard left, pure 440 Hz for the first second, then its 2nd partial fades in.+ { pan: -1, path: [{ t: 0, hz: 440, a: 0.8 }, { t: 1, hz: 440, a: 0.8, overtones: [0] }, { t: 2, hz: 440, a: 0.8, overtones: [1] }] },+ ]));+ const [left, right] = synthesizePaintedCanvas(canvas);+ expect(left).toHaveLength(2 * SR);+ expect(synthesizePaintedCanvas(canvas)).toEqual([left, right]);+ expect(Math.max(...right.map(Math.abs))).toBeLessThan(1e-6);++ const firstHalf = [Math.floor(0.2 * SR), Math.floor(0.8 * SR)];+ const lateSecond = [Math.floor(1.7 * SR), Math.floor(1.95 * SR)];+ expect(levelAt(left, 440, ...firstHalf)).toBeGreaterThan(0.1);+ expect(levelAt(left, 880, ...firstHalf)).toBeLessThan(0.001);+ expect(levelAt(left, 880, ...lateSecond)).toBeGreaterThan(0.1);+ });++ it('glides pitch on the log axis and renders a noise band around its centre', () => {+ const canvas = normalizePaintedCanvas(canvasOf([+ { pan: -1, path: [{ t: 0, hz: 220, a: 0.8 }, { t: 2, hz: 880, a: 0.8 }] },+ { pan: 1, width: 200, path: [{ t: 0, hz: 3000, a: 0.8 }, { t: 2, hz: 3000, a: 0.8 }] },+ ]));+ const [left, right] = synthesizePaintedCanvas(canvas);+ // Halfway through a two-octave log glide the pitch is one octave up.+ const mid = [Math.floor(0.98 * SR), Math.floor(1.02 * SR)];+ expect(levelAt(left, 440, ...mid)).toBeGreaterThan(levelAt(left, 550, ...mid) * 3);+ const span = [Math.floor(0.5 * SR), Math.floor(1.5 * SR)];+ expect(levelAt(right, 3000, ...span)).toBeGreaterThan(levelAt(right, 6000, ...span) * 10);+ expect(levelAt(right, 3000, ...span)).toBeGreaterThan(levelAt(right, 1000, ...span) * 10);+ });++ it('renders a multi-section ~3 minute painting within the work bound', () => {+ const sections = [0, 30, 60, 90, 120, 150].map((start) => ({ start, end: start + 30 }));+ const strokes = [];+ for (let i = 0; i < 600; i += 1) {+ const t = (i * 0.3) % 178;+ strokes.push(i % 4 === 0+ ? { width: 1500, pan: -0.5, path: [{ t, hz: 6000, a: 0.2 }, { t: t + 0.4, hz: 5000, a: 0 }] }+ : { pan: 0.3, overtones: [0.5, 0.3, 0.2], path: [{ t, hz: 196, a: 0.4 }, { t: t + 0.8, hz: 220, a: 0.5, overtones: [0.2, 0.6] }, { t: t + 1.6, hz: 220, a: 0 }] });+ }+ const canvas = normalizePaintedCanvas(canvasOf(strokes, { durationSec: 180, bpm: 120, beatsPerBar: 4, sections }));+ expect(canvas.sections).toHaveLength(6);+ expect(canvas.strokes).toHaveLength(600);+ expect(paintedCanvasStats(canvas).work).toBeLessThanOrEqual(L.WORK_MAX_PARTIAL_SEC);++ const [left, right] = synthesizeSketchChannels(canvas);+ expect(left).toHaveLength(180 * SR);+ let peak = 0;+ for (let i = 0; i < left.length; i += 1) peak = Math.max(peak, Math.abs(left[i]), Math.abs(right[i]));+ expect(Number.isFinite(peak)).toBe(true);+ expect(peak).toBeGreaterThan(0.1);+ expect(peak).toBeLessThanOrEqual(0.98 + 1e-6);+ }, 30_000);+});++describe('sync compatibility', () => {+ it('makes a tracks-v7 peer reject a painting instead of stripping it', () => {+ const painting = normalizePaintedCanvas(canvasOf([tone(440)]));+ // What a v7 peer's v1-only normalizer would do to it: strip it to null and+ // LWW the loss back — the reason for the bump.+ expect(normalizeWaveSketch({ ...painting, version: 1 })).toBeNull();+ expect(PORTOS_SCHEMA_VERSIONS.tracks).toBe(8);+ const { ahead } = compareSchemaVersions(PORTOS_SCHEMA_VERSIONS, { ...PORTOS_SCHEMA_VERSIONS, tracks: 7 });+ expect(ahead).toEqual([{ category: 'tracks', senderV: 8, receiverV: 7 }]);+ });+});diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex bdb275b299..e6f0d2a746 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -292,7 +292,12 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// a <=v6 peer's sketch-unaware sanitizer would drop the drawing and LWW the// loss back. The accepted sender-behind direction is covered by the// absent-key carry in services/tracks/logic.js mergeTrackRecord.- tracks: 7,+ // tracks v8 = `track.waveSketch` may hold a `version: 2` painted-spectrogram+ // canvas (#8464, lib/paintedCanvas.js). A <=v7 peer runs every sketch through+ // its v1-only normalizeWaveSketch, which strips a painting to null, and would+ // LWW that loss back — so it must reject the record instead. Stored v1+ // sketches still normalize and render unchanged; nothing to migrate.+ tracks: 8,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index thediff --git a/server/lib/spectrogramImage.js b/server/lib/spectrogramImage.jsnew file mode 100644index 0000000000..2ee7d4076d--- /dev/null+++ b/server/lib/spectrogramImage.js@@ -0,0 +1,104 @@+/**+ * Spectrogram picture of PCM audio — an RGB pixel buffer on a log-frequency+ * axis, for handing a model an image of what its painted canvas (#8464)+ * actually sounds like. Pure: returns raw pixels; the caller encodes them+ * (musicWaveform.js uses sharp).+ *+ * spectrogramPixels(pcm, { sampleRate, width, height, minHz, maxHz })+ * → { width, height, pixels: Uint8Array(width × height × 3) }+ *+ * Time runs left → right, frequency bottom → top (log), and brightness is+ * the level in dB over a fixed 80 dB range below the loudest cell.+ */++const FFT_SIZE = 2048;+const DB_RANGE = 80;++/** In-place iterative radix-2 FFT over separate real/imag arrays. */+function fft(re, im) {+ const n = re.length;+ for (let i = 1, j = 0; i < n; i += 1) {+ let bit = n >> 1;+ for (; j & bit; bit >>= 1) j ^= bit;+ j ^= bit;+ if (i < j) {+ [re[i], re[j]] = [re[j], re[i]];+ [im[i], im[j]] = [im[j], im[i]];+ }+ }+ for (let len = 2; len <= n; len <<= 1) {+ const angle = (-2 * Math.PI) / len;+ const wr = Math.cos(angle);+ const wi = Math.sin(angle);+ for (let i = 0; i < n; i += len) {+ let cr = 1;+ let ci = 0;+ for (let k = 0; k < len / 2; k += 1) {+ const a = i + k;+ const b = a + len / 2;+ const tr = re[b] * cr - im[b] * ci;+ const ti = re[b] * ci + im[b] * cr;+ re[b] = re[a] - tr;+ im[b] = im[a] - ti;+ re[a] += tr;+ im[a] += ti;+ const next = cr * wr - ci * wi;+ ci = cr * wi + ci * wr;+ cr = next;+ }+ }+ }+}++// Dark → violet → orange → pale yellow, readable by a vision model at a glance.+const STOPS = [[0, 0, 4], [87, 16, 110], [188, 55, 84], [249, 142, 9], [252, 255, 164]];+function colorAt(v) {+ const x = Math.min(1, Math.max(0, v)) * (STOPS.length - 1);+ const i = Math.min(STOPS.length - 2, Math.floor(x));+ const f = x - i;+ return STOPS[i].map((c, k) => Math.round(c + (STOPS[i + 1][k] - c) * f));+}++export function spectrogramPixels(pcm, {+ sampleRate = 44100, width = 1024, height = 384, minHz = 20, maxHz = 16000,+} = {}) {+ const window = Float64Array.from({ length: FFT_SIZE }, (_, i) => 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (FFT_SIZE - 1)));+ const bins = FFT_SIZE / 2;+ // Row → fractional FFT bin on the log axis (row 0 is the top = maxHz).+ const rowBin = Array.from({ length: height }, (_, row) => {+ const hz = minHz * (maxHz / minHz) ** (1 - row / Math.max(1, height - 1));+ return Math.min(bins - 1, (hz / sampleRate) * FFT_SIZE);+ });+ const levels = new Float32Array(width * height);+ const re = new Float64Array(FFT_SIZE);+ const im = new Float64Array(FFT_SIZE);+ const mags = new Float64Array(bins);+ let loudest = -Infinity;+ for (let col = 0; col < width; col += 1) {+ const centre = Math.floor(((col + 0.5) / width) * pcm.length);+ const start = centre - FFT_SIZE / 2;+ for (let i = 0; i < FFT_SIZE; i += 1) {+ const s = start + i;+ re[i] = s >= 0 && s < pcm.length ? pcm[s] * window[i] : 0;+ im[i] = 0;+ }+ fft(re, im);+ for (let k = 0; k < bins; k += 1) mags[k] = Math.hypot(re[k], im[k]);+ for (let row = 0; row < height; row += 1) {+ const x = rowBin[row];+ const k = Math.floor(x);+ const mag = mags[k] + ((mags[k + 1] ?? mags[k]) - mags[k]) * (x - k);+ const db = 20 * Math.log10(mag + 1e-9);+ levels[row * width + col] = db;+ if (db > loudest) loudest = db;+ }+ }+ const pixels = new Uint8Array(width * height * 3);+ for (let i = 0; i < levels.length; i += 1) {+ const [r, g, b] = colorAt(1 - (loudest - levels[i]) / DB_RANGE);+ pixels[i * 3] = r;+ pixels[i * 3 + 1] = g;+ pixels[i * 3 + 2] = b;+ }+ return { width, height, pixels };+}diff --git a/server/lib/waveSketch.js b/server/lib/waveSketch.jsindex 58cf192203..edfe1a1c11 100644--- a/server/lib/waveSketch.js+++ b/server/lib/waveSketch.js@@ -20,11 +20,17 @@* deterministically (noise is seeded per stroke), so the browser preview and* the server-rendered WAV are the same samples.*+ * Version 2 (#8464) replaced drawing with painting: a stereo spectrogram+ * canvas (lib/paintedCanvas.js). New paintings are always v2; v1 sketches+ * stored on tracks keep rendering here unchanged. `normalizeWaveSketch` and+ * `synthesizeSketchChannels` dispatch on `version`, so callers hold either.+ ** 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';+import { PAINTED_CANVAS_VERSION, normalizePaintedCanvas, synthesizePaintedCanvas } from './paintedCanvas.js';export const WAVE_SKETCH_VERSION = 1;export const WAVE_SKETCH_SAMPLE_RATE = 44100;@@ -107,11 +113,13 @@ function normalizeNote(raw, { durationSec, isNoise, shapeNames }) {}/**- * Validate + canonicalize an LLM (or client round-tripped) wave sketch.+ * Validate + canonicalize an LLM (or client round-tripped) wave sketch of+ * either version (a v2 painted canvas is normalized by lib/paintedCanvas.js).* Returns the normalized sketch, or null when nothing playable survives.*/export function normalizeWaveSketch(raw) {if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null;+ if (raw.version === PAINTED_CANVAS_VERSION) return normalizePaintedCanvas(raw);const shapes = {};const rawShapes = raw.shapes && typeof raw.shapes === 'object' && !Array.isArray(raw.shapes) ? raw.shapes : {};@@ -284,6 +292,17 @@ export function synthesizeWaveSketch(sketch, { sampleRate = WAVE_SKETCH_SAMPLE_Rreturn out;}+/** True for a v2 painted canvas (vs a v1 drawn sketch). */+export const isPaintedCanvas = (sketch) => sketch?.version === PAINTED_CANVAS_VERSION;++/**+ * Render a NORMALIZED sketch of either version to its PCM channels: `[mono]`+ * for a v1 drawing, `[left, right]` for a v2 painting.+ */+export function synthesizeSketchChannels(sketch, options) {+ return isPaintedCanvas(sketch) ? synthesizePaintedCanvas(sketch, options) : [synthesizeWaveSketch(sketch, options)];+}+/*** Downsample PCM into `columns` [min, max] pairs for drawing the rendered* waveform. Each column covers an equal slice of the buffer.diff --git a/server/lib/waveSketch.test.js b/server/lib/waveSketch.test.jsindex 88e538f55a..c68431ff4a 100644--- a/server/lib/waveSketch.test.js+++ b/server/lib/waveSketch.test.js@@ -1,7 +1,9 @@+import { createHash } from 'crypto';import { describe, expect, it } from 'vitest';import {- WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE, normalizeWaveSketch, pcmPeaks, synthesizeWaveSketch,+ WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE, normalizeWaveSketch, pcmPeaks, synthesizeSketchChannels, synthesizeWaveSketch,} from './waveSketch.js';+import { pcmToWavBuffer } from './chiptuneRender.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];@@ -129,6 +131,33 @@ describe('synthesizeWaveSketch', () => {});});+describe('stored v1 sketches after the v2 painted canvas (#8464)', () => {+ it('still render byte-identically, to the same mono WAV', () => {+ // A stored v1 sketch exercising glide, envelope, morph, both noise modes+ // and the contour. The hash was taken from the pre-#8464 renderer.+ const stored = {+ version: 1, title: '', durationSec: 2,+ shapes: { sine: SINE, saw: [-1, -0.5, 0, 0.5, 1] },+ voices: [+ { name: 'voice1', shape: 'sine', gain: 0.7, notes: [+ { t: 0, d: 1, hz: 220, v: 0.8, pitch: 'A3', toHz: 329.628, env: [0, 1, 0.6, 0] },+ { t: 1, d: 1, hz: 261.626, v: 0.8, pitch: 'C4', morphTo: 'saw' },+ ] },+ { name: 'voice2', shape: 'noise', gain: 0.6, notes: [{ t: 0.25, d: 0.1, hz: null, v: 0.8 }, { t: 0.75, d: 0.05, hz: 9000, v: 0.8 }] },+ ],+ contour: [0.4, 1, 0.7],+ };+ const sketch = normalizeWaveSketch(stored);+ expect(sketch).toEqual(stored);+ const channels = synthesizeSketchChannels(sketch);+ expect(channels).toHaveLength(1);+ expect(createHash('sha256').update(Buffer.from(channels[0].buffer)).digest('hex'))+ .toBe('0ee008359a28d35f4698bd77101989bce0fc54931f7a3814fc94f83e1d0dd736');+ expect(pcmToWavBuffer(channels, { sampleRate: WAVE_SKETCH_SAMPLE_RATE }))+ .toEqual(pcmToWavBuffer(channels[0], { sampleRate: WAVE_SKETCH_SAMPLE_RATE }));+ });+});+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.jsindex b4f041de22..389d36ffdf 100644--- a/server/routes/music.js+++ b/server/routes/music.js@@ -12,8 +12,8 @@* 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). `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.+ * designer's "Drawn waveform" engine: the LLM paints strokes on a stereo+ * spectrogram canvas (server/lib/paintedCanvas.js) that the browser plays directly.* `code` is its "Code" engine: the LLM writes the piece as Strudel code, which* only ever runs in the browser's sandboxed player frame, never on the server.*@@ -44,7 +44,7 @@ import { listMusicEngineCapabilities } from '../services/musicEngineCapabilitiesimport { describeMusic, writeLyrics } from '../services/musicDesigner.js';import { drawWaveSketch } from '../services/musicWaveform.js';import { MUSIC_CODE_LANGUAGES, MUSIC_CODE_MAX, writeMusicCode } from '../services/musicCode.js';-import { WAVE_SKETCH_LIMITS } from '../lib/waveSketch.js';+import { PAINTED_CANVAS_LIMITS } from '../lib/paintedCanvas.js';import { startHfDownloadStream } from '../services/hfDownloadStream.js';import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';import { createInstallLogger } from '../lib/installLogger.js';@@ -361,15 +361,16 @@ router.post('/lyrics', asyncHandler(async (req, res) => {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.+ durationSec: z.number().min(PAINTED_CANVAS_LIMITS.DURATION_MIN_SEC).max(PAINTED_CANVAS_LIMITS.DURATION_MAX_SEC).optional(),+ // The painting to revise — normalized (and size-bounded) by the service.current: z.record(z.string(), z.unknown()).optional(),+ review: z.boolean().optional(),// The drawing contract is fixed (no meta-prompt override like describe/lyrics)....designerPickerShape,}).omit({ template: true });-// POST /api/music/waveform — stateless: have the LLM DRAW the music (single-cycle-// waveforms plus timed strokes, lib/waveSketch.js) without storing it. The+// POST /api/music/waveform — stateless: have the LLM PAINT the music on a+// spectrogram canvas (lib/paintedCanvas.js) without storing it. The// designer draws via POST /api/tracks/:id/waveform/draw, which persists it.// One explicit user action per call.router.post('/waveform', asyncHandler(async (req, res) => {diff --git a/server/routes/tracks.js b/server/routes/tracks.jsindex 88ff5743f1..83b0096a2f 100644--- a/server/routes/tracks.js+++ b/server/routes/tracks.js@@ -48,7 +48,7 @@ import {import { YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE } from '../lib/youtubeUrl.js';import { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack } from '../services/chiptune.js';import { drawWaveSketchForTrack, renderWaveSketchToTrack } from '../services/musicWaveform.js';-import { WAVE_SKETCH_LIMITS } from '../lib/waveSketch.js';+import { PAINTED_CANVAS_LIMITS } from '../lib/paintedCanvas.js';import { saveCodeTakeToTrack } from '../services/musicCode.js';const router = Router();@@ -292,19 +292,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). `draw` persists the sketch on the track-// (`waveSketch`/`waveSketchPrompt`, #8376); `render` renders that STORED sketch-// with the same deterministic synth the browser previewed. Drawing is one-// explicit user action per call (AI Provider Usage Policy).+// --- Drawn waveform takes — the Music Designer's LLM-painted spectrogram+// canvas (server/lib/paintedCanvas.js, #8464). `draw` persists the painting on+// the track (`waveSketch`/`waveSketchPrompt`, #8376); `render` renders that+// STORED sketch with the same deterministic synth the browser previewed.+// Painting is one explicit user action per call (AI Provider Usage Policy).const optionalPick = (max) => z.string().max(max).optional().transform((v) => v?.trim() || undefined);const waveformDrawSchema = z.object({description: z.string().trim().min(1, 'description is required').max(tracks.PROMPT_MAX),lyrics: z.string().trim().max(tracks.LYRICS_MAX).optional(),guidance: z.string().trim().max(4000).optional(),- durationSec: z.number().min(WAVE_SKETCH_LIMITS.DURATION_MIN_SEC).max(WAVE_SKETCH_LIMITS.DURATION_MAX_SEC).optional(),- // true = revise the track's stored drawing instead of drawing from scratch.+ durationSec: z.number().min(PAINTED_CANVAS_LIMITS.DURATION_MIN_SEC).max(PAINTED_CANVAS_LIMITS.DURATION_MAX_SEC).optional(),+ // true = revise the track's stored painting instead of painting from scratch.revise: z.boolean().optional(),+ // true = show the model a spectrogram of each passage for one repaint pass.+ review: z.boolean().optional(),providerId: optionalPick(128),model: optionalPick(256),effort: optionalPick(64),diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.jsindex dec6ffe8df..8f199fbb7d 100644--- a/server/routes/tracks.test.js+++ b/server/routes/tracks.test.js@@ -424,20 +424,17 @@ describe('tracks routes', () => {});});- describe('drawn waveform (#8376)', () => {- const sketch = {- version: 1, title: 'Glass Tide', durationSec: 2,- shapes: { glass: [0, 0.8, 1, 0.3, 0, -0.5, -1, -0.2] },- voices: [{ name: 'lead', shape: 'glass', notes: [{ t: 0, d: 1, pitch: 'A4' }] }],- };-- it('POST /:id/waveform/draw persists the drawing on the track', async () => {+ describe('drawn waveform (#8376, painted canvas #8464)', () => {+ // One passage's reply: a single tonal stroke.+ const sketch = { title: 'Glass Tide', strokes: [{ path: [{ t: 0, hz: 440, a: 0.5 }, { t: 1, hz: 440, a: 0.5 }] }] };++ it('POST /:id/waveform/draw persists the painting on the track', async () => {tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(sketch) });const r = await request(app).post('/api/tracks/track-1/waveform/draw')- .send({ description: 'glassy tidal ambient', durationSec: 12, revise: true, providerId: '' });+ .send({ description: 'glassy tidal ambient', durationSec: 12, revise: true, review: false, providerId: '' });expect(r.status).toBe(200);- expect(r.body.sketch).toMatchObject({ title: 'Glass Tide' });+ expect(r.body.sketch).toMatchObject({ version: 2, title: 'Glass Tide', durationSec: 12 });expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', expect.objectContaining({waveSketch: expect.objectContaining({ title: 'Glass Tide' }), waveSketchPrompt: 'glassy tidal ambient',}));@@ -450,7 +447,7 @@ describe('tracks routes', () => {expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();});- it('POST /:id/waveform/render renders the stored drawing, never a client-supplied one', async () => {+ it('POST /:id/waveform/render renders the stored painting, never a client-supplied one', async () => {tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [], waveSketch: null });const r = await request(app).post('/api/tracks/track-1/waveform/render').send({ sketch });expect(r.status).toBe(400);diff --git a/server/services/musicWaveform.js b/server/services/musicWaveform.jsindex 67ec101fc3..d7f0672fd3 100644--- a/server/services/musicWaveform.js+++ b/server/services/musicWaveform.js@@ -1,126 +1,334 @@/**- * Drawn-waveform music — the Music Designer's "Drawn waveform" engine.+ * Painted-spectrogram music — the Music Designer's "Drawn waveform" engine.*- * drawWaveSketch() musical description → a wave sketch the LLM drew- * point by point (lib/waveSketch.js contract).+ * drawWaveSketch() musical description → a painted canvas+ * (lib/paintedCanvas.js, sketch v2, #8464).* Stateless (POST /api/music/waveform).* drawWaveSketchForTrack() the same, persisted on the track as* `waveSketch`/`waveSketchPrompt` (#8376) so the- * drawing survives reloads, syncs to the user's+ * painting survives reloads, syncs to the user's* other machines, and can be revised later.- * renderWaveSketchToTrack() the track's STORED sketch → WAV in the shared+ * renderWaveSketchToTrack() the track's STORED sketch (v2 painting, or a v1+ * drawing from before #8464) → WAV in the shared* music library, appended to the track's render* history as an `engine: 'waveform'` take.*- * The browser previews the same sketch with the same deterministic synth- * (`synthesizeWaveSketch`), so the saved take is exactly what was auditioned.+ * A piece longer than one passage is painted SECTION BY SECTION: each call+ * paints one passage of the shared canvas and sees a compact summary of the+ * painted neighbours plus the tempo grid, so no reply has to hold a whole song.+ * With `review`, the model then sees a spectrogram image of each rendered+ * passage and repaints it once — still within the same button press.*- * 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).+ * The prompt describes the canvas physics and numeric limits ONLY — never an+ * arrangement, instrument, or recipe — so a stronger model paints better with+ * no prompt edits.+ *+ * The browser previews the same sketch with the same deterministic synth, 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 { mkdtemp, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';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_SAMPLE_RATE, synthesizeSketchChannels } from '../lib/waveSketch.js';import {- WAVE_SKETCH_LIMITS, WAVE_SKETCH_SAMPLE_RATE, normalizeWaveSketch, synthesizeWaveSketch,-} from '../lib/waveSketch.js';+ PAINTED_CANVAS_DECLICK_SEC, PAINTED_CANVAS_LIMITS, PAINTED_CANVAS_MASTER_GAIN, PAINTED_CANVAS_SAMPLE_RATE,+ normalizePaintedCanvas, paintedCanvasStats, synthesizePaintedCanvas,+} from '../lib/paintedCanvas.js';+import { spectrogramPixels } from '../lib/spectrogramImage.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 DEFAULT_CANVAS_SEC = 20;+// One reply paints at most this much of the canvas.+const PASSAGE_MAX_SEC = 30;+const SUMMARY_LINES_MAX = 120;+const REVIEW_IMAGE = { width: 1024, height: 384 };const MAX_DESCRIPTION = 8000;const MAX_LYRICS = 20000;const MAX_GUIDANCE = 4000;-const L = WAVE_SKETCH_LIMITS;+const L = PAINTED_CANVAS_LIMITS;+const NYQUIST = PAINTED_CANVAS_SAMPLE_RATE / 2;const section = (label, body) => (body ? `\n\n${label}:\n${body}` : '');+const fmt = (n, places = 2) => String(Math.round(n * 10 ** places) / 10 ** places);+// Passage boundaries are stated at their stored precision, so a stroke placed+// exactly on one lands inside the passage it was meant for.+const fmtT = (n) => fmt(n, 3);+const strokeStart = (stroke) => stroke.path[0].t;+const strokeEnd = (stroke) => stroke.path[stroke.path.length - 1].t;+const inPassage = (stroke, passage, isLast) => {+ const t = strokeStart(stroke);+ return t >= passage.start && (t < passage.end || (isLast && t <= passage.end));+};++/**+ * Split the piece into passages of at most PASSAGE_MAX_SEC. With a tempo grid,+ * interior boundaries land on bar lines (measured from t=0) where that keeps+ * every passage non-empty. `from` fixes the first boundary (for re-planning+ * the rest of a piece once its tempo is known).+ */+function planPassages(durationSec, { bpm, beatsPerBar, from = 0 } = {}) {+ const span = durationSec - from;+ const count = Math.max(1, Math.ceil(span / PASSAGE_MAX_SEC - 1e-9));+ const bar = bpm ? ((beatsPerBar || 4) * 60) / bpm : null;+ const bounds = [from];+ for (let i = 1; i < count; i += 1) {+ const nominal = from + (span * i) / count;+ const snapped = bar ? Math.round(nominal / bar) * bar : nominal;+ const prev = bounds[bounds.length - 1];+ bounds.push(snapped > prev && snapped < durationSec && snapped - prev <= PASSAGE_MAX_SEC ? snapped : nominal);+ }+ bounds.push(durationSec);+ return bounds.slice(0, -1).map((start, i) => ({ start: Math.round(start * 1000) / 1000, end: Math.round(bounds[i + 1] * 1000) / 1000 }));+}++/** Each passage's share of the canvas-wide budgets, by its length. */+function passageLimits(passage, durationSec) {+ const share = (passage.end - passage.start) / durationSec;+ return {+ strokes: Math.max(1, Math.floor(L.STROKES_MAX * share)),+ keyframes: Math.max(2, Math.floor(L.KEYFRAMES_MAX * share)),+ work: Math.floor(L.WORK_MAX_PARTIAL_SEC * share),+ };+}++/** One summary line per stroke: span, pitch range, peak level, brush. */+function strokeLine(stroke) {+ const hz = stroke.path.map((k) => k.hz);+ const peak = Math.max(...stroke.path.map((k) => k.a));+ const brush = [+ stroke.width ? `noise band ${fmt(stroke.width, 0)} Hz` : null,+ stroke.overtones?.length || stroke.path.some((k) => k.overtones?.length) ? 'overtones' : null,+ stroke.pan ? `pan ${stroke.pan}` : null,+ ].filter(Boolean).join(', ');+ return `- ${stroke.name || 'unnamed'}: t ${fmt(strokeStart(stroke))}-${fmt(strokeEnd(stroke))}s, ${fmt(Math.min(...hz), 1)}-${fmt(Math.max(...hz), 1)} Hz, peak a ${fmt(peak)}${brush ? `, ${brush}` : ''}`;+}++/** Up to SUMMARY_LINES_MAX lines, keeping the most prominent strokes. */+function summarizeStrokes(strokes) {+ const weight = (s) => Math.max(...s.path.map((k) => k.a)) * (strokeEnd(s) - strokeStart(s));+ const kept = strokes.length > SUMMARY_LINES_MAX+ ? [...strokes].sort((a, b) => weight(b) - weight(a)).slice(0, SUMMARY_LINES_MAX).sort((a, b) => strokeStart(a) - strokeStart(b))+ : strokes;+ const more = strokes.length - kept.length;+ return [...kept.map(strokeLine), ...(more > 0 ? [`- (+${more} quieter or shorter strokes not listed)`] : [])].join('\n');+}++/** Pitch/level of a stroke at time t (for strokes crossing a boundary). */+function strokeAt(stroke, t) {+ const { path } = stroke;+ let i = 0;+ while (i < path.length - 2 && t > path[i + 1].t) i += 1;+ const u = Math.min(1, Math.max(0, (t - path[i].t) / (path[i + 1].t - path[i].t)));+ return { hz: path[i].hz * (path[i + 1].hz / path[i].hz) ** u, a: path[i].a + (path[i + 1].a - path[i].a) * u };+}-/** 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)')+/** What the model is told about the rest of the canvas while painting one passage. */+function neighbourContext(strokes, passages, index) {+ const passage = passages[index];+ const byPassage = passages.map((p, i) => strokes.filter((s) => inPassage(s, p, i === passages.length - 1)));+ const parts = [];+ passages.forEach((p, i) => {+ if (i === index || !byPassage[i].length) return;+ const label = `Passage ${i + 1} (t ${fmtT(p.start)}-${fmtT(p.end)}s)`;+ if (Math.abs(i - index) === 1) parts.push(`${label}, ${byPassage[i].length} strokes:\n${summarizeStrokes(byPassage[i])}`);+ else {+ const hz = byPassage[i].flatMap((s) => s.path.map((k) => k.hz));+ parts.push(`${label}: ${byPassage[i].length} strokes, ${fmt(Math.min(...hz), 0)}-${fmt(Math.max(...hz), 0)} Hz`);+ }+ });+ const crossing = strokes+ .filter((s) => strokeStart(s) < passage.start && strokeEnd(s) > passage.start)+ .map((s) => {+ const at = strokeAt(s, passage.start);+ return `- ${s.name || 'unnamed'}: sounding at t=${fmtT(passage.start)}s with hz ${fmt(at.hz, 1)}, a ${fmt(at.a)}; ends at t=${fmt(strokeEnd(s))}s`;+ });+ return { painted: parts.join('\n\n'), crossing: crossing.join('\n') };+}++function tempoLine(grid, passage) {+ if (!grid.bpm) {+ return `No tempo grid is set. You may set one with "bpm" (${L.BPM_MIN}-${L.BPM_MAX}) and "beatsPerBar" (1-${L.BEATS_PER_BAR_MAX}); later passages receive it.`;+ }+ const beatsPerBar = grid.beatsPerBar || 4;+ const beat = 60 / grid.bpm;+ const bar = beat * beatsPerBar;+ return `Tempo grid: ${fmt(grid.bpm)} BPM, ${beatsPerBar} beats per bar — a beat is ${fmt(beat, 4)}s and a bar ${fmt(bar, 4)}s, counted from t=0. This passage spans bars ${fmt(passage.start / bar + 1, 2)} to ${fmt(passage.end / bar + 1, 2)}.`;+}++/**+ * The painting contract for one passage: the brief, the canvas physics, the+ * numeric limits, and the painted context. Physics and limits only — no+ * instruments, arrangement, or recipe (asserted by musicWaveform.test.js).+ */+function buildPaintPrompt({+ description, lyrics, guidance, durationSec, grid = {}, passages, index, context = {}, current, withImage = false,+}) {+ const passage = passages[index];+ const limits = passageLimits(passage, durationSec);+ const isLast = index === passages.length - 1;+ return `You are painting sound on a spectrogram canvas. A deterministic renderer turns the painting into audio exactly as described below; what you paint is everything that is heard.${+ section('THE BRIEF', trimTo(description, MAX_DESCRIPTION) || '(none given)')}${- section('LYRICS / THEME (mood only — nothing is sung; drawn sounds carry the melody)', trimTo(lyrics, MAX_LYRICS))+ section('LYRICS / TEXT', trimTo(lyrics, MAX_LYRICS))}${section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE))+ }++THE CANVAS+- Stereo, ${PAINTED_CANVAS_SAMPLE_RATE} samples per second, ${fmt(durationSec)} seconds long. Time is in seconds from 0; frequency runs on a logarithmic axis from ${L.HZ_MIN} Hz to ${L.HZ_MAX} Hz.+- Strokes add: overlapping strokes sum sample by sample. The renderer adds nothing of its own — no reverberation, filtering, compression, or effect of any kind.+- The summed mix is output at ${PAINTED_CANVAS_MASTER_GAIN}× amplitude; if it would still clip, the whole piece is scaled down uniformly (never up).++THE BRUSH — one stroke+- "path": [{"t": <seconds>, "hz": <${L.HZ_MIN}-${L.HZ_MAX}>, "a": <0-1>}, …] — keyframes in increasing time, at least 2 and at most ${L.KEYFRAMES_PER_STROKE_MAX}. Between keyframes, pitch moves in a straight line on the log-frequency axis (equal pitch intervals per second) and amplitude moves linearly. A stroke sounds from its first keyframe to its last and is silent outside them; a ${PAINTED_CANVAS_DECLICK_SEC * 1000} ms fade at each end prevents clicks.+- Without "width" a stroke is tonal: a sine at "hz" with peak amplitude "a".+- "overtones": [r2, r3, …] — up to ${L.OVERTONES_MAX} levels 0-1 for extra sines at 2×, 3×, … the stroke's hz, each at r × a. On the stroke it is the default for every keyframe; on a keyframe it applies from that keyframe on. Between two keyframes each level moves linearly, so the balance of partials can change along one stroke. Partials at or above ${fmt(NYQUIST * 0.98, 0)} Hz are silent.+- "width": <${L.WIDTH_MIN_HZ}-${L.WIDTH_MAX_HZ} Hz> — makes the stroke noise instead: seeded white noise through a band-pass filter centred on "hz" with that bandwidth, at roughly the loudness of a sine of amplitude "a". "overtones" are ignored on a noise stroke.+- "pan": -1 (left) to 1 (right), equal-power, fixed for the stroke; default 0.+- "name": optional label, up to ${L.NAME_MAX} characters, shown again in the summaries of neighbouring passages.++THIS PASSAGE+- You are painting passage ${index + 1} of ${passages.length}: t=${fmtT(passage.start)}s to t=${fmtT(passage.end)}s of the ${fmtT(durationSec)}-second piece. Every stroke's first keyframe must be at or after t=${fmtT(passage.start)} and ${isLast ? 'at or before' : 'before'} t=${fmtT(passage.end)}${isLast ? '.' : `; a stroke may continue past t=${fmtT(passage.end)} up to t=${fmtT(durationSec)}.`} Strokes starting outside the passage are discarded.+- ${tempoLine(grid, passage)}+- Limits for this passage: at most ${limits.strokes} strokes, ${limits.keyframes} keyframes in total, and ${limits.work} units of render work — a tonal stroke costs its length in seconds × (1 + its overtone count), a noise stroke its length × ${L.NOISE_STROKE_COST}. Strokes beyond a limit are discarded in the order you list them.${+ section('ALREADY PAINTED ELSEWHERE ON THE CANVAS (summary)', context.painted)+ }${+ section('STROKES FROM EARLIER PASSAGES STILL SOUNDING WHEN THIS ONE BEGINS', context.crossing)+ }${+ current ? section('CURRENT PAINTING OF THIS PASSAGE (revise it per the request above — keep what works, change what is asked)', JSON.stringify(current)) : ''}${- current ? section('CURRENT SKETCH (revise it per the request above — keep what works, change what is asked)', JSON.stringify(current)) : ''+ withImage ? `\n\nATTACHED IMAGE: a spectrogram of this passage as it renders — time left to right from t=${fmtT(passage.start)}s to t=${fmtT(passage.end)}s, log frequency from ${L.HZ_MIN} Hz (bottom) to ${L.HZ_MAX} Hz (top), brightness = level over an 80 dB range. Compare it with what you meant to paint and return the passage repainted.` : ''}-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>]+Return ONLY a JSON object (no prose, no code fence) in this shape:+{"title": "<short title>", "bpm": <optional>, "beatsPerBar": <optional>, "strokes": [{"name": "<optional>", "pan": <optional>, "width": <optional>, "overtones": [<optional>], "path": [{"t": <seconds>, "hz": <Hz>, "a": <0-1>, "overtones": [<optional>]}]}]}`;}-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 passage's strokes from a reply, or null when none are playable. */+function passageStrokes(reply, { durationSec, passages, index }) {+ const passage = passages[index];+ const canvas = normalizePaintedCanvas(reply, { durationSec, limits: passageLimits(passage, durationSec) });+ const strokes = canvas?.strokes.filter((s) => inPassage(s, passage, index === passages.length - 1)) ?? [];+ return strokes.length ? { canvas, strokes } : null;}-// 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;+const badResponse = () => new ServerError('The AI did not return a playable painting. Try rerunning or picking a stronger model.', {+ status: 502, code: 'WAVEFORM_BAD_RESPONSE',+});++/** Write a PNG spectrogram of one passage of the rendered canvas; returns its path. */+async function writePassageSpectrogram(mono, passage, dir, index) {+ const { default: sharp } = await import('sharp');+ const from = Math.floor(passage.start * PAINTED_CANVAS_SAMPLE_RATE);+ const to = Math.min(mono.length, Math.ceil(passage.end * PAINTED_CANVAS_SAMPLE_RATE));+ const { width, height, pixels } = spectrogramPixels(mono.subarray(from, to), {+ sampleRate: PAINTED_CANVAS_SAMPLE_RATE, ...REVIEW_IMAGE, minHz: L.HZ_MIN, maxHz: L.HZ_MAX,+ });+ const file = join(dir, `passage-${index + 1}.png`);+ await sharp(Buffer.from(pixels), { raw: { width, height, channels: 3 } }).png().toFile(file);+ return file;+}/**- * 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.+ * Ask the chosen provider to paint the piece. `current` (a v2 painting) turns+ * the call into a revision of it; a v1 drawing is not revisable and paints+ * fresh. `review` adds one look-and-repaint pass per passage.*/-export async function drawWaveSketch({ description, lyrics, guidance, durationSec, current, providerId, model, effort } = {}) {+export async function drawWaveSketch({+ description, lyrics, guidance, durationSec, current, review = false, 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,- });+ assertProvider(provider, { message: 'No AI provider available to paint the music', code: 'NO_PROVIDER' });- 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 revising = current?.version === 2 ? normalizePaintedCanvas(current) : null;+ const pieceSec = Math.round(Math.min(L.DURATION_MAX_SEC, Math.max(L.DURATION_MIN_SEC,+ Number(durationSec) || revising?.durationSec || DEFAULT_CANVAS_SEC)) * 1000) / 1000;+ const grid = revising?.bpm ? { bpm: revising.bpm, beatsPerBar: revising.beatsPerBar } : {};+ let passages = revising?.sections && revising.durationSec === pieceSec+ ? revising.sections.map(({ start, end }) => ({ start, end }))+ : planPassages(pieceSec, grid);+ let title = revising?.title || '';+ let strokes = revising ? revising.strokes.filter((s) => strokeStart(s) < pieceSec) : [];+ let lastRun = null;++ const paintPassage = async (index, { withImage = null } = {}) => {+ const isLast = index === passages.length - 1;+ const mine = strokes.filter((s) => inPassage(s, passages[index], isLast));+ const others = strokes.filter((s) => !mine.includes(s));+ const opts = { durationSec: pieceSec, passages, index };+ const run = await runPromptThroughProvider({+ provider,+ model: selectedModel ?? undefined,+ effort,+ prompt: buildPaintPrompt({+ description, lyrics, guidance, durationSec: pieceSec, grid, passages, index,+ context: neighbourContext(others, passages, index),+ current: mine.length ? mine : null,+ withImage: !!withImage,+ }),+ source: 'music-waveform',+ // The runner coerces/re-requests an off-shape reply against this.+ responseSchema: (value) => passageStrokes(value, opts) !== null,+ ...(withImage ? { screenshots: [withImage] } : {}),});+ let parsed = null;+ try { parsed = JSON.parse(run.text); } catch { /* handled below */ }+ const painted = passageStrokes(parsed, opts);+ if (!painted) throw badResponse();+ lastRun = run;+ strokes = [...others, ...painted.strokes];+ if (!title && painted.canvas.title) title = painted.canvas.title;+ if (!grid.bpm && painted.canvas.bpm) {+ grid.bpm = painted.canvas.bpm;+ grid.beatsPerBar = painted.canvas.beatsPerBar;+ // The rest of a fresh piece can now fall on bar lines.+ if (!isLast) passages = [...passages.slice(0, index + 1), ...planPassages(pieceSec, { ...grid, from: passages[index].end })];+ }+ };++ for (let i = 0; i < passages.length; i += 1) await paintPassage(i);++ let reviewed = 0;+ if (review) {+ const dir = await mkdtemp(join(tmpdir(), 'portos-painting-'));+ const canvas = normalizePaintedCanvas({ durationSec: pieceSec, strokes });+ const [left, right] = synthesizePaintedCanvas(canvas);+ const mono = left.map((v, i) => (v + right[i]) / 2);+ // The review is optional polish on work already paid for: if the provider+ // can't take an image (or the pass fails), keep the painting as it stands.+ try {+ for (let i = 0; i < passages.length; i += 1) {+ const image = await writePassageSpectrogram(mono, passages[i], dir, i);+ const ok = await paintPassage(i, { withImage: image }).then(() => true, (err) => {+ console.warn(`⚠️ Painting review stopped at passage ${i + 1}: ${err.message}`);+ return false;+ });+ if (!ok) break;+ reviewed += 1;+ }+ } finally {+ await rm(dir, { recursive: true, force: true });+ }}- 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 } };++ const sketch = normalizePaintedCanvas({ title, durationSec: pieceSec, ...grid, sections: passages, strokes });+ if (!sketch) throw badResponse();+ const ranModel = lastRun?.model ?? selectedModel ?? null;+ const stats = paintedCanvasStats(sketch);+ console.log(`🎨 Painted canvas via ${provider.id}/${ranModel || 'default'} (${stats.strokes} strokes, ${stats.keyframes} keyframes, ${sketch.durationSec}s, ${passages.length} passages, ${reviewed} reviewed)`);+ return { sketch, llm: { provider: lastRun?.provider?.id || provider.id, model: ranModel }, passages: passages.length, reviewed };}const requireTrack = async (trackId) => {@@ -130,38 +338,39 @@ const requireTrack = async (trackId) => {};/**- * Draw (or, with `revise`, redraw the track's stored sketch) and persist the- * result on the track. The description it was drawn from is kept alongside as- * `waveSketchPrompt` so a remix reopens with the same brief.+ * Paint (or, with `revise`, repaint the track's stored painting) and persist+ * the result on the track. The description it was painted from is kept+ * alongside as `waveSketchPrompt` so a remix reopens with the same brief.*/export async function drawWaveSketchForTrack({ trackId, revise = false, ...params }) {const track = await requireTrack(trackId);const current = revise ? track.waveSketch : null;- const { sketch, llm } = await drawWaveSketch({ ...params, current });- const updated = await tracks.updateTrack(trackId, { waveSketch: sketch, waveSketchPrompt: trimTo(params.description, MAX_DESCRIPTION) });- return { sketch: updated.waveSketch, llm, track: updated };+ const result = await drawWaveSketch({ ...params, current });+ const updated = await tracks.updateTrack(trackId, { waveSketch: result.sketch, waveSketchPrompt: trimTo(params.description, MAX_DESCRIPTION) });+ return { ...result, sketch: updated.waveSketch, track: updated };}/*** Render the track's stored sketch into the shared music library and make it* the track's active take (same render-history contract as the chiptune and* diffusion engines). The server renders what it stored, never a- * client-supplied drawing, so the take always matches the persisted sketch.+ * client-supplied sketch, so the take always matches the persisted one. A v2+ * painting renders stereo; a v1 drawing renders mono, byte-identical to before.*/export async function renderWaveSketchToTrack({ trackId, prompt, title }) {const track = await requireTrack(trackId);const normalized = track.waveSketch;if (!normalized) {- throw new ServerError('This track has no drawing to render yet — draw one first', { status: 400, code: 'WAVEFORM_EMPTY' });+ throw new ServerError('This track has no painting to render yet — paint one first', { status: 400, code: 'WAVEFORM_EMPTY' });}- const wav = pcmToWavBuffer(synthesizeWaveSketch(normalized), { sampleRate: WAVE_SKETCH_SAMPLE_RATE });+ const wav = pcmToWavBuffer(synthesizeSketchChannels(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.waveSketchPrompt || track.prompt, engine: WAVEFORM_ENGINE, durationSec,}, title ? { title } : {});if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });- console.log(`〰️ Rendered drawn waveform take (${durationSec}s)`);+ console.log(`🎨 Rendered painted take (${durationSec}s)`);return { track: updated, filename, durationSec };}diff --git a/server/services/musicWaveform.test.js b/server/services/musicWaveform.test.jsindex 27e8d231f8..b5c5b94f0a 100644--- a/server/services/musicWaveform.test.js+++ b/server/services/musicWaveform.test.js@@ -32,81 +32,180 @@ const tracks = await import('./tracks/index.js');const promptRunner = await import('./promptRunner.js');const { drawWaveSketch, drawWaveSketchForTrack, renderWaveSketchToTrack } = await import('./musicWaveform.js');const { normalizeWaveSketch } = await import('../lib/waveSketch.js');+const { PAINTED_CANVAS_LIMITS } = await import('../lib/paintedCanvas.js');++// The passage window a prompt asks for ("passage 2 of 3: t=30s to t=60s").+const windowOf = (prompt) => {+ const m = prompt.match(/passage (\d+) of (\d+): t=([\d.]+)s to t=([\d.]+)s/);+ return { index: Number(m[1]) - 1, count: Number(m[2]), start: Number(m[3]), end: Number(m[4]) };+};++// A reply painting one tonal and one noise stroke inside the asked-for window.+const paintReply = (prompt, extra = {}) => {+ const { index, start, end } = windowOf(prompt);+ const mid = (start + end) / 2;+ return {+ title: 'Glass Tide',+ strokes: [+ { name: `line${index + 1}`, overtones: [0.4], path: [{ t: start, hz: 220, a: 0.5 }, { t: mid, hz: 330, a: 0.6, overtones: [0.1, 0.5] }] },+ // Rings on past the passage end, into the next one.+ { name: `air${index + 1}`, width: 1200, pan: -0.4, path: [{ t: mid, hz: 5000, a: 0.2 }, { t: end + 1, hz: 4000, a: 0 }] },+ // Starts outside the window — discarded.+ { name: 'stray', path: [{ t: end + 0.5, hz: 440, a: 0.5 }, { t: end + 2, hz: 440, a: 0.5 }] },+ ],+ ...extra,+ };+};+const replyWith = (extra) => async ({ prompt }) => ({ text: JSON.stringify(paintReply(prompt, extra)), model: 'model-x' });-const drawnSketch = () => ({+const baseTrack = (extra = {}) => ({ id: 'track-1', title: 'Untitled music draft', prompt: 'saved prompt', renders: [], ...extra });++const v1Sketch = () => normalizeWaveSketch({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' });+ promptRunner.runPromptThroughProvider.mockImplementation(replyWith());});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' });+ it('paints a short piece in one passage and returns the normalized v2 canvas', async () => {+ const result = await drawWaveSketch({ description: 'glassy tidal ambient', lyrics: 'salt on the glass', durationSec: 12, providerId: 'prov-1' });+ expect(promptRunner.runPromptThroughProvider).toHaveBeenCalledTimes(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(args.prompt).toContain('salt on the glass');+ expect(args.prompt).toContain('passage 1 of 1: t=0s to t=12s');+ expect(args.prompt).not.toContain('CURRENT PAINTING');+ expect(args.screenshots).toBeUndefined();+ // The runner's schema is "paints at least one stroke inside the passage".+ expect(args.responseSchema(paintReply(args.prompt))).toBe(true);+ expect(args.responseSchema({ strokes: [{ path: [{ t: 20, hz: 440, a: 1 }, { t: 21, hz: 440, a: 1 }] }] })).toBe(false);++ expect(result.sketch).toMatchObject({ version: 2, title: 'Glass Tide', durationSec: 12, sections: [{ start: 0, end: 12 }] });+ expect(result.sketch.strokes.map((s) => s.name)).toEqual(['line1', 'air1']);+ expect(normalizeWaveSketch(result.sketch)).toEqual(result.sketch);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() });+ it('describes only the canvas physics and limits — no arrangement, instruments, or vocal ban', async () => {+ await drawWaveSketch({ description: 'EXAMPLE BRIEF', lyrics: 'EXAMPLE TEXT', durationSec: 20 });const { prompt } = promptRunner.runPromptThroughProvider.mock.calls[0][0];- expect(prompt).toContain('CURRENT SKETCH');- expect(prompt).toContain('"glass"');- expect(prompt).toContain('punchier kick');+ const withoutInputs = prompt.replace('EXAMPLE BRIEF', '').replace('EXAMPLE TEXT', '');+ expect(withoutInputs).not.toMatch(/\b(melod\w*|bass\w*|drums?|percuss\w*|vocals?|voices?|sing\w*|sung|lead|pads?|chords?|harmon\w*|instruments?|compos\w*|verses?|chorus|arrang\w*|reverb|groove|genre)\b/i);+ // The numeric limits come from PAINTED_CANVAS_LIMITS.+ const L = PAINTED_CANVAS_LIMITS;+ for (const limit of [`${L.HZ_MIN} Hz`, `${L.HZ_MAX} Hz`, `up to ${L.OVERTONES_MAX} levels`, `at most ${L.KEYFRAMES_PER_STROKE_MAX}`, `${L.WIDTH_MIN_HZ}-${L.WIDTH_MAX_HZ} Hz`]) {+ expect(prompt).toContain(limit);+ }+ expect(prompt).toContain(`at most ${L.STROKES_MAX} strokes, ${L.KEYFRAMES_MAX} keyframes in total, and ${L.WORK_MAX_PARTIAL_SEC} units of render work`);+ });++ it('paints a long piece passage by passage, sharing the tempo grid and a summary of its neighbours', async () => {+ promptRunner.runPromptThroughProvider.mockImplementation(async ({ prompt }) => {+ const { index } = windowOf(prompt);+ return { text: JSON.stringify(paintReply(prompt, index === 0 ? { bpm: 100, beatsPerBar: 4 } : { bpm: 60, title: 'Ignored' })) };+ });++ const result = await drawWaveSketch({ description: 'x', durationSec: 70 });++ const prompts = promptRunner.runPromptThroughProvider.mock.calls.map(([args]) => args.prompt);+ expect(prompts).toHaveLength(3);+ expect(prompts[0]).toContain('No tempo grid is set');+ // Once the first passage sets 100 BPM (a 2.4s bar), later boundaries land on bar lines.+ expect(result.sketch.sections).toEqual([{ start: 0, end: 23.333 }, { start: 23.333, end: 45.6 }, { start: 45.6, end: 70 }]);+ expect(prompts[1]).toContain('Tempo grid: 100 BPM, 4 beats per bar');+ expect(prompts[1]).toContain('passage 2 of 3: t=23.333s to t=45.6s');+ expect(prompts[1]).toMatch(/Passage 1 \(t 0-23\.333s\), 2 strokes:\n- line1: t 0-11\.67s, 220-330 Hz, peak a 0\.6, overtones/);+ expect(prompts[1]).toContain('- air1: sounding at t=23.333s');+ expect(prompts[2]).toMatch(/Passage 1 \(t 0-23\.333s\): 2 strokes, 220-5000 Hz/);+ expect(result.sketch).toMatchObject({ title: 'Glass Tide', bpm: 100, beatsPerBar: 4 });+ expect(result.sketch.strokes.map((s) => s.name)).toEqual(['line1', 'air1', 'line2', 'air2', 'line3', 'air3']);+ expect(result.passages).toBe(3);});- it('502s when the reply has nothing playable', async () => {- promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'I drew you a lovely picture!' });+ it('repaints each passage of a v2 painting with its current strokes; a v1 drawing paints fresh', async () => {+ const { sketch: current } = await drawWaveSketch({ description: 'x', durationSec: 40 });+ vi.clearAllMocks();+ promptRunner.resolveProviderAndModel.mockResolvedValue({ provider: { id: 'prov-1', type: 'api' }, selectedModel: 'model-x' });+ promptRunner.runPromptThroughProvider.mockImplementation(replyWith({ title: 'New name' }));++ const revised = await drawWaveSketch({ description: 'x', guidance: 'brighter air', current });+ const prompts = promptRunner.runPromptThroughProvider.mock.calls.map(([args]) => args.prompt);+ expect(prompts).toHaveLength(current.sections.length);+ expect(prompts[0]).toContain('CURRENT PAINTING OF THIS PASSAGE');+ expect(prompts[0]).toContain('"name":"line1"');+ expect(prompts[0]).toContain('brighter air');+ expect(revised.sketch).toMatchObject({ durationSec: 40, sections: current.sections, title: current.title });++ promptRunner.runPromptThroughProvider.mockClear();+ await drawWaveSketch({ description: 'x', current: v1Sketch() });+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).not.toContain('CURRENT PAINTING');+ });++ it('with review, shows the model a spectrogram of each passage and repaints it once', async () => {+ const seen = [];+ promptRunner.runPromptThroughProvider.mockImplementation(async (args) => {+ if (args.screenshots) seen.push({ png: (await readFile(args.screenshots[0])).subarray(1, 4).toString(), prompt: args.prompt });+ return { text: JSON.stringify(paintReply(args.prompt)) };+ });+ const result = await drawWaveSketch({ description: 'x', durationSec: 10, review: true });+ expect(seen).toHaveLength(1);+ expect(seen[0].png).toBe('PNG');+ expect(seen[0].prompt).toContain('ATTACHED IMAGE: a spectrogram of this passage');+ expect(seen[0].prompt).toContain('CURRENT PAINTING OF THIS PASSAGE');+ expect(result.reviewed).toBe(1);+ });++ it('keeps the painting when the provider cannot take the review image', async () => {+ promptRunner.runPromptThroughProvider.mockImplementation(async (args) => {+ if (args.screenshots) throw Object.assign(new Error('cannot receive image attachments'), { code: 'VISION_PROVIDER_UNSUPPORTED' });+ return { text: JSON.stringify(paintReply(args.prompt)) };+ });+ const result = await drawWaveSketch({ description: 'x', durationSec: 10, review: true });+ expect(result.reviewed).toBe(0);+ expect(result.sketch.strokes).toHaveLength(2);+ });++ it('502s when a passage has nothing playable', async () => {+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'I painted you a lovely picture!' });await expect(drawWaveSketch({ description: 'x' })).rejects.toMatchObject({ status: 502, code: 'WAVEFORM_BAD_RESPONSE' });});});describe('drawWaveSketchForTrack', () => {- it('persists the drawing and its description on the track', async () => {+ it('persists the painting and its description on the track', async () => {tracks.getTrack.mockResolvedValue(baseTrack());- promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()), model: 'model-x' });- const result = await drawWaveSketchForTrack({ trackId: 'track-1', description: 'glassy tidal ambient', revise: true });+ const result = await drawWaveSketchForTrack({ trackId: 'track-1', description: 'glassy tidal ambient', durationSec: 8, revise: true });- // No stored drawing yet, so "revise" still draws fresh.- expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).not.toContain('CURRENT SKETCH');- expect(tracks.updateTrack).toHaveBeenCalledWith('track-1', {- waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'glassy tidal ambient',- });- expect(result.sketch).toEqual(normalizeWaveSketch(drawnSketch()));+ // No stored painting yet, so "revise" still paints fresh.+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).not.toContain('CURRENT PAINTING');+ const [, patch] = tracks.updateTrack.mock.calls[0];+ expect(patch.waveSketchPrompt).toBe('glassy tidal ambient');+ expect(patch.waveSketch).toMatchObject({ version: 2, durationSec: 8 });+ expect(result.sketch).toEqual(patch.waveSketch);expect(result.track).toMatchObject({ id: 'track-1', waveSketchPrompt: 'glassy tidal ambient' });});- it('revises the STORED drawing, and only when asked', async () => {- tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()) }));- promptRunner.runPromptThroughProvider.mockResolvedValue({ text: JSON.stringify(drawnSketch()) });+ it('revises the STORED painting, and only when asked', async () => {+ const { sketch } = await drawWaveSketch({ description: 'x', durationSec: 8 });+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: sketch }));+ promptRunner.runPromptThroughProvider.mockClear();await drawWaveSketchForTrack({ trackId: 'track-1', description: 'x', revise: true });- expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('CURRENT SKETCH');+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('CURRENT PAINTING');await drawWaveSketchForTrack({ trackId: 'track-1', description: 'x' });- expect(promptRunner.runPromptThroughProvider.mock.calls[1][0].prompt).not.toContain('CURRENT SKETCH');+ expect(promptRunner.runPromptThroughProvider.mock.calls[1][0].prompt).not.toContain('CURRENT PAINTING');});it('404s on a missing track without calling the provider', async () => {@@ -117,28 +216,34 @@ describe('drawWaveSketchForTrack', () => {});describe('renderWaveSketchToTrack', () => {- it('renders the stored drawing into the music library as the active waveform take', async () => {- tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'drawn from this' }));+ it('renders a stored painting into the music library as a stereo waveform take', async () => {+ const { sketch } = await drawWaveSketch({ description: 'x', durationSec: 2 });+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: sketch, waveSketchPrompt: 'painted from this' }));const result = await renderWaveSketchToTrack({ trackId: 'track-1', prompt: 'glassy', title: 'Glass Tide' });expect(result.filename).toMatch(/^music-.+\.wav$/);expect(await readdir(musicDir)).toContain(result.filename);- // 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);+ const wav = await readFile(join(musicDir, result.filename));+ // 2s of 16-bit stereo at 44.1 kHz behind a 44-byte header.+ expect(wav.readUInt16LE(22)).toBe(2);+ expect(wav.length).toBe(44 + 2 * 44100 * 2 * 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('defaults the take prompt to the description the drawing came from', async () => {- tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: normalizeWaveSketch(drawnSketch()), waveSketchPrompt: 'drawn from this' }));- await renderWaveSketchToTrack({ trackId: 'track-1' });+ it('still renders a stored v1 drawing as mono, defaulting the take prompt to its description', async () => {+ tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: v1Sketch(), waveSketchPrompt: 'drawn from this' }));+ const result = await renderWaveSketchToTrack({ trackId: 'track-1' });+ const wav = await readFile(join(musicDir, result.filename));+ expect(wav.readUInt16LE(22)).toBe(1);+ expect(wav.length).toBe(44 + 2 * 44100 * 2);expect(tracks.appendActiveTake.mock.calls[0][1]).toMatchObject({ prompt: 'drawn from this' });});- it('400s when the track has no drawing and 404s on a missing track', async () => {+ it('400s when the track has no painting and 404s on a missing track', async () => {tracks.getTrack.mockResolvedValue(baseTrack({ waveSketch: null }));await expect(renderWaveSketchToTrack({ trackId: 'track-1' })).rejects.toMatchObject({ status: 400, code: 'WAVEFORM_EMPTY' });diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 59ff0a0fc4..0f547a1b74 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -31,9 +31,10 @@* point at whichever render is currently ACTIVE (selected).* - chiptuneScore / chiptunePrompt — the LLM-composed looping 8-bit score* and the brief it was composed from (#2911), or null / ''- * - waveSketch / waveSketchPrompt — the Music Designer's LLM-drawn wave- * sketch (lib/waveSketch.js) and the description it was- * drawn from (#8376), or null / ''+ * - waveSketch / waveSketchPrompt — the Music Designer's LLM-painted+ * canvas (v2, lib/paintedCanvas.js, #8464) or a legacy v1+ * drawn sketch (lib/waveSketch.js), and the description it+ * came from (#8376), or null / ''** Tracks are `db-primary` (PostgreSQL `tracks` table). The audio bytes live in* the shared music library (services/pipeline/musicLibrary.js, `data/music/`);