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 Tone.js as a second Music Designer code language (#8390)

[._.]/ Adam Eivyb11cd0b2329f
diff --git a/client/src/components/music/CodePanel.jsx b/client/src/components/music/CodePanel.jsx
index c933380695..ccb83b23e5 100644
--- a/client/src/components/music/CodePanel.jsx
+++ b/client/src/components/music/CodePanel.jsx
@@ -1,22 +1,22 @@
/**
* 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.
+ * The chosen AI provider writes the track as code in the picked language
+ * (Strudel or Tone.js). 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.
+ * calls). The latest code is remembered per viewer in localStorage, tagged
+ * with the language it was written in, so a reload doesn't lose it.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useMemo, useRef, useState } from 'react';
import { Code2, Loader2, Play, Save, Square, Wand2 } from 'lucide-react';
import toast from '../ui/Toast';
import useMounted from '../../hooks/useMounted';
@@ -24,7 +24,9 @@ import { safeReadJsonStorage, safeWriteJsonStorage } from '../../lib/safeStorage
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';
+import {
+ CODE_FRAME_SOURCE, STRUDEL_VERSION, TONE_VERSION, buildStrudelFrameDoc, buildToneFrameDoc,
+} from './strudelFrame';
const CODE_KEY = 'portos.musicDesigner.strudelCode';
// Mirrors MUSIC_CODE_MAX in server/services/musicCode.js.
@@ -32,12 +34,35 @@ 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).
+// Both languages' frame documents are static per version, so build each once.
+const LANGUAGES = {
+ strudel: {
+ label: 'Strudel',
+ docsUrl: 'https://strudel.cc',
+ version: STRUDEL_VERSION,
+ frameDoc: buildStrudelFrameDoc(),
+ placeholder: 'setcps(0.5)\nstack(\n note("<c3 ab2 f2 g2>").s("sawtooth").lpf(600),\n s("sbd*4"),\n)',
+ },
+ tonejs: {
+ label: 'Tone.js',
+ docsUrl: 'https://tonejs.github.io/',
+ version: TONE_VERSION,
+ frameDoc: buildToneFrameDoc(),
+ placeholder: 'const synth = new Tone.PolySynth(Tone.Synth).toDestination();\nconst pattern = new Tone.Pattern((time, note) => {\n synth.triggerAttackRelease(note, "8n", time);\n}, ["C3", "Eb3", "G3", "Bb3"]);\npattern.start(0);\nTone.getTransport().bpm.value = 120;\nTone.getTransport().start();',
+ },
+};
+const DEFAULT_LANGUAGE = 'strudel';
+
+// Only the most recent code (and the language it was written in) 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 : '';
+ if (!trackId || stored?.trackId !== trackId) return { code: '', language: DEFAULT_LANGUAGE };
+ return {
+ code: typeof stored.code === 'string' ? stored.code : '',
+ language: LANGUAGES[stored.language] ? stored.language : DEFAULT_LANGUAGE,
+ };
};
export default function CodePanel({
@@ -46,7 +71,9 @@ export default function CodePanel({
}) {
const mountedRef = useMounted();
const frameRef = useRef(null);
- const [code, setCode] = useState(() => readStoredCode(trackId));
+ const initialStored = useMemo(() => readStoredCode(trackId), [trackId]);
+ const [code, setCode] = useState(initialStored.code);
+ const [language, setLanguage] = useState(initialStored.language);
const [guidance, setGuidance] = useState('');
// Raw field text, clamped only when used (same as the waveform panel).
const [lengthInput, setLengthInput] = useState(String(TAKE_SEC.DEFAULT));
@@ -60,6 +87,7 @@ export default function CodePanel({
const [takeSec, setTakeSec] = useState(TAKE_SEC.DEFAULT);
const saveContextRef = useRef({});
saveContextRef.current = { trackId, description, title, onRendered };
+ const busy = !!writing || !!savePhase;
const post = (msg) => frameRef.current?.contentWindow?.postMessage(msg, '*');
@@ -101,7 +129,19 @@ export default function CodePanel({
// Subscribed once; uploadTake reads the latest props through saveContextRef.
}, []);
- const rememberCode = (next) => safeWriteJsonStorage(CODE_KEY, { trackId, code: next });
+ const rememberCode = (next, lang = language) => safeWriteJsonStorage(CODE_KEY, { trackId, code: next, language: lang });
+
+ // Switching languages invalidates the code in the box (it's the wrong
+ // dialect for the new frame), so clear it and remount the player fresh.
+ const switchLanguage = (next) => {
+ if (next === language || busy) return;
+ setLanguage(next);
+ setCode('');
+ setFrameError('');
+ setFrameReady(false);
+ setFrameState('stopped');
+ rememberCode('', next);
+ };
const write = async (mode) => {
if (!description.trim()) { toast.error('Write the musical description first'); return; }
@@ -111,7 +151,7 @@ export default function CodePanel({
lyrics: lyrics.trim() || undefined,
guidance: guidance.trim() || undefined,
...(mode === 'revise' && code.trim() ? { current: code } : {}),
- language: 'strudel',
+ language,
providerId: providerId || undefined,
model: model || undefined,
effort: effort || undefined,
@@ -144,16 +184,31 @@ export default function CodePanel({
post({ type: 'record', code, seconds });
};
- const busy = !!writing || !!savePhase;
const hasCode = !!code.trim();
const playing = frameState === 'playing';
+ const lang = LANGUAGES[language];
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.
+ No audio model: the AI writes the piece as <a href={lang.docsUrl} target="_blank" rel="noreferrer" className="text-port-accent hover:underline">{lang.label}</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 role="group" aria-label="Code language" className="flex gap-2">
+ {Object.entries(LANGUAGES).map(([id, { label }]) => (
+ <button
+ key={id}
+ type="button"
+ aria-pressed={language === id}
+ onClick={() => switchLanguage(id)}
+ disabled={disabled || busy}
+ className={language === id ? PRIMARY_BTN : GHOST_BTN}
+ >
+ <span>{label}</span>
+ </button>
+ ))}
+ </div>
+
<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>
@@ -201,7 +256,7 @@ export default function CodePanel({
</div>
<label htmlFor="music-code-editor" className="block">
- <span className={LABEL_CLASS}>Strudel code</span>
+ <span className={LABEL_CLASS}>{lang.label} code</span>
<textarea
id="music-code-editor"
value={code}
@@ -211,7 +266,7 @@ export default function CodePanel({
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)'}
+ placeholder={lang.placeholder}
className={`${FIELD_CLASS} font-mono text-xs leading-relaxed`}
/>
</label>
@@ -224,13 +279,14 @@ export default function CodePanel({
<div className="space-y-2">
<iframe
+ key={language}
ref={frameRef}
- title={`Strudel ${STRUDEL_VERSION} player`}
+ title={`${lang.label} ${lang.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}
+ srcDoc={lang.frameDoc}
className="h-10 w-full rounded border border-port-border bg-port-bg"
/>
<div className="flex flex-wrap items-center gap-2">
diff --git a/client/src/components/music/CodePanel.test.jsx b/client/src/components/music/CodePanel.test.jsx
index 2516b31b92..7c35afb045 100644
--- a/client/src/components/music/CodePanel.test.jsx
+++ b/client/src/components/music/CodePanel.test.jsx
@@ -8,12 +8,14 @@ vi.mock('../../services/api', () => ({
renderTrackCode: vi.fn(),
}));
-// The real frame document loads Strudel from a CDN; the tests stub the frame
-// and speak its postMessage protocol directly.
+// The real frame documents load Strudel/Tone.js from a CDN; the tests stub
+// both frames and speak their shared postMessage protocol directly.
vi.mock('./strudelFrame', () => ({
CODE_FRAME_SOURCE: 'portos-code-frame',
STRUDEL_VERSION: '0.0.0-test',
- buildStrudelFrameDoc: () => '<!doctype html><title>stub</title>',
+ TONE_VERSION: '0.0.0-test',
+ buildStrudelFrameDoc: () => '<!doctype html><title>stub-strudel</title>',
+ buildToneFrameDoc: () => '<!doctype html><title>stub-tonejs</title>',
}));
const CODE = 'setcps(0.5)\nnote("c3 e3 g3").s("sawtooth")';
@@ -72,6 +74,26 @@ describe('<CodePanel>', () => {
expect(bundle.getAttribute('integrity')).toMatch(/^sha384-/);
});
+ it('switches the code language, clearing the code and remounting the matching frame', async () => {
+ window.localStorage.setItem('portos.musicDesigner.strudelCode', JSON.stringify({ trackId: 'track-1', code: CODE, language: 'strudel' }));
+ await mountReady();
+ expect(screen.getByLabelText('Strudel code')).toHaveValue(CODE);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Tone.js' }));
+ expect(screen.getByRole('button', { name: 'Tone.js' })).toHaveAttribute('aria-pressed', 'true');
+ expect(screen.getByRole('button', { name: 'Strudel' })).toHaveAttribute('aria-pressed', 'false');
+ // The old language's code is invalid in the new frame, so it's cleared.
+ expect(screen.getByLabelText('Tone.js code')).toHaveValue('');
+ expect(screen.getByTitle(/Tone\.js .* player/)).toBeInTheDocument();
+
+ api.writeMusicCode.mockResolvedValueOnce({ language: 'tonejs', code: 'Tone.getTransport().start();', llm: {} });
+ fireEvent.click(screen.getByRole('button', { name: /Write the code/ }));
+ await waitFor(() => expect(api.writeMusicCode).toHaveBeenCalledWith(
+ expect.objectContaining({ language: 'tonejs' }),
+ { silent: true },
+ ));
+ });
+
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' } });
diff --git a/client/src/components/music/strudelFrame.js b/client/src/components/music/strudelFrame.js
index 356f2ca495..944875c8f9 100644
--- a/client/src/components/music/strudelFrame.js
+++ b/client/src/components/music/strudelFrame.js
@@ -1,18 +1,20 @@
/**
- * The sandboxed player behind the Music Designer's "Code" engine (CodePanel).
+ * The sandboxed players 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
+ * The LLM writes the track as Strudel or Tone.js code, and that code is
+ * arbitrary JavaScript. It never runs in the PortOS origin. The panel mounts
+ * `buildStrudelFrameDoc()` or `buildToneFrameDoc()` 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.
+ * an opaque origin: no PortOS cookies, storage, or DOM. Both documents' 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 either may load is its own pinned
+ * 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; Tone.js
+ * is MIT but is fetched the same way for one consistent, auditable path.
*
- * Protocol (postMessage; every message carries `source: CODE_FRAME_SOURCE`):
+ * Protocol (postMessage; every message carries `source: CODE_FRAME_SOURCE`,
+ * shared by both frame documents):
* panel → frame { type: 'play', code } · { type: 'stop' }
* { type: 'record', code, seconds }
* frame → panel { type: 'ready' }
@@ -21,32 +23,42 @@
* { 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
+ * Recording taps the frame's audio graph. Before either 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.
+ * The tap works for any Web Audio library, which is what lets the same
+ * bootstrap serve both Strudel and Tone.js without change.
*/
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 TONE_VERSION = '15.5.42';
+export const TONE_BUNDLE_URL = `https://cdn.jsdelivr.net/npm/tone@${TONE_VERSION}/build/Tone.js`;
+// sha384 of TONE_BUNDLE_URL. Bump it together with TONE_VERSION.
+export const TONE_BUNDLE_INTEGRITY = 'sha384-rpNzF3PRX6H+JanjHDJjUnsohhGj57xP3C6y5EZqp7BC7RBHSzYPW7NHGl0hPrul';
+
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 = [
+// Both frame documents share this policy shape. Scripts may run (and `eval`,
+// which Strudel's transpiler needs and Tone.js code is run through; `data:`
+// covers Strudel's bundled AudioWorklet modules), but nothing may reach the
+// network except the one pinned bundle for that language.
+const buildFrameCsp = (bundleUrl) => [
"default-src 'none'",
- `script-src 'unsafe-inline' 'unsafe-eval' data: ${STRUDEL_BUNDLE_URL}`,
+ `script-src 'unsafe-inline' 'unsafe-eval' data: ${bundleUrl}`,
"style-src 'unsafe-inline'",
"connect-src 'none'",
"form-action 'none'",
"base-uri 'none'",
].join('; ');
+const FRAME_CSP = buildFrameCsp(STRUDEL_BUNDLE_URL);
+const TONE_FRAME_CSP = buildFrameCsp(TONE_BUNDLE_URL);
+
// 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 = `
@@ -287,3 +299,225 @@ export function buildStrudelFrameDoc() {
<script>${FRAME_CONTROLLER}</script>
</body></html>`;
}
+
+// Runs after the Tone.js bundle: boots the LLM's code and answers the panel's
+// messages the same way FRAME_CONTROLLER does for Strudel. Tone has no
+// built-in "reset everything" call, so each run re-evaluates against a fresh
+// `Tone.Transport` state and disposes every node the PREVIOUS run created —
+// tracked by wrapping constructor access on `Tone` in a Proxy, never by
+// recreating the AudioContext (that would orphan the one `Tone.Transport`
+// singleton the LLM's code is told to use).
+const TONE_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);
+ const fail = (err) => {
+ 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));
+
+ const Tone = window.Tone;
+ if (!Tone || typeof Tone.getTransport !== 'function') {
+ fail('Could not load the Tone.js engine from cdn.jsdelivr.net. Check the network connection and reload.');
+ return;
+ }
+
+ // Every instance the sandboxed code constructs through this proxy is
+ // tracked so the NEXT run can dispose it; property access that is not a
+ // "new"-able class (functions, Transport, getContext, ...) passes through.
+ const created = new Set();
+ const ctorProxies = new WeakMap();
+ const trackedTone = new Proxy(Tone, {
+ get(target, prop) {
+ const value = target[prop];
+ if (typeof value !== 'function' || typeof value.prototype?.dispose !== 'function') return value;
+ let proxy = ctorProxies.get(value);
+ if (!proxy) {
+ proxy = new Proxy(value, {
+ construct(ctor, args, newTarget) {
+ const instance = Reflect.construct(ctor, args, newTarget);
+ created.add(instance);
+ return instance;
+ },
+ });
+ ctorProxies.set(value, proxy);
+ }
+ return proxy;
+ },
+ });
+
+ const disposePrevious = () => {
+ for (const instance of created) { try { instance.dispose(); } catch (err) { /* already disposed */ } }
+ created.clear();
+ };
+
+ const resetTransport = () => {
+ const transport = Tone.getTransport();
+ transport.stop(0);
+ transport.cancel(0);
+ transport.position = 0;
+ };
+
+ // 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 = Tone.getContext().rawContext;
+ if (ctx.state !== 'running') {
+ await Promise.race([Tone.start().catch(() => {}), new Promise((resolve) => setTimeout(resolve, 800))]);
+ }
+ return Tone.getContext().rawContext.state === 'running';
+ };
+ const whenAudible = async (action) => {
+ if (await audioRunning()) return action();
+ pending = action;
+ unlockEl.hidden = false;
+ show('Click here to allow audio');
+ setState('blocked');
+ return undefined;
+ };
+ unlockEl.addEventListener('click', () => {
+ Tone.start().then(() => {
+ unlockEl.hidden = true;
+ const action = pending;
+ pending = null;
+ if (action) action();
+ }, fail);
+ });
+
+ let recording = null;
+ const stopRecording = () => {
+ if (!recording) return;
+ clearInterval(recording.timer);
+ recording = null;
+ cancel();
+ };
+
+ const evaluate = (code) => {
+ disposePrevious();
+ resetTransport();
+ try {
+ // eslint-disable-next-line no-new-func -- runs the LLM's code against the Tone global only.
+ new Function('Tone', code)(trackedTone);
+ return true;
+ } catch (err) {
+ fail(err);
+ return false;
+ }
+ };
+
+ const play = (code) => whenAudible(async () => {
+ stopRecording();
+ show('Playing');
+ if (!evaluate(code)) { resetTransport(); setState('stopped'); return; }
+ setState('playing');
+ });
+
+ const stop = () => {
+ pending = null;
+ unlockEl.hidden = true;
+ stopRecording();
+ resetTransport();
+ 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();
+ resetTransport();
+ const ctx = Tone.getContext().rawContext;
+ const take = start(ctx, seconds);
+ const startedAt = Date.now();
+ recording = { timer: 0 };
+ setState('recording');
+ show('Recording');
+ if (!evaluate(code)) { stopRecording(); resetTransport(); 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;
+ resetTransport();
+ 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);
+ });
+
+ show('Ready');
+ post({ type: 'ready' });
+})();
+`;
+
+/** The complete `srcdoc` for the sandboxed Tone.js player frame. */
+export function buildToneFrameDoc() {
+ return `<!doctype html>
+<html><head><meta charset="utf-8">
+<meta http-equiv="Content-Security-Policy" content="${TONE_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 Tone.js ${TONE_VERSION}…</span>
+<script>${FRAME_BOOTSTRAP}</script>
+<script src="${TONE_BUNDLE_URL}" integrity="${TONE_BUNDLE_INTEGRITY}" crossorigin="anonymous"></script>
+<script>${TONE_FRAME_CONTROLLER}</script>
+</body></html>`;
+}
diff --git a/server/routes/music.test.js b/server/routes/music.test.js
index 84f872003b..a2b87469c8 100644
--- a/server/routes/music.test.js
+++ b/server/routes/music.test.js
@@ -344,6 +344,27 @@ describe('music routes', () => {
expect(args.prompt).toContain('124 BPM');
});
+ it('writes Tone.js code with its own prompt contract when language is tonejs', async () => {
+ promptRunner.runPromptThroughProvider.mockResolvedValue({
+ text: 'const synth = new Tone.Synth().toDestination();\nTone.getTransport().start();',
+ model: 'fake-model',
+ });
+ const r = await request(app).post('/api/music/code').send({
+ description: 'ambient pad drone', language: 'tonejs', providerId: 'fake-provider',
+ });
+ expect(r.status).toBe(200);
+ expect(r.body).toEqual({
+ language: 'tonejs',
+ code: 'const synth = new Tone.Synth().toDestination();\nTone.getTransport().start();',
+ llm: { provider: 'fake-provider', model: 'fake-model' },
+ });
+ const prompt = promptRunner.runPromptThroughProvider.mock.calls[0][0].prompt;
+ expect(prompt).toContain('Tone.js');
+ expect(prompt).toContain('ambient pad drone');
+ expect(prompt).toContain('Tone.Transport.start()');
+ expect(prompt).not.toContain('Strudel');
+ });
+
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({
diff --git a/server/services/musicCode.js b/server/services/musicCode.js
index c6a19b4077..bee124b0ec 100644
--- a/server/services/musicCode.js
+++ b/server/services/musicCode.js
@@ -1,8 +1,8 @@
/**
* 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).
+ * writeMusicCode() musical description → Strudel or Tone.js 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.
@@ -24,8 +24,9 @@ import { assertProvider, resolveProviderAndModel, runPromptThroughProvider } fro
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']);
+// Strudel was the first language; Tone.js is the second (client/src/components/music/strudelFrame.js
+// mounts a frame document per language, same postMessage protocol for both).
+export const MUSIC_CODE_LANGUAGES = Object.freeze(['strudel', 'tonejs']);
// Longest code the designer accepts, from the LLM or back from the editor.
export const MUSIC_CODE_MAX = 20000;
@@ -60,6 +61,33 @@ Return ONLY the Strudel code: no prose and no markdown fence. It is evaluated ex
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.`;
}
+/** The Tone.js writing contract sent to the LLM. */
+function buildTonejsPrompt({ description, lyrics, guidance, current }) {
+ return `You are a composer who writes music as plain JavaScript against the Tone.js library (tonejs.github.io/), running against the global \`Tone\`. The code IS the whole piece: there is no audio model and no DAW, and it runs once per play.${
+ 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 JavaScript: no prose and no markdown fence. Rules for the code:
+- The host has already unlocked audio and reset the transport before your code runs; do not call Tone.start().
+- Build the graph, schedule the music (Tone.Transport.schedule, Tone.Transport.scheduleRepeat, or a Tone.Part/Tone.Sequence), then call Tone.Transport.start() as the LAST statement so playback actually begins.
+- Only these built-in instruments exist, all playable with no external files: Tone.Synth, Tone.AMSynth, Tone.FMSynth, Tone.MonoSynth, Tone.DuoSynth, Tone.PluckSynth, Tone.MembraneSynth (kick/toms), Tone.MetalSynth (hats/cymbals), Tone.NoiseSynth (noise/snare), and Tone.PolySynth(Tone.Synth) (or another synth) for chords. NEVER use Tone.Player, Tone.GrainPlayer, Tone.Sampler, Tone.UserMedia, or any URL/buffer/sample loading — there is no network access and no sample files, so they always fail.
+- Shape and route sound with the built-in effects: Tone.Filter, Tone.EQ3, Tone.Distortion, Tone.Chorus, Tone.FeedbackDelay, Tone.Reverb, Tone.Compressor, Tone.Gain, Tone.Panner. Chain with .connect() or .chain(), and end every audible chain with .toDestination().
+- Note names are strings like "C3", "Eb4", "G#2"; durations are Tone.js notation like "8n", "4n.", "16t". Use Tone.Time/Tone.Frequency helpers as needed.
+- Set the tempo with Tone.Transport.bpm.value = BPM before scheduling.
+- Keep levels sensible: set instrument/gain .volume around -12 to -6 dB per layer so a full mix doesn't clip.
+- Wrap the whole body in a try/catch only if you need to recover from an error yourself; otherwise let errors propagate so they can be reported.
+
+Compose real music: a memorable melody, a bassline that moves, harmony, and percussion that grooves unless the description asks otherwise. Stay in key, and vary the pattern over multiple bars (with scheduleRepeat callbacks or a Part with several events) so the piece develops instead of looping one bar forever.`;
+}
+
+const PROMPT_BUILDERS = { strudel: buildStrudelPrompt, tonejs: buildTonejsPrompt };
+
// 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?```/;
@@ -77,11 +105,12 @@ export async function writeMusicCode({ description, lyrics, guidance, current, l
const { provider, selectedModel } = await resolveProviderAndModel({ providerId, model });
assertProvider(provider, { message: 'No AI provider available to write the music code', code: 'NO_PROVIDER' });
+ const buildPrompt = PROMPT_BUILDERS[language] || buildStrudelPrompt;
const run = await runPromptThroughProvider({
provider,
model: selectedModel ?? undefined,
effort,
- prompt: buildStrudelPrompt({ description, lyrics, guidance, current: trimTo(current, MUSIC_CODE_MAX) }),
+ prompt: buildPrompt({ description, lyrics, guidance, current: trimTo(current, MUSIC_CODE_MAX) }),
source: 'music-code',
});