Files
patriothacks/e2e/openmotion/captureAssembly.mjs
T
OmO Orchestrator eb43d1c5c0 feat(demo): add OpenMotion-based promo video pipeline alongside the existing ffmpeg one
Migrates the promo video's compositing/motion-graphics layer (title cards,
margins, transitions, audio mix) to OpenMotion (Hyperframes 0.9.7), built
and verified across 3 independently-gated stages:

- e2e/openmotion-poc/: proof-of-concept proving real footage composites
  correctly with live-sourced margins and a flash-free title card
- e2e/openmotion/: the full video - intro, Act I/II/III, Epilogue, outro,
  and the real two-device Assembly sync scene, with continuous ambient
  audio, rendered to e2e/openmotion/renders/full.mp4 (1920x1080, 62.8s)

The existing e2e/demoVideoFull.e2e.mjs is untouched and remains the
production fallback (byte-for-byte unmodified, confirmed by every stage's
independent review). Real Playwright screen-recording of the actual app is
preserved as the footage source throughout - OpenMotion replaces only the
post-capture compositing, never the capture itself.

Every protection carried forward and independently re-verified at each
stage: no cursor overlay, 16:9 landscape with live-data margins, in-universe
copy (zero generic 'town' references), audible background audio (~-38dB,
no clipping), zero content clipping at any beat including the Assembly
two-device letterboxing, and the pacing fixes already proven in the ffmpeg
pipeline (no white-flash frames, graceful fade-to-black ending).
2026-11-19 16:35:31 -05:00

330 lines
14 KiB
JavaScript

