Browser patch editor for Pure Data (closes #1)

Open a .pd file, drag boxes and pull cords, save it back as a file Pd
will load. Dragging is Dragology: `d.vary` moves a box, and a cord drag
is `d.closest(...).whenFar(vary)` over every inlet in the patch, so the
plug snaps to an inlet and cancels on empty space.

The parser is a byte-exact round trip. Two Pd format details that matter:
`#X connect` indices count comments, and `;;` (an empty record) is not the
same as a blank line. Anything unmodelled — arrays, `#X declare`,
subpatches — is preserved verbatim.

Tests run real Pd: patches round trip, an edited patch loads in
`pd -nogui` without new complaints, and the bridge carries a message into
a running Pd and back.

The bridge writes to server/patches/ and runs `pd -nogui` itself, so
saving and hearing the patch is one button.
This commit is contained in:
2026-11-04 19:19:53 -08:00
commit fe6f2bfe76
24 changed files with 3920 additions and 0 deletions
+165
View File
@@ -0,0 +1,165 @@
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { WebSocket } from "ws";
const HERE = join(import.meta.dirname, "..");
const hasPd = spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null;
/**
* A patch that proves both directions of the bridge:
*
* - anything arriving on :8081 is printed, and pd's stdout is forwarded to
* the browser as log lines;
* - a second after loading, it sends `pin 42` back to the bridge on :8091.
*
* (`netsend` only accepts its own methods, so arbitrary data has to go
* through a `send ...` message rather than being piped in raw.)
*/
const LOOPBACK_PATCH = `#N canvas 0 0 400 300 10;
#X obj 20 20 netreceive -u 8081;
#X msg 20 50 connect 127.0.0.1 8091;
#X obj 20 80 netsend -u;
#X obj 120 20 loadbang;
#X obj 120 50 print in;
#X obj 220 20 del 400;
#X msg 220 50 send pin 42;
#X obj 220 0 loadbang;
#X connect 3 0 1 0;
#X connect 1 0 2 0;
#X connect 0 0 4 0;
#X connect 7 0 5 0;
#X connect 5 0 6 0;
#X connect 6 0 2 0;
`;
function startBridge(dir: string, port: number) {
const child = spawn(
process.execPath,
[join(HERE, "server", "bridge.mjs"), "--port", String(port), "--silent", "--dir", dir],
{ stdio: ["ignore", "pipe", "pipe"] },
);
let output = "";
child.stdout.on("data", (c) => (output += String(c)));
child.stderr.on("data", (c) => (output += String(c)));
return { child, log: () => output };
}
async function waitForPort(port: number, timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const ok = await new Promise<boolean>((resolve) => {
const socket = new WebSocket(`ws://127.0.0.1:${port}`);
socket.on("open", () => {
socket.close();
resolve(true);
});
socket.on("error", () => resolve(false));
});
if (ok) return;
await new Promise((r) => setTimeout(r, 100));
}
throw new Error("bridge never accepted a connection");
}
/** Collect bridge messages until `match` is satisfied. */
function collect(socket: WebSocket) {
const messages: unknown[] = [];
const waiters: { match: (m: any) => boolean; resolve: (m: any) => void }[] = [];
socket.on("message", (data) => {
const message = JSON.parse(String(data));
messages.push(message);
for (const waiter of [...waiters]) {
if (waiter.match(message)) {
waiters.splice(waiters.indexOf(waiter), 1);
waiter.resolve(message);
}
}
});
return {
messages,
next(match: (m: any) => boolean, timeoutMs = 5000): Promise<any> {
const existing = messages.find(match);
if (existing) return Promise.resolve(existing);
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error("timed out waiting for message")), timeoutMs);
waiters.push({
match,
resolve: (m) => {
clearTimeout(timer);
resolve(m);
},
});
});
},
};
}
test("bridge round trips a message through a running pd", async (t) => {
if (!hasPd) return t.skip("pd not installed");
const port = 8300 + Math.floor(Math.random() * 400);
const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-"));
const bridge = startBridge(dir, port);
let socket: WebSocket | null = null;
try {
await waitForPort(port);
socket = new WebSocket(`ws://127.0.0.1:${port}`);
// Attach before the socket opens: the bridge sends `hello` immediately,
// and a message emitted with no listener is lost.
const inbox = collect(socket);
await new Promise((r) => socket!.on("open", r));
const hello = await inbox.next((m) => m.type === "hello");
assert.equal(hello.pdRunning, false);
assert.equal(hello.toPdPort, 8081);
assert.equal(hello.fromPdPort, 8091);
socket.send(JSON.stringify({ type: "save", name: "loop.pd", text: LOOPBACK_PATCH }));
await inbox.next((m) => m.type === "log" && /saved/.test(m.line));
socket.send(JSON.stringify({ type: "run", file: "loop.pd" }));
const running = await inbox.next((m) => m.type === "pd-status" && m.running === true, 8000);
assert.match(running.file, /loop\.pd$/);
// pd announces itself once the patch has loaded.
const echoed = await inbox.next((m) => m.type === "from-pd" && m.receiver === "pin", 10000);
assert.deepEqual(echoed.args, ["42"]);
// And a message from the browser reaches the patch's netreceive.
socket.send(JSON.stringify({ type: "send", receiver: "pin", args: [42] }));
const printed = await inbox.next(
(m) => m.type === "log" && /in: pin 42/.test(m.line),
8000,
);
assert.match(printed.line, /in: pin 42/);
} finally {
socket?.close();
bridge.child.kill("SIGTERM");
}
});
test("bridge refuses to write outside its patches directory", async () => {
const port = 8700 + Math.floor(Math.random() * 200);
const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-"));
const bridge = startBridge(dir, port);
let socket: WebSocket | null = null;
try {
await waitForPort(port);
socket = new WebSocket(`ws://127.0.0.1:${port}`);
// Attach before the socket opens: the bridge sends `hello` immediately,
// and a message emitted with no listener is lost.
const inbox = collect(socket);
await new Promise((r) => socket!.on("open", r));
socket.send(JSON.stringify({ type: "save", name: "../../escape.pd", text: "#N canvas 0 0 1 1 10;\n" }));
const saved = await inbox.next((m) => m.type === "saved");
assert.equal(saved.file.startsWith(dir), true, `wrote to ${saved.file}`);
} finally {
socket?.close();
bridge.child.kill("SIGTERM");
}
});
+174
View File
@@ -0,0 +1,174 @@
import assert from "node:assert/strict";
import { spawn, spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { addNode, deleteNode, newCordId, reconcile, stateFromPatch } from "../src/editor/ops.ts";
import { nodePorts } from "../src/pd/geometry.ts";
import { parsePd } from "../src/pd/parse.ts";
import { serializePd } from "../src/pd/serialize.ts";
const SAMPLES = join(import.meta.dirname, "..", "public", "samples");
const SYNTH = join(SAMPLES, "synth.pd");
/**
* Load a patch in real Pd and report anything it complains about.
* Pd has no batch mode, so we let it start and then kill it.
*/
function pdFeedback(file: string): Promise<string> {
return new Promise((resolve) => {
const child = spawn("pd", ["-nogui", "-nosound", "-open", file], {
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
const collect = (chunk: Buffer) => {
output += String(chunk);
};
child.stdout.on("data", collect);
child.stderr.on("data", collect);
child.on("error", () => resolve(""));
const timer = setTimeout(() => {
child.kill("SIGTERM");
resolve(output);
}, 2500);
child.on("exit", () => {
clearTimeout(timer);
resolve(output);
});
});
}
/** Pd's own chatter, not a problem with the patch. */
function complaints(output: string): string[] {
return output
.split("\n")
.map((line) => line.trim())
.filter((line) => line.length > 0)
.filter((line) => !/priority \d+ scheduling failed/.test(line))
.filter((line) => !/^Pd-\d/.test(line));
}
function hasPd(): boolean {
return spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null;
}
function scratch(name: string, text: string): string {
const dir = mkdtempSync(join(tmpdir(), "dragology-pd-"));
const file = join(dir, name);
writeFileSync(file, text);
return file;
}
/**
* The shipped sample contains a line Pd rejects on purpose, so the baseline is
* not empty: we assert that what we write adds nothing new. That is the claim
* a patch editor has to be able to make.
*/
async function assertNoNewComplaints(file: string, label: string) {
const baseline = complaints(await pdFeedback(file));
const copy = scratch("copy.pd", serializePd(stateFromPatch(parsePd(readFileSync(file, "utf8"), "copy.pd"))));
const fresh = complaints(await pdFeedback(copy)).filter((line) => !baseline.includes(line));
assert.deepEqual(fresh, [], `${label}: pd said something new\n${await pdFeedback(copy)}`);
}
test("saving an untouched patch adds no pd complaints", async (t) => {
if (!hasPd()) return t.skip("pd not installed");
await assertNoNewComplaints(SYNTH, "synth.pd");
});
test("an edited patch still parses the way pd wants", async (t) => {
if (!hasPd()) return t.skip("pd not installed");
let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "edited.pd"));
const osc = Object.values(state.nodes).find((n) => n.text === "osc~");
const dac = Object.values(state.nodes).find((n) => n.text.startsWith("dac~"));
assert.ok(osc && dac, "sample has an osc~ and a dac~");
// A cord that was not there before, a moved box, and a new box.
const cordId = newCordId();
state = {
...state,
cords: { ...state.cords, [cordId]: { id: cordId, from: osc.id, outlet: 0, to: dac.id, inlet: 0 } },
nodes: { ...state.nodes, [osc.id]: { ...osc, x: osc.x + 40, y: osc.y + 12 } },
};
state = addNode(state, {
id: "added-1",
kind: "obj",
x: 600,
y: 400,
head: "#X obj",
tail: " osc~ 220",
text: "osc~ 220",
});
const text = serializePd(reconcile(state));
assert.match(text, /#X obj 600 400 osc~ 220;/);
assert.match(text, new RegExp(`#X obj ${osc.x + 40} ${osc.y + 12} osc~;`));
const baseline = complaints(await pdFeedback(SYNTH));
const fresh = complaints(await pdFeedback(scratch("edited.pd", text))).filter(
(line) => !baseline.includes(line),
);
assert.deepEqual(fresh, [], "editing introduced a pd error");
});
test("deleting a node drops its record and its cords", () => {
let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd"));
const victim = Object.values(state.nodes).find((n) =>
Object.values(state.cords).some((c) => c.to === n.id),
);
assert.ok(victim);
const before = Object.keys(state.cords).length;
const attached = Object.values(state.cords).filter(
(c) => c.to === victim.id || c.from === victim.id,
).length;
assert.ok(attached > 0);
state = deleteNode(state, victim.id);
assert.equal(Object.keys(state.cords).length, before - attached);
assert.equal(state.nodes[victim.id], undefined);
assert.ok(!state.records.some((r) => r.kind === "node" && r.id === victim.id));
assert.equal(
Object.values(state.cords).some((c) => c.to === victim.id || c.from === victim.id),
false,
);
});
test("adding a node puts it where pd expects objects", () => {
const state = addNode(stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd")), {
id: "added-1",
kind: "obj",
x: 10,
y: 10,
head: "#X obj",
tail: " print hello",
text: "print hello",
});
const records = state.records;
const nodeAt = records.findIndex((r) => r.kind === "node" && r.id === "added-1");
const firstCord = records.findIndex((r) => r.kind === "cord");
assert.ok(nodeAt >= 0);
assert.ok(nodeAt < firstCord, "node record goes before the connect records");
});
test("the parser flags the line pd rejects", () => {
const patch = parsePd(readFileSync(SYNTH, "utf8"), "synth.pd");
assert.equal(patch.warnings.length, 1);
assert.match(patch.warnings[0], /DO NOT EDIT/);
});
test("inlet counts follow the object's arguments", () => {
const node = (text: string) =>
({ id: "n", kind: "obj", x: 0, y: 0, head: "#X obj", tail: ` ${text}`, text }) as const;
assert.deepEqual(nodePorts(node("dac~")), { inlets: 2, outlets: 0 });
assert.deepEqual(nodePorts(node("dac~ 1")), { inlets: 1, outlets: 0 });
assert.deepEqual(nodePorts(node("dac~ 1 2")), { inlets: 2, outlets: 0 });
assert.deepEqual(nodePorts(node("adc~ 1")), { inlets: 0, outlets: 1 });
assert.deepEqual(nodePorts(node("route midi")), { inlets: 1, outlets: 2 });
assert.deepEqual(nodePorts(node("t b b b")), { inlets: 1, outlets: 3 });
assert.deepEqual(nodePorts(node("pack 0 0")), { inlets: 2, outlets: 1 });
assert.deepEqual(nodePorts(node("r midi-vel")), { inlets: 0, outlets: 1 });
});
+89
View File
@@ -0,0 +1,89 @@
import assert from "node:assert/strict";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import test from "node:test";
import { parsePd, splitAtoms, splitRecords } from "../src/pd/parse.ts";
import { nodePosition, serializePd } from "../src/pd/serialize.ts";
const SYNTH_PD = "/home/david/Arduino/sketches/uno-q-audio-synth/pd";
test("records split on unescaped semicolons only", () => {
assert.deepEqual(splitRecords("#X msg 0 0 a \\; b;"), ["#X msg 0 0 a \\; b"]);
});
test("atoms unescape", () => {
assert.deepEqual(splitAtoms("#X msg 0 0 a\\;b \\, \\$0"), [
"#X",
"msg",
"0",
"0",
"a;b",
",",
"$0",
]);
});
const patch = `#N canvas 0 0 400 300 10;
#X text 10 10 a comment;
#X obj 50 50 osc~ 440;
#X obj 50 90 dac~;
#X obj 120 50 \\;does\\,not\\$exist;
#X connect 1 0 2 0;
#X connect 1 0 2 1;
`;
test("comments occupy an index in the connect space", () => {
const parsed = parsePd(patch);
const cords = Object.values(parsed.cords);
assert.equal(cords.length, 2);
for (const cord of cords) {
assert.equal(parsed.nodes[cord.from].text, "osc~ 440");
assert.equal(parsed.nodes[cord.to].text, "dac~");
}
});
test("round trip is byte exact", () => {
const parsed = parsePd(patch);
assert.equal(serializePd(parsed), patch);
});
test("moving a node only changes its coordinates", () => {
const parsed = parsePd(patch);
const node = Object.values(parsed.nodes).find((n) => n.text === "osc~ 440");
assert.ok(node);
node.x = 200;
node.y = 210;
const out = serializePd(parsed);
assert.equal(out, patch.replace("#X obj 50 50 osc~ 440", "#X obj 200 210 osc~ 440"));
});
test("escaped atoms survive a move", () => {
const parsed = parsePd(patch);
const node = Object.values(parsed.nodes).find((n) => n.text === ";does,not$exist");
assert.ok(node, "escaped object text parsed");
node.y = 300;
assert.match(serializePd(parsed), /#X obj 120 300 \\;does\\,not\\\$exist;/);
});
test("every real patch in the synth project round trips", (t) => {
let files: string[];
try {
files = readdirSync(SYNTH_PD).filter((f) => f.endsWith(".pd"));
} catch {
t.skip("synth project not present");
return;
}
assert.ok(files.length > 0);
for (const file of files) {
const text = readFileSync(join(SYNTH_PD, file), "utf8");
const parsed = parsePd(text, file);
assert.equal(serializePd(parsed), text, `${file} round trip`);
// Every cord must resolve to a real object, never a comment.
for (const cord of Object.values(parsed.cords)) {
assert.notEqual(parsed.nodes[cord.from].kind, "text", `${file}: cord from comment`);
assert.notEqual(parsed.nodes[cord.to].kind, "text", `${file}: cord to comment`);
assert.ok(nodePosition(parsed, cord.from) >= 0);
}
}
});