Skip to content

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

feat: render offline HTML compositions to video (#8648)

[._.]/ Adam Eivy07f8edb7e29d
diff --git a/docs/API.md b/docs/API.md
index 90604a69da..2d2ce10ff3 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -742,6 +742,7 @@ Every mounted API prefix (see `server/index.js` for the authoritative list). Dom
| `/api/image-gen`, `/api/video-gen`, `/api/image-video/models` | Image/video generation |
| `/api/devtools/video-download` | Video download |
| `/api/video-timeline` | Video timeline editor |
+| `/api/html-composition` | Offline seekable HTML-to-MP4 rendering; [contract and job endpoints](./HTML_COMPOSITIONS.md) |
| `/api/continuous-video` | Continuous-video episodes (script + bible → chained multi-clip generation) |
| `/api/media-jobs` | Async media job queue |
| `/api/creative-director` | Creative Director projects |
diff --git a/docs/HTML_COMPOSITIONS.md b/docs/HTML_COMPOSITIONS.md
new file mode 100644
index 0000000000..fa4074f4bd
--- /dev/null
+++ b/docs/HTML_COMPOSITIONS.md
@@ -0,0 +1,65 @@
+# HTML compositions
+
+Render a local, seekable HTML scene to a text-faithful H.264 MP4 without an AI
+provider. Start the managed browser and install ffmpeg before submitting a job.
+Chrome must support CDP hidden targets; unsupported browsers fail the job rather
+than opening a visible tab.
+
+Put `index.html` and its assets in a directory such as
+`data/compositions/example/`. The page exposes:
+
+```html
+<div id="block" style="position:absolute;width:40px;height:40px;background:red"></div>
+<script>
+globalThis.portosComposition = {
+ durationSec: 2, fps: 24, width: 1280, height: 720,
+ async seek(t) {
+ document.getElementById('block').style.left = `${t * 200}px`;
+ }
+};
+</script>
+```
+
+`seek(t)` must finish all asynchronous work for that frame before resolving.
+Drive animation from `t`, not wall-clock playback, CSS animation timers or random
+state. The renderer awaits each seek, then captures frame `n` at `n / fps`.
+Duration is 1–120 seconds, fps is an integer from 12–60, and their product must
+be a whole number of frames. Dimensions are exactly 1920×1080, 1080×1920,
+1080×1080 or 1280×720. Invalid contracts name the field in the job error.
+
+Submit `POST /api/html-composition/render` with:
+
+```json
+{"directory":"compositions/example","musicTrack":"example.wav"}
+```
+
+`musicTrack` is optional and names an existing Music-library file. It loops if
+shorter than the video, is trimmed to duration, and fades out over the final half
+second. A missing requested track fails the job.
+
+The 202 response contains the media queue's `jobId`. Subscribe to
+`GET /api/html-composition/:jobId/events` for the usual queued, started, progress,
+complete, error and canceled SSE frames. Cancel through
+`POST /api/html-composition/:jobId/cancel` or the existing media-job controls.
+Jobs use the serialized local lane and are never offered to a federated peer.
+
+The renderer snapshots local assets (up to 256 MiB / 4096 files), rejects
+symlinks, and fulfills requests from that snapshot at a virtual HTTPS origin.
+Use relative asset URLs. Nothing is served by a new HTTP listener. A fresh,
+hidden browser target has no access to the operator's normal browser context.
+Network URLs, missing assets, frames, workers, popups, WebSockets and WebRTC are
+refused; a refusal fails the job instead of silently dropping content. Browser
+disconnects, failed encoding and cancellation remove partial outputs. Cancellation
+is refused once the final history write has begun.
+
+Successful outputs have BT.709 tags, fast-start MP4 layout, and a thumbnail in
+Media History. Source compositions are externally editable files, not a new
+relational store. Outputs and job state use the existing video-history and media
+queue storage contracts; no new JSON store, migration, seed or sync channel is
+introduced. Source files under `data/` follow the existing backup filters.
+
+The real-browser contract suite in
+`server/services/htmlComposition/index.test.js` needs Chrome and ffmpeg. It uses
+a temporary browser profile and data root, never the live managed browser.
+Set `CHROME_PATH` when Chrome is not in a standard location. The suite skips
+explicitly when either binary is unavailable; route and queue tests still run.
diff --git a/docs/README.md b/docs/README.md
index 95f36e997a..1d92819cff 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -8,6 +8,7 @@ Index of everything under `docs/`. Start with the [root README](../README.md) fo
| Doc | Covers |
|-----|--------|
+| [HTML_COMPOSITIONS.md](./HTML_COMPOSITIONS.md) | Seekable HTML scenes rendered offline to MP4 through hidden managed-browser targets |
| [ARCHITECTURE.md](./ARCHITECTURE.md) | System design: React client, Express server, PM2 satellites, PostgreSQL + `data/` files |
| [features/catalog-ingest.md](./features/catalog-ingest.md) | Catalog extraction graph, context budgets, coverage, and review draft contract |
| [API.md](./API.md) | REST endpoints, complete route-domain index, Socket.IO events |
diff --git a/server/index.js b/server/index.js
index 1aeafaa634..067e302dae 100644
--- a/server/index.js
+++ b/server/index.js
@@ -127,6 +127,7 @@ import videoGenRoutes from './routes/videoGen.js';
import continuousVideoEpisodeRoutes from './routes/continuousVideoEpisode.js';
import videoDownloadRoutes from './routes/videoDownload.js';
import videoTimelineRoutes from './routes/videoTimeline.js';
+import htmlCompositionRoutes from './routes/htmlComposition.js';
import mediaJobsRoutes from './routes/mediaJobs.js';
import federatedMediaRoutes from './routes/federatedMedia.js';
import creativeDirectorRoutes from './routes/creativeDirector.js';
@@ -410,6 +411,7 @@ app.use('/api/video-gen', videoGenRoutes);
app.use('/api/continuous-video', continuousVideoEpisodeRoutes);
app.use('/api/devtools/video-download', videoDownloadRoutes);
app.use('/api/video-timeline', videoTimelineRoutes);
+app.use('/api/html-composition', htmlCompositionRoutes);
app.use('/api/media-jobs', mediaJobsRoutes);
app.use('/api/federation/media/v1', federatedMediaRoutes);
app.use('/api/creative-director', creativeDirectorRoutes);
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 60ba1df8fc..7d0d64741b 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -2426,3 +2426,23 @@ export const mindBundleApplySchema = z.object({
PERSISTENT_MIND_BUNDLE_GROUPS.map((group) => [group, z.enum(MIND_BUNDLE_GROUP_CHOICES).optional()]),
)).strict(),
}).strict();
+
+// HTML composition inputs are local, editable assets, never provider prompts.
+export const htmlCompositionRenderSchema = z.object({
+ directory: z.string().min(1).max(1024).refine(value => !value.startsWith('/') && !value.includes('\\') && !value.includes(':') && !value.split('/').some(part => part === '..' || part === '.' || !part), 'directory must be a relative path inside data'),
+ musicTrack: z.string().min(1).max(255).regex(/^[^/\\]+$/, 'musicTrack must be a Music-library filename').optional(),
+});
+
+export const htmlCompositionContractSchema = z.object({
+ durationSec: z.number().min(1).max(120),
+ fps: z.number().int().min(12).max(60),
+ width: z.number().int(),
+ height: z.number().int(),
+}).superRefine((value, ctx) => {
+ if (!['1920x1080', '1080x1920', '1080x1080', '1280x720'].includes(`${value.width}x${value.height}`)) {
+ ctx.addIssue({ code: 'custom', path: ['width'], message: 'width/height must be 1920x1080, 1080x1920, 1080x1080 or 1280x720' });
+ }
+ if (Math.abs(value.durationSec * value.fps - Math.round(value.durationSec * value.fps)) > 1e-8) {
+ ctx.addIssue({ code: 'custom', path: ['durationSec'], message: 'durationSec × fps must be a whole number of frames' });
+ }
+});
diff --git a/server/routes/htmlComposition.js b/server/routes/htmlComposition.js
new file mode 100644
index 0000000000..4371aa367a
--- /dev/null
+++ b/server/routes/htmlComposition.js
@@ -0,0 +1,21 @@
+import { Router } from 'express';
+import { asyncHandler, ServerError } from '../lib/errorHandler.js';
+import { validateRequest, htmlCompositionRenderSchema } from '../lib/validation.js';
+import { enqueueJob, attachSseClient, cancelJob } from '../services/mediaJobQueue/index.js';
+
+const router = Router();
+
+router.post('/render', asyncHandler(async (req, res) => {
+ const params = validateRequest(htmlCompositionRenderSchema, req.body);
+ res.status(202).json(await enqueueJob({ kind: 'html-composition', params }));
+}));
+
+router.get('/:jobId/events', (req, res) => {
+ if (!attachSseClient(req.params.jobId, res)) throw new ServerError('Job not found or expired', { status: 404 });
+});
+
+router.post('/:jobId/cancel', asyncHandler(async (req, res) => {
+ res.json(await cancelJob(req.params.jobId));
+}));
+
+export default router;
diff --git a/server/routes/htmlComposition.test.js b/server/routes/htmlComposition.test.js
new file mode 100644
index 0000000000..a2e5c785bd
--- /dev/null
+++ b/server/routes/htmlComposition.test.js
@@ -0,0 +1,33 @@
+import { describe, it, expect, vi } from 'vitest';
+import express from 'express';
+import { request } from '../lib/testHelper.js';
+import { errorMiddleware } from '../lib/errorHandler.js';
+import { enqueueJob } from '../services/mediaJobQueue/index.js';
+import router from './htmlComposition.js';
+
+vi.mock('../services/mediaJobQueue/index.js', () => ({
+ enqueueJob: vi.fn(async () => ({ jobId: 'example-job', status: 'queued' })),
+ attachSseClient: vi.fn(() => false), cancelJob: vi.fn(),
+}));
+
+const app = express();
+app.use(express.json());
+app.use('/api/html-composition', router);
+app.use(errorMiddleware);
+
+describe('HTML composition admission', () => {
+ it('accepts local composition assets and optional library music as a local-only media job', async () => {
+ const params = { directory: 'compositions/example', musicTrack: 'example.wav' };
+ const response = await request(app).post('/api/html-composition/render').send(params);
+ expect(response.status).toBe(202);
+ expect(response.body).toMatchObject({ jobId: 'example-job' });
+ expect(enqueueJob).toHaveBeenCalledWith({ kind: 'html-composition', params });
+ });
+
+ it.each([{ directory: '../private' }, { directory: '/etc' }, { directory: 'C:\\private' }, { directory: 'valid', musicTrack: '../track.wav' }, {}])('rejects invalid paths before queue admission: %j', async body => {
+ enqueueJob.mockClear();
+ const response = await request(app).post('/api/html-composition/render').send(body);
+ expect(response.status).toBe(400);
+ expect(enqueueJob).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/htmlComposition/browser.js b/server/services/htmlComposition/browser.js
new file mode 100644
index 0000000000..1ad2e5aa55
--- /dev/null
+++ b/server/services/htmlComposition/browser.js
@@ -0,0 +1,181 @@
+import WebSocket from 'ws';
+import { readFile, readdir, realpath, stat } from 'node:fs/promises';
+import { resolve, relative, isAbsolute, join, extname } from 'node:path';
+import { PATHS } from '../../lib/fileUtils.js';
+import { cdpRequest } from '../browserService.js';
+
+const ORIGIN = 'https://composition.invalid';
+const MIME = { '.html': 'text/html', '.js': 'text/javascript', '.css': 'text/css', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.woff': 'font/woff', '.woff2': 'font/woff2', '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg', '.wav': 'audio/wav' };
+// Sandboxing removes alternate realms, popups, forms and workers. HTTP assets
+// are fulfilled below, never continued to the browser's network stack.
+const CSP = "sandbox allow-scripts; default-src 'none'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src http: https:; font-src 'self'; media-src 'self'; connect-src http: https:; frame-src 'none'; worker-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'";
+
+function inside(root, path) {
+ const rel = relative(root, path);
+ return rel && rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\') && !isAbsolute(rel);
+}
+
+// Freeze the input before any script runs. Symlinks are refused, including
+// symlinked assets, so the virtual origin cannot export another data store.
+async function snapshotAssets(directory) {
+ const root = await realpath(PATHS.data);
+ const dir = await realpath(resolve(root, directory));
+ if (!inside(root, dir)) throw new Error('directory must be inside data');
+ const assets = new Map();
+ let bytes = 0;
+ async function walk(path, prefix = '') {
+ for (const entry of await readdir(path, { withFileTypes: true })) {
+ const name = `${prefix}${entry.name}`;
+ if (entry.isSymbolicLink()) throw new Error('Composition assets must not be symlinks');
+ if (entry.isDirectory()) await walk(join(path, entry.name), `${name}/`);
+ else if (entry.isFile()) {
+ const size = (await stat(join(path, entry.name))).size;
+ if (bytes + size > 256 * 1024 * 1024 || assets.size >= 4096) throw new Error('Composition assets exceed 256 MiB or 4096 files');
+ const body = await readFile(join(path, entry.name));
+ bytes += body.length;
+ if (bytes > 256 * 1024 * 1024 || assets.size >= 4096) throw new Error('Composition assets exceed 256 MiB or 4096 files');
+ assets.set(`/${name}`, body);
+ } else throw new Error('Composition assets must be regular files');
+ }
+ }
+ await walk(dir);
+ if (!assets.has('/index.html')) throw new Error('directory must contain index.html');
+ return assets;
+}
+
+// One browser-level socket owns a disposable context and its hidden target.
+// Disconnect/abort rejects pending commands; disposeOnDetach covers crashes.
+export async function openComposition(directory, { signal } = {}) {
+ const assets = await snapshotAssets(directory);
+ signal?.throwIfAborted();
+ const response = await cdpRequest('/json/version');
+ if (!response.ok) throw new Error('Managed browser is unavailable');
+ const { webSocketDebuggerUrl } = await response.json();
+ if (!webSocketDebuggerUrl) throw new Error('Managed browser has no CDP endpoint');
+ const ws = new WebSocket(webSocketDebuggerUrl, { handshakeTimeout: 10000 });
+ const pending = new Map();
+ let nextId = 0;
+ let failure;
+ let contextId;
+ let sessionId;
+ let closing = false;
+ const fail = (error) => {
+ failure ??= error;
+ for (const command of pending.values()) command.reject(failure);
+ pending.clear();
+ };
+ const abort = () => { fail(signal.reason ?? new Error('Render canceled')); ws.terminate(); };
+ signal?.addEventListener('abort', abort, { once: true });
+ function send(method, params = {}, session = sessionId) {
+ if (failure) return Promise.reject(failure);
+ return new Promise((resolveCommand, rejectCommand) => {
+ const id = ++nextId;
+ const timer = setTimeout(() => fail(new Error(`Browser command timed out: ${method}`)), 30000);
+ const finish = (fn) => (value) => { clearTimeout(timer); pending.delete(id); fn(value); };
+ pending.set(id, { resolve: finish(resolveCommand), reject: finish(rejectCommand) });
+ ws.send(JSON.stringify({ id, method, params, ...(session ? { sessionId: session } : {}) }), error => {
+ if (error) fail(error);
+ });
+ });
+ }
+ async function request(params) {
+ const url = new URL(params.request.url);
+ const key = decodeURIComponent(url.pathname);
+ const body = url.origin === ORIGIN && !url.username && !url.password && params.request.method === 'GET' && assets.get(key);
+ if (!body) {
+ // Do not continue even a failed request. Disconnect destroys the context.
+ throw new Error(`Refused composition request: ${params.request.url}`);
+ }
+ await send('Fetch.fulfillRequest', {
+ requestId: params.requestId, responseCode: 200,
+ responseHeaders: [
+ { name: 'Content-Type', value: MIME[extname(key).toLowerCase()] ?? 'application/octet-stream' },
+ { name: 'Content-Security-Policy', value: CSP },
+ { name: 'Access-Control-Allow-Origin', value: '*' },
+ { name: 'X-DNS-Prefetch-Control', value: 'off' },
+ ], body: body.toString('base64'),
+ });
+ }
+ ws.on('message', bytes => {
+ try {
+ const message = JSON.parse(bytes.toString());
+ if (message.id) {
+ const command = pending.get(message.id);
+ if (message.error) command?.reject(new Error(message.error.message));
+ else command?.resolve(message.result);
+ } else if (!closing && message.method === 'Target.detachedFromTarget' && message.params.sessionId === sessionId) {
+ fail(new Error('Composition browser target closed'));
+ } else if (message.sessionId === sessionId) {
+ if (message.method === 'Fetch.requestPaused') request(message.params).catch(fail);
+ if (message.method === 'Runtime.bindingCalled') fail(new Error(`Refused composition request: ${message.params.payload}`));
+ if (message.method === 'Runtime.exceptionThrown') {
+ const details = message.params.exceptionDetails;
+ fail(new Error(`Composition script failed: ${details.exception?.description ?? details.text}`));
+ }
+ if (message.method === 'Inspector.targetCrashed') fail(new Error('Composition browser target crashed'));
+ }
+ } catch (error) { fail(error); }
+ });
+ ws.on('error', fail);
+ ws.on('close', () => { if (!closing) fail(new Error('Managed browser disconnected')); });
+ async function close({ verify = false } = {}) {
+ closing = true;
+ signal?.removeEventListener('abort', abort);
+ // On failure the socket detach disposes the context even if commands fail.
+ if (contextId && !failure && ws.readyState === WebSocket.OPEN) {
+ await send('Target.disposeBrowserContext', { browserContextId: contextId }, null).catch(fail);
+ }
+ const error = failure;
+ fail(new Error('Composition context closed'));
+ ws.terminate();
+ if (verify && error) throw error;
+ }
+ async function evaluate(expression) {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ if (result.exceptionDetails) throw new Error(`Composition script failed: ${result.exceptionDetails.exception?.description ?? result.exceptionDetails.text}`);
+ if (failure) throw failure;
+ return result.result.value;
+ }
+ try {
+ await new Promise((resolveOpen, rejectOpen) => {
+ if (ws.readyState === WebSocket.OPEN) return resolveOpen();
+ ws.once('open', resolveOpen);
+ ws.once('error', rejectOpen);
+ ws.once('close', () => rejectOpen(failure ?? new Error('Managed browser disconnected')));
+ });
+ signal?.throwIfAborted();
+ ({ browserContextId: contextId } = await send('Target.createBrowserContext', {
+ disposeOnDetach: true,
+ // Defense in depth for browser-originated HTTP requests outside Fetch.
+ proxyServer: 'http://127.0.0.1:9', proxyBypassList: '<-loopback>',
+ }, null));
+ const { targetId } = await send('Target.createTarget', { url: 'about:blank', browserContextId: contextId, hidden: true, background: true }, null);
+ ({ sessionId } = await send('Target.attachToTarget', { targetId, flatten: true }, null));
+ await send('Page.enable');
+ await send('Runtime.enable');
+ await send('Runtime.addBinding', { name: '__portosRefused' });
+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `(() => {
+ const report = globalThis.__portosRefused;
+ addEventListener('securitypolicyviolation', event => report(event.blockedURI));
+ // WebRTC bypasses HTTP interception. No other realm can restore these:
+ // CSP sandbox disallows frames, workers, popups and same-origin access.
+ for (const key of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport']) {
+ Object.defineProperty(globalThis, key, { configurable: false, writable: false,
+ value: function() { report(key); throw new Error(key + ' is disabled in compositions'); } });
+ }
+ for (const key of ['Worker', 'SharedWorker', 'WebSocket']) {
+ Object.defineProperty(globalThis, key, { configurable: false, writable: false,
+ value: function(url) { report(String(url)); throw new Error(key + ' is disabled in compositions'); } });
+ }
+ })();` });
+ await send('Fetch.enable', { patterns: [{ urlPattern: '*', requestStage: 'Request' }] });
+ const navigation = await send('Page.navigate', { url: `${ORIGIN}/index.html` });
+ if (navigation.errorText) throw new Error(`Composition navigation failed: ${navigation.errorText}`);
+ await evaluate(`new Promise(resolve => document.readyState === 'complete' ? resolve() : addEventListener('load', resolve, { once: true }))`);
+ await evaluate('document.fonts.ready.then(() => true)');
+ return { evaluate, send, close, check: () => { signal?.throwIfAborted(); if (failure) throw failure; } };
+ } catch (error) {
+ await close();
+ throw error;
+ }
+}
diff --git a/server/services/htmlComposition/encode.js b/server/services/htmlComposition/encode.js
new file mode 100644
index 0000000000..9aa5cd014d
--- /dev/null
+++ b/server/services/htmlComposition/encode.js
@@ -0,0 +1,63 @@
+import { spawn } from '../../lib/childProcess.js';
+import { safeChildProcessOptions } from '../../lib/processEnv.js';
+import { killWithEscalation } from '../../lib/killWithEscalation.js';
+import { findFfmpeg, H264_ENCODE_ARGS, AAC_ENCODE_ARGS, BT709_CONTAINER_ARGS, bt709TagFilter } from '../../lib/ffmpeg.js';
+
+// Stream one frame at a time. The write callback supplies back-pressure and
+// the terminal race releases a pending write on exit, disconnect or cancel.
+export async function encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress } = {}) {
+ const ffmpeg = await findFfmpeg();
+ if (!ffmpeg) throw new Error('ffmpeg not found on PATH');
+ const tag = await bt709TagFilter();
+ signal?.throwIfAborted();
+ const { fps, durationSec, width, height } = contract;
+ const numFrames = Math.round(durationSec * fps);
+ await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: false });
+ const args = ['-hide_banner', '-loglevel', 'error', '-f', 'image2pipe', '-framerate', String(fps), '-vcodec', 'png', '-i', 'pipe:0'];
+ if (musicPath) args.push('-stream_loop', '-1', '-i', musicPath);
+ args.push('-map', '0:v', '-vf', ['scale=in_range=pc:out_range=tv:out_color_matrix=bt709', tag].filter(Boolean).join(','), ...H264_ENCODE_ARGS, ...BT709_CONTAINER_ARGS);
+ if (musicPath) args.push('-map', '1:a', '-af', `atrim=duration=${durationSec},asetpts=PTS-STARTPTS,afade=t=out:st=${durationSec - 0.5}:d=0.5`, ...AAC_ENCODE_ARGS);
+ args.push('-frames:v', String(numFrames), '-t', String(durationSec), '-movflags', '+faststart', '-y', outputPath);
+ const proc = spawn(ffmpeg, args, safeChildProcessOptions({ stdio: ['pipe', 'ignore', 'pipe'] }));
+ let stderr = '';
+ let exited = false;
+ let stopping = false;
+ proc.stderr.on('data', chunk => { stderr = (stderr + chunk.toString()).slice(-2000); });
+ const finished = new Promise((resolve, reject) => {
+ proc.on('error', reject);
+ proc.stdin.on('error', reject);
+ proc.once('close', code => { exited = true; code === 0 ? resolve() : reject(new Error(`ffmpeg failed (${code}): ${stderr}`)); });
+ });
+ // Attach a rejection handler before the first browser round trip.
+ finished.catch(() => {});
+ const stop = () => {
+ if (!exited && !stopping) {
+ stopping = true;
+ killWithEscalation(proc, { label: 'HTML composition encode', stillRunning: () => !exited, delayMs: 1000 });
+ }
+ };
+ signal?.addEventListener('abort', stop, { once: true });
+ try {
+ for (let n = 0; n < numFrames; n++) {
+ page.check();
+ // awaitPromise in evaluate is essential: each seek owns its paint.
+ await page.evaluate(`globalThis.portosComposition.seek(${n / fps})`);
+ page.check();
+ const { data } = await page.send('Page.captureScreenshot', { format: 'png', fromSurface: true, captureBeyondViewport: false });
+ page.check();
+ await Promise.race([
+ new Promise((resolve, reject) => proc.stdin.write(Buffer.from(data, 'base64'), error => error ? reject(error) : resolve())),
+ finished.then(() => { throw new Error('ffmpeg exited before capture completed'); }),
+ ]);
+ onProgress?.((n + 1) / numFrames);
+ }
+ proc.stdin.end();
+ await finished;
+ page.check();
+ } finally {
+ signal?.removeEventListener('abort', stop);
+ stop();
+ // Wait for close, not just the first error, before deleting partial output.
+ if (!exited) await new Promise(resolve => proc.once('close', resolve));
+ }
+}
diff --git a/server/services/htmlComposition/index.js b/server/services/htmlComposition/index.js
new file mode 100644
index 0000000000..6dcdcf3427
--- /dev/null
+++ b/server/services/htmlComposition/index.js
@@ -0,0 +1,80 @@
+import { join } from 'node:path';
+import { PATHS, ensureDir, unlinkGuarded } from '../../lib/fileUtils.js';
+import { htmlCompositionContractSchema, htmlCompositionRenderSchema, validateRequest } from '../../lib/validation.js';
+import { generateThumbnail } from '../../lib/ffmpeg.js';
+import { videoGenEvents } from '../videoGen/events.js';
+import { mutateVideoHistory } from '../videoGen/history.js';
+import { resolveMusicTrackPath } from '../pipeline/audioMux.js';
+import { openComposition } from './browser.js';
+import { encodeComposition } from './encode.js';
+
+const active = new Map();
+
+export function cancel(jobId) {
+ const job = active.get(jobId);
+ if (!job || job.committing) return false;
+ job.controller.abort(new Error('Render canceled'));
+ return true;
+}
+
+export async function renderComposition({ jobId, ...input }) {
+ const job = { controller: new AbortController(), committing: false };
+ active.set(jobId, job);
+ const { signal } = job.controller;
+ const filename = `composition-${jobId}.mp4`;
+ const outputPath = join(PATHS.videos, filename);
+ let page;
+ let success = false;
+ let result;
+ let failure;
+ try {
+ const { directory, musicTrack } = validateRequest(htmlCompositionRenderSchema, input);
+ const musicPath = musicTrack ? await resolveMusicTrackPath(musicTrack) : null;
+ if (musicTrack && !musicPath) throw new Error('musicTrack is missing from the Music library');
+ signal.throwIfAborted();
+ page = await openComposition(directory, { signal });
+ const metadata = await page.evaluate(`(() => {
+ const c = globalThis.portosComposition;
+ if (!c || typeof c.seek !== 'function') throw new Error('portosComposition.seek is required');
+ return { durationSec: c.durationSec, fps: c.fps, width: c.width, height: c.height };
+ })()`);
+ const parsed = htmlCompositionContractSchema.safeParse(metadata);
+ if (!parsed.success) throw new Error(parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '));
+ const contract = parsed.data;
+ await ensureDir(PATHS.videos);
+ await encodeComposition(page, contract, outputPath, { musicPath, signal, onProgress: progress => {
+ videoGenEvents.emit('progress', { generationId: jobId, progress: progress * 0.95 });
+ } });
+ // End script execution before post-processing and publishing the result.
+ page.check();
+ await page.close({ verify: true });
+ page = null;
+ signal.throwIfAborted();
+ const thumbnail = await generateThumbnail(outputPath, jobId);
+ if (!thumbnail) throw new Error('Composition thumbnail generation failed');
+ signal.throwIfAborted();
+ // Once the shared history write starts, cancellation must be refused.
+ job.committing = true;
+ const meta = {
+ id: jobId, prompt: `HTML composition: ${directory}`, modelId: 'html-composition', seed: 0,
+ ...contract, numFrames: Math.round(contract.durationSec * contract.fps),
+ filename, thumbnail, createdAt: new Date().toISOString(),
+ };
+ await mutateVideoHistory(history => { history.unshift(meta); return history; });
+ success = true;
+ result = { generationId: jobId, id: jobId, filename, thumbnail, path: `/data/videos/${filename}` };
+ } catch (error) {
+ failure = error;
+ } finally {
+ await page?.close();
+ if (!success) {
+ await unlinkGuarded(outputPath).catch(() => {});
+ await unlinkGuarded(join(PATHS.videoThumbnails, `${jobId}.jpg`)).catch(() => {});
+ }
+ active.delete(jobId);
+ }
+ // Cleanup precedes the terminal event, so the queue cannot advance early.
+ if (failure) throw failure;
+ videoGenEvents.emit('completed', result);
+ return result;
+}
diff --git a/server/services/htmlComposition/index.test.js b/server/services/htmlComposition/index.test.js
new file mode 100644
index 0000000000..f3c58eb82b
--- /dev/null
+++ b/server/services/htmlComposition/index.test.js
@@ -0,0 +1,177 @@
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+import { existsSync } from 'node:fs';
+import { mkdir, writeFile, readFile, readdir, symlink } from 'node:fs/promises';
+import { join } from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { execFileSync, spawn } from 'node:child_process';
+import { once } from 'node:events';
+import { chromium } from 'playwright-core';
+import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../../lib/mockPathsDataRoot.js';
+import { findFfmpeg } from '../../lib/ffmpeg.js';
+import { PATHS } from '../../lib/fileUtils.js';
+import { loadHistory } from '../videoGen/history.js';
+import { videoGenEvents } from '../videoGen/events.js';
+import { renderComposition, cancel } from './index.js';
+
+let endpoint;
+vi.mock('../browserService.js', () => ({ cdpRequest: path => fetch(`${endpoint}${path}`) }));
+vi.mock('../../lib/fileUtils.js', async importOriginal => makePathsProxy(await importOriginal(), {
+ dataRoot: () => lazyTempDataRoot('portos-html-composition-'),
+}));
+
+const chrome = [process.env.CHROME_PATH, chromium.executablePath(),
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
+ '/usr/bin/google-chrome', '/usr/bin/chromium', '/usr/bin/chromium-browser',
+].find(path => path && existsSync(path));
+const ffmpeg = await findFfmpeg();
+let proc;
+let browser;
+let browserSession;
+
+// The delayed paint is intentional test input: a screenshot before the seek
+// promise settles MUST see the previous position, even on a fast machine.
+const fixture = (extra = '', contract = '') => `<!doctype html><html><head>
+<link rel="icon" href="/pixel.svg"><style>body { margin: 0; background: white; } #block { position:absolute; top:100px; width:40px; height:40px; background:rgb(255,0,0); }</style>
+</head><body><div id="block"></div><script>
+globalThis.portosComposition = { durationSec:1, fps:12, width:1280, height:720,
+ async seek(t) { await new Promise(resolve => setTimeout(resolve, 150)); document.getElementById('block').style.left = (40 + t * 480) + 'px'; }, ${contract} };
+${extra}</script></body></html>`;
+
+async function composition(html = fixture()) {
+ const directory = `compositions/${randomUUID()}`;
+ await mkdir(join(PATHS.data, directory), { recursive: true });
+ await writeFile(join(PATHS.data, directory, 'index.html'), html);
+ await writeFile(join(PATHS.data, directory, 'pixel.svg'), '<svg xmlns="http://www.w3.org/2000/svg"/>');
+ return { directory, jobId: randomUUID() };
+}
+
+describe.skipIf(!chrome || !ffmpeg)('HTML composition with real Chrome and ffmpeg', () => {
+ beforeAll(async () => {
+ const profile = join(PATHS.data, 'chrome-test-profile');
+ proc = spawn(chrome, ['--headless=new', '--no-sandbox', '--no-first-run', '--disable-background-networking', '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank'], { stdio: ['ignore', 'ignore', 'pipe'] });
+ const ws = await new Promise((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error('Test Chrome did not start')), 20000);
+ proc.once('error', reject);
+ proc.stderr.on('data', bytes => {
+ const match = bytes.toString().match(/DevTools listening on (ws:\/\/\S+)/);
+ if (match) { clearTimeout(timer); resolve(match[1]); }
+ });
+ });
+ endpoint = new URL(ws).origin.replace('ws:', 'http:');
+ browser = await chromium.connectOverCDP(endpoint);
+ browserSession = await browser.newBrowserCDPSession();
+ }, 30000);
+
+ afterAll(async () => {
+ await browser?.close();
+ if (proc && proc.exitCode === null) { const exited = once(proc, 'close'); proc.kill(); await exited; }
+ cleanupTempDataRoots();
+ });
+
+ it('awaits every seek, encodes exactly 12 frames, keeps the target hidden and registers a thumbnail', async () => {
+ const input = await composition();
+ const before = await browserSession.send('Target.getTargets');
+ const observed = [];
+ const onProgress = event => {
+ if (event.generationId !== input.jobId) return;
+ observed.push(browserSession.send('Target.getTargets'));
+ };
+ videoGenEvents.on('progress', onProgress);
+ let result;
+ try { result = await renderComposition(input); } finally { videoGenEvents.off('progress', onProgress); }
+ const output = join(PATHS.videos, result.filename);
+ const pixels = execFileSync(ffmpeg, ['-v', 'error', '-i', output, '-f', 'rawvideo', '-pix_fmt', 'rgb24', '-'], { maxBuffer: 40 * 1024 * 1024 });
+ const frameBytes = 1280 * 720 * 3;
+ expect(pixels.length / frameBytes).toBe(12);
+ // Frame six is t=.5: block left=280, not the preceding seek's 240.
+ const redAt = x => pixels.subarray(6 * frameBytes + (110 * 1280 + x) * 3, 6 * frameBytes + (110 * 1280 + x) * 3 + 3);
+ expect(redAt(290)[0]).toBeGreaterThan(220);
+ expect(redAt(290)[1]).toBeLessThan(30);
+ expect(redAt(250)[1]).toBeGreaterThan(220);
+ // Chrome creates its own browser_ui/component-extension targets in the
+ // default context asynchronously. Pin OUR context plus visible pages,
+ // rather than requiring the browser's unrelated internal targets to freeze.
+ const extraTargets = (await Promise.all(observed)).flatMap(snapshot => snapshot.targetInfos).filter(info => info.url === 'https://composition.invalid/index.html');
+ expect(extraTargets.length).toBeGreaterThan(0);
+ expect(extraTargets.every(info => info.type === 'other')).toBe(true); // hidden CDP target type
+ const renderContexts = new Set(extraTargets.map(info => info.browserContextId));
+ expect(before.targetInfos.every(info => !renderContexts.has(info.browserContextId))).toBe(true);
+ const after = await browserSession.send('Target.getTargets');
+ expect(after.targetInfos.some(info => renderContexts.has(info.browserContextId))).toBe(false);
+ expect(after.targetInfos.filter(info => info.type === 'page').map(info => info.targetId).sort()).toEqual(before.targetInfos.filter(info => info.type === 'page').map(info => info.targetId).sort());
+ expect(await loadHistory()).toContainEqual(expect.objectContaining({ id: input.jobId, numFrames: 12, thumbnail: result.thumbnail, modelId: 'html-composition' }));
+ expect((await readFile(join(PATHS.videoThumbnails, result.thumbnail))).length).toBeGreaterThan(0);
+ }, 30000);
+
+ it('refuses a remote request by its full URL and removes partial artifacts', async () => {
+ const url = 'https://example.com/forbidden.png';
+ const input = await composition(fixture(`new Image().src = '${url}';`));
+ await expect(renderComposition(input)).rejects.toThrow(url);
+ expect((await readdir(PATHS.videos)).some(name => name.includes(input.jobId))).toBe(false);
+ expect(await loadHistory()).not.toContainEqual(expect.objectContaining({ id: input.jobId }));
+ });
+
+ it('loops and trims library music to the video with a half-second tail fade', async () => {
+ await mkdir(PATHS.music, { recursive: true });
+ execFileSync(ffmpeg, ['-v', 'error', '-f', 'lavfi', '-i', 'sine=frequency=440:duration=0.3', '-y', join(PATHS.music, 'example.wav')]);
+ const result = await renderComposition({ ...await composition(), musicTrack: 'example.wav' });
+ const pcm = execFileSync(ffmpeg, ['-v', 'error', '-i', join(PATHS.videos, result.filename), '-vn', '-f', 'f32le', '-ac', '1', '-ar', '48000', '-']);
+ expect(pcm.length / 4 / 48000).toBeGreaterThanOrEqual(1);
+ expect(pcm.length / 4 / 48000).toBeLessThan(1.05); // AAC packet padding
+ const rms = (start, end) => {
+ let sum = 0;
+ for (let n = start; n < end; n++) sum += pcm.readFloatLE(n * 4) ** 2;
+ return Math.sqrt(sum / (end - start));
+ };
+ expect(rms(45000, 47500)).toBeLessThan(rms(5000, 10000) * 0.2);
+ }, 30000);
+
+ it.each([
+ ["new WebSocket('wss://example.com/socket')", 'wss://example.com/socket'],
+ ['new RTCPeerConnection()', 'RTCPeerConnection'],
+ ["try { new Worker('/worker.js'); } catch {}", '/worker.js'],
+ ])('refuses non-HTTP escape paths: %s', async (script, error) => {
+ await expect(renderComposition(await composition(fixture(script)))).rejects.toThrow(error);
+ });
+
+ it.each([
+ ['durationSec', 'durationSec:0'], ['fps', 'fps:12.5'], ['width', 'width:123'],
+ ['durationSec', 'durationSec:1.01'], ['seek', 'seek:null'],
+ ])('names the invalid %s before capture', async (field, contract) => {
+ const input = await composition(fixture('', contract));
+ await expect(renderComposition(input)).rejects.toThrow(field);
+ });
+
+ it('cancels during capture and deletes partial video without publishing history', async () => {
+ const input = await composition();
+ const onProgress = event => { if (event.generationId === input.jobId) expect(cancel(input.jobId)).toBe(true); };
+ videoGenEvents.on('progress', onProgress);
+ try { await expect(renderComposition(input)).rejects.toThrow(/cancel/i); }
+ finally { videoGenEvents.off('progress', onProgress); }
+ expect((await readdir(PATHS.videos)).some(name => name.includes(input.jobId))).toBe(false);
+ expect(await loadHistory()).not.toContainEqual(expect.objectContaining({ id: input.jobId }));
+ });
+
+ it('rejects symlinked assets and directory traversal before opening a target', async () => {
+ const input = await composition();
+ await symlink(join(PATHS.data, 'video-history.json'), join(PATHS.data, input.directory, 'outside.json'));
+ await expect(renderComposition(input)).rejects.toThrow(/symlink/);
+ await expect(renderComposition({ ...input, directory: '../outside' })).rejects.toThrow(/Validation/);
+ });
+
+ it('settles and removes partial output after the browser target disappears', async () => {
+ const input = await composition();
+ let closed;
+ const onProgress = event => {
+ if (event.generationId !== input.jobId || closed) return;
+ closed = browserSession.send('Target.getTargets').then(({ targetInfos }) => {
+ const target = targetInfos.find(info => info.type === 'other');
+ return browserSession.send('Target.closeTarget', { targetId: target.targetId });
+ });
+ };
+ videoGenEvents.on('progress', onProgress);
+ try { await expect(renderComposition(input)).rejects.toThrow(/closed|target|session|context/i); }
+ finally { videoGenEvents.off('progress', onProgress); await closed; }
+ expect((await readdir(PATHS.videos)).some(name => name.includes(input.jobId))).toBe(false);
+ });
+});
diff --git a/server/services/mediaJobQueue/index.js b/server/services/mediaJobQueue/index.js
index fd36f93fb4..57168f27c6 100644
--- a/server/services/mediaJobQueue/index.js
+++ b/server/services/mediaJobQueue/index.js
@@ -170,7 +170,7 @@ 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', 'image', 'training', 'audio']);
+export const JOB_KINDS = Object.freeze(['video', 'video-upscale', 'html-composition', 'image', 'training', 'audio']);
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
@@ -183,6 +183,7 @@ function getGenModuleForJob(job) {
// later local branch would happily claim it and render a second time on this
// machine.
if (isRemoteMediaJob(job)) return REMOTE_MEDIA_MODULES[job.kind]();
+ if (job.kind === 'html-composition') return import('../htmlComposition/index.js');
if (job.kind === 'video-upscale') return import('../videoGen/upscaleJob.js');
if (job.kind === 'video' && job.params?.mode === IMAGE_GEN_MODE.GROK) return import('../videoGen/grok.js');
if (job.kind === 'video' && job.params?.mode === VIDEO_GEN_MODE.FAL) return import('../videoGen/fal.js');
@@ -1123,7 +1124,7 @@ async function runJob(job) {
await resolveLiveParams(job, safeParams);
- const emitter = job.kind === 'video' || job.kind === 'video-upscale' ? videoGenEvents
+ const emitter = job.kind === 'video' || job.kind === 'video-upscale' || job.kind === 'html-composition' ? videoGenEvents
: job.kind === 'training' ? trainingEvents
: job.kind === 'audio' ? audioGenEvents
: imageGenEvents;
@@ -1226,6 +1227,8 @@ async function runJob(job) {
await mod.generateChainedVideo({ ...safeParams, jobId: job.id });
} else if (job.kind === 'video') {
await mod.generateVideo({ ...safeParams, jobId: job.id });
+ } else if (job.kind === 'html-composition') {
+ await mod.renderComposition({ ...safeParams, jobId: job.id });
} else if (job.kind === 'video-upscale') {
await mod.runVideoUpscale({ ...safeParams, jobId: job.id });
} else if (job.kind === 'training') {
diff --git a/server/services/mediaJobQueue/index.test.js b/server/services/mediaJobQueue/index.test.js
index 7c4ce47828..cc26f624ae 100644
--- a/server/services/mediaJobQueue/index.test.js
+++ b/server/services/mediaJobQueue/index.test.js
@@ -79,6 +79,8 @@ const stubs = {
hasSurvivingTrainer: vi.fn(async () => false),
runVideoUpscale: vi.fn(() => new Promise(() => {})),
cancelVideoUpscale: vi.fn(),
+ renderComposition: vi.fn(async () => ({})),
+ cancelComposition: vi.fn(),
};
vi.mock('../creativeDirector/videoExecution.js', () => ({
@@ -92,6 +94,11 @@ vi.mock('../videoGen/local.js', () => ({
cancel: (...args) => stubs.cancelVideo(...args),
}));
+vi.mock('../htmlComposition/index.js', () => ({
+ renderComposition: (...args) => stubs.renderComposition(...args),
+ cancel: (...args) => stubs.cancelComposition(...args),
+}));
+
vi.mock('../videoGen/upscaleJob.js', () => ({
runVideoUpscale: (...args) => stubs.runVideoUpscale(...args),
cancel: (...args) => stubs.cancelVideoUpscale(...args),
@@ -237,6 +244,19 @@ describe('mediaJobQueue', () => {
// The generative video upscale (#6511) rides the queue as its own kind, on
// the serialized GPU lane and the videoGen event bus, so it can be watched,
// cancelled and watchdogged exactly like a render.
+ it('dispatches HTML compositions locally, forwards progress and cancellation, and settles the queue', async () => {
+ const { jobId } = await mediaJobQueue.enqueueJob({ kind: 'html-composition', params: { directory: 'compositions/example' } });
+ await waitFor(() => stubs.renderComposition.mock.calls.length === 1);
+ expect(stubs.renderComposition).toHaveBeenCalledWith(expect.objectContaining({ directory: 'compositions/example', jobId }));
+ expect(mediaJobQueue.isRemoteMediaJob(mediaJobQueue.getJob(jobId))).toBe(false);
+ videoGenEvents.emit('progress', { generationId: jobId, progress: 0.5 });
+ expect(mediaJobQueue.getJob(jobId).progress).toBe(0.5);
+ await mediaJobQueue.cancelJob(jobId);
+ expect(stubs.cancelComposition).toHaveBeenCalledWith(jobId);
+ videoGenEvents.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 };