// STAGE-3 OpenMotion: Assembly two-device sync scene capture + composite.
//
// Records the REAL Assembly mini-app driven by TWO genuinely isolated
// Playwright browser contexts (separate storage origins) through the real
// "Sync with nearby devices" toggle over a real local y-webrtc signaling
// server + real WebRTC transport: connect -> transport-proven -> partition
// -> heal -> converged. This is the SAME real two-device interaction as
// e2e/demoVideoFull.e2e.mjs's recordAssemblySyncScene() - ported here (not
// imported) because demoVideoFull.e2e.mjs self-invokes main() on import and
// is explicitly off-limits, exactly the Stage-2 rationale for runTour().
// Nothing here is fabricated: both device streams are real app recordings.
//
// The two real device panes are then composited side-by-side and letterboxed
// into one 1920x1080 clip with the SAME symmetric-margin convention the
// fix-miniapp-gaps-and-demo-video work fixed (scale the 828x896 hstack to
// LANDSCAPE_PHONE_HEIGHT=960 and pad to 1920x1080 centered - real margin on
// every side, no edge clipping), plus the proven fade-in-from-black (0.5s) /
// fade-out-to-black (0.6s) pacing so the scene lands out of the dark outro
// card and the whole film closes on a graceful dim-to-black. The OpenMotion
// composition then plays this clip as a full-canvas <video> after the outro
// card, with the continuous ambient <audio> running underneath.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import ffmpegStatic from "ffmpeg-static";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, rmSync, writeFileSync, existsSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const OM_DIR = __dirname;
const ROOT = resolve(__dirname, "..", ".."); // worktree root
const VIDEO_TMP_DIR = resolve(OM_DIR, ".tmp-capture");
const ASSETS_DIR = resolve(OM_DIR, "assets");
const MANIFEST_OUT = resolve(OM_DIR, "assembly-manifest.json");
const FFMPEG_BIN = ffmpegStatic;
const PANE = { width: 414, height: 896 };
const FINAL_W = 1920;
const FINAL_H = 1080;
const LANDSCAPE_PHONE_HEIGHT = 960; // 60px top/bottom padding on a 1080 canvas
const SIG_PORT = 44000 + Math.floor(Math.random() * 10000);
const VITE_PORT = 45000 + Math.floor(Math.random() * 10000);
const SIG = `ws://127.0.0.1:${SIG_PORT}`;
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, label, timeoutMs = 20000) {
const start = Date.now();
let lastErr;
while (Date.now() - start < timeoutMs) {
try {
const v = await fn();
if (v) return v;
} catch (e) {
lastErr = e;
}
await sleep(150);
}
throw new Error(`timeout waiting for: ${label}${lastErr ? ` (last error: ${lastErr})` : ""}`);
}
function startSignaling() {
return new Promise((resolvePromise, reject) => {
const child = spawn("node", ["node_modules/y-webrtc/bin/server.js"], {
cwd: ROOT,
env: { ...process.env, PORT: String(SIG_PORT) },
stdio: ["ignore", "pipe", "pipe"],
});
const to = setTimeout(() => reject(new Error("signaling start timeout")), 10000);
child.stdout.on("data", (b) => {
if (String(b).includes("Signaling server running")) {
clearTimeout(to);
resolvePromise(child);
}
});
child.stderr.on("data", (b) => process.stderr.write(`[sig] ${b}`));
child.on("exit", (code) => reject(new Error(`signaling exited early: ${code}`)));
});
}
async function startVite() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: { host: "127.0.0.1", port: VITE_PORT, strictPort: true },
});
await vite.listen();
return vite;
}
function probeDurationSeconds(videoPath) {
try {
execFileSync(FFMPEG_BIN, ["-i", videoPath], { stdio: ["ignore", "pipe", "pipe"] });
return null;
} catch (e) {
const m = String(e.stderr ?? "").match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (!m) return null;
return Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]);
}
}
// Records the two isolated device panes through the real Assembly screen.
async function recordAssemblySyncScene() {
console.log("\n=== Assembly real-screen sync (two isolated devices) ===");
const videoDirA = resolve(VIDEO_TMP_DIR, "assembly-deviceA");
const videoDirB = resolve(VIDEO_TMP_DIR, "assembly-deviceB");
rmSync(videoDirA, { recursive: true, force: true });
rmSync(videoDirB, { recursive: true, force: true });
mkdirSync(videoDirA, { recursive: true });
mkdirSync(videoDirB, { recursive: true });
const sig = await startSignaling();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const ctxA = await browser.newContext({ viewport: PANE, recordVideo: { dir: videoDirA, size: PANE } });
const ctxB = await browser.newContext({ viewport: PANE, recordVideo: { dir: videoDirB, size: PANE } });
const sigState = { blockSig: false };
for (const ctx of [ctxA, ctxB]) {
await ctx.routeWebSocket(new RegExp(`127\\.0\\.0\\.1:${SIG_PORT}`), (ws) => {
if (sigState.blockSig) {
ws.close();
return;
}
ws.connectToServer();
});
}
const pageA = await ctxA.newPage();
const pageB = await ctxB.newPage();
const sceneStartRef = { value: Date.now() };
const beats = [];
const room = `full-demo-${Math.random().toString(36).slice(2)}`;
const ASSEMBLY_URL = `${APP_URL}/miniapp/assembly`;
const ENGINE_MODULE_URL = `${APP_URL}/src/miniapps/assembly/useAssemblyEngine.ts`;
const ASSEMBLY_LIB_URL = `${APP_URL}/src/lib/assembly.ts`;
async function beat(label, note) {
const offsetS = (Date.now() - sceneStartRef.value) / 1000;
beats.push({ label, note, offsetS });
console.log(`[assembly +${offsetS.toFixed(1)}s] ${label}: ${note}`);
}
async function setSyncTransportOverride(page) {
await page.evaluate(
async ({ moduleUrl, room, signaling }) => {
const mod = await import(/* @vite-ignore */ moduleUrl);
mod.setAssemblySyncTransportOverrideForTesting({
room,
signaling: [signaling],
peerOpts: { config: { iceServers: [] } },
});
},
{ moduleUrl: ENGINE_MODULE_URL, room, signaling: SIG },
);
}
async function readPeerCount(page) {
const el = page.getByTestId("assembly-peer-count");
if ((await el.count()) === 0) return 0;
const text = (await el.textContent()) ?? "";
const match = text.match(/Connected to (\d+)/);
return match ? Number(match[1]) : 0;
}
try {
await pageA.goto(ASSEMBLY_URL, { waitUntil: "load" });
await pageB.goto(ASSEMBLY_URL, { waitUntil: "load" });
await pageA.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await pageB.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await setSyncTransportOverride(pageA);
await setSyncTransportOverride(pageB);
await beat("boot", "two genuinely isolated devices (separate storage origins) open the real Assembly screen; sync is honestly off by default");
await sleep(650);
// 1. Connect through the real UI toggle.
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await readPeerCount(pageA)) >= 1, "device A connects");
await waitFor(async () => (await readPeerCount(pageB)) >= 1, "device B connects");
await beat("connected", "real WebRTC transport connected over a local signaling server - both devices see a live peer count");
await sleep(600);
// 2. Prove the transport genuinely carries data: a proposal seeded on A
// (via the real putProposal production function) arrives on B.
await pageA.evaluate(
async ({ engineUrl, libUrl, proposal }) => {
const engineMod = await import(/* @vite-ignore */ engineUrl);
const libMod = await import(/* @vite-ignore */ libUrl);
const { assembly } = engineMod.getAssemblyEngineForTesting(engineMod.DEFAULT_ASSEMBLY_DB_NAME);
libMod.putProposal(assembly, proposal);
},
{
engineUrl: ENGINE_MODULE_URL,
libUrl: ASSEMBLY_LIB_URL,
proposal: {
id: "sync-demo-prop",
title: "Install solar lanterns on the east path",
description: "Seeded on device A only - must arrive on device B purely over WebRTC.",
authorId: "seed",
createdAt: Date.now(),
status: "open",
},
},
);
await waitFor(
async () => (await pageB.getByTestId("assembly-proposal-sync-demo-prop").count()) > 0,
"device B receives device A's proposal over real WebRTC",
);
await beat("transport-proven", "a proposal created on device A arrived on device B purely over the real WebRTC transport - B's own IndexedDB never had it");
await sleep(750);
// 3. Partition: toggle sync OFF on both sides (real teardown) + block
// signaling + go offline, as defense in depth.
sigState.blockSig = true;
await ctxA.setOffline(true);
await ctxB.setOffline(true);
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await pageA.getByTestId("assembly-peer-count").count()) === 0, "device A's peer indicator disappears");
await waitFor(async () => (await pageB.getByTestId("assembly-peer-count").count()) === 0, "device B's peer indicator disappears");
await pageA.getByTestId(`assembly-vote-yes-sync-demo-prop`).click();
await pageB.getByTestId(`assembly-vote-no-sync-demo-prop`).click();
await sleep(500);
const aSeesB = await pageA.getByTestId("assembly-vote-status-sync-demo-prop").textContent();
const bSeesA = await pageB.getByTestId("assembly-vote-status-sync-demo-prop").textContent();
await beat(
"partitioned",
`both devices genuinely isolated (peer count 0, network offline, signaling blocked) - independent votes cast (A sees "${aSeesB?.trim()}", B sees "${bSeesA?.trim()}")`,
);
await sleep(750);
// 4. Heal: restore network + signaling, toggle sync back on, converge.
sigState.blockSig = false;
await ctxA.setOffline(false);
await ctxB.setOffline(false);
await pageA.getByTestId("assembly-sync-toggle").click();
await pageB.getByTestId("assembly-sync-toggle").click();
await waitFor(async () => (await readPeerCount(pageA)) >= 1, "device A reconnects");
await waitFor(async () => (await readPeerCount(pageB)) >= 1, "device B reconnects");
await sleep(600);
await beat("healed-reconnected", "both devices reconnected after the partition - real WebrtcProvider re-established");
await sleep(1000);
} finally {
await ctxA.close();
await ctxB.close();
await browser.close();
sig.kill("SIGKILL");
}
const videoPathA = await pageA.video().path();
const videoPathB = await pageB.video().path();
console.log(`Assembly recorded: deviceA=${videoPathA} deviceB=${videoPathB} (${((Date.now() - sceneStartRef.value) / 1000).toFixed(1)}s wall-clock)`);
return { videoPathA, videoPathB, beats };
}
// Composites the two real device panes side-by-side, then letterboxes the
// 828x896 stack into the final 1920x1080 canvas with symmetric margins
// (scale to LANDSCAPE_PHONE_HEIGHT=960, pad centered) - the F3 letterbox fix
// - plus fade-in-from-black (0.5s) and fade-out-to-black (0.6s).
const LEAD_TRIM = 0.8; // skip each device page's blank/white React-mount boot frames before the fade
function compositeSideBySide(videoPathA, videoPathB, outPath) {
mkdirSync(dirname(outPath), { recursive: true });
const durA = probeDurationSeconds(videoPathA);
const durB = probeDurationSeconds(videoPathB);
// hstack ends at the shorter input; both are trimmed by LEAD_TRIM up front.
const dur = Math.max(0.1, Math.min(durA ?? 10, durB ?? 10) - LEAD_TRIM);
const fadeOutStart = Math.max(0, dur - 0.6);
// -ss before each -i trims the white boot frames so the fade-in lands on the
// real Assembly screen (never on a bright blank mount) - the outro card
// above and this 0.5s fade-in-from-black then make the cut dark->dark.
const filter =
`[0:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=30[v0];` +
`[1:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=30[v1];` +
"[v0][v1]hstack=inputs=2[stacked];" +
`[stacked]scale=-2:${LANDSCAPE_PHONE_HEIGHT},pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,` +
`fade=t=in:st=0:d=0.5,fade=t=out:st=${fadeOutStart.toFixed(2)}:d=0.6[v]`;
execFileSync(FFMPEG_BIN, [
"-y",
"-ss", String(LEAD_TRIM), "-i", videoPathA,
"-ss", String(LEAD_TRIM), "-i", videoPathB,
"-filter_complex", filter, "-map", "[v]",
"-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "+faststart",
outPath,
], { stdio: ["ignore", "pipe", "pipe"] });
}
async function main() {
console.log("=== STAGE-3 capture: Assembly two-device sync scene (real app footage) ===");
const vite = await startVite();
let scene;
try {
scene = await recordAssemblySyncScene();
} finally {
await vite.close();
}
mkdirSync(ASSETS_DIR, { recursive: true });
const outPath = resolve(ASSETS_DIR, "assembly.mp4");
if (existsSync(outPath)) rmSync(outPath);
compositeSideBySide(scene.videoPathA, scene.videoPathB, outPath);
const outDur = probeDurationSeconds(outPath);
console.log(`[assembly] composite -> ${outPath} (${outDur?.toFixed(2)}s, 1920x1080)`);
writeFileSync(
MANIFEST_OUT,
JSON.stringify(
{
recordedAt: new Date().toISOString(),
canvas: { width: FINAL_W, height: FINAL_H },
clip: { name: "assembly", path: "assets/assembly.mp4", durationS: outDur },
beats: scene.beats,
},
null,
2,
),
);
console.log(`\nAssembly manifest: ${MANIFEST_OUT}`);
}
main().catch((e) => {
console.error(e);
process.exit(1);
});