Strudel — live-coding music from text patterns
prompts/pkg/llms/strudel.md on every deploy, so it
can't drift from what the platform actually does. Read it from your terminal any
time with npx vibes-diy skills.
When someone asks for live coding, Strudel or Tidal, mini-notation, an
algorave page, "type a beat and hear it", a pattern jam, generative or
algorithmic music built from little text patterns, a groovebox whose buttons
write a pattern, or a page where a model rewrites the music on request, this
is the recipe. Strudel is a music engine that plays patterns written as
text: s("bd*4, ~ cp ~ cp, hh*8") is a whole groove, and a pattern can be
typed by a person, written by an interface, saved as a document, remixed, or
produced by callAI from a sentence. The engine arrives from the CDN the
first time someone presses play, so the app ships only its own code.
Strudel builds on the Web Audio doc above: the engine arrives by its
runtime-import rule, and the app's own interface sounds (a click on a pad)
still go through its unlockAudio(). The pattern's sound plays inside a
sandboxed frame, so the press that starts it is play itself. A synth
built from oscillators, a drum machine with its own clock, mic monitoring or a
metronome is the web-music skill. Strudel is the right call when the music is
a pattern expressed as text (or compiled into text from a grid, sliders or a
prompt).
The worked examples are jchris/strudel (an editor, saved patterns and a
prompt box that rewrites the groove), jchris/strudel-groovebook (a step
grid whose toggles write mini-notation, with a shared public gallery), and
the four tutorial vibes jchris/strudel-hello-beat, strudel-notation,
strudel-layers and strudel-effects behind the "You can just make music"
posts on good.vibes.diy.
The engine arrives at play time
Import the engine with its full pinned esm.sh URL inside a memoized
player made by the first play press:
await import("https://esm.sh/@strudel/[email protected]") is the first line of the
player's frame program, and the module makes that one player the first time
play is pressed, so first paint owes nothing to a 165 KB engine plus a drum
kit. The program makes its own AudioContext and hands it to the engine with
setAudioContext ahead of initStrudel.
The press in the app starts the sound in the frame. The player frame
carries allow="autoplay", so the app's press reaches the frame's
AudioContext (measured 2026-11-27 in Chromium with the autoplay policy that
wants a user activation: one press on the app's Play button, the frame's
context running and the pattern's events arriving; with no press at all,
the context stays asleep). A browser that wants a tap inside the frame itself
gets one: the player shows its own "Tap to start the sound" button over the
page, and play() waits for that tap, then plays the pattern and resolves
true, so the app's Play button turns to Stop at the moment the sound starts.
A stop() or a newer play() while it waits wins.
Strudel is AGPL-3.0 licensed; load it from its own CDN address as shown and credit Strudel visibly (a footer line with a link to strudel.cc is the house shape), and keep its code at its URL rather than copied into the app.
The drum kit is the Dirt-Samples bank, loaded in prebake from the jsDelivr
mirror (https://cdn.jsdelivr.net/gh/tidalcycles/Dirt-Samples@master/strudel.json);
jsDelivr serves it with CORS and without rate limits. The first play fetches
the engine and the kit together (measured 2026-10-07: about two seconds in
Chromium), so the play button shows a short "fetching the drum kit" state on
that first press and plays at once ever after.
evaluate() reports a pattern that did not compile through onEvalError
rather than by throwing (measured: a syntax error logs to the console, the
call resolves with nothing, and the previous pattern keeps playing). Pass
onEvalError to initStrudel and show its message in the app's own words,
beside the editor, while the last good pattern plays on.
Patterns play in a sandboxed frame
A pattern is JavaScript, so the engine and every pattern run inside a
<iframe sandbox="allow-scripts"> with no same-origin access. A pattern
from the shared gallery, from another visitor or from callAI can then play
without reaching the app's Fireproof data, its storage or its page: the frame
has an opaque origin, and a policy inside it lets it fetch only the CDNs that
serve the engine and the drum kits. The app and the frame talk through
postMessage and nothing else: play this pattern, hush; back come "ok", the
error message, or the events as they sound. lib/sandbox.js is that frame,
shared word for word with the hydra skill, and lib/strudel.js below runs
the engine inside it.
- The frame program is a real function sent as text.
openSandbox(el, { program })turnsprograminto source withtoString(), so the program names nothing from its own file: it imports the engine inside itself, and it reaches the app only through thehostit is handed. - The pattern text only ever travels as a message, never into
srcdocor the program's source. - What the frame posts back is data, never instructions. The app reads only the message types it expects and clamps every number before it drives a timer.
- The frame runs only its own two scripts, each named by its hash, which
start the program;
'strict-dynamic'lets the program import the engine and what the engine imports. A frame a pattern nests runs no script at all, and a second policy keeps the CDN list for any script a pattern adds itself. - The frame sits in a holder that loads no page (
frame-src 'none'), so the browser refuses every navigation the frame starts before a request leaves, even while a pattern holds the thread. The frame also tells the app as it begins to leave, and the app closes it. - The frame has no
RTCPeerConnection, so a pattern cannot open a peer connection to a host it names.
Measured 2026-11-27 in headless Chromium with this file and lib/strudel.js:
the frame's origin reads null; parent.document, localStorage,
document.cookie and indexedDB each throw SecurityError; a fetch to a
host outside the list is refused by the policy; and the drum kit plays,
because the Dirt-Samples map's own sound files live on
raw.githubusercontent.com, which the list carries. Measured again for
#11246 and #11293: a pattern finds no RTCPeerConnection; a nested frame's
inline script, on… handlers and a script by URL from a listed CDN never run;
navigations, even from a loop that never yields, send no request; and one
press in the app still starts the sound. lib/sandbox.js is the first file
of the starter below.
Add a CDN to CDNS when the program needs one (a sample map on another
host, say), and nothing else: the list is what a pattern can reach.
Project shape
App.jsx the interface: editor or grid, play and stop, saved patterns, the credit line
lib/sandbox.js the sandboxed frame the engine and every pattern run in
lib/strudel.js the frame program, play(), stop(), the error hook, helpers that write mini-notation, EXAMPLES
access.js who may publish a pattern to the shared gallery
seed.json three or four finished patterns so the first visit has something to press
Relative imports include the extension (./lib/strudel.js). Everything that
touches the engine lives in the module, so App.jsx reads as an interface.
Complete starter — a pattern pad
The engine module. strudelFrame is the program the player's frame runs;
play(code, onEvent) compiles a pattern there and starts it; the optional
onEvent callback receives every sounding event so the interface can light
up with the music; stop() hushes; onPatternError delivers the message a
bad pattern produces. The frame itself is lib/sandbox.js, which comes
first.
lib/sandbox.js
js// lib/sandbox.js — run code someone else wrote in a frame that cannot reach this app.
// sandbox="allow-scripts" and never allow-same-origin: the frame gets an opaque origin, so it has no
// Fireproof, no storage or cookies and no reach into this page. Its own policy lets it fetch only
// the CDNs named here. It hears from the app, and answers it, through postMessage alone.
const CDNS = "https://esm.sh https://cdn.jsdelivr.net https://raw.githubusercontent.com";
// The frame runs its own two scripts, each named by its hash, and no other: 'strict-dynamic' lets
// them import the engine and everything the engine imports, so a frame the code nests (an iframe
// with a srcdoc of its own) runs no script and no on… handler, and gets no fresh realm to work from.
const policy = (startHash, bootHash) =>
[
"default-src 'none'",
`script-src '${startHash}' '${bootHash}' 'strict-dynamic' 'unsafe-eval' blob: ${CDNS}`,
`connect-src blob: data: ${CDNS}`,
`img-src blob: data: ${CDNS}`,
`media-src blob: data: ${CDNS}`,
"worker-src blob:",
"style-src 'unsafe-inline'",
].join("; ");
// 'strict-dynamic' sets aside the host list, so a second policy keeps it: a script the code adds,
// or an import() it makes, still loads only from the CDNs. The browser enforces both policies.
const scriptHosts = (startHash, bootHash) => `script-src '${startHash}' '${bootHash}' 'unsafe-eval' blob: ${CDNS}`;
// The holder is a plain frame of this app's own around the sandboxed one, and its policy says no
// page may load inside it, so the browser refuses every navigation the sandboxed frame starts
// before a request leaves, even while the code holds the thread.
const HOLDER =
`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="frame-src 'none'">` +
`<style>html,body{margin:0;height:100%;overflow:hidden}</style></head><body></body></html>`;
// The frame's half of the wire. It also takes away the peer connection, the one way out the policy
// does not govern in Chromium (ICE reaches any STUN host the code names), and it tells the app the
// moment the frame starts to leave, so the app takes the frame away.
// `host.on(type, fn)` answers a request with what fn returns;
// `host.post(type, data)` tells the app something. The app's build turns `?.` and `??` into calls
// to helpers kept at the top of the app's module, and the program travels as text without them,
// so the frame defines the same helpers itself.
const WIRE = `
function _nullishCoalesce(v, f) { return v != null ? v : f(); }
async function _asyncNullishCoalesce(v, f) { return v != null ? v : await f(); }
function _optionalChain(ops) {
let v = ops[0], self;
for (let i = 1; i < ops.length; i += 2) {
const op = ops[i], fn = ops[i + 1];
if ((op === "optionalAccess" || op === "optionalCall") && v == null) return undefined;
if (op === "access" || op === "optionalAccess") { self = v; v = fn(v); }
else { const f = v, t = self; v = fn((...a) => f.call(t, ...a)); self = undefined; }
}
return v;
}
async function _asyncOptionalChain(ops) {
let v = ops[0], self;
for (let i = 1; i < ops.length; i += 2) {
const op = ops[i], fn = ops[i + 1];
if ((op === "optionalAccess" || op === "optionalCall") && v == null) return undefined;
if (op === "access" || op === "optionalAccess") { self = v; v = await fn(v); }
else { const f = v, t = self; v = await fn((...a) => f.call(t, ...a)); self = undefined; }
}
return v;
}
function _optionalChainDelete(ops) { const r = _optionalChain(ops); return r == null ? true : r; }
async function _asyncOptionalChainDelete(ops) { const r = await _asyncOptionalChain(ops); return r == null ? true : r; }
const handlers = {};
delete self.RTCPeerConnection;
delete self.webkitRTCPeerConnection;
const holder = parent; // the app's holder frame: the app hears this frame there
const app = parent.parent; // the app itself, the one window this frame takes requests from
addEventListener("beforeunload", () => holder.postMessage({ sandbox: true, type: "leaving" }, "*"));
const host = {
on(type, fn) { handlers[type] = fn; },
post(type, data) { holder.postMessage({ sandbox: true, type, data }, "*"); },
};
addEventListener("message", async (e) => {
if (e.source !== app || typeof e.data?.type !== "string") return;
const { id, type, data } = e.data;
try {
const value = await handlers[type]?.(data);
if (id) holder.postMessage({ sandbox: true, id, ok: true, value }, "*");
} catch (error) {
if (id) holder.postMessage({ sandbox: true, id, ok: false, message: String(error?.message || error) }, "*");
}
});
`;
/** The policy's name for a script: its SHA-256 in base64, over the script's text. */
async function scriptHash(text) {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
return `sha256-${btoa(String.fromCharCode(...digest))}`;
}
/**
* Mount a sandboxed frame in `el` that runs `program(host)`. `program` is a function in this app's
* source that names nothing outside itself (it is sent as text), so it imports its engine inside.
* `onEvent(type, data)` hears what the frame posts: untrusted data, never instructions.
* `ready` resolves true once the program has finished starting, false when it failed.
*/
export function openSandbox(el, { program, onEvent = () => {}, allow = "autoplay", title = "player" }) {
const holder = document.createElement("iframe");
holder.setAttribute("allow", allow); // what the sandboxed frame may use passes through the holder too
holder.title = title;
holder.style.cssText = "display:block;width:100%;height:100%;border:0";
holder.srcdoc = HOLDER;
let frame = null;
let holderWindow = null;
const boot = `${WIRE}\n(${program.toString()})(host).then(() => host.post("ready"), (e) => host.post("failed", String(e?.message || e)));`;
// The page's parser writes only `start`, which adds the boot as a module script of its own: in
// Chromium a module the parser wrote cannot import the engine under 'strict-dynamic', and one a
// script added can. The boot travels as a JSON string with every < escaped, so it cannot end the
// script early, and the policy names both texts by hash.
const start =`{const s=document.createElement("script");s.type="module";s.textContent=${JSON.stringify(boot).replace(/</g, "\\u003c")};document.body.appendChild(s);}`;
let seq = 0;
let loads = 0;
let closed = false;
const pending = new Map();
let settle;
const ready = new Promise((resolve) => (settle = resolve));
function onMessage(e) {
if (!frame || e.source !== frame.contentWindow || e.data?.sandbox !== true) return; // this frame's wire only
const { id, type, data } = e.data;
if (id && pending.has(id)) {
pending.get(id)(e.data.ok ? { ok: true, value: e.data.value } : { ok: false, message: String(e.data.message) });
pending.delete(id);
} else if (type === "leaving") close(); // the frame started to navigate away
else if (type === "ready") settle(true);
else if (type === "failed") settle(false);
else if (typeof type === "string") onEvent(type, data);
}
function close() {
closed = true;
holderWindow?.removeEventListener("message", onMessage);
for (const resolve of pending.values()) resolve({ ok: false, message: "the player closed" });
pending.clear();
settle(false);
holder.remove();
}
async function mount() {
const held = new Promise((resolve) => holder.addEventListener("load", resolve, { once: true }));
el.appendChild(holder);
const [startHash, bootHash] = await Promise.all([scriptHash(start), scriptHash(boot), held]);
if (closed) return;
holderWindow = holder.contentWindow;
const doc = holder.contentDocument;
frame = doc.createElement("iframe");
frame.setAttribute("sandbox", "allow-scripts");
frame.setAttribute("allow", allow);
frame.title = title;
frame.style.cssText = "display:block;width:100%;height:100%;border:0";
frame.srcdoc =
`<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${policy(startHash, bootHash)}">` +
`<meta http-equiv="Content-Security-Policy" content="${scriptHosts(startHash, bootHash)}">` +
`<style>html,body{margin:0;height:100%;overflow:hidden}</style></head><body>` +
`<script>${start}</script></body></html>`;
// The frame posts to its parent, the holder, so the app listens there.
holderWindow.addEventListener("message", onMessage);
// The frame loads once. A second load means code inside it navigated away, so the frame goes.
frame.addEventListener("load", () => ++loads > 1 && close());
doc.body.appendChild(frame);
}
mount().catch(() => close());
return {
ready,
/** Ask the frame to do something: resolves { ok: true, value } or { ok: false, message }, never throws. */
async request(type, data) {
if (!(await ready)) return { ok: false, message: "the player did not start" };
if (closed || !frame?.isConnected) return { ok: false, message: "the player closed" };
const id = ++seq;
return new Promise((resolve) => {
pending.set(id, resolve);
frame.contentWindow.postMessage({ id, type, data }, "*");
});
},
/** Tell the frame something with no answer (levels, beats, camera frames). */
send(type, data, transfer = []) {
if (!closed && frame?.isConnected) frame.contentWindow?.postMessage({ type, data }, "*", transfer);
},
close,
};
}
lib/strudel.js
js// lib/strudel.js — the music engine. It runs in a sandboxed frame (lib/sandbox.js), so a pattern
// from the gallery, another visitor or callAI plays without reaching this app's data.
import { openSandbox } from "./sandbox.js";
/**
* The player's own program. It runs inside the frame, sent there as text, so it names nothing from
* this module: only `host` and the browser. Patterns arrive as messages; events go back out.
*/
async function strudelFrame(host) {
const web = await import("https://esm.sh/@strudel/[email protected]");
const context = new AudioContext();
web.setAudioContext(context);
const repl = await web.initStrudel({
prebake: () =>
Promise.all([
web.samples("https://cdn.jsdelivr.net/gh/tidalcycles/Dirt-Samples@master/strudel.json"),
web.samples("https://cdn.jsdelivr.net/gh/felixroos/dough-samples@main/tidal-drum-machines.json"),
]),
onEvalError: (error) => host.post("pattern-error", String(error?.message || error)),
});
// A browser that wants a tap inside the frame itself gets one: the app shows this button.
const wake = document.createElement("button");
wake.textContent = "Tap to start the sound";
wake.style.cssText = "width:100%;height:100%;border:0;font:600 16px system-ui;cursor:pointer";
wake.hidden = true;
const waiting = []; // plays waiting for that tap
let asked = 0; // counts every play and hush, so a play that waited knows whether it is still wanted
const release = () => {
wake.hidden = true;
for (const go of waiting.splice(0)) go();
};
wake.onclick = async () => {
await context.resume();
host.post("sound-on");
release();
};
document.body.appendChild(wake);
const awake = () =>
Promise.race([context.resume(), new Promise((r) => setTimeout(r, 300))]).then(() => context.state === "running");
host.on("play", async (ask) => {
const mine = ++asked;
// The press in the app reaches this frame's sound through allow="autoplay".
if (!(await awake())) {
wake.hidden = false;
host.post("needs-tap");
await new Promise((go) => waiting.push(go)); // the tap, or a hush
if (mine !== asked || context.state !== "running") return false; // stopped or replaced meanwhile
}
const pattern = await web.evaluate(String(ask?.code), false);
if (!pattern) return false; // the reason arrived through pattern-error
const sounding = ask?.events
? pattern.onTrigger((hap, time, cps, target) => {
const v = hap.value || {};
host.post("event", { s: String(v.s ?? ""), note: v.note ?? v.n ?? null, gain: v.gain ?? 1, begin: hap.whole?.begin?.valueOf() ?? 0, delay: (target - time) * 1000 });
}, false)
: pattern;
await repl.setPattern(sounding, true);
return true;
});
host.on("hush", () => {
asked++;
release();
web.hush();
});
}
let player; // the one sandboxed player, made on the first press
let box; // where it lives: out of sight, unless the browser asks for a tap inside it
let eventListener = null;
const listeners = new Set();
function report(message) {
for (const fn of listeners) fn(new Error(message));
}
function showBox(shown) {
Object.assign(box.style, shown ? { width: "240px", height: "56px", opacity: "1", pointerEvents: "auto" } : { width: "1px", height: "1px", opacity: "0", pointerEvents: "none" });
}
/** One player, made the first time play is pressed, so first paint owes nothing to the engine. */
function getPlayer() {
if (player) return player;
box = document.createElement("div");
box.style.cssText = "position:fixed;left:50%;bottom:96px;transform:translateX(-50%);z-index:50;border-radius:12px;overflow:hidden";
showBox(false);
document.body.appendChild(box);
player = openSandbox(box, {
program: strudelFrame,
title: "Strudel player",
onEvent(type, data) {
if (type === "pattern-error") report(String(data));
if (type === "needs-tap") showBox(true);
if (type === "sound-on") showBox(false); // the play that waited for the tap resolves now
if (type === "event" && eventListener) {
// What the frame sends is untrusted: short strings and finite, clamped numbers only.
const note = data?.note;
eventListener({
s: String(data?.s ?? "").slice(0, 32),
note: typeof note === "string" ? note.slice(0, 8) : Number.isFinite(note) ? note : null,
gain: Math.max(0, Math.min(2, Number(data?.gain) || 0)),
begin: Number.isFinite(data?.begin) ? data.begin : 0,
delay: Math.max(0, Math.min(4000, Number(data?.delay) || 0)),
});
}
},
});
return player;
}
/** Hear about a pattern that did not compile; the engine reports it here instead of throwing. */
export function onPatternError(fn) {
listeners.add(fn);
return () => listeners.delete(fn);
}
/**
* Compile and start a pattern in the player. `onEvent` (optional) hears every sounding event as
* { s, note, gain, begin, delay }: `begin` is its position in cycles, `delay` the milliseconds
* until it sounds. Resolves true when it plays and false when it did not (the reason arrives
* through onPatternError). When the browser wants a tap inside the player, it resolves once that
* tap has started the sound, or false when stop() or a newer play() came first.
*/
export async function play(code, onEvent) {
eventListener = onEvent || null;
const reply = await getPlayer().request("play", { code: String(code), events: Boolean(onEvent) });
if (!reply.ok) report(reply.message);
return reply.ok && reply.value === true;
}
/** Silence everything the player holds. Safe to call before it was ever made. */
export async function stop() {
if (box) showBox(false);
await player?.request("hush");
}
/** Tempo in beats per minute for a 4/4 feel: cpm counts cycles (whole bars), so bpm/4. */
export function cpm(bpm, beatsPerCycle = 4) {
return `.cpm(${bpm}/${beatsPerCycle})`;
}
/**
* Mini-notation from a step grid: a lit step is its sound, an unlit one is `~`. The grid is read
* as ONE cycle of `beatsPerCycle` beats however many steps it has (8 steps are eighth notes, 16 are
* sixteenths of one 4/4 bar), so the tempo stays the bpm the person set.
*/
export function gridToCode(grid, rows, bpm = 110, beatsPerCycle = 4) {
const lines = rows.map((sound) => ` s("${grid[sound].map((on) => (on ? sound : "~")).join(" ")}")`);
return `stack(\n${lines.join(",\n")}\n)${cpm(bpm, beatsPerCycle)}`;
}
export const EXAMPLES = [
{ name: "four on the floor", code: `s("bd*4, ~ cp ~ cp, hh*8").cpm(120/4)` },
{ name: "dusty boom bap", code: `stack(\n s("bd ~ [~ bd] ~, ~ sd ~ sd, hh*8"),\n note("<c2 c2 eb2 g1>").s("sawtooth").lpf(600).gain(0.6)\n).cpm(90/4)` },
{ name: "acid line", code: `note("c2 [eb2 c2] g1 [c2 bb1]").s("sawtooth")\n .lpf(sine.range(200, 2000).slow(4))\n .resonance(10).gain(0.7).cpm(130/4)` },
{ name: "polyrhythm", code: `stack(\n s("bd(3,8)"),\n s("hh(7,16)").gain(0.5),\n note("c3 eb3 g3 bb3").s("triangle").slow(2).room(0.5)\n).cpm(100/4)` },
];
The prompt the rewrite box sends. It is the verbatim system prompt for
turning a sentence into a pattern (its own section below); the module
exports it so any app can hand it to callAI.
lib/pattern-prompt.js
js// lib/pattern-prompt.js — the system prompt for turning a sentence into a Strudel pattern.
// Hand it to callAI with the person's request and the current pattern; read back { name, code }.
export const PATTERN_PROMPT = `You write Strudel patterns. Strudel is a live-coding music language. A pattern is ONE JavaScript expression that loops forever over a cycle.
MINI-NOTATION (the text inside quotes). Events are separated by spaces and share the cycle equally.
"~" is a rest. "a*2" plays a twice in its slot. "a/2" plays a once every two cycles. "[a b]" fits two events into one slot. "<a b>" alternates: a this cycle, b the next. "a(3,8)" spreads 3 hits over 8 steps. "a, b" plays both lines at once. "a!3" repeats a across three slots. "a?" plays a about half the time.
DRUMS. s("…") names drum samples. Always available: bd (kick), sd (snare), hh (closed hat), cp (clap), cr (crash), lt mt ht (toms), perc. With .bank("RolandTR808") or .bank("RolandTR909") on the pattern, also oh (open hat) and rim, in that machine's voice.
NOTES. note("c3 e3 g3 b3").s("sawtooth") plays a synth; voices are sine, triangle, square, sawtooth. A note is a letter, an optional # or b, and an octave from 1 to 6. n("0 2 4").scale("C4:minor") picks scale degrees instead.
EFFECTS chain on the end: .gain(0 to 1) volume, .pan(0 to 1), .lpf(hz) low-pass from 100 to 8000, .hpf(hz), .resonance(0 to 30), .room(0 to 1) reverb, .delay(0 to 1), .speed(n) sample pitch, .slow(n) stretches a pattern over n cycles, .fast(n) fits n repeats into one, .rev() reverses, .jux(rev) plays a reversed copy in the other ear, .every(n, f) applies f every nth cycle, .sometimes(f) applies f at random. A number can be a slow sweep: sine.range(200, 2000).slow(4).
COMBINING. stack(a, b, c) plays patterns together. cat(a, b) plays them one cycle after another.
TEMPO. Put .cpm(cycles per minute) on the outermost pattern. One cycle is one pass through the string, so count the beats the string holds: a four-beat bar at 120 bpm is .cpm(120/4); an eight-beat phrase at 120 bpm is .cpm(120/8). Leaving .cpm off means 120 bpm in 4/4.
OUTPUT. Exactly one expression. No imports, no variables, no comments, no prose. Double quotes inside s(), note() and n(). Only the sound names listed above.
EXAMPLES
Request: a slow dusty hip hop beat
Pattern: stack(s("bd ~ [~ bd] ~, ~ sd ~ sd, hh*8").bank("RolandTR808"), note("<c2 c2 eb2 g1>").s("sawtooth").lpf(600).gain(0.6)).cpm(88/4)
Request: fast techno, open hat on the offbeat
Pattern: stack(s("bd*4"), s("~ oh ~ oh").gain(0.6), s("hh*16").gain(0.3)).bank("RolandTR909").cpm(138/4)
Request: a gentle arpeggio in a minor key
Pattern: n("0 2 4 7 4 2").scale("C4:minor").s("triangle").room(0.6).slow(2).cpm(100/4)
Request: a two-bar phrase where the snare moves on the second bar
Pattern: stack(s("bd*4 bd*4"), s("~ sd ~ sd ~ sd sd ~"), s("hh*16")).cpm(120/8)`;
/** The full prompt for one request: the spec, the ask, and the pattern that is playing now. */
export function rewritePrompt(request, currentCode) {
return `${PATTERN_PROMPT}\n\nRequest: ${request}\nCurrent pattern (change it, or replace it when the request asks for something new):\n${currentCode}\n\nReturn JSON with "name" (two or three words) and "code" (the pattern).`;
}
The interface: an editor, example chips, play and stop, a prompt box that
asks callAI to rewrite the pattern, and the saved patterns from Fireproof
with every write gated on can.
App.jsx
jsximport React, { useEffect, useMemo, useState } from "react";
import { useFireproof } from "use-fireproof";
import { callAI, useVibe, useViewer } from "use-vibes";
import { Badge, Button, Card, Field, Heading, Input, Row, Skeleton, Spacer, Stack, Text } from "@vibes.diy/ui";
import { EXAMPLES, onPatternError, play, stop } from "./lib/strudel.js";
import { rewritePrompt } from "./lib/pattern-prompt.js";
const FIRST = `// ${EXAMPLES[0].name}\n${EXAMPLES[0].code}`;
export default function App() {
const { database, useLiveQuery } = useFireproof("patternPad");
const { me, can, ready } = useVibe("patternPad");
const { requestLogin, ViewerTag } = useViewer();
const { docs } = useLiveQuery("type", { key: "pattern" });
const saved = useMemo(() => [...docs].sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0)), [docs]);
const [code, setCode] = useState(FIRST);
const [state, setState] = useState("idle"); // idle | loading | playing
const [problem, setProblem] = useState(null);
const [ask, setAsk] = useState("");
const [asking, setAsking] = useState(false);
const [name, setName] = useState("");
useEffect(() => onPatternError((error) => setProblem(String(error.message || error))), []);
useEffect(() => () => void stop(), []);
async function handlePlay(source = code) {
setProblem(null);
const wasPlaying = state === "playing"; // read once: `state` is this render's value
if (!wasPlaying) setState("loading");
const pattern = await play(source);
if (pattern) setState("playing");
else if (!wasPlaying) setState("idle");
}
async function handleStop() {
await stop();
setState("idle");
}
function pick(example) {
const next = `// ${example.name}\n${example.code}`;
setCode(next);
if (state === "playing") handlePlay(next);
}
async function rewrite() {
if (!ask.trim() || asking) return;
setAsking(true);
const reply = await callAI(rewritePrompt(ask, code), {
schema: { properties: { name: { type: "string" }, code: { type: "string" } } },
});
const next = JSON.parse(reply);
const source = `// ${next.name}\n${next.code}`;
setCode(source);
setAsk("");
setAsking(false);
if (state === "playing") handlePlay(source);
}
const draft = { type: "pattern", name: name || "untitled", code, authorHandle: me?.userHandle };
const verdict = can.create(draft);
async function keep() {
setName(""); // ready for the next name at once
const { ok } = await database.put({ ...draft, createdAt: Date.now() });
if (!ok) setName((now) => now || name);
}
return (
<main className="min-h-screen bg-background text-foreground p-4 md:p-8">
<Stack gap={4}>
<Row gap={2} align="center" wrap>
<Heading level={1}>Pattern Pad</Heading>
<Spacer />
<Badge tone={state === "playing" ? "up" : "idle"}>{state === "playing" ? "Playing" : state === "loading" ? "Fetching the drum kit…" : "Ready"}</Badge>
</Row>
<textarea
value={code}
onChange={(e) => setCode(e.target.value)}
onKeyDown={(e) => { if ((e.ctrlKey || e.metaKey) && e.key === "Enter") { e.preventDefault(); handlePlay(); } }}
spellCheck={false}
rows={8}
className="w-full rounded-md border border-border bg-card p-3 font-mono text-sm text-foreground outline-none"
/>
{problem && <Text size="sm" tone="down">That pattern needs a tweak: {problem}. The last good one keeps playing.</Text>}
<Row gap={2} align="center" wrap>
<Button onClick={() => handlePlay()}>{state === "playing" ? "Replay" : "Play"}</Button>
<Button variant="quiet" onClick={handleStop}>Stop</Button>
<Text size="sm" muted>Ctrl+Enter plays the editor</Text>
</Row>
<Row gap={2} wrap>
{EXAMPLES.map((ex) => (
<Button key={ex.name} size="sm" variant="quiet" onClick={() => pick(ex)}>{ex.name}</Button>
))}
</Row>
<Card variant="tight">
<Row gap={2} align="top" wrap>
<Field label="Ask for a change">{(id, d) => <Input id={id} describedBy={d} value={ask} onChange={setAsk} placeholder="make it darker and slower" />}</Field>
<Button size="sm" onClick={rewrite} disabled={asking}>{asking ? "Rewriting…" : "Rewrite"}</Button>
</Row>
</Card>
<Card variant="tight">
<Stack gap={3}>
<Heading level={2}>Keep this pattern</Heading>
{!ready && <div aria-busy="true"><Skeleton variant="row" /></div>}
{ready && !me && <Row gap={2} align="center" wrap><Text muted>Sign in and your patterns stay with you.</Text><Button size="sm" variant="quiet" onClick={requestLogin}>Sign in to keep patterns</Button></Row>}
{ready && me && verdict.ok && (
<Row gap={2} align="top" wrap>
<Field label="Name">{(id, d) => <Input id={id} describedBy={d} value={name} onChange={setName} placeholder="late night groove" />}</Field>
<Button size="sm" onClick={keep}>Keep</Button>
</Row>
)}
{ready && me && !verdict.ok && !verdict.pending && <Text muted>Patterns here are kept by the pad's owner; remix the pad to keep your own.</Text>}
{saved.map((p) => (
<Row key={p._id} gap={2} align="center" wrap>
<Button size="sm" variant="quiet" onClick={() => { setCode(p.code); if (state === "playing") handlePlay(p.code); }}>{p.name}</Button>
{p.authorHandle && <ViewerTag userHandle={p.authorHandle} />}
<Spacer />
{can.delete(p).ok && <Button size="sm" variant="quiet" tone="down" onClick={() => database.del(p._id)}>Remove</Button>}
</Row>
))}
</Stack>
</Card>
<Text size="sm" muted>
Sound by <a className="underline" href="https://strudel.cc" target="_blank" rel="noreferrer">Strudel</a> (AGPL), fetched from its own address when you press play.
</Text>
</Stack>
</main>
);
}
access.js
js// pattern: a saved groove. Anyone signed in keeps their own; everyone can read the gallery.
export function patternPad(doc, oldDoc, user, ctx) {
if (!user) throw { forbidden: "sign in to keep patterns" };
if (doc.type === "pattern" || (doc._deleted && oldDoc && oldDoc.type === "pattern")) {
const author = oldDoc ? oldDoc.authorHandle : doc.authorHandle;
if (author !== user.userHandle) throw { forbidden: "sign your pattern with your own handle" };
return { channels: ["patterns"], grant: { public: ["patterns"] } };
}
throw { forbidden: "unknown document type" };
}
Mini-notation — the whole language in a dozen symbols
A pattern string loops over one cycle; spaces divide the cycle into
equal slots. Words are sounds (s("bd sd hh cp")) or notes
(note("c3 e3 g3")).
| write | meaning |
|---|---|
bd sd |
kick, then snare |
~ |
silence for that slot |
bd*2 |
twice in the slot |
bd/2 |
once every two cycles |
[sd sd] |
two squeezed into one slot |
<sd cp> |
snare this cycle, clap the next |
bd(3,8) |
three hits spread over eight steps (Euclidean) |
bd sd, hh*8 |
both lines at once |
bd!3 sd |
the same sound three slots running |
hh? hh? |
each hit plays about half the time |
Builders: stack(a, b) plays patterns together; cat(a, b) plays them one
cycle after another; note("c3 e3").s("sawtooth") chooses a synth voice
(sine, square, triangle, sawtooth); s("bd oh rim").bank("RolandTR808")
plays those drums in that machine's voice. Effects chain on the end: .gain(0.6),
.pan(0.3), .lpf(800), .hpf(200), .resonance(10), .room(0.4),
.delay(0.25), .slow(2), .fast(2), .rev(), .jux(rev),
.every(4, x => x.fast(2)), .sometimes(x => x.speed(2)). A signal such as
sine.range(200, 2000).slow(4) turns any number into a slow sweep.
Tempo, cycles and loop length — worked examples
Tempo is in cycles: .cpm(bpm/4) for a 4/4 feel. Strudel has no bpm
setting. cpm is cycles per minute, and a cycle is one pass through the
pattern string, so the tempo a listener hears depends on how many beats the
string holds. The engine's default is 0.5 cycles per second (.cpm(30)),
which reads as 120 bpm when the string is one bar of four beats. Measured
2026-10-07 with onTrigger on the real engine: s("bd*4").cpm(120/4) hits
every 0.500 s, which is 120 bpm.
The arithmetic, once: cpm = bpm ÷ beats per cycle. Decide how many beats the string spans, then divide.
| the string | beats it holds | at 120 bpm | why |
|---|---|---|---|
s("bd*4") or s("bd sd hh cp") |
4 | .cpm(120/4) |
one bar, four quarter notes |
s("bd*4 bd*4") or an 8-step grid of quarters |
8 | .cpm(120/8) |
two bars; each hit still lands every 0.5 s (measured) |
| an 8-step grid read as eighth notes | 4 | .cpm(120/4) |
one bar, twice as dense |
| a 16-step grid of sixteenths | 4 | .cpm(120/4) |
one bar; 16 slots in 2 s |
cat(a, b) where each is one bar |
4 per cycle | .cpm(120/4) |
two cycles, one bar each |
note("<c2 eb2>") under a one-bar beat |
4 | .cpm(120/4) |
<> alternates across cycles; it adds no beats |
Two rules fall out of the table:
- The same grid can be two tempos. Eight steps are one bar of eighths or
two bars of quarters; the app decides, names it in the UI ("8 steps = one
bar"), and divides by that number.
gridToCodereads any grid as one bar of four beats, so 8 steps are eighths and 16 are sixteenths; a grid meant as two bars passesbeatsPerCycle = 8. .slow(n)and.fast(n)change a line's length and leave the tempo alone.note("c3 eb3 g3 bb3").slow(2)unders("bd*4")spreads four notes over two bars while the drums keep their bar;.fast(2)fits the phrase into half a bar. Change.cpmonly when the whole piece should speed up.
A tempo slider sets .cpm(${bpm}/4) on the outer pattern and re-evaluates,
or calls repl.setCps(bpm / 60 / 4) to change the tempo of everything
playing without a re-evaluate (cps is cycles per second, so bpm ÷ 60 ÷
beats per cycle). A bpm pasted straight into .cpm(120) plays four times
too fast; the lane reports that shape without failing on it, since a bare
literal is right when the string holds one or two beats (s("bd sd").cpm(60)
is 120 bpm).
The interface writes the pattern
The pad above shows the editor shape. The other shape is the one most people
want: buttons, grids and sliders that compile to a pattern string and
re-evaluate it while it plays. A step grid is one function (gridToCode
above); sliders are numbers dropped into the same string (toCode({ tempo, filter, space }) returning `stack(…).lpf(${filter}).room(${space}).cpm(${tempo}/8)`);
a prompt box hands rewritePrompt(request, code) to callAI with a
{ name, code } schema and plays what comes back. Every
change calls play(next) when the engine is playing, and the engine swaps
patterns in time without a stop.
A groovebox whose lights follow the music, built on the same module:
App.jsx
jsximport React, { useEffect, useRef, useState } from "react";
import { useFireproof } from "use-fireproof";
import { useVibe, useViewer } from "use-vibes";
import { Badge, Button, Card, Field, Heading, Icon, IconButton, Input, Row, Skeleton, Spacer, Stack, Text } from "@vibes.diy/ui";
import { Slider } from "@vibes.diy/ui/interactive";
import { gridToCode, play, stop } from "./lib/strudel.js";
const ROWS = ["bd", "sd", "hh", "cp"];
const LABELS = { bd: "kick", sd: "snare", hh: "hat", cp: "clap" };
const START = {
bd: [1, 0, 0, 0, 1, 0, 0, 0],
sd: [0, 0, 1, 0, 0, 0, 1, 0],
hh: [1, 1, 1, 1, 1, 1, 1, 1],
cp: [0, 0, 0, 0, 0, 0, 1, 0],
};
export default function App() {
const { database, useLiveQuery } = useFireproof("groovebox");
const { me, can, ready } = useVibe("groovebox");
const { requestLogin, ViewerTag } = useViewer();
const { docs: grooves } = useLiveQuery("type", { key: "groove" });
const [grid, setGrid] = useState(START);
const [bpm, setBpm] = useState(110);
const [playing, setPlaying] = useState(false);
const [loading, setLoading] = useState(false);
const [step, setStep] = useState(-1);
const [name, setName] = useState("");
const timers = useRef([]);
useEffect(() => () => void stop(), []);
// Every sounding event names its slot; the light moves when the sound does.
function onEvent(event) {
const slot = Math.round(event.begin * 8) % 8;
timers.current.push(setTimeout(() => setStep(slot), event.delay));
}
async function start(nextGrid = grid, nextBpm = bpm) {
if (!playing) setLoading(true);
const pattern = await play(gridToCode(nextGrid, ROWS, nextBpm), onEvent);
setLoading(false);
if (pattern) setPlaying(true);
}
async function halt() {
await stop();
for (const t of timers.current) clearTimeout(t);
timers.current = [];
setPlaying(false);
setStep(-1);
}
function toggle(sound, i) {
const next = { ...grid, [sound]: grid[sound].map((v, j) => (j === i ? (v ? 0 : 1) : v)) };
setGrid(next);
if (playing) start(next, bpm);
}
function tempo([value]) {
setBpm(value);
if (playing) start(grid, value);
}
const draft = { type: "groove", name: name || "untitled", grid, bpm, authorHandle: me?.userHandle };
const verdict = can.create(draft);
return (
<main className="min-h-screen bg-background text-foreground p-4 md:p-8">
<Stack gap={4}>
<Row gap={2} align="center" wrap>
<Heading level={1}>Groovebox</Heading>
<Spacer />
<Badge tone={playing ? "up" : "idle"}>{playing ? "Playing" : loading ? "Fetching the drum kit…" : "Ready"}</Badge>
</Row>
<Card variant="tight">
<Stack gap={2}>
{ROWS.map((sound) => (
<Row key={sound} gap={2} align="center">
<Text size="sm" muted>{LABELS[sound]}</Text>
<Spacer />
{grid[sound].map((on, i) => (
<IconButton
key={i}
size="sm"
label={`${LABELS[sound]} step ${i + 1}${on ? ", on" : ", off"}`}
variant={on ? "solid" : "quiet"}
tone={i === step ? "info" : on ? "up" : "idle"}
icon={<Icon name={on ? "idle" : "off"} size="sm" />}
onClick={() => toggle(sound, i)}
/>
))}
</Row>
))}
</Stack>
</Card>
<Row gap={3} align="center" wrap>
<Button onClick={() => (playing ? halt() : start())}>{playing ? "Stop" : "Play"}</Button>
<Slider value={[bpm]} onChange={tempo} min={60} max={180} label="Tempo" />
<Text size="sm" muted>{bpm} bpm</Text>
</Row>
<Card variant="tight">
<Stack gap={3}>
<Heading level={2}>Shared grooves</Heading>
{!ready && <div aria-busy="true"><Skeleton variant="row" /></div>}
{ready && !me && <Row gap={2} align="center" wrap><Text muted>Sign in to publish a groove to the shared book.</Text><Button size="sm" variant="quiet" onClick={requestLogin}>Sign in</Button></Row>}
{ready && me && verdict.ok && (
<Row gap={2} align="top" wrap>
<Field label="Groove name">{(id, d) => <Input id={id} describedBy={d} value={name} onChange={setName} />}</Field>
<Button size="sm" onClick={() => database.put({ ...draft, createdAt: Date.now() }).then(() => setName(""))}>Publish</Button>
</Row>
)}
{grooves.map((g) => (
<Row key={g._id} gap={2} align="center" wrap>
<Button size="sm" variant="quiet" onClick={() => { setGrid(g.grid); setBpm(g.bpm); if (playing) start(g.grid, g.bpm); }}>{g.name}</Button>
{g.authorHandle && <ViewerTag userHandle={g.authorHandle} />}
</Row>
))}
</Stack>
</Card>
<Text size="sm" muted>
Sound by <a className="underline" href="https://strudel.cc" target="_blank" rel="noreferrer">Strudel</a> (AGPL), fetched from its own address when you press play.
</Text>
</Stack>
</main>
);
}
The text-to-pattern prompt, verbatim
lib/pattern-prompt.js above is the system prompt for a text box that
turns a sentence into a pattern, or an app that rewrites the pattern on
request. Use it as written: it names only sounds the two sample maps hold,
its four examples were played on the engine as the doc was written, and it
states the tempo rule in the form the model gets right (count the beats the
string holds, then divide). rewritePrompt(request, code) appends the ask
and the pattern that is playing; the callAI schema is
{ name: string, code: string }, and the app plays code through play()
so a pattern the model got wrong still surfaces through onPatternError
rather than silence. For a text box with no current pattern, pass the
starter example as code.
The interface follows the music
Light the step that is sounding from the engine's own events, with
pattern.onTrigger(callback, false). In the frame the callback receives
(hap, time, cps, targetTime) and posts each event to the app as
{ s, note, gain, begin, delay }: begin is the event's position in cycles
(so begin * steps % steps is its slot) and delay is the milliseconds
until it sounds ((targetTime - time) * 1000), so a setTimeout of delay
lands the light on the beat. The false keeps the engine's own sound output
in place; the default replaces it, which is how a visualiser goes silent.
Clear the pending timers in stop.
Live-coded visuals that move with the pattern are the hydra skill's: its
beat-visuals example feeds these same events to a Hydra sketch.
Play, stop and the lifecycle
- Stop calls
hush()(the module'sstop()asks the player to), which silences every pattern the engine holds and halts the scheduler;play(nextCode)after a stop starts it again (measured:startedreads false afterhush(), true after the nextsetPattern). AuseEffectcleanup that callsstop()keeps a navigated- away page quiet. - A change while playing calls
play(next)again; the engine swaps patterns without a gap. Keepplayingin state (or a ref the handlers read) so a toggle on a stopped grid changes the grid and nothing else. - The first play shows a short loading state with warm copy ("fetching the drum kit") and the button stays pressable; from the second play on the engine is already here.
- A bad pattern arrives through
onPatternError: show the message in the app's words beside the editor, keep the editor's text, and let the last good pattern play on.play()resolvesfalsefor it, so the state stays where it was.
Persistence — the pattern text is the document
Save the pattern text itself (code, or the grid and bpm a grid
compiles from) with a name, the author's handle and a timestamp; the engine
rebuilds the sound from it on every play, so a saved document is tiny and
remixable, and a change to the generator reaches every saved groove. Seed
three or four finished patterns in seed.json so the first visit has
something to press. The shared gallery is one useLiveQuery over the
pattern type, and the access rule above makes it public to read and
author-owned to write; a signed-out visitor jams on the pad and is invited
to sign in at "Keep".
Samples and voices
Two sample maps arrive in prebake, both from jsDelivr. The Dirt-Samples
kit names the drums a bare s("…") can play: bd, sd, hh, cp, cr,
lt, mt, ht, perc, plus named one-offs such as 808bd, 808oh,
jvbass, casio, tabla, arpy. The tidal-drum-machines map adds the
banks: .bank("RolandTR808"), .bank("RolandTR909"), .bank("LinnDrum")
and dozens more, each with bd sd hh oh cp rim cr lt mt ht. Measured
2026-10-07: with only the Dirt kit loaded, oh and rim play nothing and
the engine logs "sound oh not found" to the console; with both maps loaded
every name above plays. The engine's own synths need no download:
note("c3 e3 g3").s("sawtooth"). The app's own sounds load the same way as
the kits: samples({ kick: "https://…/kick.wav", snare: "…" }) inside
prebake, then s("kick snare").
Mobile
Play is a large button near the top; nothing sounds until it is pressed. A
grid's steps are IconButtons whose label names the row, the step and its
state, and a tempo slider sits beside play rather than in a settings drawer. The tap calls
play() before anything awaits, so the press is still live when the player
starts the sound; a phone that wants its own tap inside the player gets the
player's button.
Shapes a Strudel vibe takes
- A pattern pad — editor, examples, play and stop, saved patterns, a prompt box that rewrites the groove. The starter above.
- A groovebox — a grid of pads that writes mini-notation, a tempo slider, lights that follow the music, a shared groovebook with an access rule. The second example above.
- A knob instrument — three sliders (tempo, brightness, space) over one fixed pattern, re-evaluated on every drag.
- A generative radio —
catof several patterns with.sometimesand.everyvariations and a seed, playing for as long as the tab is open. - A jam room — the pattern document is shared, every member's edit is a version, and the gallery doubles as the set list.
Common gotchas
- Tempo is twice, half or four times what was meant —
cpmcounts cycles. Divide the bpm by the beats one cycle holds (the table above). - A drum name plays nothing and the console says "sound X not found" —
the name is in a bank, not the bare kit. Load both sample maps and use
.bank(…), or pick a bare-kit name. - The music stops when a visualiser is added —
onTriggerwith its default second argument replaces the sound output. Passfalse. - A typo stops nothing and shows nothing —
evaluatereports throughonEvalError; wire it ininitStrudeland show the message. - The engine loads twice — two players, or an inline
import()in a handler. One memoized player, made by the module on the first press. - The app's data shows up inside a pattern, or a pattern reaches the page
— the pattern was evaluated in the app (
evaluateimported intoApp.jsx, or a frame withallow-same-origin). Every pattern goes throughplay()into the sandboxed player, and the frame'ssandboxisallow-scriptsalone. - A sample map loads but its sounds stay silent — the map's sound files
live on a host the sandbox does not list. Add that host to
CDNSinlib/sandbox.js. - A pattern built from typed text breaks on a quote — strip or escape
"before interpolating a person's text intos("…"). - Sound carries on after leaving the page — call
stop()in the effect cleanup.