Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: render SuperCollider source in a contained, cancellable media-queue job (#9413)
[._.]/ Adam Eivy5dbd750eb372
diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 7c3c76f8fc..ea02a86056 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -713,4 +713,4 @@ originals and is distinct from space reclamation.### SuperCollider runtime evidence-`data/supercollider/` is `ephemeral-file`: `runtime-evidence.json` caches the last synthetic render probe for the managed SuperCollider image (bound to this machine's local image id, runtime version and containment policy), and `jobs/` holds in-flight probe/render scratch that each run removes. Nothing in it relates to other records, needs search, or federates. Setup re-derives it, so it is excluded from backups (`/supercollider/`) and purgeable from the Data Manager. See [SUPERCOLLIDER.md](./SUPERCOLLIDER.md).+`data/supercollider/` is `ephemeral-file`: `runtime-evidence.json` caches the last synthetic render probe for the managed SuperCollider image (bound to this machine's local image id, runtime version and containment policy), `jobs/` holds in-flight probe/render scratch that each run removes, and `previews/` holds validated Music Designer render previews (WAV + provenance sidecar) for 24 hours until the user saves one as a take. Nothing in it relates to other records, needs search, or federates. Setup re-derives it, so it is excluded from backups (`/supercollider/`) and purgeable from the Data Manager. See [SUPERCOLLIDER.md](./SUPERCOLLIDER.md).diff --git a/docs/SUPERCOLLIDER.md b/docs/SUPERCOLLIDER.mdindex 6fd35d26f5..2fecffe162 100644--- a/docs/SUPERCOLLIDER.md+++ b/docs/SUPERCOLLIDER.md@@ -91,6 +91,61 @@ The image is stamped with two labels: the runtime version (`SUPERCOLLIDER_RUNTIMThe runner (`runSuperColliderContainer`) enforces a wall-time limit and cancellation. It always runs `docker rm --force` afterwards, because killing the docker CLI does not stop a container. Removing the container removes every process inside it. Files the container writes are read back only if they are regular files within the size limit (`readContainedOutput`). A symlink in the output directory cannot point the host at its own files.+## Renders++A Music Designer render is a media-queue job of kind `supercollider` (`server/services/superColliderRender.js`). It runs on the queue's serialized local lane, the same lane as HTML compositions, so it never competes with another heavy local render for the machine.++| Route | Purpose |+|---|---|+| `GET /api/music/supercollider/status` | The readiness verdict above. Reads only; never builds or renders. |+| `POST /api/music/supercollider/setup` | SSE stream of an explicit setup (`{ "rebuild": true }` to repair). The build continues if the page closes. |+| `POST /api/music/supercollider/render` | `{ code, durationSec, seed? }`, with a whole-second duration from 4 to 120 s. Returns `202 { jobId, position, status, seed, sourceHash }`. Returns `409 SUPERCOLLIDER_UNAVAILABLE` with the setup action when the runtime is not ready. |+| `GET /api/music/supercollider/renders/:jobId/events` | Queue progress over SSE: `queued`, `started`, `progress`/`status` phases, then `complete` with the preview, `error`, or `canceled` |+| `POST /api/music/supercollider/renders/:jobId/cancel` | Cancel. The container is force-removed. |+| `GET /api/music/supercollider/renders/:jobId/audio` | The validated preview WAV |++What one render does:++1. **Snapshot.** The job's params carry the source text, so each job, including a retry, writes its own copy into `data/supercollider/jobs/<jobId>/in/`. A shipped wrapper (`render.scd`) sits beside it. The source cannot name any path, format or duration.+2. **Contain.** Both run through `runSuperColliderContainer` under the policy above, pinned to the verified image id. The only writable mount is `data/supercollider/jobs/<jobId>/out/`. The host stops the container early if that directory exceeds its byte or file-count budget.+3. **Score.** The wrapper compiles the source. On a parse error nothing runs. It then seeds the interpreter and evaluates the source, whose **last expression must be a pattern** (for example `Pbind` or `Ppar`). It scores that pattern for exactly the requested duration at 120 BPM. It sends every SynthDef the source `.add`ed, plus the stock `\default`, and renders 48 kHz stereo float through non-realtime `scsynth`.+4. **Validate.** The host reads back one regular file within a size bound; symlinks are refused. It decodes the file and checks that it has 2 channels at 48 kHz, lasts the requested duration within 50 ms, contains only finite samples, and peaks above -40 dBFS.+5. **Publish or clean up.** A passing render becomes a preview: `data/supercollider/previews/<jobId>.wav` plus a `<jobId>.json` provenance sidecar. The sidecar records the source, its SHA-256, the seed, the settings, the runtime version, the policy version, the image id and the measured audio. Previews expire after 24 hours. A preview never changes a track. Saving one as a take is a separate action. The job directory is removed on every outcome, and the container is always force-removed.++Before each render, the service removes leftovers from a crashed process: labeled render containers and job directories older than any possible run (the wall limit plus 5 minutes).++Failures carry a `SUPERCOLLIDER_*` code:++| Code | Cause |+|---|---|+| `SUPERCOLLIDER_UNAVAILABLE` | The runtime is not `ready`. The message names the setup step. |+| `SUPERCOLLIDER_SYNTAX_ERROR` | The source did not compile. The message includes sclang's `line N char M`. |+| `SUPERCOLLIDER_SOURCE_ERROR` | Evaluating the source threw an error. |+| `SUPERCOLLIDER_NOT_A_PATTERN` | The source's last value was not a pattern. |+| `SUPERCOLLIDER_SCORE_ERROR` / `SUPERCOLLIDER_SYNTHESIS_FAILED` | Scoring or `scsynth` failed. |+| `SUPERCOLLIDER_TIMEOUT` | The render ran past the wall limit (180 s) and was killed. |+| `SUPERCOLLIDER_OUTPUT_QUOTA` | The render wrote more output than its budget allows. |+| `SUPERCOLLIDER_OUTPUT_INVALID` | The output is missing, a symlink, the wrong format, the wrong length, non-finite, or silent. |+| `SUPERCOLLIDER_CANCELED` | The user canceled the render. |++### Live containment evidence++`server/services/superColliderRender.test.js` covers the workflow against a Docker double. The real boundary is exercised by an opt-in suite that needs a machine where setup has passed:++```bash+cd server && PORTOS_SUPERCOLLIDER_LIVE=1 npx vitest run services/superColliderRender.live.test.js+```++The suite renders stock synths and measures the result. It then confirms that generated source cannot do any of the following:++- read an unmounted host file or the server's environment,+- write to its input or root filesystem, directly or through a shell,+- connect to a host listener,+- load an operator startup file,+- run as root.++It also checks syntax errors, the timeout, cancellation and overlapping renders. With the flag set, an unready runtime fails the suite rather than skipping it.+## Platform evidenceThe recipe targets Linux `amd64` and `arm64` Docker engines. Readiness is per machine: a host is `ready` only after the probe has passed on that host's engine with the current image. The probe result records the engine version, OS and architecture, so the evidence names the platform it was proven on. Any other configuration stays visibly unavailable.@@ -111,3 +166,4 @@ Import the contract rather than re-deriving it:- `server/lib/superColliderRuntime.js`: version and policy constants, `SUPERCOLLIDER_RENDER_FORMAT`, `SUPERCOLLIDER_CONTAINER_LIMITS`, `SUPERCOLLIDER_CONTAINER_LABEL` (for orphan sweeps), `buildSuperColliderRunArgs`, `evaluateSuperColliderStatus`- `server/services/superColliderRuntime.js`: `getSuperColliderStatus`, `setupSuperColliderRuntime` (concurrent calls share one run), `runSuperColliderContainer`, `readContainedOutput`- `server/lib/wavAudioFile.js`: `measureWavAudio` for decoded duration, channel, rate, level and non-finite checks+- `server/services/superColliderRender.js`: `renderSuperColliderSource` (one contained render to a validated preview), `readSuperColliderPreview(jobId)` → `{ wavPath, preview }` for saving a preview as a take, `presentSuperColliderPreview`diff --git a/server/index.js b/server/index.jsindex 822fb139a1..4e062f4dce 100644--- a/server/index.js+++ b/server/index.js@@ -159,6 +159,7 @@ import artistsRoutes from './routes/artists.js';import albumsRoutes from './routes/albums.js';import tracksRoutes from './routes/tracks.js';import musicRoutes from './routes/music.js';+import superColliderRoutes from './routes/superCollider.js';import conflictJournalRoutes from './routes/conflictJournal.js';import pipelineRoutes from './routes/pipeline/index.js';import importerRoutes from './routes/importer.js';@@ -449,6 +450,7 @@ app.use('/api/authors', authorsRoutes);app.use('/api/artists', artistsRoutes);app.use('/api/albums', albumsRoutes);app.use('/api/tracks', tracksRoutes);+app.use('/api/music/supercollider', superColliderRoutes);app.use('/api/music', musicRoutes);app.use('/api/pipeline', pipelineRoutes);app.use('/api/conflict-journal', conflictJournalRoutes);diff --git a/server/lib/README.md b/server/lib/README.mdindex 7adb056319..62cec2586b 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -537,7 +537,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). || `pitchMath.js` | Dependency-free scientific-pitch math shared by the LLM-authored music formats on both runtimes: `pitchToMidi("C4")` → 60 (null when unparseable) and `midiToFreq(69)` → 440. || `wavAudioFile.js` | `writeWavAudioFile(wav, dir, basename)` — land a synthesized WAV Buffer as `<basename>.ogg` via the system ffmpeg, falling back to `<basename>.wav` (and dropping a stale `.ogg`) when ffmpeg is missing or the encode fails; resolves to the filename used. Shared by the chiptune and drawn-waveform renderers and the code-engine take upload. `wavDurationMs(buffer)` reads a PCM WAV's duration from its RIFF header (0 for anything that is not a parseable WAV). `measureWavAudio(buffer)` decodes PCM 16/24/32-bit or float 32/64 (EXTENSIBLE included) into `{ channels, sampleRate, frames, durationMs, peak, rms, nonFinite }` so native renders are judged by their samples (null when undecodable). |-| `superColliderRuntime.js` | Managed SuperCollider runtime contract (#9412), pure: image/runtime/policy version constants, `buildSuperColliderRunArgs` (the one contained `docker run` for untrusted `sclang` source: no network/caps, read-only root, limits, ro input, private output), `buildSuperColliderBuildArgs`, the shipped synthetic probe, `evaluateSuperColliderStatus` (docker-missing … ready, with stale image/evidence invalidation). I/O lives in `services/superColliderRuntime.js`. |+| `superColliderRuntime.js` | Managed SuperCollider runtime contract (#9412), pure: image/runtime/policy version constants, `buildSuperColliderRunArgs` (the one contained `docker run` for untrusted `sclang` source: no network/caps, read-only root, limits, ro input, private output), `buildSuperColliderBuildArgs`, the shipped synthetic probe, `evaluateSuperColliderStatus` (docker-missing … ready, with stale image/evidence invalidation), and the render contract (#9413): `SUPERCOLLIDER_RENDER` bounds, the trusted NRT `SUPERCOLLIDER_RENDER_WRAPPER_SOURCE`, `classifySuperColliderRenderLog` (syntax/source/pattern/score/synthesis failures) and `parseDockerContainerList` for orphan sweeps. I/O lives in `services/superColliderRuntime.js`. || `waveSketch.js` | Drawn-waveform music contract v1 (browser-safe; new paintings are v2 — see `paintedCanvas.js`): the LLM draws single-cycle `shapes` (point polylines in [-1, 1]) played by `voices` as timed strokes with optional glide, shape morph, and drawn envelope, plus a whole-piece `contour`. `normalizeWaveSketch(raw)` is the one lenient, idempotent validator (null when nothing playable survives); `synthesizeWaveSketch(sketch)` → deterministic mono PCM (seeded noise), so the client preview and server render match; `pcmPeaks(pcm, columns)` for drawing it; `WAVE_SKETCH_LIMITS`. `normalizeWaveSketch` dispatches a `version: 2` sketch to `normalizePaintedCanvas`; `synthesizeSketchChannels(sketch)` renders either version to its channel list; `isPaintedCanvas(sketch)`. || `paintedCanvas.js` | Painted-spectrogram canvas, wave sketch v2 (#8464, browser-safe): stereo time × log-frequency canvas painted with strokes (`path` keyframes `{t, hz, a}`, per-keyframe `overtones`, noise `width`, `pan`), plus optional `sections` and tempo grid. `normalizePaintedCanvas(raw, { durationSec, limits })` is the lenient idempotent validator; `synthesizePaintedCanvas(canvas)` → deterministic `[left, right]` PCM using only IEEE-exact math (series sine table, log2/exp2), so server WAV and browser preview match on any engine; render work bounded by `PAINTED_CANVAS_LIMITS.WORK_MAX_PARTIAL_SEC`; `paintedCanvasStats(canvas)` → stroke/keyframe/noise/work totals. || `spectrogramImage.js` | `spectrogramPixels(pcm, { sampleRate, width, height, minHz, maxHz })` → raw RGB pixels of a log-frequency STFT spectrogram (80 dB range) — the picture a model gets of its own painted canvas in the review pass (#8464). Pure; the caller encodes the PNG. |diff --git a/server/lib/superColliderRuntime.js b/server/lib/superColliderRuntime.jsindex 77a88ae28f..097e63bb8c 100644--- a/server/lib/superColliderRuntime.js+++ b/server/lib/superColliderRuntime.js@@ -271,7 +271,7 @@ export function parseDockerImage(stdout) {* format and duration. Returns null when it passes, else the reason.*/export function superColliderSmokeFailure(measurement, { durationSec = SUPERCOLLIDER_SMOKE.durationSec } = {}) {- if (!measurement) return 'the probe wrote no readable WAV';+ if (!measurement) return 'no readable WAV was written';const { sampleRate, channels } = SUPERCOLLIDER_RENDER_FORMAT;if (measurement.channels !== channels) return `expected ${channels} channels, got ${measurement.channels}`;if (measurement.sampleRate !== sampleRate) return `expected ${sampleRate} Hz, got ${measurement.sampleRate} Hz`;@@ -283,6 +283,138 @@ export function superColliderSmokeFailure(measurement, { durationSec = SUPERCOLLreturn null;}+/**+ * The bounded render the Music Designer asks for (#9413). Duration is the Code+ * panel's 4–120 s take window; format, tempo and every path come from the+ * trusted runner, never from the source.+ */+export const SUPERCOLLIDER_RENDER = Object.freeze({+ minDurationSec: 4,+ maxDurationSec: 120,+ tempoBpm: 120,+ maxSeed: 2_147_483_647,+ wrapper: 'render.scd',+ source: 'source.scd',+ output: 'render.wav',+});++/**+ * The trusted render wrapper. It compiles the untrusted source file without+ * executing anything on a parse error, seeds the interpreter, evaluates the+ * source (its last expression must be a Pattern), scores that pattern for+ * exactly the requested duration at the fixed tempo, sends every SynthDef the+ * source `.add`ed (plus the stock `\\default`), and renders 48 kHz stereo+ * float through non-realtime scsynth. It runs INSIDE the same container as the+ * source — it is a convenience contract, not a security boundary.+ *+ * `thisProcess.argv`: source path, output path, duration (s), sample rate,+ * seed, beat length (s). Each failure prints ONE+ * `PORTOS_RENDER_ERROR <kind>: <message>` line and exits non-zero, so the+ * host can tell a syntax error from a runtime error from a failed synthesis.+ */+export const SUPERCOLLIDER_RENDER_WRAPPER_SOURCE = `var argv = thisProcess.argv;+var sourcePath = argv[0];+var outPath = argv[1];+var duration = argv[2].asFloat;+var sampleRate = argv[3].asInteger;+var seed = argv[4].asInteger;+var stretch = argv[5].asFloat;+var fail = { |kind, code, message|+ ("PORTOS_RENDER_ERROR " ++ kind ++ ": " ++ message).postln;+ code.exit;+};+var compiled, pattern, problem, defs, proto, score, options;+"PORTOS_PHASE compiling".postln;+compiled = thisProcess.interpreter.compileFile(sourcePath);+if(compiled.isNil) {+ fail.("syntax", 65, "the source has a syntax error");+} {+ thisThread.randSeed = seed;+ { pattern = compiled.value }.try { |error|+ error.reportError;+ problem = error.errorString;+ };+ if(problem.notNil) {+ fail.("source", 67, "the source raised an error: " ++ problem);+ } {+ if(pattern.isKindOf(Pattern).not) {+ fail.("pattern", 66, "the source must end with a pattern expression (Pbind, Ppar, Pseq, ...); its last value was a " ++ pattern.class.name);+ } {+ {+ "PORTOS_PHASE scoring".postln;+ defs = List.new;+ SynthDescLib.global.synthDescs.do { |desc|+ desc.def !? { |def| defs.add([0.0, [\\d_recv, def.asBytes]]) };+ };+ proto = Event.default;+ proto[\\stretch] = stretch;+ score = pattern.asScore(duration, 0, proto);+ score = Score(defs.asArray ++ score.score);+ options = ServerOptions.new.numOutputBusChannels_(2).numInputBusChannels_(0).sampleRate_(sampleRate);+ "PORTOS_PHASE rendering".postln;+ score.recordNRT(nil, outPath, nil, sampleRate, "WAV", "float", options, "", duration, { |exitCode|+ if(exitCode == 0) { 0.exit } { fail.("synthesis", 70, "scsynth exited with code " ++ exitCode) };+ });+ }.try { |error|+ error.reportError;+ fail.("score", 68, "the pattern could not be scored: " ++ error.errorString);+ };+ };+ };+};+`;++const RENDER_ERROR_RE = /^PORTOS_RENDER_ERROR (syntax|source|pattern|score|synthesis): (.*)$/;+const SCLANG_DIAGNOSTIC_RE = /^ERROR:|^\s*line \d+ char \d+/;+export const SUPERCOLLIDER_RENDER_ERROR_CODES = Object.freeze({+ syntax: 'SUPERCOLLIDER_SYNTAX_ERROR',+ source: 'SUPERCOLLIDER_SOURCE_ERROR',+ pattern: 'SUPERCOLLIDER_NOT_A_PATTERN',+ score: 'SUPERCOLLIDER_SCORE_ERROR',+ synthesis: 'SUPERCOLLIDER_SYNTHESIS_FAILED',+});++/** Is this sclang output line one the failure classifier reads? (Lets the runner keep only those.) */+export const isSuperColliderDiagnosticLine = (line) => RENDER_ERROR_RE.test(line) || SCLANG_DIAGNOSTIC_RE.test(line);++/**+ * Classify a failed render from the wrapper's output: the LAST+ * `PORTOS_RENDER_ERROR` marker names the kind, and sclang's own `ERROR:` /+ * `line N char M` lines are the detail (where a syntax error is). Null when the+ * wrapper never reported (crash, kill, timeout).+ * @param {string[]} lines+ * @returns {{ kind: string, code: string, message: string, detail: string } | null}+ */+export function classifySuperColliderRenderLog(lines) {+ let marker = null;+ const detail = [];+ for (const line of lines) {+ const match = RENDER_ERROR_RE.exec(line);+ if (match) marker = { kind: match[1], message: match[2] };+ else if (SCLANG_DIAGNOSTIC_RE.test(line) && detail.length < 4) detail.push(line.trim());+ }+ if (!marker) return null;+ return { ...marker, code: SUPERCOLLIDER_RENDER_ERROR_CODES[marker.kind], detail: detail.join(' ') };+}++/**+ * Parse `docker ps --format '{{json .}}'` (one object per line) into+ * `[{ name, createdAtMs }]`; `createdAtMs` is null when docker's+ * `2006-01-02 15:04:05 -0700 MST` timestamp cannot be read, so a caller can+ * refuse to judge that container's age.+ */+export function parseDockerContainerList(stdout) {+ return String(stdout || '').split('\n').flatMap((line) => {+ let row;+ try { row = JSON.parse(line); } catch { return []; }+ const name = String(row?.Names ?? '').split(',')[0].trim();+ if (!name) return [];+ const stamp = /^(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})(?:\.\d+)? ([+-])(\d{2})(\d{2})\b/.exec(String(row?.CreatedAt ?? ''));+ const createdAtMs = stamp ? Date.parse(`${stamp[1]}T${stamp[2]}${stamp[3]}${stamp[4]}:${stamp[5]}`) : NaN;+ return [{ name, createdAtMs: Number.isFinite(createdAtMs) ? createdAtMs : null }];+ });+}+/** Does recorded evidence describe THIS runtime, policy and image? */function isSuperColliderEvidenceCurrent(evidence, image) {return Boolean(evidence && image?.iddiff --git a/server/routes/superCollider.js b/server/routes/superCollider.jsnew file mode 100644index 0000000000..965ba04eda--- /dev/null+++ b/server/routes/superCollider.js@@ -0,0 +1,101 @@+/**+ * Music Designer SuperCollider runtime and renders (#9413, epic #9407).+ *+ * GET /api/music/supercollider/status → readiness verdict (never builds or renders)+ * POST /api/music/supercollider/setup → SSE: build/verify the managed image (explicit action)+ * POST /api/music/supercollider/render → { jobId, position, status } (202, media queue)+ * GET /api/music/supercollider/renders/:jobId/events → SSE progress (shared media-queue stream)+ * POST /api/music/supercollider/renders/:jobId/cancel → cancel; the container is force-removed+ * GET /api/music/supercollider/renders/:jobId/audio → the validated preview WAV+ *+ * Source runs only inside the contained runtime (services/superColliderRender.js);+ * nothing here calls an AI provider, and setup/render each need the user's request.+ */++import { Router } from 'express';+import { randomInt } from 'crypto';+import { z } from 'zod';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import { openSseStream } from '../lib/sseDownload.js';+import { SUPERCOLLIDER_RENDER } from '../lib/superColliderRuntime.js';+import { MUSIC_CODE_MAX } from '../services/musicCode.js';+import { getSuperColliderStatus, setupSuperColliderRuntime } from '../services/superColliderRuntime.js';+import { readSuperColliderPreview, superColliderSourceHash } from '../services/superColliderRender.js';+import { attachSseClient, cancelJob, enqueueJob, getJob } from '../services/mediaJobQueue/index.js';++const router = Router();++router.get('/status', asyncHandler(async (_req, res) => {+ res.json(await getSuperColliderStatus());+}));++const setupSchema = z.object({ rebuild: z.boolean().optional().default(false) });++// The build compiles SuperCollider from source (10–30 minutes on first run), so+// progress streams as SSE log lines. Concurrent requests share one run, and the+// run continues if the browser leaves — closing the page does not abort a+// half-built image.+router.post('/setup', asyncHandler(async (req, res) => {+ const { rebuild } = validateRequest(setupSchema, req.body ?? {});+ const { send, safeEnd } = openSseStream(res);+ send({ type: 'log', message: rebuild ? 'Rebuilding the SuperCollider runtime' : 'Setting up the SuperCollider runtime' });+ const result = await setupSuperColliderRuntime({ rebuild, onLine: (line) => send({ type: 'log', message: line }) })+ .catch((err) => ({ outcome: 'error', error: err.message, status: null }));+ send(result.outcome === 'ready'+ ? { type: 'complete', status: result.status, built: result.built, probed: result.probed }+ : { type: 'error', outcome: result.outcome, message: result.error || result.status?.message || 'SuperCollider setup failed', status: result.status });+ safeEnd();+}));++const renderSchema = z.object({+ code: z.string().max(MUSIC_CODE_MAX).refine((code) => code.trim().length > 0, 'code is required'),+ durationSec: z.number().int().min(SUPERCOLLIDER_RENDER.minDurationSec).max(SUPERCOLLIDER_RENDER.maxDurationSec),+ seed: z.number().int().min(0).max(SUPERCOLLIDER_RENDER.maxSeed).optional(),+}).strict();++// Refuse up front when the runtime is not ready, so the user is told what to+// set up instead of queuing a job that can only fail. The job still re-checks+// at dispatch: readiness can change while it waits.+router.post('/render', asyncHandler(async (req, res) => {+ const { code, durationSec, seed } = validateRequest(renderSchema, req.body ?? {});+ const status = await getSuperColliderStatus();+ if (!status.ready) {+ throw new ServerError(`SuperCollider is not available: ${status.message}`, {+ status: 409, code: 'SUPERCOLLIDER_UNAVAILABLE', context: { state: status.state, action: status.action },+ });+ }+ // The job carries its own frozen copy of the source; an explicit seed (or+ // a fresh one) makes the render's randomness part of its provenance.+ const params = { source: code, sourceHash: superColliderSourceHash(code), durationSec, seed: seed ?? randomInt(SUPERCOLLIDER_RENDER.maxSeed) };+ res.status(202).json({ ...await enqueueJob({ kind: 'supercollider', params }), seed: params.seed, sourceHash: params.sourceHash });+}));++const renderJob = (jobId) => {+ const job = getJob(jobId);+ if (job?.kind !== 'supercollider') throw new ServerError('SuperCollider render not found', { status: 404, code: 'NOT_FOUND' });+ return job;+};++router.get('/renders/:jobId/events', (req, res) => {+ renderJob(req.params.jobId);+ if (!attachSseClient(req.params.jobId, res)) throw new ServerError('SuperCollider render not found', { status: 404, code: 'NOT_FOUND' });+});++router.post('/renders/:jobId/cancel', asyncHandler(async (req, res) => {+ renderJob(req.params.jobId);+ const result = await cancelJob(req.params.jobId);+ if (!result.ok) throw new ServerError(result.error, { status: result.code === 'NOT_FOUND' ? 404 : 409, code: result.code });+ res.json(result);+}));++// Served from the host-written preview store only after the render passed+// validation; a failed or canceled render never has one.+router.get('/renders/:jobId/audio', asyncHandler(async (req, res) => {+ const found = await readSuperColliderPreview(req.params.jobId);+ if (!found) throw new ServerError('Preview not found or expired', { status: 404, code: 'NOT_FOUND' });+ res.type('audio/wav');+ res.sendFile(found.wavPath, { dotfiles: 'deny', headers: { 'Cache-Control': 'private, max-age=3600' } });+}));++export default router;diff --git a/server/routes/superCollider.test.js b/server/routes/superCollider.test.jsnew file mode 100644index 0000000000..9cfcc358f1--- /dev/null+++ b/server/routes/superCollider.test.js@@ -0,0 +1,132 @@+import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { mkdtempSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { cancelJob, enqueueJob, getJob } from '../services/mediaJobQueue/index.js';+import { getSuperColliderStatus, setupSuperColliderRuntime } from '../services/superColliderRuntime.js';+import { readSuperColliderPreview } from '../services/superColliderRender.js';+import router from './superCollider.js';++vi.mock('../services/mediaJobQueue/index.js', () => ({+ enqueueJob: vi.fn(async () => ({ jobId: 'job-1', position: 1, status: 'queued' })),+ getJob: vi.fn(() => null),+ cancelJob: vi.fn(),+ attachSseClient: vi.fn(() => false),+}));+vi.mock('../services/superColliderRuntime.js', () => ({+ getSuperColliderStatus: vi.fn(),+ setupSuperColliderRuntime: vi.fn(),+}));+vi.mock('../services/superColliderRender.js', async (importOriginal) => ({+ ...await importOriginal(),+ readSuperColliderPreview: vi.fn(async () => null),+}));++const app = express();+app.use(express.json());+app.use('/api/music/supercollider', router);+app.use(errorMiddleware);++const READY = { state: 'ready', ready: true, message: 'ready', action: null };+const SOURCE = 'Pbind(\\degree, Pseq([0, 2, 4], inf), \\dur, 0.5)';+const scratch = mkdtempSync(join(tmpdir(), 'portos-sc-route-'));+afterAll(() => rmSync(scratch, { recursive: true, force: true }));++beforeEach(() => {+ vi.clearAllMocks();+ getSuperColliderStatus.mockResolvedValue(READY);+});++describe('POST /api/music/supercollider/render', () => {+ it('queues a job carrying a frozen copy of the source, its hash and an explicit seed', async () => {+ const res = await request(app).post('/api/music/supercollider/render').send({ code: SOURCE, durationSec: 30, seed: 7 });+ expect(res.status).toBe(202);+ expect(res.body).toMatchObject({ jobId: 'job-1', status: 'queued', seed: 7 });+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'supercollider', params: {+ source: SOURCE, sourceHash: res.body.sourceHash, durationSec: 30, seed: 7,+ } });+ expect(res.body.sourceHash).toMatch(/^[0-9a-f]{64}$/);+ });++ it('picks a seed when none is given so the render stays reproducible', async () => {+ const res = await request(app).post('/api/music/supercollider/render').send({ code: SOURCE, durationSec: 4 });+ expect(res.status).toBe(202);+ expect(Number.isInteger(res.body.seed)).toBe(true);+ expect(enqueueJob.mock.calls[0][0].params.seed).toBe(res.body.seed);+ });++ it.each([+ ['a duration under the take window', { code: SOURCE, durationSec: 3 }],+ ['a duration over the take window', { code: SOURCE, durationSec: 121 }],+ ['a fractional duration', { code: SOURCE, durationSec: 10.5 }],+ ['empty source', { code: ' ', durationSec: 10 }],+ ['oversized source', { code: 'x'.repeat(20001), durationSec: 10 }],+ // Paths and format belong to the trusted runner; the request cannot name them.+ ['a caller-chosen output path', { code: SOURCE, durationSec: 10, outputPath: '/etc/passwd' }],+ ])('rejects %s', async (_label, body) => {+ const res = await request(app).post('/api/music/supercollider/render').send(body);+ expect(res.status).toBe(400);+ expect(enqueueJob).not.toHaveBeenCalled();+ });++ it('refuses with the setup action instead of queuing when the runtime is not ready', async () => {+ getSuperColliderStatus.mockResolvedValue({ state: 'docker-stopped', ready: false, message: 'Docker is installed but its engine is not reachable.', action: 'Start Docker' });+ const res = await request(app).post('/api/music/supercollider/render').send({ code: SOURCE, durationSec: 10 });+ expect(res.status).toBe(409);+ expect(res.body).toMatchObject({ code: 'SUPERCOLLIDER_UNAVAILABLE', context: { state: 'docker-stopped', action: 'Start Docker' } });+ expect(enqueueJob).not.toHaveBeenCalled();+ });+});++describe('SuperCollider render jobs', () => {+ it('cancels only SuperCollider jobs, and reports a finished one as a conflict', async () => {+ getJob.mockReturnValue({ id: 'job-1', kind: 'video' });+ expect((await request(app).post('/api/music/supercollider/renders/job-1/cancel')).status).toBe(404);+ expect(cancelJob).not.toHaveBeenCalled();++ getJob.mockReturnValue({ id: 'job-1', kind: 'supercollider' });+ cancelJob.mockResolvedValueOnce({ ok: true, status: 'canceling' });+ const canceling = await request(app).post('/api/music/supercollider/renders/job-1/cancel');+ expect(canceling.body).toEqual({ ok: true, status: 'canceling' });++ cancelJob.mockResolvedValueOnce({ ok: false, code: 'ALREADY_TERMINAL', status: 'completed', error: 'Job is already completed' });+ expect((await request(app).post('/api/music/supercollider/renders/job-1/cancel')).status).toBe(409);+ });++ it('serves a validated preview as WAV and 404s one that never passed', async () => {+ expect((await request(app).get('/api/music/supercollider/renders/job-1/audio')).status).toBe(404);++ const wavPath = join(scratch, 'job-1.wav');+ writeFileSync(wavPath, Buffer.from('RIFF----WAVE'));+ readSuperColliderPreview.mockResolvedValueOnce({ wavPath, preview: { jobId: 'job-1' } });+ const res = await request(app).get('/api/music/supercollider/renders/job-1/audio');+ expect(res.status).toBe(200);+ expect(res.headers['content-type']).toMatch(/^audio\/wav/);+ });+});++describe('POST /api/music/supercollider/setup', () => {+ const frames = (text) => text.split('\n\n').filter(Boolean).map((frame) => JSON.parse(frame.replace(/^data: /, '')));++ it('streams setup output and finishes with the ready status', async () => {+ setupSuperColliderRuntime.mockImplementation(async ({ onLine }) => {+ onLine('Step 1/9 : FROM debian');+ return { outcome: 'ready', built: true, probed: true, status: READY };+ });+ const res = await request(app).post('/api/music/supercollider/setup').send({ rebuild: true });+ expect(setupSuperColliderRuntime).toHaveBeenCalledWith(expect.objectContaining({ rebuild: true }));+ const events = frames(res.text);+ expect(events).toContainEqual({ type: 'log', message: 'Step 1/9 : FROM debian' });+ expect(events.at(-1)).toMatchObject({ type: 'complete', built: true, status: { state: 'ready' } });+ });++ it('ends with an actionable error, never readiness, when Docker is unavailable', async () => {+ const status = { state: 'docker-missing', ready: false, message: 'Docker is not installed.', action: 'Install Docker' };+ setupSuperColliderRuntime.mockResolvedValue({ outcome: 'docker-unavailable', error: null, status });+ const res = await request(app).post('/api/music/supercollider/setup').send({});+ expect(frames(res.text).at(-1)).toMatchObject({ type: 'error', outcome: 'docker-unavailable', message: 'Docker is not installed.', status });+ });+});diff --git a/server/services/README.md b/server/services/README.mdindex 633268d5f2..ff60b04ea9 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -13,6 +13,7 @@ image-generation paths below are useful entry points when tracing render jobs.| `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. || `imageGen/index.js` | Mode-aware image backend dispatcher and shared image-generation helpers. Direct queue consumers still resolve local model identity before enqueueing. || `superColliderRuntime.js` | Managed SuperCollider runtime I/O (#9412): Docker probe, recipe-hash-stamped image build, `runSuperColliderContainer` (contained `sclang` run with forced container removal), the synthetic render probe and its cached evidence, `getSuperColliderStatus` and idempotent `setupSuperColliderRuntime`. Never runs at boot. |+| `superColliderRender.js` | Contained SuperCollider renders (#9413): media-queue `supercollider` jobs that snapshot source into a job-private dir, run the trusted NRT wrapper via `runSuperColliderContainer` (output quota, timeout, cancel → container force-removed), validate the decoded WAV and publish a 24 h preview + provenance sidecar (`readSuperColliderPreview`). Sweeps orphaned containers/scratch before each render. || `universeBuilderRender.js` | Universe Builder batch render jobs. || `pipeline/visualStageHelpers.js` | Shared pipeline visual prompt, LoRA compatibility, and image-job enqueue helpers. || `creativeStyleSources.js` | Resolves a universe style guide or mood board into art-direction text plus local reference images; shared by Code Animation and Creative Commissions. |diff --git a/server/services/backup.js b/server/services/backup.jsindex df4eb71ca1..93cb376d67 100644--- a/server/services/backup.js+++ b/server/services/backup.js@@ -185,7 +185,7 @@ export const DEFAULT_EXCLUDES = [// Anchored, like every entry here. Readiness evidence is bound to THIS// machine's local image id (a restored copy would read as stale anyway) and// the rest is in-flight render scratch; setup re-derives all of it.- { path: '/supercollider/', reason: 'SuperCollider runtime readiness evidence and in-flight render scratch — machine-local, re-derived by npm run setup:supercollider', overridable: false },+ { path: '/supercollider/', reason: 'SuperCollider runtime readiness evidence, in-flight render scratch and 24-hour render previews — machine-local, re-derived by npm run setup:supercollider', overridable: false },// Sprite animation-run raw intermediates: 30–96 ffmpeg-extracted PNGs per// run, byte-for-byte regenerable from the archived source video by the// deterministic postprocess (walkPostprocess.js). The source video, packageddiff --git a/server/services/dataManager.js b/server/services/dataManager.jsindex abbff08d99..5c8ba5e8ac 100644--- a/server/services/dataManager.js+++ b/server/services/dataManager.js@@ -171,7 +171,7 @@ export const CATEGORIES = {'spotify': { label: 'Spotify Sync', description: 'Machine-local Spotify sync cursor and cache — purging resets the cursor and can leave a gap in imported history', archivable: true, deletable: false },'sprites': { label: 'Sprites', description: 'Sprite reference art, walk frames, and runtime atlases — the only copy of the generated art; records live in Postgres', archivable: false, deletable: false },'story-builder': { label: 'Story Builder', description: 'Story Builder project records', archivable: true, deletable: false },- 'supercollider': { label: 'SuperCollider Runtime', description: 'Machine-local readiness evidence for the managed SuperCollider image and in-flight render scratch — re-created by npm run setup:supercollider, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },+ 'supercollider': { label: 'SuperCollider Runtime', description: 'Machine-local readiness evidence for the managed SuperCollider image, in-flight render scratch and 24-hour render previews — re-created by npm run setup:supercollider, safe to purge', archivable: false, deletable: true, purgeScope: 'category' },'telegram': { label: 'Telegram', description: 'Telegram bot data', archivable: true, deletable: true, purgeScope: 'category' },'templates': { label: 'Visual Templates', description: 'Shipped layout assets used as render anchors', archivable: false, deletable: false },'tools': { label: 'Tools', description: 'Tool execution data', archivable: true, deletable: true, purgeScope: 'category' },diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.jsindex 0885348aee..ea1c9c7161 100644--- a/server/services/mediaJobQueue/index.js+++ b/server/services/mediaJobQueue/index.js@@ -170,7 +170,9 @@ async function safeUnlinkUpload(path) {// KNOWN_MEDIA_KINDS in federatedMedia/) are closed lists that do not name it,// so shipping a user's source video across the wire would take a deliberate// edit to one of them rather than a mode string slipping through.-export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'html-composition', 'image', 'training', 'audio']);+// 'supercollider' (#9413) is likewise local-only: it executes untrusted source+// inside this machine's verified container, so no peer map names it.+export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'html-composition', 'image', 'training', 'audio', 'supercollider']);export const JOB_STATUSES = Object.freeze(['queued', 'running', 'completed', 'failed', 'canceled']);// Returns a Promise that resolves to the gen module for the given job's@@ -191,6 +193,7 @@ function getGenModuleForJob(job) {if (job.kind === 'video') return import('../videoGen/local.js');if (job.kind === 'training') return import('../loraTraining/index.js');if (job.kind === 'audio') return import('../audioGen/local.js');+ if (job.kind === 'supercollider') return import('../superColliderRender.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.CODEX) return import('../imageGen/codex.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../imageGen/grok.js');if (job.kind === 'image' && job.params?.mode === IMAGE_GEN_MODE.AGY) return import('../imageGen/agy.js');@@ -1173,7 +1176,7 @@ async function runJobLifecycle(job, markDispatched) {const emitter = job.kind === 'video' || job.kind === 'video-upscale' || job.kind === 'html-composition' ? videoGenEvents: job.kind === 'training' ? trainingEvents- : job.kind === 'audio' ? audioGenEvents+ : job.kind === 'audio' || job.kind === 'supercollider' ? audioGenEvents: imageGenEvents;const dispatcher = makeGenDispatcher(emitter, job, handlers);dispatcher.attach();@@ -1288,6 +1291,7 @@ async function runJobLifecycle(job, markDispatched) {: job.kind === 'video-upscale' ? mod.runVideoUpscale(request): job.kind === 'training' ? mod.runTraining(request): job.kind === 'audio' ? mod.generateAudio(request)+ : job.kind === 'supercollider' ? mod.renderSuperCollider(request): mod.generateImage(request);markDispatched();await kickoff;diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.jsindex 9b64f876ad..c79a1ae210 100644--- a/server/services/mediaJobQueue/index.test.js+++ b/server/services/mediaJobQueue/index.test.js@@ -84,6 +84,8 @@ const stubs = {cancelVideoUpscale: vi.fn(),renderComposition: vi.fn(async () => ({})),cancelComposition: vi.fn(),+ renderSuperCollider: vi.fn(() => new Promise(() => {})),+ cancelSuperCollider: vi.fn(() => true),};vi.mock('../musicVideo/revisionService.js', () => ({ assertPerformanceRepairDispatch: vi.fn().mockResolvedValue(undefined) }));@@ -104,6 +106,11 @@ vi.mock('../htmlComposition/index.js', () => ({cancel: (...args) => stubs.cancelComposition(...args),}));+vi.mock('../superColliderRender.js', () => ({+ renderSuperCollider: (...args) => stubs.renderSuperCollider(...args),+ cancel: (...args) => stubs.cancelSuperCollider(...args),+}));+vi.mock('../videoGen/upscaleJob.js', () => ({runVideoUpscale: (...args) => stubs.runVideoUpscale(...args),cancel: (...args) => stubs.cancelVideoUpscale(...args),@@ -279,6 +286,22 @@ describe('mediaJobQueue', () => {await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'canceled');});+ // SuperCollider renders (#9413) are local-only audio jobs: progress rides the+ // audio bus, and a cancel reaches the render module so it can remove the container.+ it('dispatches SuperCollider renders locally with their frozen source and cancels through the render module', async () => {+ const params = { source: 'Pbind(\\dur, 1)', sourceHash: 'a'.repeat(64), durationSec: 8, seed: 7 };+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'supercollider', params });+ await waitFor(() => stubs.renderSuperCollider.mock.calls.length === 1);+ expect(stubs.renderSuperCollider).toHaveBeenCalledWith(expect.objectContaining({ ...params, jobId }));+ expect(mediaJobQueue.isRemoteMediaJob(mediaJobQueue.getJob(jobId))).toBe(false);+ audioGenEvents.emit('progress', { generationId: jobId, progress: 0.5, message: 'Rendering the SuperCollider score' });+ expect(mediaJobQueue.getJob(jobId)).toMatchObject({ progress: 0.5, statusMsg: 'Rendering the SuperCollider score' });+ expect(await mediaJobQueue.cancelJob(jobId)).toMatchObject({ ok: true, status: 'canceling' });+ expect(stubs.cancelSuperCollider).toHaveBeenCalledWith(jobId);+ audioGenEvents.emit('failed', { generationId: jobId, error: 'Render canceled' });+ await waitFor(() => mediaJobQueue.getJob(jobId)?.status === 'canceled');+ });+describe('video-upscale kind', () => {const upscaleParams = { historyId: 'src-1', sourceFilename: 'src-1.mp4', runtime: 'ltx25', seed: 7 };diff --git a/server/services/musicCode.js b/server/services/musicCode.jsindex 92b4263681..b5c1102dd6 100644--- a/server/services/musicCode.js+++ b/server/services/musicCode.js@@ -99,9 +99,9 @@ function buildSupercolliderPrompt({ description, lyrics, guidance, current }) {}Return ONLY the sclang code: no prose and no markdown fence. Rules for the code:-- Define instruments with SynthDef(\\name, { |out=0, freq=440, amp=0.2, gate=1| ... }) using ONLY stock UGens (SinOsc, Saw, Pulse, LFTri, WhiteNoise, PinkNoise, RLPF, RHPF, LPF, HPF, EnvGen, Env, Pan2, FreeVerb, CombL, Splay, Mix, ...), and finish each with Out.ar(out, signal) in stereo.-- Compose with Pbind/Pseq/Prand/Pwhite/Pn/Ppar patterns on those SynthDefs, using \\dur, \\degree or \\note, \\scale, \\octave and \\amp. Express timing in beats via \\dur; the runner fixes the tempo at 120 BPM.-- The runner turns your patterns into a bounded offline score (it supplies the length, 48 kHz stereo, and the output file). Do NOT call s.boot, s.record, Server.default, Score.recordNRT, play, or write any file path.+- Define instruments with SynthDef(\\name, { |out=0, freq=440, amp=0.2, gate=1| ... }) using ONLY stock UGens (SinOsc, Saw, Pulse, LFTri, WhiteNoise, PinkNoise, RLPF, RHPF, LPF, HPF, EnvGen, Env, Pan2, FreeVerb, CombL, Splay, Mix, ...), finish each with Out.ar(out, signal) in stereo, and register it with .add (e.g. SynthDef(\\lead, { ... }).add;). Give every sustained instrument an envelope that frees it (doneAction: 2), gated by gate when it has one.+- Compose with Pbind/Pseq/Prand/Pwhite/Pn/Ppar patterns on those SynthDefs, using \\dur, \\degree or \\note, \\scale, \\octave and \\amp. Express timing in beats via \\dur; the runner fixes the tempo at 120 BPM. Use finite or long-running patterns; the runner cuts the piece at its length.+- The runner turns your patterns into a bounded offline score (it supplies the length, 48 kHz stereo, and the output file). The LAST expression of the code must be ONE pattern (usually Ppar([...]) layering the parts); the runner renders that value. Do NOT call s.boot, s.record, Server.default, Score.recordNRT, play, or write any file path.- NEVER use unixCmd, unixCmdGetStdOut, systemCmd, String.runInTerminal, File, Pipe, Document, thisProcess.interpreter.executeFile, load, loadRelative, include, Quarks, SoundFile, Buffer.read or any sample/URL/path loading: there is no filesystem or network access and no sample files, so they always fail.- Keep levels sensible (per-voice amp around 0.05-0.3) so a full mix does not clip.diff --git a/server/services/superColliderRender.js b/server/services/superColliderRender.jsnew file mode 100644index 0000000000..f2203c48b0--- /dev/null+++ b/server/services/superColliderRender.js@@ -0,0 +1,375 @@+/**+ * Contained SuperCollider renders for the Music Designer (#9413, epic #9407).+ *+ * One render = one media-queue job of kind `supercollider`. The job's params+ * carry the frozen source text, so every job (a retry included) writes its own+ * snapshot into a job-private directory:+ *+ * data/supercollider/jobs/<jobId>/in/ source.scd + the trusted wrapper (mounted read-only)+ * data/supercollider/jobs/<jobId>/out/ the only writable mount+ *+ * The wrapper (`SUPERCOLLIDER_RENDER_WRAPPER_SOURCE`) scores the source's+ * pattern for the requested duration and renders it offline through+ * `runSuperColliderContainer`, i.e. under the same containment policy the+ * readiness probe proved. The container is force-removed on success, failure,+ * timeout and cancel. The host then reads back ONE regular file within a size+ * bound and judges it by its decoded samples (format, duration, finite,+ * non-silent) before anything is published. A passing render lands as a+ * preview — `data/supercollider/previews/<jobId>.wav` plus a provenance+ * sidecar — and the job directory is always removed. Previews never touch a+ * track; saving one as a take is a separate explicit action.+ *+ * Machine-local and ephemeral (docs/STORAGE.md): previews expire after+ * PREVIEW_TTL_MS, and each render first sweeps stale job scratch and orphaned+ * render containers (a server restart mid-render leaves both behind).+ *+ * Nothing here runs at boot or calls an AI provider: a render starts only from+ * the user's explicit Render request.+ */++import { createHash } from 'crypto';+import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'fs/promises';+import { join } from 'path';+import { ServerError } from '../lib/errorHandler.js';+import { PATHS } from '../lib/paths.js';+import { measureWavAudio } from '../lib/wavAudioFile.js';+import {+ SUPERCOLLIDER_CONTAINER_LABEL,+ SUPERCOLLIDER_CONTAINER_LIMITS,+ SUPERCOLLIDER_CONTAINER_PATHS,+ SUPERCOLLIDER_POLICY_VERSION,+ SUPERCOLLIDER_RENDER,+ SUPERCOLLIDER_RENDER_FORMAT,+ SUPERCOLLIDER_RENDER_WRAPPER_SOURCE,+ SUPERCOLLIDER_RUNTIME_VERSION,+ classifySuperColliderRenderLog,+ isSuperColliderDiagnosticLine,+ parseDockerContainerList,+ superColliderSmokeFailure,+} from '../lib/superColliderRuntime.js';+import { getSuperColliderStatus, readContainedOutput, resolveDockerCli, runSuperColliderContainer } from './superColliderRuntime.js';+import { audioGenEvents } from './audioGen/events.js';++const PREVIEW_TTL_MS = 24 * 60 * 60 * 1000;+// A job directory older than the wall limit plus slack cannot belong to a live+// run (every run is killed at the wall limit), whichever process started it.+const STALE_SCRATCH_MS = SUPERCOLLIDER_CONTAINER_LIMITS.wallTimeoutMs + 5 * 60_000;+const QUOTA_CHECK_MS = 1_000;+const MAX_OUTPUT_ENTRIES = 32;+const MAX_DIAGNOSTIC_LINES = 50;+const MAX_ERROR_CHARS = 600;+const JOB_ID_RE = /^[A-Za-z0-9][A-Za-z0-9-]{0,79}$/;++/** In-flight renders by job id: `{ controller, committing }`. */+const active = new Map();++const sha256 = (text) => createHash('sha256').update(text).digest('hex');+const clip = (text) => {+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim();+ return flat.length > MAX_ERROR_CHARS ? `${flat.slice(0, MAX_ERROR_CHARS)}…` : flat;+};+const renderError = (message, code, status = 422) => new ServerError(clip(message), { status, code });++/** Bytes a valid float32 stereo render of `durationSec` occupies, plus header slack. */+const expectedWavBytes = (durationSec) => Math.ceil(durationSec * SUPERCOLLIDER_RENDER_FORMAT.sampleRate)+ * SUPERCOLLIDER_RENDER_FORMAT.channels * 4 + 64 * 1024;++export const superColliderSourceHash = (source) => sha256(String(source));++function resolveDirs(dataDir = PATHS.data) {+ const root = join(dataDir, 'supercollider');+ return { root, jobs: join(root, 'jobs'), previews: join(root, 'previews') };+}++const assertJobId = (jobId) => {+ if (!JOB_ID_RE.test(String(jobId ?? ''))) throw new ServerError('Invalid render id', { status: 400, code: 'VALIDATION_ERROR' });+};++/** Total bytes and entry count under `dir`, never following a symlink. */+async function measureTree(dir) {+ let bytes = 0;+ let entries = 0;+ const pending = [dir];+ while (pending.length) {+ const current = pending.pop();+ const names = await readdir(current).catch(() => []);+ for (const name of names) {+ entries += 1;+ if (entries > MAX_OUTPUT_ENTRIES) return { bytes, entries };+ const info = await lstat(join(current, name)).catch(() => null);+ if (info?.isDirectory()) pending.push(join(current, name));+ else if (info) bytes += info.size;+ }+ }+ return { bytes, entries };+}++/**+ * Remove render containers that outlived any possible run (a restart killed the+ * server mid-render, so nothing force-removed them). Age-gated, so a render or+ * setup probe started by another process on this machine is left alone.+ */+async function sweepOrphanContainers(docker, now = Date.now()) {+ const listed = await docker.capture(['ps', '--all', '--filter', `label=${SUPERCOLLIDER_CONTAINER_LABEL}=1`, '--format', '{{json .}}']);+ if (!listed.success) return 0;+ const orphans = parseDockerContainerList(listed.stdout)+ .filter(({ createdAtMs }) => createdAtMs !== null && now - createdAtMs > STALE_SCRATCH_MS);+ for (const { name } of orphans) {+ await docker.capture(['rm', '--force', name]);+ console.warn(`🧹 Removed orphaned SuperCollider render container ${name}`);+ }+ return orphans.length;+}++/** Drop job scratch no live render owns and previews past their TTL. */+async function sweepLocalArtifacts(dirs, now = Date.now()) {+ for (const name of await readdir(dirs.jobs).catch(() => [])) {+ if (active.has(name)) continue;+ const info = await lstat(join(dirs.jobs, name)).catch(() => null);+ if (info && now - info.mtimeMs > STALE_SCRATCH_MS) await rm(join(dirs.jobs, name), { recursive: true, force: true });+ }+ for (const name of await readdir(dirs.previews).catch(() => [])) {+ const info = await lstat(join(dirs.previews, name)).catch(() => null);+ if (info && now - info.mtimeMs > PREVIEW_TTL_MS) await rm(join(dirs.previews, name), { force: true });+ }+}++/**+ * Render one SuperCollider source to a preview WAV inside a disposable+ * container. Resolves the preview record; throws a ServerError (with a+ * `SUPERCOLLIDER_*` code) for an unavailable runtime, a source error, a+ * timeout, a cancellation or output that fails validation. Every path leaves+ * no job scratch behind, and only a passing render leaves a preview.+ *+ * @param {object} params+ * @param {string} params.jobId - names the job directory and the preview+ * @param {string} params.source - the frozen SuperCollider source+ * @param {number} params.durationSec - SUPERCOLLIDER_RENDER bounds+ * @param {number} params.seed+ * @param {AbortSignal} [params.signal]+ * @param {(event: {phase: string, message: string, progress?: number}) => void} [params.onPhase]+ * @param {object} [params.docker] - docker CLI adapter (tests); resolved when omitted+ * @param {string} [params.dataDir]+ * @param {number} [params.timeoutMs]+ */+export async function renderSuperColliderSource({+ jobId, source, durationSec, seed, signal, onPhase = () => {}, onActivity = () => {},+ docker: injectedDocker, dataDir = PATHS.data, timeoutMs = SUPERCOLLIDER_CONTAINER_LIMITS.wallTimeoutMs,+}) {+ assertJobId(jobId);+ if (typeof source !== 'string' || !source.trim()) throw renderError('The SuperCollider source is empty', 'VALIDATION_ERROR', 400);+ if (!Number.isFinite(durationSec) || durationSec < SUPERCOLLIDER_RENDER.minDurationSec || durationSec > SUPERCOLLIDER_RENDER.maxDurationSec) {+ throw renderError(`Duration must be ${SUPERCOLLIDER_RENDER.minDurationSec}–${SUPERCOLLIDER_RENDER.maxDurationSec} seconds`, 'VALIDATION_ERROR', 400);+ }+ if (!Number.isInteger(seed) || seed < 0 || seed > SUPERCOLLIDER_RENDER.maxSeed) throw renderError('Seed must be a non-negative 32-bit integer', 'VALIDATION_ERROR', 400);++ const docker = injectedDocker === undefined ? await resolveDockerCli() : injectedDocker;+ const status = await getSuperColliderStatus({ docker, dataDir });+ if (!status.ready) {+ throw new ServerError(`SuperCollider is not available: ${status.message}`, {+ status: 409, code: 'SUPERCOLLIDER_UNAVAILABLE', context: { state: status.state, action: status.action },+ });+ }++ const dirs = resolveDirs(dataDir);+ await sweepOrphanContainers(docker).catch((err) => console.warn(`⚠️ SuperCollider orphan sweep skipped: ${err.message}`));+ await sweepLocalArtifacts(dirs).catch((err) => console.warn(`⚠️ SuperCollider scratch sweep skipped: ${err.message}`));++ const jobDir = join(dirs.jobs, jobId);+ const inputDir = join(jobDir, 'in');+ const outputDir = join(jobDir, 'out');+ const sourceHash = superColliderSourceHash(source);+ const quota = {+ maxBytes: expectedWavBytes(durationSec) * 2 + 8 * 1024 * 1024,+ exceeded: null,+ };+ // One abort for both reasons the host stops a running container early: the+ // user canceled, or the output directory blew its quota.+ const stop = new AbortController();+ const forwardAbort = () => stop.abort();+ signal?.addEventListener('abort', forwardAbort, { once: true });+ if (signal?.aborted) stop.abort();+ const diagnostics = [];+ let quotaTimer = null;+ try {+ // Exclusive: two jobs can never share a directory, and a stale one with+ // this id (an earlier process's scratch) is replaced rather than reused.+ await rm(jobDir, { recursive: true, force: true });+ await mkdir(inputDir, { recursive: true });+ await mkdir(outputDir, { recursive: true });+ await writeFile(join(inputDir, SUPERCOLLIDER_RENDER.source), source, { flag: 'wx' });+ await writeFile(join(inputDir, SUPERCOLLIDER_RENDER.wrapper), SUPERCOLLIDER_RENDER_WRAPPER_SOURCE, { flag: 'wx' });+ if (stop.signal.aborted) throw renderError('Render canceled', 'SUPERCOLLIDER_CANCELED', 409);++ // The per-file size ulimit bounds one file; this bounds the directory, so+ // source that writes many files cannot fill the host disk. Checked on a+ // timer because the container, not this process, does the writing.+ quotaTimer = setInterval(() => {+ measureTree(outputDir).then(({ bytes, entries }) => {+ if (bytes > quota.maxBytes || entries > MAX_OUTPUT_ENTRIES) {+ quota.exceeded = `the render wrote ${entries > MAX_OUTPUT_ENTRIES ? `more than ${MAX_OUTPUT_ENTRIES} files` : `${bytes} bytes`}, over its output limit`;+ stop.abort();+ }+ }).catch((err) => console.warn(`⚠️ SuperCollider output check failed: ${err.message}`));+ }, QUOTA_CHECK_MS);+ quotaTimer.unref?.();++ onPhase({ phase: 'starting', message: 'Starting the SuperCollider container', progress: 0.05 });+ const { input, output } = SUPERCOLLIDER_CONTAINER_PATHS;+ const run = await runSuperColliderContainer({+ docker,+ image: status.image.id,+ inputDir,+ outputDir,+ script: SUPERCOLLIDER_RENDER.wrapper,+ scriptArgs: [+ `${input}/${SUPERCOLLIDER_RENDER.source}`,+ `${output}/${SUPERCOLLIDER_RENDER.output}`,+ durationSec,+ SUPERCOLLIDER_RENDER_FORMAT.sampleRate,+ seed,+ 60 / SUPERCOLLIDER_RENDER.tempoBpm,+ ],+ timeoutMs,+ signal: stop.signal,+ onLine: (line) => {+ onActivity();+ const phase = /^PORTOS_PHASE (\w+)$/.exec(line)?.[1];+ if (phase) {+ const progress = { compiling: 0.15, scoring: 0.3, rendering: 0.5 }[phase];+ onPhase({ phase, message: `${phase[0].toUpperCase()}${phase.slice(1)} the SuperCollider score`, ...(progress ? { progress } : {}) });+ } else if (isSuperColliderDiagnosticLine(line)) {+ diagnostics.push(line);+ if (diagnostics.length > MAX_DIAGNOSTIC_LINES) diagnostics.shift();+ }+ },+ });+ clearInterval(quotaTimer);+ quotaTimer = null;++ if (signal?.aborted || (run.cancelled && !quota.exceeded)) throw renderError('Render canceled', 'SUPERCOLLIDER_CANCELED', 409);+ if (quota.exceeded) throw renderError(`Render stopped: ${quota.exceeded}`, 'SUPERCOLLIDER_OUTPUT_QUOTA');+ if (run.timedOut) {+ throw renderError(`The SuperCollider render did not finish within ${Math.round(timeoutMs / 1000)}s and was stopped`, 'SUPERCOLLIDER_TIMEOUT', 504);+ }+ if (!run.ok) {+ const failure = classifySuperColliderRenderLog(diagnostics);+ if (failure) throw renderError(`${failure.message}${failure.detail ? ` (${failure.detail})` : ''}`, failure.code);+ throw renderError(`The SuperCollider render failed: ${run.error}`, 'SUPERCOLLIDER_RENDER_FAILED', 500);+ }++ onPhase({ phase: 'validating', message: 'Checking the rendered audio', progress: 0.9 });+ const tree = await measureTree(outputDir);+ if (tree.bytes > quota.maxBytes || tree.entries > MAX_OUTPUT_ENTRIES) {+ throw renderError('The render wrote more output than its limit allows', 'SUPERCOLLIDER_OUTPUT_QUOTA');+ }+ const wav = await readContainedOutput(outputDir, SUPERCOLLIDER_RENDER.output, { maxBytes: expectedWavBytes(durationSec) });+ const measurement = wav ? measureWavAudio(wav) : null;+ const invalid = superColliderSmokeFailure(measurement, { durationSec });+ if (invalid) throw renderError(`The rendered audio was rejected: ${invalid}`, 'SUPERCOLLIDER_OUTPUT_INVALID');++ if (stop.signal.aborted) throw renderError('Render canceled', 'SUPERCOLLIDER_CANCELED', 409);+ const job = active.get(jobId);+ if (job) job.committing = true;+ const preview = {+ jobId,+ createdAt: new Date().toISOString(),+ language: 'supercollider',+ source,+ sourceHash,+ seed,+ settings: {+ durationSec,+ sampleRate: SUPERCOLLIDER_RENDER_FORMAT.sampleRate,+ channels: SUPERCOLLIDER_RENDER_FORMAT.channels,+ tempoBpm: SUPERCOLLIDER_RENDER.tempoBpm,+ },+ runtime: { version: SUPERCOLLIDER_RUNTIME_VERSION, policyVersion: SUPERCOLLIDER_POLICY_VERSION, imageId: status.image.id },+ measurement: {+ durationMs: measurement.durationMs,+ channels: measurement.channels,+ sampleRate: measurement.sampleRate,+ peak: Number(measurement.peak.toFixed(4)),+ rms: Number(measurement.rms.toFixed(4)),+ },+ };+ await mkdir(dirs.previews, { recursive: true });+ // Audio first, sidecar last: a sidecar names a preview only once its audio is whole.+ const wavPath = join(dirs.previews, `${jobId}.wav`);+ await writeFile(`${wavPath}.partial`, wav);+ await rename(`${wavPath}.partial`, wavPath);+ const metaPath = join(dirs.previews, `${jobId}.json`);+ await writeFile(`${metaPath}.partial`, `${JSON.stringify(preview)}\n`);+ await rename(`${metaPath}.partial`, metaPath);+ console.log(`🎛️ SuperCollider render ${jobId.slice(0, 8)} passed (${measurement.durationMs} ms, peak ${preview.measurement.peak})`);+ return preview;+ } finally {+ if (quotaTimer) clearInterval(quotaTimer);+ signal?.removeEventListener('abort', forwardAbort);+ await rm(jobDir, { recursive: true, force: true })+ .catch((err) => console.error(`❌ SuperCollider job scratch ${jobId.slice(0, 8)} not removed: ${err.message}`));+ }+}++/** The public projection of a preview record (no source text: the client already holds it). */+export function presentSuperColliderPreview(preview) {+ const { source: _source, ...rest } = preview;+ return { ...rest, audioUrl: `/api/music/supercollider/renders/${encodeURIComponent(preview.jobId)}/audio` };+}++/**+ * Media-queue entry point for `kind: 'supercollider'` jobs: renders, then+ * announces the outcome on the audio event bus the queue listens to. Throws+ * on failure (the queue turns that into failed, or canceled after a cancel).+ */+export async function renderSuperCollider({ jobId, source, durationSec, seed }) {+ const job = { controller: new AbortController(), committing: false };+ active.set(jobId, job);+ let preview;+ try {+ preview = await renderSuperColliderSource({+ jobId,+ source,+ durationSec,+ seed,+ signal: job.controller.signal,+ onActivity: () => audioGenEvents.emit('activity', { generationId: jobId }),+ onPhase: ({ phase, message, progress }) => {+ if (typeof progress === 'number') audioGenEvents.emit('progress', { generationId: jobId, progress, message, phase });+ else audioGenEvents.emit('status', { generationId: jobId, message, phase });+ },+ });+ } finally {+ active.delete(jobId);+ }+ const result = { generationId: jobId, ...presentSuperColliderPreview(preview) };+ audioGenEvents.emit('completed', result);+ return result;+}++/** Cancel a running render; the container is force-removed by the runner. False once it is publishing. */+export function cancel(jobId) {+ const job = active.get(jobId);+ if (!job || job.committing) return false;+ job.controller.abort();+ return true;+}++/**+ * A finished preview: `{ wavPath, preview }`, or null when it never passed,+ * expired or the id is not one. The audio is only ever read back from the+ * host-written preview directory, never from a container's output.+ */+export async function readSuperColliderPreview(jobId, { dataDir = PATHS.data } = {}) {+ if (!JOB_ID_RE.test(String(jobId ?? ''))) return null;+ const { previews } = resolveDirs(dataDir);+ const wavPath = join(previews, `${jobId}.wav`);+ const [wavInfo, metaText] = await Promise.all([+ lstat(wavPath).catch(() => null),+ readFile(join(previews, `${jobId}.json`), 'utf8').catch(() => null),+ ]);+ if (!wavInfo?.isFile() || !metaText) return null;+ let preview;+ try { preview = JSON.parse(metaText); } catch { return null; }+ return preview?.jobId === jobId ? { wavPath, preview } : null;+}diff --git a/server/services/superColliderRender.live.test.js b/server/services/superColliderRender.live.test.jsnew file mode 100644index 0000000000..262744fa5f--- /dev/null+++ b/server/services/superColliderRender.live.test.js@@ -0,0 +1,137 @@+/**+ * LIVE containment evidence for SuperCollider renders (#9413): real Docker, the+ * real managed image, real sclang/scsynth. Opt-in, because it needs a machine+ * where `npm run setup:supercollider -- --yes` has passed and each case starts a+ * container:+ *+ * cd server && PORTOS_SUPERCOLLIDER_LIVE=1 npx vitest run services/superColliderRender.live.test.js+ *+ * With the flag set, an unready runtime FAILS (it never silently skips), so a+ * green run is evidence. Record the platform it ran on in epic #9407.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'fs';+import { createServer } from 'net';+import { tmpdir } from 'os';+import { join } from 'path';+import { PATHS } from '../lib/paths.js';+import { SUPERCOLLIDER_CONTAINER_LABEL } from '../lib/superColliderRuntime.js';+import { getSuperColliderStatus, resolveDockerCli } from './superColliderRuntime.js';+import { renderSuperColliderSource } from './superColliderRender.js';++const LIVE = process.env.PORTOS_SUPERCOLLIDER_LIVE === '1';++const STOCK_SOURCE = `SynthDef(\\pluck, { |out = 0, freq = 440, amp = 0.2|+ var env = EnvGen.kr(Env.perc(0.01, 0.4), doneAction: 2);+ Out.ar(out, Pan2.ar(Saw.ar(freq) * env * amp, 0));+}).add;+Ppar([+ Pbind(\\instrument, \\pluck, \\degree, Pseq([0, 2, 4, 7], inf), \\dur, 0.5, \\amp, 0.2),+ Pbind(\\degree, Pseq([0, -3], inf), \\octave, 3, \\dur, 2, \\amp, 0.15)+])`;+const INFINITE_SOURCE = 'inf.do { 1 + 1 };\nPbind(\\dur, 1)';++describe.skipIf(!LIVE)('SuperCollider renders under real containment', () => {+ let docker;+ let dataDir;+ let listener;+ let connections = 0;+ let seq = 0;+ const render = (overrides) => renderSuperColliderSource({ jobId: `live-${(seq += 1)}`, durationSec: 4, seed: 1, docker, dataDir, ...overrides });+ const labeledContainers = async () => (await docker.capture(['ps', '--all', '--quiet', '--filter', `label=${SUPERCOLLIDER_CONTAINER_LABEL}=1`])).stdout.trim();+ const scratchLeft = () => {+ const jobs = join(dataDir, 'supercollider', 'jobs');+ return existsSync(jobs) ? readdirSync(jobs) : [];+ };++ beforeAll(async () => {+ docker = await resolveDockerCli();+ const status = await getSuperColliderStatus({ docker });+ if (!status.ready) throw new Error(`The SuperCollider runtime is not ready (${status.state}): ${status.message} — run ${status.action}`);+ dataDir = mkdtempSync(join(tmpdir(), 'portos-sc-live-'));+ // The probe evidence is bound to this machine's image, so it carries over.+ mkdirSync(join(dataDir, 'supercollider'), { recursive: true });+ cpSync(join(PATHS.data, 'supercollider', 'runtime-evidence.json'), join(dataDir, 'supercollider', 'runtime-evidence.json'));+ listener = createServer((socket) => { connections += 1; socket.destroy(); });+ await new Promise((resolve) => listener.listen(0, '0.0.0.0', resolve));+ });++ afterAll(async () => {+ listener?.close();+ if (dataDir) rmSync(dataDir, { recursive: true, force: true });+ });++ it('renders an audible stereo 48 kHz WAV of the requested length from stock synths', async () => {+ const preview = await render({ source: STOCK_SOURCE, durationSec: 6 });+ expect(preview.measurement).toMatchObject({ channels: 2, sampleRate: 48000 });+ expect(Math.abs(preview.measurement.durationMs - 6000)).toBeLessThanOrEqual(50);+ expect(preview.measurement.peak).toBeGreaterThan(0.01);+ expect(scratchLeft()).toEqual([]);+ }, 120_000);++ it('cannot read an unmounted host file or the server environment, write outside its output, reach the network, or load an operator startup file', async () => {+ const hostFixture = join(dataDir, 'host-credential.txt');+ writeFileSync(hostFixture, 'example-secret');+ process.env.PORTOS_LIVE_PROBE_SECRET = 'example-secret';+ const { port } = listener.address();+ const probe = `var connect = { |host| { NetAddr(host, ${port}).connect; true }.try { false } };+"touch /in/via-shell /via-shell 2>/dev/null".systemCmd;+Error("PROBE" ++ ("hostFixture=" ++ File.exists("${hostFixture}")) ++ ("env=" ++ "PORTOS_LIVE_PROBE_SECRET".getenv.notNil) ++ ("home=" ++ "HOME".getenv) ++ ("uid=" ++ "id -u".unixCmdGetStdOut.replace("\\n", "")) ++ ("writeIn=" ++ File.new("/in/escape.txt", "w").isOpen) ++ ("writeRoot=" ++ File.new("/escape.txt", "w").isOpen) ++ ("shellIn=" ++ File.exists("/in/via-shell")) ++ ("shellRoot=" ++ File.exists("/via-shell")) ++ ("startup=" ++ File.exists(Platform.userConfigDir +/+ "startup.scd")) ++ ("netHost=" ++ connect.("host.docker.internal")) ++ ("netGateway=" ++ connect.("172.17.0.1"))+).throw;`;+ const error = await render({ source: probe }).catch((err) => err);+ delete process.env.PORTOS_LIVE_PROBE_SECRET;+ expect(error.code).toBe('SUPERCOLLIDER_SOURCE_ERROR');+ const report = Object.fromEntries([...error.message.matchAll(/(\w+)=(\S+)/g)].map(([, key, value]) => [key, value]));+ expect(report).toMatchObject({+ hostFixture: 'false', env: 'false', home: '/tmp', writeIn: 'false', writeRoot: 'false',+ shellIn: 'false', shellRoot: 'false', startup: 'false', netHost: 'false', netGateway: 'false',+ });+ expect(report.uid).not.toBe('0');+ expect(connections).toBe(0);+ expect(scratchLeft()).toEqual([]);+ }, 120_000);++ it('reports a syntax error without executing anything', async () => {+ await expect(render({ source: 'Pbind(\\dur, ' })).rejects.toMatchObject({ code: 'SUPERCOLLIDER_SYNTAX_ERROR' });+ expect(scratchLeft()).toEqual([]);+ }, 120_000);++ it('kills and removes a render that exceeds its wall time', async () => {+ await expect(render({ source: INFINITE_SOURCE, timeoutMs: 15_000 })).rejects.toMatchObject({ code: 'SUPERCOLLIDER_TIMEOUT' });+ expect(await labeledContainers()).toBe('');+ expect(scratchLeft()).toEqual([]);+ }, 120_000);++ it('cancel removes the running container and its files', async () => {+ const controller = new AbortController();+ let compiling;+ const started = new Promise((resolve) => { compiling = resolve; });+ const pending = render({ source: INFINITE_SOURCE, signal: controller.signal, onPhase: ({ phase }) => phase === 'compiling' && compiling() });+ await started;+ controller.abort();+ await expect(pending).rejects.toMatchObject({ code: 'SUPERCOLLIDER_CANCELED' });+ expect(await labeledContainers()).toBe('');+ expect(scratchLeft()).toEqual([]);+ }, 120_000);++ it('runs overlapping renders in isolation', async () => {+ const [short, long] = await Promise.all([+ render({ source: STOCK_SOURCE, durationSec: 4, seed: 1 }),+ render({ source: STOCK_SOURCE, durationSec: 7, seed: 2 }),+ ]);+ expect(Math.abs(short.measurement.durationMs - 4000)).toBeLessThanOrEqual(50);+ expect(Math.abs(long.measurement.durationMs - 7000)).toBeLessThanOrEqual(50);+ expect(scratchLeft()).toEqual([]);+ }, 180_000);+});diff --git a/server/services/superColliderRender.test.js b/server/services/superColliderRender.test.jsnew file mode 100644index 0000000000..820008d6a8--- /dev/null+++ b/server/services/superColliderRender.test.js@@ -0,0 +1,253 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import {+ SUPERCOLLIDER_IMAGE_LABELS,+ SUPERCOLLIDER_RENDER_WRAPPER_SOURCE,+} from '../lib/superColliderRuntime.js';+import { setupSuperColliderRuntime } from './superColliderRuntime.js';+import { readSuperColliderPreview, renderSuperColliderSource } from './superColliderRender.js';++// Interleaved IEEE-float WAV — the format the render wrapper asks scsynth for.+function floatWav(seconds, amplitude, { channels = 2, sampleRate = 48000 } = {}) {+ const frames = Math.round(seconds * sampleRate);+ const data = Buffer.alloc(frames * channels * 4);+ for (let i = 0; i < frames * channels; i += 1) data.writeFloatLE(amplitude * Math.sin(i / 7), i * 4);+ const header = Buffer.alloc(44);+ header.write('RIFF', 0, 'ascii'); header.writeUInt32LE(36 + data.length, 4); header.write('WAVE', 8, 'ascii');+ header.write('fmt ', 12, 'ascii'); header.writeUInt32LE(16, 16); header.writeUInt16LE(3, 20); header.writeUInt16LE(channels, 22);+ header.writeUInt32LE(sampleRate, 24); header.writeUInt32LE(sampleRate * channels * 4, 28); header.writeUInt16LE(channels * 4, 32); header.writeUInt16LE(32, 34);+ header.write('data', 36, 'ascii'); header.writeUInt32LE(data.length, 40);+ return Buffer.concat([header, data]);+}++const STOCK_SOURCE = 'SynthDef(\\lead, { |out = 0, freq = 440, amp = 0.2| Out.ar(out, SinOsc.ar(freq ! 2) * amp * EnvGen.kr(Env.perc, doneAction: 2)) }).add;\nPbind(\\instrument, \\lead, \\degree, Pseq([0, 2, 4], inf), \\dur, 0.5)';++/**+ * A docker CLI double with the adapter's two methods. `run` hands the test the+ * HOST directories mounted at /in and /out plus the script argv, the same+ * contract the real container has; `render` decides what the "container" does.+ */+function fakeDocker({ render = defaultRender, containers = [] } = {}) {+ const calls = { runs: [], removed: [] };+ let image = null;+ const label = (args, key) => args.flatMap((arg, i) => (arg === '--label' && args[i + 1].startsWith(`${key}=`) ? [args[i + 1].slice(key.length + 1)] : []))[0];+ return {+ calls,+ capture: async (args) => {+ if (args[0] === 'version') return { success: true, stdout: JSON.stringify({ Client: { Version: '27.0.0' }, Server: { Version: '27.0.0', Os: 'linux', Arch: 'arm64' } }), stderr: '' };+ if (args[0] === 'image') return image ? { success: true, stdout: JSON.stringify(image), stderr: '' } : { success: false, stdout: '', stderr: 'No such image' };+ if (args[0] === 'ps') return { success: true, stdout: containers.map((row) => JSON.stringify(row)).join('\n'), stderr: '' };+ if (args[0] === 'rm') calls.removed.push(args[2]);+ return { success: true, stdout: '', stderr: '' };+ },+ stream: async (args, onLine, options) => {+ if (args[0] === 'build') {+ image = { Id: 'sha256:image-1', Os: 'linux', Architecture: 'arm64', Config: { Labels: {+ [SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion]: label(args, SUPERCOLLIDER_IMAGE_LABELS.runtimeVersion),+ [SUPERCOLLIDER_IMAGE_LABELS.recipeHash]: label(args, SUPERCOLLIDER_IMAGE_LABELS.recipeHash),+ } } };+ return { success: true };+ }+ const mount = (target) => args.find((arg) => arg.includes(`,target=${target}`)).match(/source=(.*?),target=/)[1];+ const scriptAt = args.indexOf('-l') + 2;+ const run = {+ args, inputDir: mount('/in'), outputDir: mount('/out'), script: args[scriptAt], argv: args.slice(scriptAt + 1),+ name: args[args.indexOf('--name') + 1], onLine: (line) => onLine?.(line), isCancelled: options.isCancelled ?? (() => false),+ };+ if (run.script === '/in/smoke.scd') {+ writeFileSync(join(run.outputDir, 'smoke.wav'), floatWav(2, 0.25));+ return { success: true };+ }+ run.source = readFileSync(join(run.inputDir, 'source.scd'), 'utf8');+ calls.runs.push(run);+ return render(run);+ },+ };+}++function defaultRender(run) {+ writeFileSync(join(run.outputDir, 'render.wav'), floatWav(Number(run.argv[2]), 0.3));+ return { success: true };+}++const waitUntil = async (predicate) => {+ for (let i = 0; i < 400 && !predicate(); i += 1) await new Promise((resolve) => setTimeout(resolve, 10));+ if (!predicate()) throw new Error('condition never became true');+};++describe('contained SuperCollider renders', () => {+ let dataDir;+ let jobSeq = 0;+ const jobsDir = () => join(dataDir, 'supercollider', 'jobs');+ const leftoverScratch = () => (existsSync(jobsDir()) ? readdirSync(jobsDir()) : []);+ const ready = async (docker) => {+ expect((await setupSuperColliderRuntime({ docker, dataDir })).outcome).toBe('ready');+ return docker;+ };+ const render = (docker, overrides = {}) => renderSuperColliderSource({+ jobId: `job-${(jobSeq += 1)}`, source: STOCK_SOURCE, durationSec: 4, seed: 42, docker, dataDir, ...overrides,+ });++ beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'portos-sc-render-')); });+ afterEach(() => rmSync(dataDir, { recursive: true, force: true }));++ it('renders frozen source through the contained wrapper into a validated preview and leaves no scratch', async () => {+ const docker = await ready(fakeDocker());+ const preview = await render(docker, { jobId: 'job-ok', durationSec: 8 });++ const [run] = docker.calls.runs;+ expect(run.script).toBe('/in/render.scd');+ expect(run.source).toBe(STOCK_SOURCE);+ // The trusted runner supplies every path, the duration, the format, the seed and the tempo.+ expect(run.argv).toEqual(['/in/source.scd', '/out/render.wav', '8', '48000', '42', '0.5']);+ expect(run.args).toContain(`type=bind,source=${run.inputDir},target=/in,readonly`);+ expect(run.args[run.args.indexOf('--network') + 1]).toBe('none');+ // The verified image is pinned by id, not resolved by a mutable tag.+ expect(run.args).toContain('sha256:image-1');+ expect(docker.calls.removed).toContain(run.name);++ expect(preview).toMatchObject({+ jobId: 'job-ok', sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/), seed: 42,+ settings: { durationSec: 8, sampleRate: 48000, channels: 2, tempoBpm: 120 },+ measurement: { durationMs: 8000, channels: 2, sampleRate: 48000 },+ });+ const stored = await readSuperColliderPreview('job-ok', { dataDir });+ expect(stored.preview.source).toBe(STOCK_SOURCE);+ expect(readFileSync(stored.wavPath).length).toBeGreaterThan(8 * 48000 * 2 * 4);+ expect(leftoverScratch()).toEqual([]);+ });++ it('writes the shipped wrapper beside the source, never anything the source chose', async () => {+ let wrapper;+ const docker = await ready(fakeDocker({ render: (run) => {+ wrapper = readFileSync(join(run.inputDir, 'render.scd'), 'utf8');+ return defaultRender(run);+ } }));+ await render(docker, { source: '"/tmp/elsewhere.wav".postln; Pbind(\\dur, 1)' });+ expect(wrapper).toBe(SUPERCOLLIDER_RENDER_WRAPPER_SOURCE);+ });++ it('reports a syntax error with sclang\'s location and publishes nothing', async () => {+ const docker = await ready(fakeDocker({ render: (run) => {+ run.onLine('PORTOS_PHASE compiling');+ run.onLine('ERROR: syntax error, unexpected BINOP, expecting $end');+ run.onLine(' line 2 char 7:');+ run.onLine('PORTOS_RENDER_ERROR syntax: the source has a syntax error');+ return { success: false, error: 'exit 65: the source has a syntax error' };+ } }));+ await expect(render(docker, { jobId: 'job-syntax' })).rejects.toMatchObject({+ code: 'SUPERCOLLIDER_SYNTAX_ERROR', message: expect.stringContaining('line 2 char 7'),+ });+ expect(await readSuperColliderPreview('job-syntax', { dataDir })).toBeNull();+ expect(docker.calls.removed).toContain(docker.calls.runs[0].name);+ expect(leftoverScratch()).toEqual([]);+ });++ it('turns a wall-time kill into a timeout and still removes the container and its partial output', async () => {+ const docker = await ready(fakeDocker({ render: (run) => {+ writeFileSync(join(run.outputDir, 'render.wav'), Buffer.from('partial'));+ return { success: false, error: 'timed out after 1s' };+ } }));+ await expect(render(docker, { jobId: 'job-slow', timeoutMs: 1000 })).rejects.toMatchObject({ code: 'SUPERCOLLIDER_TIMEOUT' });+ expect(docker.calls.removed).toContain(docker.calls.runs[0].name);+ expect(await readSuperColliderPreview('job-slow', { dataDir })).toBeNull();+ expect(leftoverScratch()).toEqual([]);+ });++ it('cancels a running render: the container is stopped and removed and nothing is published', async () => {+ const docker = await ready(fakeDocker({ render: async (run) => {+ writeFileSync(join(run.outputDir, 'render.wav'), floatWav(1, 0.3));+ await waitUntil(run.isCancelled);+ return { success: false, error: 'cancelled' };+ } }));+ const controller = new AbortController();+ const pending = render(docker, { jobId: 'job-cancel', signal: controller.signal });+ await waitUntil(() => docker.calls.runs.length === 1);+ controller.abort();+ await expect(pending).rejects.toMatchObject({ code: 'SUPERCOLLIDER_CANCELED' });+ expect(docker.calls.removed).toContain(docker.calls.runs[0].name);+ expect(await readSuperColliderPreview('job-cancel', { dataDir })).toBeNull();+ expect(leftoverScratch()).toEqual([]);+ });++ it('stops a render that floods its output directory', async () => {+ const docker = await ready(fakeDocker({ render: async (run) => {+ for (let i = 0; i < 40; i += 1) writeFileSync(join(run.outputDir, `junk-${i}.bin`), 'x');+ await waitUntil(run.isCancelled);+ return { success: false, error: 'cancelled' };+ } }));+ await expect(render(docker)).rejects.toMatchObject({ code: 'SUPERCOLLIDER_OUTPUT_QUOTA' });+ expect(leftoverScratch()).toEqual([]);+ });++ it.each([+ ['mono', (out) => writeFileSync(join(out, 'render.wav'), floatWav(4, 0.3, { channels: 1 }))],+ ['44.1 kHz', (out) => writeFileSync(join(out, 'render.wav'), floatWav(4, 0.3, { sampleRate: 44100 }))],+ ['silent', (out) => writeFileSync(join(out, 'render.wav'), floatWav(4, 0))],+ ['too short', (out) => writeFileSync(join(out, 'render.wav'), floatWav(2, 0.3))],+ ['not audio', (out) => writeFileSync(join(out, 'render.wav'), Buffer.from('#!/bin/sh\necho hi\n'))],+ ['missing', () => {}],+ // A symlink would point the host at its own files; it must never be followed.+ ['a symlink to a host file', (out, fixture) => symlinkSync(fixture, join(out, 'render.wav'))],+ ])('rejects %s output without publishing a preview', async (_label, write) => {+ const fixture = join(dataDir, 'host-fixture.wav');+ writeFileSync(fixture, floatWav(4, 0.3));+ const docker = await ready(fakeDocker({ render: (run) => {+ write(run.outputDir, fixture);+ return { success: true };+ } }));+ await expect(render(docker, { jobId: 'job-bad' })).rejects.toMatchObject({ code: 'SUPERCOLLIDER_OUTPUT_INVALID' });+ expect(await readSuperColliderPreview('job-bad', { dataDir })).toBeNull();+ expect(leftoverScratch()).toEqual([]);+ });++ it('keeps overlapping renders isolated: separate snapshots, mounts and outputs', async () => {+ let release;+ const gate = new Promise((resolve) => { release = resolve; });+ const docker = await ready(fakeDocker({ render: async (run) => {+ await gate;+ return defaultRender(run);+ } }));+ const first = render(docker, { jobId: 'job-a', source: `${STOCK_SOURCE} // a`, durationSec: 4 });+ const second = render(docker, { jobId: 'job-b', source: `${STOCK_SOURCE} // b`, durationSec: 6 });+ await waitUntil(() => docker.calls.runs.length === 2);+ release();+ const [a, b] = await Promise.all([first, second]);++ const [runA, runB] = docker.calls.runs.sort((x, y) => x.source.localeCompare(y.source));+ expect(runA.inputDir).not.toBe(runB.inputDir);+ expect(runA.outputDir).not.toBe(runB.outputDir);+ expect([runA.source.endsWith('// a'), runB.source.endsWith('// b')]).toEqual([true, true]);+ expect(a.measurement.durationMs).toBe(4000);+ expect(b.measurement.durationMs).toBe(6000);+ expect(a.sourceHash).not.toBe(b.sourceHash);+ expect(leftoverScratch()).toEqual([]);+ });++ it('refuses with the setup action when the runtime is not ready, without starting a container', async () => {+ const docker = fakeDocker();+ await expect(render(docker)).rejects.toMatchObject({ code: 'SUPERCOLLIDER_UNAVAILABLE', status: 409 });+ expect(docker.calls.runs).toEqual([]);+ });++ it('sweeps containers and scratch a crashed process left behind, but not a run that could still be live', async () => {+ const stamp = (msAgo) => new Date(Date.now() - msAgo).toISOString().replace('T', ' ').replace(/\.\d+Z$/, ' +0000 UTC');+ const docker = await ready(fakeDocker({ containers: [+ { Names: 'portos-sc-orphan', CreatedAt: stamp(60 * 60_000) },+ { Names: 'portos-sc-live', CreatedAt: stamp(5_000) },+ ] }));+ const stale = join(jobsDir(), 'job-from-a-crash');+ const fresh = join(jobsDir(), 'job-another-process-is-running');+ mkdirSync(stale, { recursive: true });+ mkdirSync(fresh, { recursive: true });+ const anHourAgo = new Date(Date.now() - 60 * 60_000);+ utimesSync(stale, anHourAgo, anHourAgo);++ await render(docker);+ expect(docker.calls.removed).toContain('portos-sc-orphan');+ expect(docker.calls.removed).not.toContain('portos-sc-live');+ expect(leftoverScratch()).toEqual(['job-another-process-is-running']);+ });+});diff --git a/server/services/superColliderRuntime.js b/server/services/superColliderRuntime.jsindex ab3680befa..bd1b5b8bbd 100644--- a/server/services/superColliderRuntime.js+++ b/server/services/superColliderRuntime.js@@ -80,7 +80,7 @@ function createDockerCli(bin) {}/** The local docker CLI, or null when it is not installed. */-async function resolveDockerCli() {+export async function resolveDockerCli() {const bin = await whichFirst('docker') || DOCKER_FALLBACK_PATHS.find((path) => existsSync(path)) || null;return bin ? createDockerCli(bin) : null;}diff --git a/server/services/superColliderRuntime.test.js b/server/services/superColliderRuntime.test.jsindex 75e4fccdab..adedb26f2d 100644--- a/server/services/superColliderRuntime.test.js+++ b/server/services/superColliderRuntime.test.js@@ -114,7 +114,7 @@ describe('SuperCollider runtime setup', () => {const hostFile = join(dataDir, 'host-audio.wav');writeFileSync(hostFile, stereoWav(2, 0.25));const linked = await setupSuperColliderRuntime({ docker: fakeDocker({ render: (out) => symlinkSync(hostFile, join(out, 'smoke.wav')) }), dataDir });- expect(linked.status.smoke).toMatchObject({ ok: false, error: 'the probe wrote no readable WAV' });+ expect(linked.status.smoke).toMatchObject({ ok: false, error: 'no readable WAV was written' });const docker = fakeDocker({ render: () => {}, runResult: { success: false, error: 'timed out after 120s' } });const timedOut = await setupSuperColliderRuntime({ docker, dataDir });