Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: add a Strudel code render engine to the Music Designer (#8375)

[._.]/ Adam Eivyc3ff40f7d317
diff --git a/client/src/components/music/CodePanel.jsx b/client/src/components/music/CodePanel.jsx
new file mode 100644
index 0000000000..bd4766a944
--- /dev/null
+++ b/client/src/components/music/CodePanel.jsx
@@ -0,0 +1,260 @@
+/**
+ * CodePanel — the Music Designer's "Code" engine.
+ *
+ * The chosen AI provider writes the track as Strudel code (strudel.cc). The code
+ * lands in an editable box, and Play runs it in a sandboxed player frame
+ * (`strudelFrame.js`): an opaque-origin `<iframe sandbox="allow-scripts">`
+ * whose CSP blocks all network access. LLM code therefore never runs in the
+ * PortOS origin, and an error it throws is reported back and shown inline
+ * without breaking the page.
+ *
+ * "Save as take" records the code in the frame for the chosen length and
+ * uploads the WAV into the track's render history (`engine: 'code'`).
+ *
+ * The LLM call fires only from the Write/Revise buttons (no cold-bootstrap LLM
+ * calls). The latest code is remembered per viewer in localStorage so a reload
+ * doesn't lose it.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Code2, Loader2, Play, Save, Square, Wand2 } from 'lucide-react';
+import toast from '../ui/Toast';
+import useMounted from '../../hooks/useMounted';
+import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage.js';
+import { clamp, formatTimecode } from '../../utils/formatters';
+import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';
+import { renderTrackCode, writeMusicCode } from '../../services/api';
+import { CODE_FRAME_SOURCE, STRUDEL_VERSION, buildStrudelFrameDoc } from './strudelFrame';
+
+const CODE_KEY = 'portos.musicDesigner.strudelCode';
+// Mirrors MUSIC_CODE_MAX in server/services/musicCode.js.
+const CODE_MAX = 20000;
+// Recording length. At 120s a 48 kHz stereo WAV is ~23 MB, under the 50 MB
+// music upload cap.
+const TAKE_SEC = { MIN: 4, MAX: 120, DEFAULT: 30 };
+const FRAME_DOC = buildStrudelFrameDoc();
+
+// Only the most recent code is kept (one key, tagged with its draft track).
+const readStoredCode = (trackId) => {
+ const stored = safeReadJsonStorage(CODE_KEY);
+ return trackId && stored?.trackId === trackId && typeof stored.code === 'string' ? stored.code : '';
+};
+
+export default function CodePanel({
+ trackId, disabled = false, description = '', lyrics = '', title = '',
+ providerId, model, effort, providerPicker, onRendered,
+}) {
+ const mountedRef = useMounted();
+ const frameRef = useRef(null);
+ const [code, setCode] = useState(() => readStoredCode(trackId));
+ const [guidance, setGuidance] = useState('');
+ // Raw field text, clamped only when used (same as the waveform panel).
+ const [lengthInput, setLengthInput] = useState(String(TAKE_SEC.DEFAULT));
+ const [writing, setWriting] = useState(null); // 'fresh' | 'revise' | null
+ const [frameReady, setFrameReady] = useState(false);
+ const [frameState, setFrameState] = useState('stopped'); // 'stopped' | 'playing' | 'recording' | 'blocked'
+ const [frameError, setFrameError] = useState('');
+ // null → not saving; 'recording' → the frame is capturing; 'uploading' → sending the WAV.
+ const [savePhase, setSavePhase] = useState(null);
+ const [recordedSec, setRecordedSec] = useState(0);
+ const [takeSec, setTakeSec] = useState(TAKE_SEC.DEFAULT);
+ const saveContextRef = useRef({});
+ saveContextRef.current = { trackId, description, title, onRendered };
+
+ const post = (msg) => frameRef.current?.contentWindow?.postMessage(msg, '*');
+
+ const uploadTake = async (wav, durationSec) => {
+ const { trackId: id, description: prompt, title: takeTitle, onRendered: done } = saveContextRef.current;
+ setSavePhase('uploading');
+ const form = new FormData();
+ form.append('track', new Blob([wav], { type: 'audio/wav' }), 'code-take.wav');
+ if (prompt.trim()) form.append('prompt', prompt.trim());
+ if (takeTitle.trim()) form.append('title', takeTitle.trim());
+ const res = await renderTrackCode(id, form, { silent: true })
+ .catch((err) => { toast.error(err?.message || 'Could not save the take'); return null; });
+ if (!mountedRef.current) return;
+ setSavePhase(null);
+ if (!res?.track) return;
+ toast.success(`Saved the code take (${res.durationSec ?? Math.round(durationSec)}s)`);
+ done?.(res.track);
+ };
+
+ // Everything the frame says arrives here. Only messages from OUR frame's
+ // window with the protocol tag count; anything else on the page is ignored.
+ useEffect(() => {
+ const onMessage = (event) => {
+ if (!frameRef.current || event.source !== frameRef.current.contentWindow) return;
+ const msg = event.data;
+ if (!msg || msg.source !== CODE_FRAME_SOURCE) return;
+ if (msg.type === 'ready') setFrameReady(true);
+ else if (msg.type === 'state') setFrameState(msg.state);
+ else if (msg.type === 'progress') setRecordedSec(Number(msg.seconds) || 0);
+ else if (msg.type === 'error') {
+ setFrameError(String(msg.message || 'The code failed to run'));
+ setSavePhase((phase) => (phase === 'recording' ? null : phase));
+ } else if (msg.type === 'recorded' && msg.wav instanceof ArrayBuffer) {
+ uploadTake(msg.wav, Number(msg.durationSec) || 0);
+ }
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+ // Subscribed once; uploadTake reads the latest props through saveContextRef.
+ }, []);
+
+ const rememberCode = (next) => safeWriteJsonStorage(CODE_KEY, { trackId, code: next });
+
+ const write = async (mode) => {
+ if (!description.trim()) { toast.error('Write the musical description first'); return; }
+ setWriting(mode);
+ const res = await writeMusicCode({
+ description: description.trim(),
+ lyrics: lyrics.trim() || undefined,
+ guidance: guidance.trim() || undefined,
+ ...(mode === 'revise' && code.trim() ? { current: code } : {}),
+ language: 'strudel',
+ providerId: providerId || undefined,
+ model: model || undefined,
+ effort: effort || undefined,
+ }, { silent: true }).catch((err) => { toast.error(err?.message || 'Could not write the music code'); return null; });
+ if (!mountedRef.current) return;
+ setWriting(null);
+ if (!res?.code) return;
+ setCode(res.code);
+ setFrameError('');
+ rememberCode(res.code);
+ };
+
+ const play = () => {
+ setFrameError('');
+ post({ type: 'play', code });
+ };
+ const stop = () => post({ type: 'stop' });
+
+ const save = () => {
+ if (!code.trim() || !trackId) return;
+ const seconds = clamp(Number(lengthInput) || TAKE_SEC.DEFAULT, TAKE_SEC.MIN, TAKE_SEC.MAX);
+ setTakeSec(seconds);
+ setFrameError('');
+ setRecordedSec(0);
+ setSavePhase('recording');
+ post({ type: 'record', code, seconds });
+ };
+
+ const busy = !!writing || !!savePhase;
+ const hasCode = !!code.trim();
+ const playing = frameState === 'playing';
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-gray-400">
+ No audio model: the AI writes the piece as <a href="https://strudel.cc" target="_blank" rel="noreferrer" className="text-port-accent hover:underline">Strudel</a> code, and your browser plays it in a sandboxed player. Edit the code freely, then save a recording of it as a take.
+ </p>
+
+ <div className="grid gap-3 sm:grid-cols-[1fr_auto]">
+ <label htmlFor="music-code-guidance" className="block">
+ <span className={LABEL_CLASS}>Code guidance (optional)</span>
+ <input
+ id="music-code-guidance"
+ value={guidance}
+ onChange={(event) => setGuidance(event.target.value)}
+ disabled={disabled}
+ maxLength={4000}
+ placeholder={hasCode ? 'Double the hats and add a filter sweep on the bass…' : 'Four-on-the-floor, a supersaw lead, 124 BPM…'}
+ className={FIELD_CLASS}
+ />
+ </label>
+ <label htmlFor="music-code-length" className="block">
+ <span className={LABEL_CLASS}>Take length (sec)</span>
+ <input
+ id="music-code-length"
+ type="number"
+ min={TAKE_SEC.MIN}
+ max={TAKE_SEC.MAX}
+ value={lengthInput}
+ onChange={(event) => setLengthInput(event.target.value)}
+ disabled={disabled || busy}
+ className={`${FIELD_CLASS} sm:w-28`}
+ />
+ </label>
+ </div>
+
+ <div className="rounded border border-port-border bg-port-bg/60 p-3">
+ <span className={LABEL_CLASS}>AI provider</span>
+ {providerPicker}
+ </div>
+
+ <div className="flex flex-wrap gap-2">
+ <button type="button" onClick={() => write('fresh')} disabled={disabled || busy || !description.trim()} className={hasCode ? GHOST_BTN : PRIMARY_BTN}>
+ {writing === 'fresh' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Code2 className="h-4 w-4" />}
+ <span>{writing === 'fresh' ? 'Writing…' : hasCode ? 'Write from scratch' : 'Write the code'}</span>
+ </button>
+ {hasCode && (
+ <button type="button" onClick={() => write('revise')} disabled={disabled || busy || !description.trim()} className={PRIMARY_BTN}>
+ {writing === 'revise' ? <Loader2 className="h-4 w-4 animate-spin" /> : <Wand2 className="h-4 w-4" />}
+ <span>{writing === 'revise' ? 'Revising…' : 'Revise code'}</span>
+ </button>
+ )}
+ </div>
+
+ <label htmlFor="music-code-editor" className="block">
+ <span className={LABEL_CLASS}>Strudel code</span>
+ <textarea
+ id="music-code-editor"
+ value={code}
+ onChange={(event) => setCode(event.target.value)}
+ onBlur={() => rememberCode(code)}
+ disabled={disabled || !!writing}
+ rows={12}
+ maxLength={CODE_MAX}
+ spellCheck={false}
+ placeholder={'setcps(0.5)\nstack(\n note("<c3 ab2 f2 g2>").s("sawtooth").lpf(600),\n s("sbd*4"),\n)'}
+ className={`${FIELD_CLASS} font-mono text-xs leading-relaxed`}
+ />
+ </label>
+
+ {frameError && (
+ <p role="alert" className="whitespace-pre-wrap break-words rounded border border-port-error/50 bg-port-error/10 px-3 py-2 font-mono text-xs text-port-error">
+ {frameError}
+ </p>
+ )}
+
+ <div className="space-y-2">
+ <iframe
+ ref={frameRef}
+ title={`Strudel ${STRUDEL_VERSION} player`}
+ // Opaque origin (no allow-same-origin): the LLM's code gets no access
+ // to PortOS cookies, storage, or DOM. Do not widen this.
+ sandbox="allow-scripts"
+ allow="autoplay"
+ srcDoc={FRAME_DOC}
+ className="h-10 w-full rounded border border-port-border bg-port-bg"
+ />
+ <div className="flex flex-wrap items-center gap-2">
+ <button type="button" onClick={play} disabled={!frameReady || !hasCode || !!savePhase} className={GHOST_BTN}>
+ <Play className="h-4 w-4" />
+ <span>{playing ? 'Re-run' : 'Play'}</span>
+ </button>
+ <button type="button" onClick={stop} disabled={!frameReady || !!savePhase || !playing} className={GHOST_BTN}>
+ <Square className="h-4 w-4" />
+ <span>Stop</span>
+ </button>
+ <button type="button" onClick={save} disabled={disabled || busy || !frameReady || !hasCode || !trackId} className={PRIMARY_BTN}>
+ {savePhase ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />}
+ <span>{savePhase === 'recording' ? 'Recording…' : savePhase === 'uploading' ? 'Saving…' : 'Save as take'}</span>
+ </button>
+ {savePhase === 'recording' && (
+ <span className="text-xs font-mono tabular-nums text-gray-500">
+ {formatTimecode(recordedSec)}{' / '}{formatTimecode(takeSec)}
+ </span>
+ )}
+ </div>
+ {frameState === 'blocked' && (
+ <p className="text-xs text-port-warning">The browser is holding audio back. Click “Enable audio” in the player above.</p>
+ )}
+ <p className="text-xs text-gray-500">
+ Saving plays the code in real time while it records, so a {clamp(Number(lengthInput) || TAKE_SEC.DEFAULT, TAKE_SEC.MIN, TAKE_SEC.MAX)}s take takes that long.
+ </p>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/music/CodePanel.test.jsx b/client/src/components/music/CodePanel.test.jsx
new file mode 100644
index 0000000000..6a65e2c9a8
--- /dev/null
+++ b/client/src/components/music/CodePanel.test.jsx
@@ -0,0 +1,142 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { render, screen, fireEvent, waitFor, cleanup, act } from '@testing-library/react';
+import CodePanel from './CodePanel';
+import * as api from '../../services/api';
+
+vi.mock('../../services/api', () => ({
+ writeMusicCode: vi.fn(),
+ renderTrackCode: vi.fn(),
+}));
+
+// The real frame document loads Strudel from a CDN; the tests stub the frame
+// and speak its postMessage protocol directly.
+vi.mock('./strudelFrame', () => ({
+ CODE_FRAME_SOURCE: 'portos-code-frame',
+ STRUDEL_VERSION: '0.0.0-test',
+ buildStrudelFrameDoc: () => '<!doctype html><title>stub</title>',
+}));
+
+const CODE = 'setcps(0.5)\nnote("c3 e3 g3").s("sawtooth")';
+
+const renderPanel = (props = {}) => render(
+ <CodePanel
+ trackId="track-1"
+ description="neon synthwave drive"
+ lyrics=""
+ title="Night Drive"
+ providerId="provider-a"
+ model="model-a"
+ effort=""
+ providerPicker={<div data-testid="picker" />}
+ {...props}
+ />,
+);
+
+const frame = () => screen.getByTitle(/Strudel .* player/);
+// Deliver a message as if the frame had posted it.
+const fromFrame = (data, source = frame().contentWindow) => act(() => {
+ window.dispatchEvent(new MessageEvent('message', { data: { source: 'portos-code-frame', ...data }, source }));
+});
+
+describe('<CodePanel>', () => {
+ let posted;
+ beforeEach(() => {
+ vi.clearAllMocks();
+ window.localStorage.clear();
+ api.writeMusicCode.mockResolvedValue({ language: 'strudel', code: CODE, llm: { provider: 'provider-a', model: 'model-a' } });
+ api.renderTrackCode.mockResolvedValue({ track: { id: 'track-1' }, filename: 'music-x.wav', durationSec: 4 });
+ });
+ afterEach(() => { cleanup(); });
+
+ const mountReady = async (props) => {
+ renderPanel(props);
+ posted = vi.spyOn(frame().contentWindow, 'postMessage').mockImplementation(() => {});
+ await fromFrame({ type: 'ready' });
+ };
+
+ it('runs the code only in an opaque-origin sandboxed frame', () => {
+ renderPanel();
+ // allow-same-origin would hand LLM code the PortOS origin: cookies, storage, and API.
+ expect(frame().getAttribute('sandbox')).toBe('allow-scripts');
+ });
+
+ it('ships a frame document that blocks network access and pins the bundle by hash', async () => {
+ const real = await vi.importActual('./strudelFrame');
+ const doc = new DOMParser().parseFromString(real.buildStrudelFrameDoc(), 'text/html');
+ const csp = doc.querySelector('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
+ // connect-src none is what stops frame code from calling the PortOS API.
+ expect(csp).toContain("connect-src 'none'");
+ expect(csp).toContain("default-src 'none'");
+ const bundle = doc.querySelector('script[src]');
+ expect(bundle.getAttribute('src')).toBe(real.STRUDEL_BUNDLE_URL);
+ expect(bundle.getAttribute('integrity')).toMatch(/^sha384-/);
+ });
+
+ it('writes code from the description with the chosen provider, then revises the edited code', async () => {
+ await mountReady();
+ fireEvent.change(screen.getByLabelText('Code guidance (optional)'), { target: { value: '124 BPM' } });
+ fireEvent.click(screen.getByRole('button', { name: /Write the code/ }));
+
+ await waitFor(() => expect(screen.getByLabelText('Strudel code')).toHaveValue(CODE));
+ expect(api.writeMusicCode).toHaveBeenCalledWith({
+ description: 'neon synthwave drive',
+ lyrics: undefined,
+ guidance: '124 BPM',
+ language: 'strudel',
+ providerId: 'provider-a',
+ model: 'model-a',
+ effort: undefined,
+ }, { silent: true });
+
+ const edited = `${CODE}.lpf(800)`;
+ fireEvent.change(screen.getByLabelText('Strudel code'), { target: { value: edited } });
+ fireEvent.click(screen.getByRole('button', { name: /Revise code/ }));
+ await waitFor(() => expect(api.writeMusicCode).toHaveBeenCalledTimes(2));
+ expect(api.writeMusicCode.mock.calls[1][0].current).toBe(edited);
+ });
+
+ it('plays and stops through the frame, and shows a thrown error inline', async () => {
+ window.localStorage.setItem('portos.musicDesigner.strudelCode', JSON.stringify({ trackId: 'track-1', code: CODE }));
+ await mountReady();
+ expect(screen.getByLabelText('Strudel code')).toHaveValue(CODE);
+
+ fireEvent.click(screen.getByRole('button', { name: /^Play$/ }));
+ expect(posted).toHaveBeenLastCalledWith({ type: 'play', code: CODE }, '*');
+ await fromFrame({ type: 'state', state: 'playing' });
+ fireEvent.click(screen.getByRole('button', { name: /^Stop$/ }));
+ expect(posted).toHaveBeenLastCalledWith({ type: 'stop' }, '*');
+
+ await fromFrame({ type: 'error', message: 'note(...).nope is not a function' });
+ expect(screen.getByRole('alert')).toHaveTextContent('note(...).nope is not a function');
+ // A message from anywhere but our frame is ignored.
+ await fromFrame({ type: 'error', message: 'spoofed' }, window);
+ expect(screen.getByRole('alert')).not.toHaveTextContent('spoofed');
+ });
+
+ it('records the take in the frame and uploads it as a WAV to the draft track', async () => {
+ window.localStorage.setItem('portos.musicDesigner.strudelCode', JSON.stringify({ trackId: 'track-1', code: CODE }));
+ const onRendered = vi.fn();
+ await mountReady({ onRendered });
+ fireEvent.change(screen.getByLabelText('Take length (sec)'), { target: { value: '4' } });
+ fireEvent.click(screen.getByRole('button', { name: /Save as take/ }));
+ expect(posted).toHaveBeenLastCalledWith({ type: 'record', code: CODE, seconds: 4 }, '*');
+ expect(screen.getByRole('button', { name: /Recording/ })).toBeDisabled();
+
+ await fromFrame({ type: 'recorded', wav: new ArrayBuffer(64), durationSec: 4 });
+ await waitFor(() => expect(onRendered).toHaveBeenCalledWith({ id: 'track-1' }));
+ const [trackId, form] = api.renderTrackCode.mock.calls[0];
+ expect(trackId).toBe('track-1');
+ expect(form.get('track').type).toBe('audio/wav');
+ expect(form.get('prompt')).toBe('neon synthwave drive');
+ expect(form.get('title')).toBe('Night Drive');
+ });
+
+ it('ends a failed recording without uploading', async () => {
+ window.localStorage.setItem('portos.musicDesigner.strudelCode', JSON.stringify({ trackId: 'track-1', code: CODE }));
+ await mountReady();
+ fireEvent.click(screen.getByRole('button', { name: /Save as take/ }));
+ await fromFrame({ type: 'error', message: 'The code played only silence, so there is nothing to save.' });
+ expect(screen.getByRole('button', { name: /Save as take/ })).toBeEnabled();
+ expect(api.renderTrackCode).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/music/MusicDesigner.jsx b/client/src/components/music/MusicDesigner.jsx
index b13b302162..4717b1729f 100644
--- a/client/src/components/music/MusicDesigner.jsx
+++ b/client/src/components/music/MusicDesigner.jsx
@@ -8,8 +8,10 @@
* AI provider of their choosing expands it into a rich, genre-dense musical
* description, they optionally generate lyrics from that description plus their
* own extra guidance, and the render step either hands it to an audio model
- * (`MusicGenPanel`) or asks the AI to DRAW the waveform itself (`WaveformPanel`,
- * `?engine=drawn`) and plays that drawing back in the browser. Every
+ * (`MusicGenPanel`), asks the AI to DRAW the waveform itself (`WaveformPanel`,
+ * `?engine=drawn`) and plays that drawing back in the browser, or asks it to
+ * write the piece as Strudel code (`CodePanel`, `?engine=code`) that a
+ * sandboxed player frame runs and records. Every
* step's output lands in an editable textarea — **the AI drafts, the human owns
* the text** — and every step stays revisitable from the step bar.
*
@@ -28,8 +30,9 @@
import { useEffect, useRef, useState } from 'react';
import { Navigate, useNavigate, useParams, useSearchParams } from 'react-router';
import {
- AudioLines, AudioWaveform, Brush, ChevronDown, ChevronUp, FileText, Lightbulb, Loader2, Mic2, Sparkles, Wand2,
+ AudioLines, AudioWaveform, Brush, ChevronDown, ChevronUp, Code2, FileText, Lightbulb, Loader2, Mic2, Sparkles, Wand2,
} from 'lucide-react';
+import CodePanel from './CodePanel';
import MusicGenPanel from './MusicGenPanel';
import WaveformPanel from './WaveformPanel';
import { FIELD_CLASS, GHOST_BTN, LABEL_CLASS, PRIMARY_BTN } from './designerStyles';
@@ -51,12 +54,23 @@ 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, or a waveform the AI draws point by point. Rides in `?engine=`.
+// audio model, a waveform the AI draws point by point, or Strudel code the AI
+// writes. Rides in `?engine=` (absent = the audio model).
const RENDER_ENGINES = [
{ id: 'model', label: 'Audio model', icon: AudioWaveform },
{ id: 'drawn', label: 'Drawn waveform', icon: Brush },
+ { id: 'code', label: 'Code', icon: Code2 },
];
-const DRAWN_ENGINE = 'drawn';
+const DEFAULT_ENGINE = 'model';
+const ENGINE_IDS = RENDER_ENGINES.map((e) => e.id);
+// The engines where the chosen AI provider writes the music itself. Both panels
+// take the same props; the audio model gets MusicGenPanel instead.
+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.',
+ code: 'Required. The AI writes the Strudel code from this editable description.',
+};
const FIRST_STEP = STEP_IDS[0];
const DRAFT_TITLE = 'Untitled music draft';
const ACTIVE_DRAFT_KEY = 'portos.musicDesigner.activeDraft';
@@ -74,7 +88,8 @@ export default function MusicDesigner() {
const [searchParams, setSearchParams] = useSearchParams();
const mountedRef = useMounted();
const requestedTrackId = searchParams.get('trackId') || '';
- const renderEngine = searchParams.get('engine') === DRAWN_ENGINE ? DRAWN_ENGINE : 'model';
+ const renderEngine = ENGINE_IDS.includes(searchParams.get('engine')) ? searchParams.get('engine') : DEFAULT_ENGINE;
+ const LlmEnginePanel = LLM_ENGINE_PANELS[renderEngine];
const storedDraftId = requestedTrackId || safeReadStorage(ACTIVE_DRAFT_KEY) || '';
// Wizard text — lifted here so MusicGenPanel (which never writes back to
@@ -224,8 +239,8 @@ export default function MusicDesigner() {
const setRenderEngine = (engineId) => {
setSearchParams((prev) => {
const next = new URLSearchParams(prev);
- if (engineId === DRAWN_ENGINE) next.set('engine', DRAWN_ENGINE);
- else next.delete('engine');
+ if (engineId === DEFAULT_ENGINE || !ENGINE_IDS.includes(engineId)) next.delete('engine');
+ else next.set('engine', engineId);
return next;
}, { replace: true });
};
@@ -581,9 +596,7 @@ export default function MusicDesigner() {
className={FIELD_CLASS}
/>
<span id="music-designer-render-prompt-hint" className="mt-1 block text-xs text-gray-500">
- {renderEngine === DRAWN_ENGINE
- ? 'Required. The AI draws the waveform from this editable description.'
- : 'Required. This editable description is the prompt sent to the selected audio engine.'}
+ {PROMPT_HINTS[renderEngine]}
</span>
</label>
<label htmlFor="music-designer-title" className="block">
@@ -604,8 +617,8 @@ export default function MusicDesigner() {
className={FIELD_CLASS}
/>
</label>
- {renderEngine === DRAWN_ENGINE ? (
- <WaveformPanel
+ {LlmEnginePanel ? (
+ <LlmEnginePanel
key={trackId}
trackId={trackId}
disabled={!draftReady || busy}
diff --git a/client/src/components/music/MusicDesigner.test.jsx b/client/src/components/music/MusicDesigner.test.jsx
index 4a82248e30..73913b010f 100644
--- a/client/src/components/music/MusicDesigner.test.jsx
+++ b/client/src/components/music/MusicDesigner.test.jsx
@@ -24,6 +24,12 @@ vi.mock('./MusicGenPanel', () => ({
),
}));
+vi.mock('./CodePanel', () => ({
+ default: ({ trackId, description }) => (
+ <div data-testid="code-panel" data-track={trackId} data-description={description} />
+ ),
+}));
+
vi.mock('./WaveformPanel', () => ({
default: ({ trackId, description, providerId }) => (
<div data-testid="waveform-panel" data-track={trackId} data-description={description} data-provider={providerId} />
@@ -55,7 +61,7 @@ vi.mock('../../hooks/useProviderModels', () => ({
function LocationDisplay() {
const location = useLocation();
- return <div data-testid="location">{location.pathname}</div>;
+ return <div data-testid="location">{location.pathname}{location.search}</div>;
}
const renderAt = (path) => render(
@@ -206,6 +212,22 @@ describe('<MusicDesigner>', () => {
fireEvent.click(await screen.findByRole('tab', { name: /^render$/i }));
expect(await screen.findByTestId('waveform-panel')).toBeInTheDocument();
});
+
+ it('opens the code engine from ?engine=code and drops the param when switching back', async () => {
+ api.getTrack.mockResolvedValue({
+ id: 'track-saved', title: 'Named Track', concept: 'x', prompt: 'Neon synthwave.', lyrics: '',
+ });
+ renderAt('/music/generate/render?trackId=track-saved&engine=code');
+ await findEnabledByLabelText(/prompt for this render/i);
+ const panel = await screen.findByTestId('code-panel');
+ expect(panel).toHaveAttribute('data-track', 'track-saved');
+ expect(panel).toHaveAttribute('data-description', 'Neon synthwave.');
+ expect(screen.getByText(/writes the Strudel code/i)).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('tab', { name: /audio model/i }));
+ expect(await screen.findByTestId('gen-panel')).toBeInTheDocument();
+ expect(screen.getByTestId('location')).not.toHaveTextContent('engine=');
+ });
});
describe('the describe step', () => {
diff --git a/client/src/components/music/TracksManager.jsx b/client/src/components/music/TracksManager.jsx
index a5ef65a31a..632854a3d9 100644
--- a/client/src/components/music/TracksManager.jsx
+++ b/client/src/components/music/TracksManager.jsx
@@ -354,6 +354,11 @@ export default function TracksManager() {
navigate(`/music/generate/render?trackId=${encodeURIComponent(persisted.id)}&engine=drawn`);
return;
}
+ // Same for a code take: its Strudel code lives in the designer's code engine.
+ if (render.engine === 'code' && persisted) {
+ navigate(`/music/generate/render?trackId=${encodeURIComponent(persisted.id)}&engine=code`);
+ return;
+ }
setGenMode('audio');
setForm((f) => ({
...f,
diff --git a/client/src/components/music/strudelFrame.js b/client/src/components/music/strudelFrame.js
new file mode 100644
index 0000000000..356f2ca495
--- /dev/null
+++ b/client/src/components/music/strudelFrame.js
@@ -0,0 +1,289 @@
+/**
+ * The sandboxed player behind the Music Designer's "Code" engine (CodePanel).
+ *
+ * The LLM writes the track as Strudel code, and that code is arbitrary
+ * JavaScript. It never runs in the PortOS origin. The panel mounts
+ * `buildStrudelFrameDoc()` as the `srcdoc` of an
+ * `<iframe sandbox="allow-scripts">` (no `allow-same-origin`), so the frame has
+ * an opaque origin: no PortOS cookies, storage, or DOM. The document's CSP adds
+ * `connect-src 'none'`, so code in the frame can't call the PortOS API (which
+ * sends no CORS restrictions) or anything else over fetch, XHR, WebSocket, or
+ * beacon. The only script it may load is the pinned Strudel bundle, checked
+ * against its SRI hash. Strudel is AGPL-3.0, so it is fetched at runtime from
+ * the CDN rather than vendored into this repository.
+ *
+ * Protocol (postMessage; every message carries `source: CODE_FRAME_SOURCE`):
+ * panel → frame { type: 'play', code } · { type: 'stop' }
+ * { type: 'record', code, seconds }
+ * frame → panel { type: 'ready' }
+ * { type: 'state', state: 'playing' | 'stopped' | 'recording' | 'blocked' }
+ * { type: 'error', message }
+ * { type: 'progress', seconds } while recording
+ * { type: 'recorded', wav, durationSec } wav: a transferred ArrayBuffer
+ *
+ * Recording taps the frame's audio graph. Before the bundle loads, the frame
+ * wraps `AudioNode.prototype.connect` so every connection into an
+ * AudioContext's destination is mirrored into a capture node. That node
+ * collects real-time PCM, and the frame encodes it as a 16-bit stereo WAV.
+ * The tap works for any Web Audio library, so a later Tone.js language can use
+ * the same capture path.
+ */
+
+export const STRUDEL_VERSION = '1.3.0';
+export const STRUDEL_BUNDLE_URL = `https://cdn.jsdelivr.net/npm/@strudel/web@${STRUDEL_VERSION}/dist/index.js`;
+// sha384 of STRUDEL_BUNDLE_URL. Bump it together with STRUDEL_VERSION.
+export const STRUDEL_BUNDLE_INTEGRITY = 'sha384-Be7toEZy01lox8utUZEOBM2nCd1jVX8R9A3YwfZ7j5kBTv/MKy+LlCbTWqE97W8x';
+export const CODE_FRAME_SOURCE = 'portos-code-frame';
+
+// The frame document's policy. Scripts may run (and `eval`, which Strudel's
+// transpiler needs; `data:` covers its bundled AudioWorklet modules), but
+// nothing may reach the network except the one pinned bundle.
+const FRAME_CSP = [
+ "default-src 'none'",
+ `script-src 'unsafe-inline' 'unsafe-eval' data: ${STRUDEL_BUNDLE_URL}`,
+ "style-src 'unsafe-inline'",
+ "connect-src 'none'",
+ "form-action 'none'",
+ "base-uri 'none'",
+].join('; ');
+
+// Runs inside the frame BEFORE the bundle, so the destination tap is in place
+// before Strudel builds its audio graph. Kept as plain ES2020 source text.
+const FRAME_BOOTSTRAP = `
+(() => {
+ 'use strict';
+ const SOURCE = ${JSON.stringify(CODE_FRAME_SOURCE)};
+ const post = (msg, transfer) => parent.postMessage({ source: SOURCE, ...msg }, '*', transfer || []);
+ const origConnect = AudioNode.prototype.connect;
+ const taps = new WeakMap();
+ let capture = null;
+
+ const tapFor = (ctx) => {
+ let tap = taps.get(ctx);
+ if (tap) return tap;
+ tap = ctx.createGain();
+ const proc = ctx.createScriptProcessor(4096, 2, 2);
+ const mute = ctx.createGain();
+ mute.gain.value = 0;
+ origConnect.call(tap, proc);
+ origConnect.call(proc, mute);
+ origConnect.call(mute, ctx.destination);
+ proc.onaudioprocess = (event) => {
+ if (!capture || capture.ctx !== ctx) return;
+ const input = event.inputBuffer;
+ const n = Math.min(input.length, capture.limit - capture.frames);
+ if (n <= 0) return;
+ capture.left.push(input.getChannelData(0).slice(0, n));
+ capture.right.push(input.getChannelData(input.numberOfChannels > 1 ? 1 : 0).slice(0, n));
+ capture.frames += n;
+ };
+ taps.set(ctx, tap);
+ return tap;
+ };
+
+ AudioNode.prototype.connect = function connect(destination, ...rest) {
+ const result = origConnect.call(this, destination, ...rest);
+ if (destination instanceof AudioDestinationNode) origConnect.call(this, tapFor(destination.context), rest[0] || 0);
+ return result;
+ };
+
+ window.__portosCapture = {
+ post,
+ start(ctx, seconds) {
+ tapFor(ctx);
+ capture = { ctx, left: [], right: [], frames: 0, limit: Math.round(seconds * ctx.sampleRate) };
+ return capture;
+ },
+ cancel() { capture = null; },
+ finish() {
+ const done = capture;
+ capture = null;
+ return done;
+ },
+ };
+})();
+`;
+
+// Runs after the bundle: boots Strudel and answers the panel's messages.
+const FRAME_CONTROLLER = `
+(() => {
+ 'use strict';
+ const { post, start, cancel, finish } = window.__portosCapture;
+ const statusEl = document.getElementById('status');
+ const unlockEl = document.getElementById('unlock');
+ const show = (text) => { statusEl.textContent = text; };
+ const messageOf = (err) => String((err && err.message) || err || 'Unknown error').slice(0, 600);
+ let failed = false;
+ const fail = (err) => {
+ failed = true;
+ const message = messageOf(err);
+ show('Error: ' + message);
+ post({ type: 'error', message });
+ };
+ const setState = (state) => { post({ type: 'state', state }); };
+
+ window.addEventListener('error', (event) => fail(event.error || event.message));
+ window.addEventListener('unhandledrejection', (event) => fail(event.reason));
+ // Strudel reports scheduler and sound errors through its logger, not by throwing.
+ document.addEventListener('strudel.log', (event) => {
+ const detail = event.detail || {};
+ if (detail.type === 'error' || /\\berror\\b/i.test(String(detail.message || ''))) fail(detail.message);
+ });
+
+ const lib = window.strudel;
+ if (!lib || typeof lib.initStrudel !== 'function') {
+ fail('Could not load the Strudel engine from cdn.jsdelivr.net. Check the network connection and reload.');
+ return;
+ }
+
+ let recording = null;
+ const ready = lib.initStrudel({
+ onEvalError: fail,
+ onToggle: (started) => { if (!recording) setState(started ? 'playing' : 'stopped'); },
+ });
+
+ // Browsers only start audio after a gesture INSIDE this frame (the parent's
+ // click doesn't count everywhere). When the context stays suspended, ask for
+ // one click here and replay the pending action.
+ let pending = null;
+ const audioRunning = async () => {
+ const ctx = lib.getAudioContext();
+ if (ctx.state !== 'running') {
+ await Promise.race([ctx.resume().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 800))]);
+ }
+ return ctx.state === 'running';
+ };
+ const whenAudible = async (action) => {
+ await ready;
+ if (await audioRunning()) return action();
+ pending = action;
+ unlockEl.hidden = false;
+ show('Click here to allow audio');
+ setState('blocked');
+ return undefined;
+ };
+ unlockEl.addEventListener('click', () => {
+ lib.getAudioContext().resume().then(() => {
+ unlockEl.hidden = true;
+ const action = pending;
+ pending = null;
+ if (action) action();
+ }, fail);
+ });
+
+ const evaluate = async (code) => {
+ failed = false;
+ await lib.evaluate(code, true);
+ return !failed;
+ };
+
+ const stopRecording = () => {
+ if (!recording) return;
+ clearInterval(recording.timer);
+ recording = null;
+ cancel();
+ };
+
+ const play = (code) => whenAudible(async () => {
+ stopRecording();
+ show('Playing');
+ if (!(await evaluate(code))) { lib.hush(); setState('stopped'); }
+ });
+
+ const stop = () => {
+ pending = null;
+ unlockEl.hidden = true;
+ stopRecording();
+ lib.hush();
+ show('Stopped');
+ setState('stopped');
+ };
+
+ const encodeWav = (take) => {
+ const frames = take.frames;
+ const buffer = new ArrayBuffer(44 + frames * 4);
+ const view = new DataView(buffer);
+ const text = (offset, value) => { for (let i = 0; i < value.length; i += 1) view.setUint8(offset + i, value.charCodeAt(i)); };
+ const rate = take.ctx.sampleRate;
+ text(0, 'RIFF'); view.setUint32(4, 36 + frames * 4, true); text(8, 'WAVE');
+ text(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); view.setUint16(22, 2, true);
+ view.setUint32(24, rate, true); view.setUint32(28, rate * 4, true); view.setUint16(32, 4, true); view.setUint16(34, 16, true);
+ text(36, 'data'); view.setUint32(40, frames * 4, true);
+ let offset = 44;
+ let peak = 0;
+ for (let c = 0; c < take.left.length; c += 1) {
+ const left = take.left[c];
+ const right = take.right[c];
+ for (let i = 0; i < left.length; i += 1) {
+ const l = Math.max(-1, Math.min(1, left[i]));
+ const r = Math.max(-1, Math.min(1, right[i]));
+ peak = Math.max(peak, Math.abs(l), Math.abs(r));
+ view.setInt16(offset, l < 0 ? l * 0x8000 : l * 0x7fff, true);
+ view.setInt16(offset + 2, r < 0 ? r * 0x8000 : r * 0x7fff, true);
+ offset += 4;
+ }
+ }
+ return { buffer, peak };
+ };
+
+ const record = (code, seconds) => whenAudible(async () => {
+ stopRecording();
+ lib.hush();
+ const ctx = lib.getAudioContext();
+ const take = start(ctx, seconds);
+ const startedAt = Date.now();
+ recording = { timer: 0 };
+ setState('recording');
+ show('Recording');
+ if (!(await evaluate(code))) { stopRecording(); lib.hush(); setState('stopped'); return; }
+ if (!recording) return;
+ recording.timer = setInterval(() => {
+ post({ type: 'progress', seconds: take.frames / ctx.sampleRate });
+ const stalled = Date.now() - startedAt > (seconds + 15) * 1000;
+ if (take.frames < take.limit && !stalled) return;
+ clearInterval(recording.timer);
+ recording = null;
+ lib.hush();
+ const done = finish();
+ if (stalled || !done || done.frames === 0) { fail('The recording stalled before it finished. Try again.'); setState('stopped'); return; }
+ const { buffer, peak } = encodeWav(done);
+ if (peak < 0.0005) { fail('The code played only silence, so there is nothing to save.'); setState('stopped'); return; }
+ show('Recorded');
+ post({ type: 'recorded', wav: buffer, durationSec: done.frames / ctx.sampleRate }, [buffer]);
+ setState('stopped');
+ }, 250);
+ });
+
+ window.addEventListener('message', (event) => {
+ if (event.source !== parent) return;
+ const msg = event.data || {};
+ if (msg.type === 'stop') { stop(); return; }
+ const code = typeof msg.code === 'string' ? msg.code : '';
+ if (!code.trim()) { fail('There is no code to run.'); return; }
+ if (msg.type === 'play') play(code).catch(fail);
+ else if (msg.type === 'record') record(code, Math.max(1, Math.min(600, Number(msg.seconds) || 30))).catch(fail);
+ });
+
+ ready.then(() => { show('Ready'); post({ type: 'ready' }); }, fail);
+})();
+`;
+
+/** The complete `srcdoc` for the sandboxed Strudel player frame. */
+export function buildStrudelFrameDoc() {
+ return `<!doctype html>
+<html><head><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="${FRAME_CSP}">
+<style>
+ html, body { margin: 0; height: 100%; background: transparent; color: #9ca3af; font: 12px/1.4 ui-sans-serif, system-ui, sans-serif; }
+ body { display: flex; align-items: center; gap: 8px; padding: 0 8px; overflow: hidden; }
+ #status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ #unlock { font: inherit; padding: 4px 10px; border-radius: 6px; border: 1px solid #6b7280; background: #1f2937; color: #fff; cursor: pointer; }
+</style></head>
+<body>
+<button id="unlock" type="button" hidden>Enable audio</button>
+<span id="status">Loading Strudel ${STRUDEL_VERSION}…</span>
+<script>${FRAME_BOOTSTRAP}</script>
+<script src="${STRUDEL_BUNDLE_URL}" integrity="${STRUDEL_BUNDLE_INTEGRITY}" crossorigin="anonymous"></script>
+<script>${FRAME_CONTROLLER}</script>
+</body></html>`;
+}
diff --git a/client/src/services/README.md b/client/src/services/README.md
index b17ec64b98..2b67320c4c 100644
--- a/client/src/services/README.md
+++ b/client/src/services/README.md
@@ -123,9 +123,9 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire
| `apiAuthors.js` | Author personas (name, writing style, bio, headshot description/style). |
| `apiArtists.js` | Music artist personas (name, genre, bio, musical style, portrait description/style). |
| `apiAlbums.js` | Music albums (title, artist FK + name, description, genre, release year, cover art, ordered track ids). |
-| `apiTracks.js` | Music tracks (title, album/artist FKs, lyrics, prompt, gen metadata, audio-library pointer) + shared music-library list + audio upload/attach. |
+| `apiTracks.js` | Music tracks (title, album/artist FKs, lyrics, prompt, gen metadata, audio-library pointer) + shared music-library list + audio upload/attach + saving drawn-waveform and code-engine takes. |
| `apiVideoDownload.js` | Dev Tools video downloader (#1946): start/cancel a YouTube/x.com full-video download via yt-dlp (SSE progress), list + delete downloaded clips, plus `getYtDlpStatus`/`updateYtDlp` for the in-place yt-dlp update the page offers when a download fails on a stale binary. |
-| `apiMusic.js` | On-device music generation (MusicGen / AudioLDM2 / ACE-Step): list engines (+ readiness), the stepped designer's AI describe/lyrics steps, and generate a track from a prompt/lyrics. |
+| `apiMusic.js` | On-device music generation (MusicGen / AudioLDM2 / ACE-Step): list engines (+ readiness), the stepped designer's AI describe/lyrics steps, the drawn-waveform and Strudel-code engines' LLM calls, and generate a track from a prompt/lyrics. |
| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). |
| `apiSharing.js` | Share buckets + federation sync. |
| `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). |
diff --git a/client/src/services/apiMusic.js b/client/src/services/apiMusic.js
index 3afd4129e0..bafc4871ec 100644
--- a/client/src/services/apiMusic.js
+++ b/client/src/services/apiMusic.js
@@ -57,6 +57,16 @@ export const drawWaveform = (body, requestOptions = {}) => request('/music/wavef
...requestOptions,
});
+// Have the LLM write the piece as Strudel code (the Music Designer's code
+// engine). Nothing runs server-side; the browser plays it in a sandboxed frame.
+// body: { description, lyrics?, guidance?, current? (code to revise),
+// language?, providerId?, model?, effort? } → { language, code, llm }
+export const writeMusicCode = (body, requestOptions = {}) => request('/music/code', {
+ method: 'POST',
+ body: JSON.stringify(body),
+ ...requestOptions,
+});
+
// De-register a user-installed model (id is the HF repo id) → { removed }.
export const removeAudioModel = (engine, id, requestOptions = {}) =>
request(`/music/models/${encodeURIComponent(engine)}/${id.split('/').map(encodeURIComponent).join('/')}`, {
diff --git a/client/src/services/apiTracks.js b/client/src/services/apiTracks.js
index 5b2c1de249..b32ae1e98e 100644
--- a/client/src/services/apiTracks.js
+++ b/client/src/services/apiTracks.js
@@ -113,6 +113,15 @@ export const renderTrackWaveform = (id, body, requestOptions = {}) => request(`/
...requestOptions,
});
+// Save a take recorded from the code engine's sandboxed player. `formData`
+// carries the WAV as a `track` file plus optional `prompt`/`title` fields.
+// → { track, filename, durationSec }.
+export const renderTrackCode = (id, formData, requestOptions = {}) => request(`/tracks/${encodeURIComponent(id)}/code/render`, {
+ method: 'POST',
+ body: formData,
+ ...requestOptions,
+});
+
// Mirror server caps in server/services/tracks/logic.js — bump both sides.
export const TRACK_TITLE_MAX = 200;
export const TRACK_LYRICS_MAX = 20000;
diff --git a/server/lib/README.md b/server/lib/README.md
index a39d92487d..e0d78aa8cf 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -513,7 +513,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `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. |
+| `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`. |
| `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. |
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 0716c0b134..3292fee284 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -83,7 +83,7 @@ const RAW_NAV_COMMANDS = [
{ id: 'nav.create.rounds', path: '/rounds', label: 'Rounds', section: 'Create', aliases: ['rounds', 'round', 'songs', 'song', 'a-cappella', 'acappella', 'sing'], keywords: ['round', 'song', 'lyrics', 'melody', 'harmony', 'dirge', 'ballad', 'a cappella', 'vocal', 'choir', 'singing', 'arrangement', 'quodlibet', '500 miles'] },
{ id: 'nav.create.rounds-guide', path: '/rounds/guide', label: 'Rounds Guide', section: 'Create', aliases: ['rounds-guide', 'round-guide', 'songs-guide', 'song-guide', 'singing-guide', 'round-learning'], keywords: ['rhythm shapes', 'dirge', 'voice layers', 'harmony', 'notation', 'lead sheet', 'solfege', 'learn round', 'learn song', 'a cappella', 'singing help'] },
{ id: 'nav.create.music', path: '/music', label: 'Music', section: 'Create', aliases: ['music', 'music-studio', 'generate-music'], keywords: ['music generation', 'ace-step', 'acestep', 'musicgen', 'audioldm', 'album', 'track', 'single', 'album art', 'artist', 'song generation', 'audio', 'beat', 'producer'] },
- { id: 'nav.create.music-generate', path: '/music/generate', label: 'Music Designer', section: 'Create', tabGroup: 'music', tabId: 'generate', tabLabel: 'Generate', aliases: ['music-generate', 'music-designer', 'design-music', 'write-a-song', 'make-music'], keywords: ['generate music', 'music designer', 'describe music', 'enrich prompt', 'write lyrics', 'lyrics', 'ace-step', 'reference track', 'vibe', 'step by step', 'wizard', 'draw waveform', 'drawn waveform', 'wavetable'] },
+ { id: 'nav.create.music-generate', path: '/music/generate', label: 'Music Designer', section: 'Create', tabGroup: 'music', tabId: 'generate', tabLabel: 'Generate', aliases: ['music-generate', 'music-designer', 'design-music', 'write-a-song', 'make-music'], keywords: ['generate music', 'music designer', 'describe music', 'enrich prompt', 'write lyrics', 'lyrics', 'ace-step', 'reference track', 'vibe', 'step by step', 'wizard', 'draw waveform', 'drawn waveform', 'wavetable', 'strudel', 'live code', 'music code'] },
{ id: 'nav.create.music-artists', path: '/music/artists', label: 'Music Artists', section: 'Create', tabGroup: 'music', tabId: 'artists', tabLabel: 'Artists', aliases: ['music-artists', 'artists', 'artist', 'artist-persona', 'musician', 'band'], keywords: ['artist persona', 'musician', 'band', 'byline', 'portrait', 'genre', 'musical style', 'stage name'] },
{ id: 'nav.create.music-albums', path: '/music/albums', label: 'Music Albums', section: 'Create', tabGroup: 'music', tabId: 'albums', tabLabel: 'Albums', aliases: ['albums', 'album', 'music-albums', 'discography', 'lp', 'ep'], keywords: ['album', 'cover art', 'tracklist', 'release', 'discography', 'record'] },
{ id: 'nav.create.music-tracks', path: '/music/tracks', label: 'Music Tracks', section: 'Create', tabGroup: 'music', tabId: 'tracks', tabLabel: 'Tracks', aliases: ['tracks', 'track', 'music-tracks', 'singles', 'songs-audio'], keywords: ['track', 'single', 'audio', 'recording', 'lyrics', 'mp3', 'wav', 'generate track'] },
diff --git a/server/lib/wavAudioFile.js b/server/lib/wavAudioFile.js
index 0a83b70185..ee56101830 100644
--- a/server/lib/wavAudioFile.js
+++ b/server/lib/wavAudioFile.js
@@ -2,7 +2,8 @@
* Land a synthesized 16-bit WAV on disk as game/library-ready audio:
* `<dir>/<basename>.ogg` (Vorbis via the system ffmpeg) or, when ffmpeg is
* missing or the encode fails, `<dir>/<basename>.wav`. Shared by the offline
- * renderers of LLM-authored music (chiptune scores, drawn wave sketches).
+ * renderers of LLM-authored music (chiptune scores, drawn wave sketches) and
+ * the Music Designer code engine's browser-recorded takes.
*/
import { join } from 'path';
@@ -31,3 +32,39 @@ export async function writeWavAudioFile(wav, dir, basename) {
await unlinkGuarded(wavPath).catch(() => {});
return `${basename}.ogg`;
}
+
+/**
+ * Compute the playback duration (ms) of a PCM WAV buffer by reading its
+ * canonical RIFF header — `data` chunk size ÷ `fmt ` byte rate. Used by the
+ * narration timeline (karaoke-style highlight sync) where the client needs a
+ * per-segment duration without decoding the audio itself, and to validate an
+ * uploaded code-engine take (a non-WAV body measures 0).
+ *
+ * Pure + defensive: scans the sub-chunk list (the `fmt ` and `data` chunks
+ * aren't guaranteed to be adjacent or first), and returns 0 for anything that
+ * isn't a parseable WAV so a malformed buffer degrades to "unknown length"
+ * instead of throwing into the synth path.
+ */
+export function wavDurationMs(buffer) {
+ if (!Buffer.isBuffer(buffer) || buffer.length < 12) return 0;
+ if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return 0;
+ let byteRate = 0;
+ let dataSize = 0;
+ let offset = 12;
+ while (offset + 8 <= buffer.length) {
+ const id = buffer.toString('ascii', offset, offset + 4);
+ const size = buffer.readUInt32LE(offset + 4);
+ const body = offset + 8;
+ if (id === 'fmt ' && body + 16 <= buffer.length) {
+ byteRate = buffer.readUInt32LE(body + 8);
+ } else if (id === 'data') {
+ // Clamp to the bytes actually present — a truncated stream can carry a
+ // larger declared size than the buffer holds.
+ dataSize = Math.min(size, buffer.length - body);
+ }
+ // Chunks are word-aligned: an odd size carries a trailing pad byte.
+ offset = body + size + (size % 2);
+ }
+ if (!byteRate || !dataSize) return 0;
+ return Math.round((dataSize / byteRate) * 1000);
+}
diff --git a/server/routes/music.js b/server/routes/music.js
index 3a9d73c370..f2780968af 100644
--- a/server/routes/music.js
+++ b/server/routes/music.js
@@ -5,6 +5,7 @@
* POST /api/music/describe → { description, llm }
* POST /api/music/lyrics → { lyrics, llm }
* POST /api/music/waveform → { sketch, llm }
+ * POST /api/music/code → { language, code, llm }
* POST /api/music/generate → { jobId, position, status }
*
* `describe`/`lyrics` are the Generate tab's stepped designer (#4305): an LLM
@@ -13,6 +14,8 @@
* 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.
+ * `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.
*
* Generation runs the engine-agnostic `generateMusic` (server/services/pipeline/
* musicGen.js) through the unified audio media-job lane. The completion hook
@@ -40,6 +43,7 @@ import { listEngineModels, addAudioModel, removeAudioModel, isValidRepoId } from
import { listMusicEngineCapabilities } from '../services/musicEngineCapabilities.js';
import { 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 { startHfDownloadStream } from '../services/hfDownloadStream.js';
import { onClientDisconnect, openSseStream } from '../lib/sseDownload.js';
@@ -372,6 +376,23 @@ router.post('/waveform', asyncHandler(async (req, res) => {
res.json(await drawWaveSketch(body));
}));
+const codeSchema = z.object({
+ description: z.string().trim().min(1, 'description is required').max(8000),
+ lyrics: z.string().trim().max(20000).optional(),
+ // The code in the editor, to revise. Only its size is checked: it is text
+ // for the prompt here and runs nowhere but the browser's sandboxed frame.
+ current: z.string().max(MUSIC_CODE_MAX).optional().transform(blankToUndefined),
+ language: z.enum(MUSIC_CODE_LANGUAGES).optional().default('strudel'),
+ ...designerPickerShape,
+}).omit({ template: true });
+
+// POST /api/music/code — have the LLM write the piece as Strudel code for the
+// browser to play. One explicit user action per call; nothing is executed here.
+router.post('/code', asyncHandler(async (req, res) => {
+ const body = validateRequest(codeSchema, req.body ?? {});
+ res.json(await writeMusicCode(body));
+}));
+
const generateSchema = z.object({
prompt: z.string().trim().min(1, 'prompt is required').max(8000),
// No default: distinguish ABSENT (don't touch the track's lyrics) from a
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index b82668c2d1..84f872003b 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -163,7 +163,17 @@ vi.mock('../services/musicDesigner.js', () => ({
writeLyrics: vi.fn(),
}));
+// The code engine (#8375) runs its one LLM call through the shared runner.
+// Stub the runner (not the service) so the route test covers the service's
+// prompt, fence stripping, and size check too.
+vi.mock('../services/promptRunner.js', async () => ({
+ ...(await vi.importActual('../services/promptRunner.js')),
+ resolveProviderAndModel: vi.fn(),
+ runPromptThroughProvider: vi.fn(),
+}));
+
import * as tracks from '../services/tracks/index.js';
+import * as promptRunner from '../services/promptRunner.js';
import * as albums from '../services/albums/index.js';
import * as designer from '../services/musicDesigner.js';
import { errorMiddleware } from '../lib/errorHandler.js';
@@ -308,6 +318,63 @@ describe('music routes', () => {
});
});
+ describe('POST /code', () => {
+ beforeEach(() => {
+ promptRunner.resolveProviderAndModel.mockReset().mockResolvedValue({ provider: { id: 'fake-provider', type: 'api' }, selectedModel: 'fake-model' });
+ promptRunner.runPromptThroughProvider.mockReset();
+ });
+
+ it('returns the fence-stripped Strudel code with attribution', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: 'Here is your track:\n\n```javascript\nsetcps(0.5)\nnote("c3 e3 g3").s("sawtooth")\n```\nEnjoy!',
+ model: 'fake-model',
+ });
+ const r = await request(app).post('/api/music/code').send({
+ description: 'neon synthwave drive', guidance: '124 BPM', providerId: 'fake-provider', effort: 'high',
+ });
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({
+ language: 'strudel',
+ code: 'setcps(0.5)\nnote("c3 e3 g3").s("sawtooth")',
+ llm: { provider: 'fake-provider', model: 'fake-model' },
+ });
+ const args = promptRunner.runPromptThroughProvider.mock.calls[0][0];
+ expect(args).toMatchObject({ source: 'music-code', model: 'fake-model', effort: 'high' });
+ expect(args.prompt).toContain('neon synthwave drive');
+ expect(args.prompt).toContain('124 BPM');
+ });
+
+ it('sends the editor code back as the revision target', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({ text: 'note("c3").s("sine")' });
+ const r = await request(app).post('/api/music/code').send({
+ description: 'ambient', current: 'note("a2 e3").s("triangle")',
+ });
+ expect(r.status).toBe(200);
+ expect(r.body.code).toBe('note("c3").s("sine")');
+ expect(promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt).toContain('note("a2 e3").s("triangle")');
+ });
+
+ it('rejects a missing description, oversize editor code, or an unknown language', async () => {
+ const missing = await request(app).post('/api/music/code').send({});
+ const oversize = await request(app).post('/api/music/code').send({ description: 'x', current: 'x'.repeat(20001) });
+ const language = await request(app).post('/api/music/code').send({ description: 'x', language: 'python' });
+ expect([missing.status, oversize.status, language.status]).toEqual([400, 400, 400]);
+ expect(promptRunner.runPromptThroughProvider).not.toHaveBeenCalled();
+ });
+
+ it('refuses an empty or oversize LLM reply with a 502', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValueOnce({ text: '```js\n\n```' });
+ const empty = await request(app).post('/api/music/code').send({ description: 'x' });
+ expect(empty.status).toBe(502);
+ expect(empty.body.code).toBe('MUSIC_CODE_EMPTY');
+
+ promptRunner.runPromptThroughProvider.mockResolvedValueOnce({ text: 'x'.repeat(20001) });
+ const long = await request(app).post('/api/music/code').send({ description: 'x' });
+ expect(long.status).toBe(502);
+ expect(long.body.code).toBe('MUSIC_CODE_TOO_LONG');
+ });
+ });
+
it('GET /engines lists engines with readiness + lyric capability + merged models', async () => {
const r = await request(app).get('/api/music/engines');
expect(r.status).toBe(200);
diff --git a/server/routes/tracks.js b/server/routes/tracks.js
index b1709ba17e..c74491d5cd 100644
--- a/server/routes/tracks.js
+++ b/server/routes/tracks.js
@@ -16,6 +16,7 @@
* POST /api/tracks/:id/audio/attach → Track (attach a library filename)
* DELETE /api/tracks/:id/audio → Track (clear the audio pointer)
* POST /api/tracks/:id/waveform/render → { track, filename, durationSec } (drawn-waveform take)
+ * POST /api/tracks/:id/code/render → { track, filename, durationSec } (multipart 'track' WAV recorded from code)
*
* Tracks store only a pointer (`audioFilename`) into the shared music library
* (services/pipeline/musicLibrary.js, `data/music/`); the bytes are uploaded /
@@ -29,6 +30,7 @@
*/
import { Router } from 'express';
+import { readFile, unlink } from 'fs/promises';
import { z } from 'zod';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { validateRequest, isPaginationRequested, paginateArray } from '../lib/validation.js';
@@ -45,6 +47,7 @@ import {
import { YOUTUBE_VIDEO_URL_RE, YOUTUBE_URL_INVALID_MESSAGE } from '../lib/youtubeUrl.js';
import { generateChiptuneScore, renderChiptuneTrack, publishChiptuneTrack } from '../services/chiptune.js';
import { renderWaveSketchToTrack } from '../services/musicWaveform.js';
+import { saveCodeTakeToTrack } from '../services/musicCode.js';
const router = Router();
@@ -302,6 +305,22 @@ router.post('/:id/waveform/render', asyncHandler(async (req, res) => {
res.json(await renderWaveSketchToTrack({ trackId: req.params.id, ...body }));
}));
+// --- Code takes: the Music Designer's code engine runs LLM-written Strudel in
+// a sandboxed browser frame and records it there. The server stores the
+// recorded WAV and never runs the code.
+const codeRenderSchema = z.object({
+ prompt: z.string().trim().max(tracks.PROMPT_MAX).optional(),
+ title: z.string().trim().max(200).optional(),
+});
+
+router.post('/:id/code/render', musicUpload, asyncHandler(async (req, res) => {
+ if (!req.file) throw new ServerError('No recorded take uploaded', { status: 400, code: 'TRACK_AUDIO_MISSING_FILE' });
+ // Read the temp upload before validating so a rejected body can't strand it.
+ const wav = await readFile(req.file.path).finally(() => unlink(req.file.path).catch(() => {}));
+ const body = validateRequest(codeRenderSchema, req.body ?? {});
+ res.json(await saveCodeTakeToTrack({ trackId: req.params.id, wav, ...body }));
+}));
+
// Make a past render the active one (re-point the player + gen-metadata badges
// at it). The user-authored prompt/lyrics are left untouched — they drive the
// NEXT generation, independent of which take is selected for playback.
diff --git a/server/routes/tracks.test.js b/server/routes/tracks.test.js
index 68eb5027d6..f413f1c2ce 100644
--- a/server/routes/tracks.test.js
+++ b/server/routes/tracks.test.js
@@ -1,7 +1,25 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';
import express from 'express';
+import { readdir, rm } from 'fs/promises';
import { request } from '../lib/testHelper.js';
+// Code-engine takes land in the shared music library; point it at a temp dir
+// and keep the WAV (no ffmpeg in tests).
+const { musicDir } = await vi.hoisted(async () => {
+ const { mkdtemp } = await import('fs/promises');
+ const { tmpdir } = await import('os');
+ const { join } = await import('path');
+ return { musicDir: await mkdtemp(join(tmpdir(), 'tracks-code-take-')) };
+});
+vi.mock('../lib/fileUtils.js', async (importOriginal) => {
+ const actual = await importOriginal();
+ return { ...actual, PATHS: { ...actual.PATHS, music: musicDir } };
+});
+vi.mock('../lib/ffmpeg.js', () => ({
+ findFfmpeg: vi.fn().mockResolvedValue(null),
+ runFfmpegProcess: vi.fn(),
+}));
+
vi.mock('../services/tracks/index.js', () => ({
TITLE_MAX: 200,
ALBUM_ID_MAX: 80,
@@ -29,6 +47,7 @@ vi.mock('../services/tracks/index.js', () => ({
const r = (track.renders || []).find((x) => x.id === renderId);
return r ? { audioFilename: r.audioFilename, engine: r.engine, modelId: r.modelId, durationSec: r.durationSec } : null;
}),
+ appendActiveTake: vi.fn(async (id, take, patch) => ({ id, ...take, ...patch })),
deleteRenderPatch: vi.fn((track, renderId) => {
const renders = track.renders || [];
if (!renders.some((x) => x.id === renderId)) return null;
@@ -343,4 +362,58 @@ describe('tracks routes', () => {
expect(r.status).toBe(404);
expect(r.body.code).toBe('TRACK_RENDER_NOT_FOUND');
});
+
+ describe('POST /:id/code/render (code-engine take, #8375)', () => {
+ afterAll(async () => { await rm(musicDir, { recursive: true, force: true }); });
+
+ // A 2-second 16-bit stereo 8 kHz PCM WAV.
+ const wav = (() => {
+ const dataBytes = 8000 * 4 * 2;
+ const buf = Buffer.alloc(44 + dataBytes);
+ buf.write('RIFF', 0); buf.writeUInt32LE(36 + dataBytes, 4); buf.write('WAVE', 8);
+ buf.write('fmt ', 12); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(2, 22);
+ buf.writeUInt32LE(8000, 24); buf.writeUInt32LE(8000 * 4, 28); buf.writeUInt16LE(4, 32); buf.writeUInt16LE(16, 34);
+ buf.write('data', 36); buf.writeUInt32LE(dataBytes, 40);
+ return buf;
+ })();
+ const boundary = '----portoscodetake';
+ const multipart = (fileBytes, fields = {}) => Buffer.concat([
+ ...Object.entries(fields).map(([k, v]) => Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`)),
+ Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="track"; filename="code-take.wav"\r\nContent-Type: audio/wav\r\n\r\n`),
+ fileBytes,
+ Buffer.from(`\r\n--${boundary}--\r\n`),
+ ]);
+ const post = (body) => request(app).post('/api/tracks/track-1/code/render')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`).send(body);
+
+ it('lands the recorded WAV in the library and appends it as the active code take', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', prompt: 'saved prompt', renders: [] });
+ const r = await post(multipart(wav, { prompt: 'neon synthwave', title: 'Night Drive' }));
+ expect(r.status).toBe(200);
+ expect(r.body.durationSec).toBe(2);
+ expect(r.body.filename).toMatch(/^music-.+\.wav$/);
+ expect(await readdir(musicDir)).toContain(r.body.filename);
+ expect(tracks.appendActiveTake).toHaveBeenCalledWith('track-1', {
+ audioFilename: r.body.filename, prompt: 'neon synthwave', engine: 'code', durationSec: 2,
+ }, { title: 'Night Drive' });
+ });
+
+ it('rejects an upload that is not a PCM WAV, or no upload at all', async () => {
+ tracks.getTrack.mockResolvedValue({ id: 'track-1', renders: [] });
+ const notWav = await post(multipart(Buffer.from('OggS not a wav at all')));
+ expect(notWav.status).toBe(400);
+ expect(notWav.body.code).toBe('MUSIC_CODE_TAKE_NOT_WAV');
+ const noFile = await request(app).post('/api/tracks/track-1/code/render')
+ .set('content-type', `multipart/form-data; boundary=${boundary}`)
+ .send(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="prompt"\r\n\r\nx\r\n--${boundary}--\r\n`));
+ expect(noFile.status).toBe(400);
+ expect(tracks.appendActiveTake).not.toHaveBeenCalled();
+ });
+
+ it('404s for an unknown track', async () => {
+ tracks.getTrack.mockResolvedValue(null);
+ const r = await post(multipart(wav));
+ expect(r.status).toBe(404);
+ });
+ });
});
diff --git a/server/services/musicCode.js b/server/services/musicCode.js
new file mode 100644
index 0000000000..c6a19b4077
--- /dev/null
+++ b/server/services/musicCode.js
@@ -0,0 +1,122 @@
+/**
+ * Code-rendered music: the Music Designer's "Code" engine.
+ *
+ * writeMusicCode() musical description → Strudel code the LLM wrote
+ * (fence-stripped and size-checked; nothing runs here).
+ * saveCodeTakeToTrack() a WAV the browser recorded from that code → the
+ * shared music library, appended to the track's render
+ * history as an `engine: 'code'` take.
+ *
+ * The code is arbitrary JavaScript, so the server never executes it. The
+ * browser runs it inside a sandboxed, network-blocked iframe
+ * (client/src/components/music/strudelFrame.js) and records the take there.
+ *
+ * Nothing here runs on its own: every call is driven by an explicit button
+ * press in the same request (AI Provider Usage Policy: no cold bootstrap).
+ */
+
+import { randomUUID } from 'crypto';
+import { ServerError } from '../lib/errorHandler.js';
+import { PATHS } from '../lib/fileUtils.js';
+import { trimTo } from '../lib/textUtils.js';
+import { wavDurationMs, writeWavAudioFile } from '../lib/wavAudioFile.js';
+import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } from './promptRunner.js';
+import * as tracks from './tracks/index.js';
+
+const CODE_ENGINE = 'code';
+// Strudel is the first language. Tone.js joins this list as a second choice.
+export const MUSIC_CODE_LANGUAGES = Object.freeze(['strudel']);
+// Longest code the designer accepts, from the LLM or back from the editor.
+export const MUSIC_CODE_MAX = 20000;
+
+const MAX_DESCRIPTION = 8000;
+const MAX_LYRICS = 20000;
+const MAX_GUIDANCE = 4000;
+
+const section = (label, body) => (body ? `\n\n${label}:\n${body}` : '');
+
+/** The Strudel writing contract sent to the LLM. */
+function buildStrudelPrompt({ description, lyrics, guidance, current }) {
+ return `You are a composer who writes music as Strudel code (the JavaScript port of TidalCycles, strudel.cc). The code runs in a browser with the @strudel/web bundle and is the whole piece: there is no audio model and no DAW.${
+ section('MUSIC TO WRITE', trimTo(description, MAX_DESCRIPTION) || '(none given)')
+ }${
+ section('LYRICS / THEME (mood only; nothing is sung, so instruments carry the melody)', trimTo(lyrics, MAX_LYRICS))
+ }${
+ section('ADDITIONAL GUIDANCE FROM THE USER', trimTo(guidance, MAX_GUIDANCE))
+ }${
+ current ? section('CURRENT CODE (revise it per the request above; keep what works, change what is asked)', current) : ''
+ }
+
+Return ONLY the Strudel code: no prose and no markdown fence. It is evaluated exactly like the strudel.cc REPL:
+- Set the tempo first with setcps(BPM / 60 / 4), e.g. setcps(0.5) for 120 BPM in 4/4.
+- End with ONE pattern expression, usually stack(...) with one layer per part (lead, bass, harmony, drums).
+- Double-quoted strings are mini-notation: "c3 e3 g3" steps, "~" rests, "[a b]" subdivides a step, "<a b c>" picks one per cycle, "a*4" repeats, "a!2" duplicates, "a@3" lengthens.
+- Pitch: note("c3 eb3 g3") or n("0 2 4 <5 7>").scale("C4:minor"). Chords: note("<[c3,eb3,g3] [ab2,c3,eb3]>").
+- Sounds: ONLY these built-in synths exist: "sine", "triangle", "square", "sawtooth", "supersaw", "pulse", the noises "white", "pink", "brown", "crackle", and the synth kick "sbd". Pick one with .s("sawtooth"). NO samples are loaded, so s("bd"), s("hh"), s("piano"), and samples(...) fail. Never load or fetch anything.
+- Drums from synths: kick s("sbd*4"); snare s("~ pink ~ pink").decay(.12).sustain(0); hats s("white*8").decay(.04).sustain(0).gain(.35).
+- Shape sounds with .lpf(), .hpf(), .attack(), .decay(), .sustain(), .release(), .gain(), .pan(), .room(), .delay(), .vowel(); slow or vary with .slow(), .fast(), .every(4, x => x.rev()), .sometimes(...).
+- Keep master levels sensible (layer gains around 0.3-0.8).
+
+Compose real music: a memorable melody, a bassline that moves, harmony, and percussion that grooves unless the description asks otherwise. Stay in key, and use "<...>" alternation over several cycles so the piece develops instead of looping one bar.`;
+}
+
+// A reply usually arrives bare, but a fenced block (with or without prose
+// around it) is common. Take the first fence's body when there is one.
+const FENCE_RE = /```[^\n`]*\n([\s\S]*?)\n?```/;
+function extractCode(text) {
+ const raw = typeof text === 'string' ? text : '';
+ const fenced = raw.match(FENCE_RE);
+ return (fenced ? fenced[1] : raw).trim();
+}
+
+/**
+ * Ask the chosen provider to write the piece as code. `current` (the code in
+ * the editor) turns the call into a revision of it.
+ */
+export async function writeMusicCode({ description, lyrics, guidance, current, language = 'strudel', providerId, model, effort } = {}) {
+ const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
+ assertProvider(provider, { message: 'No AI provider available to write the music code', code: 'NO_PROVIDER' });
+
+ const run = await runPromptThroughProvider({
+ provider,
+ model: selectedModel ?? undefined,
+ effort,
+ prompt: buildStrudelPrompt({ description, lyrics, guidance, current: trimTo(current, MUSIC_CODE_MAX) }),
+ source: 'music-code',
+ });
+
+ const code = extractCode(run.text);
+ if (!code) {
+ throw new ServerError('The AI returned no code. Try rerunning or picking a stronger model.', { status: 502, code: 'MUSIC_CODE_EMPTY' });
+ }
+ if (code.length > MUSIC_CODE_MAX) {
+ throw new ServerError(`The AI returned more than ${MUSIC_CODE_MAX} characters of code. Try rerunning or asking for a shorter piece.`, {
+ status: 502, code: 'MUSIC_CODE_TOO_LONG',
+ });
+ }
+ const ranModel = run.model ?? selectedModel ?? null;
+ console.log(`🎹 Wrote ${language} music code via ${provider.id}/${ranModel || 'default'} (${code.length} chars)`);
+ return { language, code, llm: { provider: run.provider?.id || provider.id, model: ranModel } };
+}
+
+/**
+ * Land a browser-recorded WAV (a Buffer) in the shared music library and make
+ * it the track's active take.
+ */
+export async function saveCodeTakeToTrack({ trackId, wav, prompt, title }) {
+ const durationMs = wavDurationMs(wav);
+ if (!durationMs) {
+ throw new ServerError('The take must be a PCM WAV file', { status: 400, code: 'MUSIC_CODE_TAKE_NOT_WAV' });
+ }
+ const track = await tracks.getTrack(trackId);
+ if (!track) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+
+ const filename = await writeWavAudioFile(wav, PATHS.music, `music-${randomUUID()}`);
+ const durationSec = Math.max(1, Math.round(durationMs / 1000));
+ const updated = await tracks.appendActiveTake(trackId, {
+ audioFilename: filename, prompt: prompt || track.prompt, engine: CODE_ENGINE, durationSec,
+ }, title ? { title } : {});
+ if (!updated) throw new ServerError('Track not found', { status: 404, code: 'NOT_FOUND' });
+ console.log(`🎹 Saved code-rendered take (${durationSec}s)`);
+ return { track: updated, filename, durationSec };
+}
diff --git a/server/services/pipeline/audio.js b/server/services/pipeline/audio.js
index 25dc544078..5be7b9a670 100644
--- a/server/services/pipeline/audio.js
+++ b/server/services/pipeline/audio.js
@@ -25,6 +25,7 @@ import {
VALID_ENGINES,
} from '../voice/tts.js';
import { ServerError } from '../../lib/errorHandler.js';
+import { wavDurationMs } from '../../lib/wavAudioFile.js';
const VOICE_ID_RE = /^([a-z][a-z0-9-]*):(.+)$/i;
@@ -202,40 +203,8 @@ export function extractDialogueLines(issue, canon, { preserveFrom = [] } = {}) {
return { lines, preservedCount };
}
-/**
- * Compute the playback duration (ms) of a PCM WAV buffer by reading its
- * canonical RIFF header — `data` chunk size ÷ `fmt ` byte rate. Used by the
- * narration timeline (karaoke-style highlight sync) where the client needs a
- * per-segment duration without decoding the audio itself.
- *
- * Pure + defensive: scans the sub-chunk list (the `fmt ` and `data` chunks
- * aren't guaranteed to be adjacent or first), and returns 0 for anything that
- * isn't a parseable WAV so a malformed buffer degrades to "unknown length"
- * instead of throwing into the synth path.
- */
-export function wavDurationMs(buffer) {
- if (!Buffer.isBuffer(buffer) || buffer.length < 12) return 0;
- if (buffer.toString('ascii', 0, 4) !== 'RIFF' || buffer.toString('ascii', 8, 12) !== 'WAVE') return 0;
- let byteRate = 0;
- let dataSize = 0;
- let offset = 12;
- while (offset + 8 <= buffer.length) {
- const id = buffer.toString('ascii', offset, offset + 4);
- const size = buffer.readUInt32LE(offset + 4);
- const body = offset + 8;
- if (id === 'fmt ' && body + 16 <= buffer.length) {
- byteRate = buffer.readUInt32LE(body + 8);
- } else if (id === 'data') {
- // Clamp to the bytes actually present — a truncated stream can carry a
- // larger declared size than the buffer holds.
- dataSize = Math.min(size, buffer.length - body);
- }
- // Chunks are word-aligned: an odd size carries a trailing pad byte.
- offset = body + size + (size % 2);
- }
- if (!byteRate || !dataSize) return 0;
- return Math.round((dataSize / byteRate) * 1000);
-}
+// wavDurationMs moved to lib/wavAudioFile.js (shared with the Music Designer code engine).
+export { wavDurationMs };
export async function synthesizeToFile({ text, voiceId, profileId, route = 'studio', signal } = {}) {
const trimmed = (text || '').trim();