Skip to content

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

fix: steady the code preview and isolate section playback (#9076)

[._.]/ Adam Eivyc7ef20582322
diff --git a/client/src/components/musicVideo/CodeVideoPanel.jsx b/client/src/components/musicVideo/CodeVideoPanel.jsx
index 9e78007b46..4a3b8920ee 100644
--- a/client/src/components/musicVideo/CodeVideoPanel.jsx
+++ b/client/src/components/musicVideo/CodeVideoPanel.jsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { Film, RotateCcw } from 'lucide-react';
import toast from '../ui/Toast';
@@ -40,7 +40,7 @@ export default function CodeVideoPanel({ project, audioUrl, onProject }) {
return () => { active = false; };
}, [project.id, project.updatedAt, project.composition?.codeVideo?.generatedAt]);
- const sections = doc?.song?.sections || doc?.timeline?.sections || [];
+ const sections = useMemo(() => doc?.song?.sections || doc?.timeline?.sections || [], [doc]);
const fps = doc?.fps || 24;
const duration = doc?.durationSec || 0;
const requested = searchParams.get('section');
@@ -58,7 +58,7 @@ export default function CodeVideoPanel({ project, audioUrl, onProject }) {
const srcDoc = useMemo(() => (doc?.html ? prepareAnimationHtml(doc.html, 'MV_CODE_AUDIO', null) : null), [doc]);
- const seek = (time) => {
+ const seek = useCallback((time) => {
const next = Math.min(Math.max(0, time), duration || time);
tRef.current = next;
setT(next);
@@ -66,7 +66,7 @@ export default function CodeVideoPanel({ project, audioUrl, onProject }) {
if (audioRef.current && Math.abs((audioRef.current.currentTime || 0) - next) > 0.05) {
audioRef.current.currentTime = next;
}
- };
+ }, [duration]);
useEffect(() => {
const step = (dir) => seek(tRef.current + dir / fps);
@@ -98,11 +98,12 @@ export default function CodeVideoPanel({ project, audioUrl, onProject }) {
};
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
- });
+ }, [seek, fps, sections, section, setSearchParams]);
useEffect(() => {
if (!playing) return undefined;
- let frame = 0;
+ let handle = 0;
+ let posted = -1;
const tick = () => {
const audio = audioRef.current;
if (!audio) return;
@@ -111,14 +112,18 @@ export default function CodeVideoPanel({ project, audioUrl, onProject }) {
time = section.startSec || 0;
audio.currentTime = time;
}
- tRef.current = time;
- setT(time);
- iframeRef.current?.contentWindow?.postMessage({ type: 'mv-code:seek', t: time }, '*');
- frame = requestAnimationFrame(tick);
+ const frameIndex = Math.floor(time * fps + 1e-9);
+ if (frameIndex !== posted) {
+ posted = frameIndex;
+ tRef.current = time;
+ setT(time);
+ iframeRef.current?.contentWindow?.postMessage({ type: 'mv-code:seek', t: time }, '*');
+ }
+ handle = requestAnimationFrame(tick);
};
- frame = requestAnimationFrame(tick);
- return () => cancelAnimationFrame(frame);
- }, [playing, looping, section]);
+ handle = requestAnimationFrame(tick);
+ return () => cancelAnimationFrame(handle);
+ }, [playing, looping, section, fps]);
const providerLabel = selectedProvider?.name || selectedProviderId || 'the active provider';
const modelLabel = selectedModel ? ` / ${selectedModel}` : '';
diff --git a/server/services/musicVideo/codeFrame.js b/server/services/musicVideo/codeFrame.js
index afd445a73c..7baa292542 100644
--- a/server/services/musicVideo/codeFrame.js
+++ b/server/services/musicVideo/codeFrame.js
@@ -6,7 +6,14 @@
* over module state — every input arrives on the argument, and the helpers it
* calls are emitted beside it. Seeking the same `t` twice paints the same
* pixels. Jitter, when a section uses it, is keyed to `env.frame`.
+ *
+ * Request handlers never call this painter. The preview runs it in a
+ * sandboxed iframe and the file render runs it in the composition browser,
+ * both with network globals removed first. The node sampler below passes its
+ * own `compile` so a test does not evaluate section source against this
+ * process's globals.
*/
+import vm from 'node:vm';
export const CODE_FPS = 24;
export const CODE_SAFE_INSET = 0.1;
@@ -43,7 +50,7 @@ export function lineActive(line, t) {
* Paint one frame. `sources` maps a section id to `function render(ctx, env)`.
* A missing or throwing section still leaves the palette and the lyric line.
*/
-export function drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps }) {
+export function drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps, compile }) {
const duration = song.durationSec;
const time = Math.min(Math.max(0, t), Math.max(0, duration));
const frame = Math.max(0, Math.floor(time * fps + 1e-9));
@@ -69,16 +76,22 @@ export function drawCodeFrame({ ctx, song, palette, sources, t, width, height, f
}),
}));
const env = { t: time, localT, frame, width, height, song, palette, section, safe, karaoke };
+ // The page uses this when the caller does not pass its own compiler.
+ // It stays inside this function so the embedded page has it too.
+ function defaultCompile(source) {
+ const wrapped = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;
+ return new Function('ctx', 'env', `${wrapped}\nreturn typeof render === 'function' ? render(ctx, env) : undefined;`);
+ }
const source = sources && sources[section.id];
if (typeof source === 'string' && source) {
- const body = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;
const restore = lockClock();
try {
if (!drawCodeFrame.compiled) drawCodeFrame.compiled = new Map();
- let fn = drawCodeFrame.compiled.get(body);
+ const key = `${typeof compile === 'function' ? 'custom' : 'page'}:${source}`;
+ let fn = drawCodeFrame.compiled.get(key);
if (!fn) {
- fn = new Function('ctx', 'env', `${body}\nreturn typeof render === 'function' ? render(ctx, env) : undefined;`);
- drawCodeFrame.compiled.set(body, fn);
+ fn = (typeof compile === 'function' ? compile : defaultCompile)(source);
+ drawCodeFrame.compiled.set(key, fn);
}
fn(ctx, env);
} catch { /* the host lyric pass below still runs */ } finally { restore(); }
@@ -204,10 +217,25 @@ export function createSoftwareCanvas(width, height) {
};
}
+// Section source under test runs in a context with no process, require, or
+// network. The page compiler is the browser's, after network globals are removed.
+function sandboxCompile(source) {
+ const wrapped = source.includes('function render') ? source : `function render(ctx, env) {\n${source}\n}`;
+ const sandbox = {
+ Math: { ...Math, random() { throw new Error('Math.random is disabled'); } },
+ Date: { now() { throw new Error('Date.now is disabled'); } },
+ };
+ vm.createContext(sandbox);
+ return vm.runInContext(
+ `(function (ctx, env) {\n${wrapped}\nreturn typeof render === "function" ? render(ctx, env) : undefined;\n})`,
+ sandbox,
+ );
+}
+
/** Paint `t` and return the pixel buffer plus the lyric placements. */
export function sampleFrame({ song, palette, sources, t, width, height, fps = CODE_FPS }) {
const ctx = createSoftwareCanvas(width, height);
- const meta = drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps });
+ const meta = drawCodeFrame({ ctx, song, palette, sources, t, width, height, fps, compile: sandboxCompile });
return { data: ctx.data, textOps: ctx.textOps, ...meta, width, height };
}
diff --git a/server/services/musicVideo/excerptRender.js b/server/services/musicVideo/excerptRender.js
index 6bbb3add39..85b39486a0 100644
--- a/server/services/musicVideo/excerptRender.js
+++ b/server/services/musicVideo/excerptRender.js
@@ -80,6 +80,8 @@ const unlinkUnder = (root, filename) => {
// instead of the footage concat. Footage generation is not involved.
async function launchCodeExcerpt({ projectId, project, startSec, endSec, revisionId, handOff }) {
const full = prepareCodeRender(project);
+ // Same order as a full code render: a missing master throws before the
+ // excerpt is marked rendering.
const audioPath = await resolveMasterAudioPath(project);
if (!(startSec >= 0) || !(endSec > startSec) || endSec > full.durationSec + 1e-6) {
throw new ServerError(
diff --git a/server/services/musicVideo/render.js b/server/services/musicVideo/render.js
index b40b5b320c..3014c3e61a 100644
--- a/server/services/musicVideo/render.js
+++ b/server/services/musicVideo/render.js
@@ -624,6 +624,8 @@ async function renderMusicVideoCode(projectId, { codeDirectory, startSec = 0 })
// routes apply, and it never asks a footage model for pixels.
async function renderCodeMode(projectId, project, handOff) {
const plan = prepareCodeRender(project);
+ // Resolve the master before any rendering mark. A missing track throws here
+ // and the caller releases the pending slot without leaving a job running.
const audioPath = await resolveMasterAudioPath(project);
await ensureDir(PATHS.videos);
await ensureDir(PATHS.videoThumbnails);