Files
patriothacks/e2e/demoVideoFull.e2e.mjs
T
OmO Orchestrator f8ceb980a1 feat(e2e): add playwright-recast motion graphics to the demo video pipeline
Adds cursor overlay, click ripples, auto-zoom, kinetic-typography intro/outro cards, real per-beat captions, and a self-synthesized ambient music bed to the main demo scene via playwright-recast, with ffmpeg-static/ffprobe-static as real devDependencies. Fixes a concat-stage audio/duration regression found during verification (a single filter_complex mixing a real audio stream with an anullsrc generator node silently truncated output duration) by splitting the final concat into three separately-verified ffmpeg passes.
2026-11-18 14:17:16 -05:00

1058 lines
52 KiB
JavaScript

// Full-feature demo video (ad-hoc, user-requested - not tied to a plan
// todo number). Self-contained Playwright runner, same shape as every
// other e2e/*.e2e.mjs script in this project: starts a real local Vite
// dev server, drives the REAL shipped app through its REAL rendered UI
// (no bypass/internal-function calls for anything shown on camera), and
// records real video via Playwright's `recordVideo` context option.
//
// Two recording scenes:
// Scene 1 ("main"): one browser context, one continuous tour touching
// all 13 mini-apps plus the wallet, admin seed, and the upload-a-
// mini-app flow. `window.crypto.getRandomValues` is pinned (the same
// technique e2e/fairDrawWalletCredit.e2e.mjs already uses) so Fair
// Draw's real commit/reveal/verify cycle deterministically resolves to
// "You" winning, making the wallet-credit beat reliably demonstrable on
// camera without touching any other real logic. The raw capture is then
// run through `playwright-recast` (a real trace-based motion-graphics
// pipeline - see .omo/ulw-research/20261118-121942/ for the research
// that picked it over a from-scratch Remotion/Manim rebuild) to add a
// synthetic cursor, click ripples, and auto-zoom onto the exact element
// being interacted with, derived from the real Playwright trace - not
// hand-authored keyframes. It also gets a motion-graphics polish pass
// (see .omo/evidence/full-feature-demo/DEMO_VIDEO_NOTES.md for the
// research behind each choice): a kinetic-typography title card as a
// cold open/outro (crossfaded in via `.intro()`/`.outro()` - the same
// "bold statement before the product" hook used by Linear/Apple/Raycast
// launch films), real on-screen captions generated from this script's
// own beat-log narration (written into the trace via
// `context.tracing.group()` using the exact marker convention
// `subtitlesFromTrace()` already looks for, so no voiceover/TTS key is
// needed - captions carry the explanation instead), and a short
// self-synthesized ambient pad (`ffmpeg` sine-wave tones, not a
// copyrighted track) via `.backgroundMusic()` so the video isn't silent.
//
// Scene 2 ("assembly-sync"): TWO genuinely isolated browser contexts
// (separate storage origins - the same discipline
// e2e/assemblyScreenSync.e2e.mjs already proved out) open the real
// shipped Assembly screen and drive its real "Sync with nearby devices"
// toggle through connect -> partition -> heal -> converge, recorded as
// two side-by-side panes. Left as a plain capture (no recast pass): the
// point of this scene is the side-by-side proof of independent device
// state, which a zoom/cursor layer would only obscure.
//
// The two scenes are concatenated (scale/pad to one common canvas) into
// a single final video with a real ffmpeg binary.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { Recast } from "playwright-recast";
import { NARRATE_TITLE_PREFIX } from "playwright-recast/helpers";
import ffmpegStatic from "ffmpeg-static";
import ffprobeStatic from "ffprobe-static";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, existsSync, readdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const EVIDENCE_DIR = resolve(ROOT, ".omo/evidence/full-feature-demo");
const VIDEO_TMP_DIR = resolve(ROOT, ".tmp/full-feature-demo");
const FINAL_VIDEO = resolve(ROOT, ".omo/evidence/full-feature-demo/the-commons-hollow-full-demo.mp4");
// The Playwright-bundled ffmpeg (~/.cache/ms-playwright/ffmpeg-*/ffmpeg-linux)
// is a `--disable-everything` build meant only for Playwright's own
// frame-to-webm screencast conversion: it has no `hstack`/`concat`/
// `setsar`/`fps` filters and no libx264 encoder at all, so it cannot do
// the compositing/concatenation this script needs, nor what
// `playwright-recast` needs (`zoompan`, `xfade`, `overlay`, `subtitles`/
// `ass` - confirmed present; `drawtext` confirmed ABSENT, so `.urlBar()`
// is not used anywhere in this script). `ffmpeg-static`/`ffprobe-static`
// are real devDependencies of this project (not a throwaway /tmp
// install) providing a full static build of both binaries; their
// directory is prepended to PATH so `playwright-recast`'s own internal
// `execFileSync('ffmpeg'|'ffprobe', ...)` calls find them too.
const FFMPEG_BIN = process.env.FFMPEG_BIN ?? ffmpegStatic;
const FFPROBE_BIN = process.env.FFPROBE_BIN ?? ffprobeStatic.path;
if (!existsSync(FFMPEG_BIN)) {
throw new Error(`ffmpeg binary not found at ${FFMPEG_BIN}. Set FFMPEG_BIN env var to override.`);
}
if (!existsSync(FFPROBE_BIN)) {
throw new Error(`ffprobe binary not found at ${FFPROBE_BIN}. Set FFPROBE_BIN env var to override.`);
}
process.env.PATH = `${dirname(FFMPEG_BIN)}:${dirname(FFPROBE_BIN)}:${process.env.PATH ?? ""}`;
const PANE = { width: 414, height: 896 };
// The main scene is recorded at 2x device-pixel density (recast's own
// documented fix for sharp zoomed/overlaid text - plain `deviceScaleFactor`
// never reaches a headless recording; it needs BOTH the
// `--force-device-scale-factor` launch arg AND a matching `recordVideo`
// `size`, confirmed by this project's own test render during the research
// pass, which otherwise warned of a 4.64x upscale and visibly soft text).
const RECAST_SCALE = 2;
const MAIN_VIDEO_SIZE = { width: PANE.width * RECAST_SCALE, height: PANE.height * RECAST_SCALE };
const FINAL_W = PANE.width * 2;
const FINAL_H = PANE.height;
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})` : ""}`);
}
// `context` is optional (Scene 2's dualBeat has its own logger and never
// passes one): when present, each beat also opens a `context.tracing.group()`
// titled with recast's own `NARRATE_TITLE_PREFIX` marker - the exact
// convention its `subtitlesFromTrace()` stage already looks for (confirmed
// against `helpers.d.ts` and a standalone trace-parse probe), so this
// script's real beat narration becomes real on-screen captions without
// needing playwright-bdd or a TTS key. Each caption's window runs from its
// own beat to the next one's (or scene end), matching `narrate()`'s own
// documented span semantics.
function makeBeatLog(sceneName, sceneStartRef, context) {
const beats = [];
let captionOpen = false;
return {
beats,
async log(label, note, page) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
let screenshot;
if (page) {
screenshot = resolve(EVIDENCE_DIR, `${sceneName}-${String(beats.length).padStart(2, "0")}-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await page.screenshot({ path: screenshot }).catch(() => {});
}
beats.push({ scene: sceneName, label, note, sceneRelativeMs, screenshot });
console.log(`[${sceneName} +${(sceneRelativeMs / 1000).toFixed(1)}s] ${label}: ${note}`);
if (context) {
if (captionOpen) await context.tracing.groupEnd();
await context.tracing.group(`${NARRATE_TITLE_PREFIX}${note}`);
captionOpen = true;
}
},
async closeCaption() {
if (context && captionOpen) {
await context.tracing.groupEnd();
captionOpen = false;
}
},
};
}
// ---------------------------------------------------------------------
// Motion-graphics assets: a kinetic-typography title card (cold-open hook
// + outro, the same "bold statement before the product" pattern
// reverse-engineered from Linear/Apple/Raycast launch films - see
// DEMO_VIDEO_NOTES.md) and a short self-synthesized ambient pad (plain
// `ffmpeg` sine oscillators - no third-party/copyrighted audio file).
// Both are rendered with the same Chromium/ffmpeg this script already
// uses, at the exact resolution `addMotionGraphics()` needs so recast's
// internal `xfade`/`amix` compositing doesn't choke on a mismatch.
// ---------------------------------------------------------------------
const TITLE_CARD_CSS = `
* { margin:0; padding:0; box-sizing:border-box; }
html,body { width:100%; height:100%; background:#05070d; overflow:hidden; font-family: -apple-system, 'Helvetica Neue', Arial, sans-serif; }
.wrap { width:100%; height:100%; display:flex; flex-direction:column; align-items:center; justify-content:center; position:relative; padding:0 60px; text-align:center; }
.glow { position:absolute; width:900px; height:900px; border-radius:50%; background:radial-gradient(circle, rgba(22,119,255,0.35) 0%, rgba(22,119,255,0) 70%); filter:blur(10px); }
.eyebrow { color:#4f9dff; letter-spacing:0.4em; font-size:20px; font-weight:600; text-transform:uppercase; opacity:0; transform:translateY(14px); animation: rise 0.6s ease forwards 0.15s; }
.title { color:#f5f7ff; font-size:72px; font-weight:800; letter-spacing:-0.02em; margin-top:18px; line-height:1.05; opacity:0; transform:translateY(20px); animation: rise 0.7s ease forwards 0.45s; }
.rule { width:110px; height:4px; background:#1677FF; margin-top:26px; transform:scaleX(0); transform-origin:center; animation: grow 0.6s ease forwards 0.95s; }
.tagline { color:#9fb3d9; font-size:26px; font-weight:400; margin-top:26px; max-width:620px; opacity:0; transform:translateY(14px); animation: rise 0.6s ease forwards 1.3s; }
@keyframes rise { to { opacity:1; transform:translateY(0); } }
@keyframes grow { to { transform:scaleX(1); } }
`;
function titleCardHtml({ eyebrow, title, tagline }) {
return `<!doctype html><html><head><style>${TITLE_CARD_CSS}</style></head>
<body><div class="wrap"><div class="glow"></div>
<div class="eyebrow">${eyebrow}</div>
<div class="title">${title}</div>
<div class="rule"></div>
<div class="tagline">${tagline}</div>
</div></body></html>`;
}
// Records the title card through a real throwaway Playwright context (same
// `recordVideo` mechanism as the real scenes) so the reveal animation plays
// out as genuine composited video frames, not a hand-assembled still.
async function renderTitleCard({ html, size, durationMs, outDir }) {
mkdirSync(outDir, { recursive: true });
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ viewport: size, recordVideo: { dir: outDir, size } });
const page = await context.newPage();
await page.setContent(html, { waitUntil: "load" });
await page.waitForTimeout(durationMs);
await context.close();
await browser.close();
const file = readdirSync(outDir).find((f) => f.endsWith(".webm"));
if (!file) throw new Error(`title card recording produced no .webm in ${outDir}`);
return resolve(outDir, file);
}
// A soft three-note pad (C3/E3/G3) with slow tremolo, faded in and out -
// generated entirely by ffmpeg's `lavfi` sine-wave source, so there's no
// licensing question around the audio bed `.backgroundMusic()` needs.
function generateAmbientTrack(outPath, durationSeconds = 26) {
mkdirSync(dirname(outPath), { recursive: true });
const fadeOutStart = Math.max(0, durationSeconds - 4);
execFileSync(
FFMPEG_BIN,
[
"-y",
"-f", "lavfi", "-i", `sine=frequency=130.81:duration=${durationSeconds}`,
"-f", "lavfi", "-i", `sine=frequency=164.81:duration=${durationSeconds}`,
"-f", "lavfi", "-i", `sine=frequency=196.00:duration=${durationSeconds}`,
"-filter_complex",
`[0][1][2]amix=inputs=3:duration=longest:weights=1 0.8 0.7[mix];` +
`[mix]tremolo=f=0.15:d=0.3,volume=0.14,afade=t=in:st=0:d=3,afade=t=out:st=${fadeOutStart}:d=4[out]`,
"-map", "[out]",
"-c:a", "libmp3lame", "-b:a", "128k",
outPath,
],
{ stdio: ["ignore", "pipe", "pipe"] },
);
return outPath;
}
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;
}
// ---------------------------------------------------------------------
// Generic shell navigation helpers
// ---------------------------------------------------------------------
async function backHome(page) {
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
}
async function openTile(page, label) {
await page.getByRole("button", { name: label }).click();
await page.locator(`[aria-label="${label}"]`).first().waitFor({ state: "visible", timeout: 10000 });
}
async function walletBalanceText(page) {
return (await page.getByTestId("wallet-balance").textContent())?.trim();
}
// ---------------------------------------------------------------------
// Fair Draw deterministic-winner override (mirrors
// e2e/fairDrawWalletCredit.e2e.mjs FILL_FOR_YOU_WINS exactly).
// ---------------------------------------------------------------------
async function forceLocalIdentityWinsFairDraw(context) {
await context.addInitScript(() => {
window.crypto.getRandomValues = function (arr) {
arr.fill(0x02);
return arr;
};
});
}
// =======================================================================
// SCENE 1: main single-context tour
// =======================================================================
async function recordMainScene() {
console.log("\n=== Scene 1: main feature tour ===");
const videoDir = resolve(VIDEO_TMP_DIR, "main");
mkdirSync(videoDir, { recursive: true });
const browser = await chromium.launch({
headless: true,
args: ["--no-sandbox", `--force-device-scale-factor=${RECAST_SCALE}`],
});
const context = await browser.newContext({
viewport: PANE,
deviceScaleFactor: RECAST_SCALE,
recordVideo: { dir: videoDir, size: MAIN_VIDEO_SIZE },
});
// Real Playwright tracing (actions, screencast frames, cursor positions)
// is what playwright-recast's autoZoom()/cursorOverlay()/clickEffect()
// read to find click/fill coordinates - this is the one new line of
// capture this motion-graphics pass needed; the tour script below is
// completely unmodified.
await context.tracing.start({ screenshots: true, snapshots: true });
await forceLocalIdentityWinsFairDraw(context);
const page = await context.newPage();
const sceneStartRef = { value: Date.now() };
const beatLog = makeBeatLog("main", sceneStartRef, context);
try {
// --- Cold start: real non-custodial identity resolves, honest empty state ---
await page.goto(`${APP_URL}/`, { waitUntil: "load" });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await waitFor(async () => (await walletBalanceText(page)) !== "--", "identity resolves (wallet leaves '--')");
await beatLog.log("cold-start", "fresh local Ed25519 identity resolved, honest empty home grid + wallet", page);
await sleep(1200);
// --- Admin: Load Hollow demo seed ---
await page.goto(`${APP_URL}/admin`, { waitUntil: "load" });
await page.getByRole("button", { name: "Load Hollow demo" }).click();
await waitFor(
async () => ((await page.getByTestId("demo-load-status").textContent()) ?? "").includes("Demo data loaded"),
"demo seed load status",
);
await beatLog.log("admin-seed", "Load Hollow demo clicked - signed seed.* events appended (roster, proposal, housing, mentor, wallet balance)", page);
await sleep(1000);
await page.goto(`${APP_URL}/`, { waitUntil: "load" });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await sleep(800);
// --- Water Watch: GAP-8 false-alert fix + genuine corroborated detection ---
await openTile(page, "Water Watch");
async function reportReading(sensorId, value) {
await page.getByTestId("report-reading-sensor").fill(sensorId);
await page.getByTestId("report-reading-value").fill(String(value));
await page.getByTestId("report-reading-submit").click();
await waitFor(
async () => !((await page.getByTestId("report-reading-status").textContent()) ?? "").includes("Submitting..."),
`submit ${sensorId}=${value} settles`,
);
}
await reportReading("sensor-A", 7);
await sleep(400);
await reportReading("sensor-A", 7.05);
const stateAfterFlat = await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state");
if (stateAfterFlat === "alert") {
throw new Error("REGRESSION: a flat 2nd reading triggered a false alert (GAP-8 fix did not hold)");
}
await beatLog.log("waterwatch-no-false-alert", `flat 2nd reading (7.0 -> 7.05) did NOT fire a false alert - state is "${stateAfterFlat}", not "alert"`, page);
await sleep(1200);
await reportReading("sensor-A", 50);
await waitFor(
async () => (await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state")) === "corroborating",
"pH channel reaches corroborating after a genuine spike",
);
await beatLog.log("waterwatch-corroborating", "genuine spike (7 -> 50) correctly flagged - awaiting a second independent sensor", page);
await sleep(1000);
await reportReading("sensor-B", 7);
await reportReading("sensor-B", 55);
await waitFor(
async () => (await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state")) === "alert",
"pH channel reaches alert once corroborated",
);
await beatLog.log("waterwatch-alert", "independent sensor-B corroborated the spike - real signed alert, Fair Share re-solve triggered", page);
await sleep(1400);
// --- Fair Share: water allocation re-solved ---
await backHome(page);
await openTile(page, "Fair Share");
await waitFor(async () => {
const text = (await page.getByTestId("tile-water-allocation").textContent()) ?? "";
return text.trim().length > 0 && text !== "No allocation yet";
}, "Fair Share water tile shows a real re-solved allocation");
await beatLog.log("fairshare-water", "Fair Share's water tile reflects the honesty-anchor chain's re-solved CEEI allocation", page);
await sleep(1400);
// --- Farms -> Fair Share food edge (2nd integration edge) ---
await backHome(page);
await openTile(page, "Farms");
await page.getByTestId("farms-temp-date").fill("2026-05-01");
await page.getByTestId("farms-temp-tmin").fill("10");
await page.getByTestId("farms-temp-tmax").fill("30");
await page.getByTestId("farms-temp-add").click();
await page.getByTestId("farms-plot-id").fill("plot-a");
await page.getByTestId("farms-plot-area").fill("100");
await page.getByTestId("farms-plot-add").click();
await page.getByTestId("farms-crop-id").fill("wheat");
await page.getByTestId("farms-crop-maturity-gdd").fill("10");
await page.getByTestId("farms-crop-yield").fill("2");
await page.getByTestId("farms-crop-add").click();
await waitFor(
async () => ((await page.getByTestId("farms-forecast-total").textContent()) ?? "").includes("200.00 kg"),
"Farms LP optimizer reaches a real 200.00 kg forecast",
);
await beatLog.log("farms-forecast", "real GDD + LP optimizer forecast (1 temp reading, 1 plot, 1 crop) -> 200.00 kg", page);
await sleep(1200);
await backHome(page);
await openTile(page, "Fair Share");
await waitFor(async () => {
const text = (await page.getByTestId("tile-food-allocation").textContent()) ?? "";
return text.trim().length > 0 && text !== "No allocation yet" && text.trim() !== "0";
}, "Fair Share food tile reflects the Farms forecast");
await beatLog.log("fairshare-food", "Farms' real forecast fed Fair Share's second cross-mini-app integration edge - food tile re-solved", page);
await sleep(1400);
// --- Fair Draw: real commit-reveal-verify -> real wallet credit ---
await backHome(page);
await openTile(page, "Fair Draw");
await page.getByRole("button", { name: "Start Draw" }).click();
await page.getByRole("button", { name: "Reveal" }).click();
await page.getByTestId("reveal-draw-revealed").waitFor({ state: "visible" });
const winnerText = (await page.getByTestId("reveal-draw-winner").textContent())?.trim();
const badgeState = await page.getByTestId("reveal-draw-badge").getAttribute("data-state");
await beatLog.log("fairdraw-reveal", `real commit -> reveal -> verify cycle: "${winnerText}", badge state "${badgeState}"`, page);
await sleep(1200);
await waitFor(async () => (await walletBalanceText(page)) !== undefined, "wallet balance chip present on fair-draw route");
await beatLog.log("fairdraw-wallet-live", "WalletCard balance updates live on the same route, no reload, from the real Fair Draw win", page);
await sleep(1000);
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByTestId("history-entry").first().waitFor({ state: "visible" });
await beatLog.log("fairdraw-history-row", "full transaction history now shows the real signed wallet.issue credit row", page);
await sleep(1000);
// --- Wallet signature verification (headline crypto feature) ---
const firstRow = page.getByTestId("history-entry").first();
const badge = firstRow.locator('[data-testid^="history-signature-badge-"]');
await waitFor(async () => ((await badge.textContent()) ?? "").trim() === "Verified", "signature badge resolves to Verified");
await beatLog.log("wallet-sig-verified", "independent verifyEntrySignature() re-check confirms the entry's Ed25519 signature is genuine", page);
await sleep(900);
const toggle = firstRow.locator('[data-testid^="history-expand-toggle-"]');
await toggle.click();
const detail = firstRow.locator('[data-testid^="history-signature-detail-"]');
await detail.waitFor({ state: "visible" });
await beatLog.log("wallet-sig-expanded", "raw Ed25519 signature + author public key bytes are directly inspectable, not just a claimed verification", page);
await sleep(1600);
await toggle.click();
// --- Housing: real assigned slot from the demo seed ---
// Already on the home route from the wallet-history step above -
// ShellLayout hides the "Back to home" link on "/" itself, so
// backHome() must NOT be called here.
await openTile(page, "Housing");
await page.getByTestId("housing-assigned-slot").waitFor({ state: "visible" });
await beatLog.log("housing", "Housing shows a real assigned room slot from the seeded assignment cycle, not a permanent empty state", page);
await sleep(1200);
// --- Mentor: real at-risk skill ---
await backHome(page);
await openTile(page, "Mentor");
await page.getByTestId("mentor-card-well-repair").waitFor({ state: "visible" });
await beatLog.log("mentor", "Mentor shows a real at-risk skill card (deduped dependents count) from the seeded skill-holder data", page);
await sleep(1200);
// --- Health Post: WHO-IMCI triage classification ---
await backHome(page);
await openTile(page, "Health Post");
await page.getByTestId("triage-age-input").fill("24");
await page.getByTestId("triage-hasCough-yes").click();
await page.getByTestId("triage-breathsPerMinute-input").fill("45");
await page.getByTestId("triage-chestIndrawing-no").click();
await page.getByTestId("triage-stridorWhenCalm-no").click();
await page.getByTestId("triage-hasDiarrhea-yes").click();
await page.getByTestId("triage-durationDays-input").fill("3");
await page.getByTestId("triage-bloodInStool-no").click();
await page.getByTestId("triage-restlessOrIrritable-no").click();
await page.getByTestId("triage-sunkenEyes-no").click();
await page.getByTestId("triage-ableToDrink-select").selectOption("normal");
await page.getByTestId("triage-skinPinch-select").selectOption("immediate");
await page.getByTestId("triage-submit").click();
await page.getByTestId("triage-result").waitFor({ state: "visible" });
const urgency = (await page.getByTestId("triage-urgency").textContent())?.trim();
await beatLog.log("healthpost-triage", `real WHO-IMCI classification from a full exam: "${urgency}"`, page);
await sleep(1400);
// --- Sky: memory-wall post + double-click double-post guard (GAP-20) ---
await backHome(page);
await openTile(page, "Sky");
const skyMessage = "The sky over the Hollow turned amber tonight.";
await page.getByTestId("sky-memory-input").fill(skyMessage);
const countBefore = await page.getByTestId("sky-memory-list").locator("li").count().catch(() => 0);
await Promise.all([
page.getByTestId("sky-memory-submit").click(),
page.getByTestId("sky-memory-submit").click(),
]);
await waitFor(
async () => (await page.getByTestId("sky-memory-list").locator("li").count()) === countBefore + 1,
"exactly one memory-wall entry posted despite two synchronous clicks",
);
await beatLog.log("sky-post", "posted to the memory wall; a fast double-click produced exactly one entry, not two (GAP-20 fix)", page);
await sleep(1200);
// --- Tunnel Safety: real hazard report ---
await backHome(page);
await openTile(page, "Tunnel Safety");
await page.getByTestId("tunnel-safety-report-submit").click();
await waitFor(
async () => ((await page.getByTestId("tunnel-safety-report-status-text").textContent()) ?? "").includes("Hazard reported"),
"hazard report submitted",
);
await beatLog.log("tunnelsafety", "real hazard report appended for the selected corridor segment", page);
await sleep(1200);
// --- Find Family: on-device PSI search ---
await backHome(page);
await openTile(page, "Find Family");
await page.getByTestId("findfamily-search-input").fill("Ana Ramirez");
await page.getByTestId("findfamily-search-button").click();
await waitFor(
async () => (await page.getByTestId("findfamily-result-match").count()) > 0 || (await page.getByTestId("findfamily-result-nomatch").count()) > 0,
"PSI search resolves",
);
await beatLog.log("findfamily", "on-device private-set-intersection search resolved - the query never left the device", page);
await sleep(1200);
// --- Light Clock: manual sleep/wake log ---
// This headless browser has no real motion-sensor hardware, but
// Chromium's DOM still defines a DeviceMotionEvent constructor, so
// requestMotionPermission() would otherwise resolve "granted" and the
// screen would land on its (sample-less) sensor-active panel instead
// of the manual-log fallback. Removing the constructor makes
// requestMotionPermission() honestly report "unavailable", which is
// what's actually true of this machine - it exercises the exact
// fallback contract startLightClockDataSource documents, through the
// real "Enable motion sensor" button, not a bypass.
await page.evaluate(() => {
delete window.DeviceMotionEvent;
});
await backHome(page);
await openTile(page, "Light Clock");
await page.getByTestId("lightclock-enable-sensor").click();
await page.getByTestId("lightclock-manual-hours").waitFor({ state: "visible" });
await beatLog.log("lightclock-manual-fallback", "no motion sensor available - the real sensor-first/manual-fallback contract switched to the manual log form", page);
await page.getByTestId("lightclock-manual-hours").fill("8");
await page.getByTestId("lightclock-manual-state").selectOption("asleep");
await page.getByTestId("lightclock-manual-add").click();
await page.getByTestId("lightclock-manual-entries").locator("li").first().waitFor({ state: "visible" });
await page.getByTestId("lightclock-manual-compute").click();
await beatLog.log("lightclock", "manual sleep/wake log entry added and circadian status computed", page);
await sleep(1200);
// --- The Climb: schedule inputs feeding the min-cost-flow engine ---
await backHome(page);
await openTile(page, "The Climb");
await page.getByTestId("theclimb-shaft-id").fill("shaft-1");
await page.getByTestId("theclimb-shaft-from").fill("D1");
await page.getByTestId("theclimb-shaft-to").fill("surface");
await page.getByTestId("theclimb-shaft-capacity").fill("20");
await page.getByTestId("theclimb-shaft-travel").fill("2");
await page.getByTestId("theclimb-shaft-add").click();
await page.getByTestId("theclimb-demand-id").fill("wave-1");
await page.getByTestId("theclimb-demand-sector").fill("D1");
await page.getByTestId("theclimb-demand-ready-period").fill("0");
await page.getByTestId("theclimb-demand-count").fill("15");
await page.getByTestId("theclimb-demand-add").click();
await page.getByTestId("theclimb-capacity-period").fill("0");
await page.getByTestId("theclimb-capacity-value").fill("20");
await page.getByTestId("theclimb-capacity-add").click();
await beatLog.log("theclimb", "real shaft/wave-demand/surface-capacity schedule fed to the min-cost-flow congestion engine", page);
await sleep(1200);
// --- Assembly (single-user half): seeded roster/proposal + create/vote ---
await backHome(page);
await openTile(page, "Assembly");
await page.getByTestId("assembly-sync-toggle").waitFor({ state: "visible" });
await beatLog.log("assembly-seeded", "demo-seeded roster (Aria, Kade) and an open proposal visible cold, no manual setup", page);
await sleep(1000);
await page.getByTestId("assembly-create-proposal-title-input").fill("Repave the common courtyard");
await page.getByTestId("assembly-create-proposal-description-input").fill("The paving stones have cracked and are a tripping hazard.");
await page.getByTestId("assembly-create-proposal-submit").click();
await page.getByText("Repave the common courtyard").waitFor({ state: "visible" });
const proposalArticle = page.locator("article", { hasText: "Repave the common courtyard" }).first();
const proposalId = (await proposalArticle.getAttribute("data-testid"))?.replace("assembly-proposal-", "");
await beatLog.log("assembly-create-proposal", "a new proposal was created through the real form", page);
await sleep(900);
await page.getByTestId("assembly-add-resident-name-input").fill("Nguyen");
await page.getByTestId("assembly-add-resident-submit").click();
await waitFor(
async () => (await page.locator('[data-testid^="assembly-roster-"]', { hasText: "Nguyen" }).count()) > 0,
"new resident appears on the roster",
);
await beatLog.log("assembly-add-resident", "a new resident was added to the roster through the real form", page);
await sleep(900);
if (proposalId) {
await page.getByTestId(`assembly-vote-yes-${proposalId}`).click();
await waitFor(
async () => ((await page.getByTestId(`assembly-vote-status-${proposalId}`).textContent()) ?? "").includes("You voted Yes"),
"vote registers",
);
await beatLog.log("assembly-vote", "a direct vote was cast on the new proposal and the status readout updated live", page);
await sleep(1000);
}
// --- Upload a mini-app ---
await backHome(page);
await page.getByRole("button", { name: "+ Upload a mini-app" }).click();
await page.getByLabel("Mini-app name").fill("Counter Widget");
await page.getByLabel("Icon (emoji or data URI)").fill("\uD83D\uDD22");
await page.getByLabel("Entry point").fill("index.html");
await page.getByLabel("ledger.read").check();
await page.setInputFiles("#upload-html-file", {
name: "index.html",
mimeType: "text/html",
buffer: Buffer.from("<html><body><p>Counter Widget</p></body></html>"),
});
await beatLog.log("upload-form-filled", "real manifest form filled + a real HTML file attached via the real file input", page);
await sleep(900);
await page.getByRole("button", { name: "Upload mini-app" }).click();
await page.getByTestId("upload-success").waitFor({ state: "visible" });
await beatLog.log("upload-success", "the real uploadMiniapp() storage path accepted the package", page);
await sleep(900);
await page.getByRole("button", { name: "Go to home" }).click();
await page.getByRole("button", { name: "Counter Widget" }).waitFor({ state: "visible" });
await beatLog.log("upload-tile-appears", "the uploaded mini-app now appears as a real tile on the home grid", page);
await sleep(1400);
await beatLog.closeCaption();
} finally {
await context.tracing.stop({ path: resolve(videoDir, "trace.zip") });
await context.close();
await browser.close();
}
const videoPath = await page.video().path();
console.log(`Scene 1 recorded: ${videoPath} (${((Date.now() - sceneStartRef.value) / 1000).toFixed(1)}s wall-clock)`);
const enhancedPath = await addMotionGraphics(videoDir);
return { videoPath: enhancedPath, rawVideoPath: videoPath, beats: beatLog.beats };
}
// Runs the real Playwright trace this scene just recorded through
// playwright-recast: a synthetic cursor + click ripples at every real
// click/selectOption action, and an auto-zoom onto the exact element a
// fill/type/click action targeted, timed to that action's own real
// duration - all derived from the trace, never hand-authored keyframes.
// `.subtitlesFromTrace()` is required by `.autoZoom()` (confirmed by
// actually running this pipeline - it throws "autoZoom() requires
// subtitles() first" otherwise); it now also carries real captions, since
// `beatLog.log()` writes each beat's narration into the trace via
// `context.tracing.group()` using recast's own marker convention.
//
// Motion-graphics pass (see DEMO_VIDEO_NOTES.md for the research this is
// drawn from):
// 1. Kinetic-typography intro/outro title cards, crossfaded in/out -
// the "bold statement before the product" cold-open hook reverse-
// engineered from Linear/Apple/Raycast launch films.
// 2. Real captions (above) with a restyled, high-contrast caption box
// instead of the library default - legible on a 414px-wide pane and
// consistent with the app's own accent blue (#1677FF).
// 3. A short self-synthesized ambient pad via `.backgroundMusic()` - no
// voiceover (no TTS key in this environment), so sound design leans
// on music + pacing instead, at a volume low enough not to compete
// with the captions.
async function addMotionGraphics(videoDir) {
console.log("\nAdding motion graphics (cursor, click ripples, auto-zoom, intro/outro, captions, music) via playwright-recast...");
const outputPath = resolve(videoDir, "main-enhanced.mp4");
const assetsDir = resolve(VIDEO_TMP_DIR, "assets");
const introPath = await renderTitleCard({
html: titleCardHtml({
eyebrow: "PatriotHacks 2026",
title: "THE COMMONS",
tagline: "One identity. One signed ledger. No backend.",
}),
size: MAIN_VIDEO_SIZE,
durationMs: 2600,
outDir: resolve(assetsDir, "intro"),
});
const outroPath = await renderTitleCard({
html: titleCardHtml({
eyebrow: "Built in 36 hours",
title: "The Commons",
tagline: "13 mini-apps. 1 wallet. Every balance a signed, replayable event.",
}),
size: MAIN_VIDEO_SIZE,
durationMs: 2600,
outDir: resolve(assetsDir, "outro"),
});
const musicPath = generateAmbientTrack(resolve(assetsDir, "ambient.mp3"), 26);
await Recast.from(videoDir)
.parse()
.speedUp({ duringIdle: 3.0, duringUserAction: 1.0, duringNetworkWait: 2.0, duringNavigation: 2.0, minSegmentDuration: 500 })
.subtitlesFromTrace()
.autoZoom({ inputLevel: 1.4, clickLevel: 1.25, centerBias: 0.3 })
.cursorOverlay()
.clickEffect()
.intro({ path: introPath, fadeDuration: 600 })
.outro({ path: outroPath, fadeDuration: 600 })
.backgroundMusic({ path: musicPath, volume: 0.1, ducking: false, fadeOutMs: 2500, loop: true })
.render({
format: "mp4",
resolution: MAIN_VIDEO_SIZE,
fps: 30,
// `burnSubtitles` defaults to false (confirmed in
// `dist/render/renderer.js`) - without it, `subtitlesFromTrace()`'s
// cues are parsed but never drawn, which is exactly what an earlier
// test render of this change showed (real captions in the trace,
// nothing burned into the frames).
burnSubtitles: true,
// `fontSize` is calibrated against the library's internal
// 1080p-widescreen reference canvas - on this project's narrow
// 828px-wide portrait canvas the library's own default ran text off
// the right edge uncut (confirmed by an earlier test render's
// extracted frames), so it's scaled down to roughly the 0.43x width
// ratio (828/1920) instead of reused verbatim. `chunkOptions` was
// tried and reverted: it splits one beat's full caption into many
// ~17-char fragments each on its own short timer, which flashed
// past before a viewer could read it (confirmed by frame extraction
// showing a single orphaned word per frame) - `wrapStyle: 'smart'`
// alone lets libass wrap the full line across 2-3 lines and hold it
// for the beat's whole on-screen window instead.
subtitleStyle: {
fontSize: 30,
primaryColor: "#F5F7FF",
backgroundColor: "#05070D",
backgroundOpacity: 0.82,
padding: 16,
position: "bottom",
marginVertical: 70,
marginHorizontal: 36,
bold: true,
wrapStyle: "smart",
},
})
.toFile(outputPath);
console.log(`Motion-graphics pass written: ${outputPath}`);
return outputPath;
}
// =======================================================================
// SCENE 2: Assembly real-screen WebRTC partition-and-heal, two devices
// =======================================================================
async function recordAssemblySyncScene() {
console.log("\n=== Scene 2: Assembly real-screen sync (two isolated devices) ===");
const videoDirA = resolve(VIDEO_TMP_DIR, "assembly-deviceA");
const videoDirB = resolve(VIDEO_TMP_DIR, "assembly-deviceB");
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 beatLog = makeBeatLog("assembly-sync", sceneStartRef);
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 dualBeat(label, note) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
const shotA = resolve(EVIDENCE_DIR, `assembly-sync-${String(beatLog.beats.length).padStart(2, "0")}-deviceA-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
const shotB = resolve(EVIDENCE_DIR, `assembly-sync-${String(beatLog.beats.length).padStart(2, "0")}-deviceB-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await pageA.screenshot({ path: shotA }).catch(() => {});
await pageB.screenshot({ path: shotB }).catch(() => {});
beatLog.beats.push({ scene: "assembly-sync", label, note, sceneRelativeMs, screenshot: shotA, screenshotDeviceB: shotB });
console.log(`[assembly-sync +${(sceneRelativeMs / 1000).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 dualBeat("boot", "two genuinely isolated devices (separate storage origins) open the real Assembly screen; sync is honestly off by default");
await sleep(1000);
// 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 dualBeat("connected", "real WebRTC transport connected over a local signaling server - both devices see a live peer count");
await sleep(1200);
// 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 dualBeat("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(1400);
// 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(600);
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 dualBeat(
"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(1400);
// 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(1500);
await dualBeat("healed-reconnected", "both devices reconnected after the partition - real WebrtcProvider re-established");
await sleep(1500);
} 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(`Scene 2 recorded: deviceA=${videoPathA} deviceB=${videoPathB} (${((Date.now() - sceneStartRef.value) / 1000).toFixed(1)}s wall-clock)`);
return { videoPathA, videoPathB, beats: beatLog.beats };
}
function compositeSideBySide(videoPathA, videoPathB, outPath) {
mkdirSync(dirname(outPath), { recursive: true });
const filter =
`[0:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=25[v0];` +
`[1:v]scale=${PANE.width}:${PANE.height},setsar=1,fps=25[v1];` +
"[v0][v1]hstack=inputs=2[v]";
execFileSync(FFMPEG_BIN, [
"-y", "-i", videoPathA, "-i", videoPathB,
"-filter_complex", filter, "-map", "[v]",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
outPath,
], { stdio: ["ignore", "pipe", "pipe"] });
}
function concatToFinal(mainVideoPath, assemblyCompositePath) {
mkdirSync(dirname(FINAL_VIDEO), { recursive: true });
// mainVideoPath may carry a real audio track (intro/outro/background
// music muxed in by addMotionGraphics()); assemblyCompositePath never
// does. concat requires matching stream counts per segment, so a
// silent pad stands in for segment 2's missing audio rather than
// dropping audio for both (which silently lost it before, and - the
// real bug this fixes - a `-map "[v]"`-only map with an unreferenced
// audio stream still present on input 0 was truncating the output's
// duration well short of its real video length).
// A single filter_complex mixing a real [0:a] stream with a
// filter-graph-generated anullsrc pad truncated this video's duration
// hard (confirmed by direct testing: per-stream ffprobe showed both
// main-enhanced streams genuinely ~43.5s, but that one-pass concat
// produced a ~26s output) - so this does it as three separately
// verifiable passes instead: video-only concat (the pattern already
// proven to work), a real silent file concatenated onto a real
// extracted copy of the main audio (not a filter-graph source node),
// then a final mux.
const assemblyDuration = ffmpegDurationSeconds(assemblyCompositePath) ?? 10;
const tmpVideo = resolve(VIDEO_TMP_DIR, "final-video-only.mp4");
const tmpSilence = resolve(VIDEO_TMP_DIR, "silence.m4a");
const tmpMainAudio = resolve(VIDEO_TMP_DIR, "main-audio.m4a");
const tmpAudio = resolve(VIDEO_TMP_DIR, "padded-audio.m4a");
const tmpAudioList = resolve(VIDEO_TMP_DIR, "audio-concat-list.txt");
const vfilter =
`[0:v]scale=${FINAL_W}:${FINAL_H}:force_original_aspect_ratio=decrease,pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=25[v0];` +
`[1:v]scale=${FINAL_W}:${FINAL_H}:force_original_aspect_ratio=decrease,pad=${FINAL_W}:${FINAL_H}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=25[v1];` +
"[v0][v1]concat=n=2:v=1:a=0[v]";
execFileSync(FFMPEG_BIN, [
"-y", "-i", mainVideoPath, "-i", assemblyCompositePath,
"-filter_complex", vfilter, "-map", "[v]",
"-c:v", "libx264", "-pix_fmt", "yuv420p",
tmpVideo,
], { stdio: ["ignore", "pipe", "pipe"] });
const hasAudio = (() => {
try {
execFileSync(FFMPEG_BIN, ["-i", mainVideoPath, "-vn", "-c:a", "copy", "-f", "null", "-"], { stdio: ["ignore", "pipe", "pipe"] });
return true;
} catch {
return false;
}
})();
if (hasAudio) {
execFileSync(FFMPEG_BIN, ["-y", "-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=44100", "-t", String(assemblyDuration), "-c:a", "aac", tmpSilence], { stdio: ["ignore", "pipe", "pipe"] });
execFileSync(FFMPEG_BIN, ["-y", "-i", mainVideoPath, "-vn", "-c:a", "aac", tmpMainAudio], { stdio: ["ignore", "pipe", "pipe"] });
writeFileSync(tmpAudioList, `file '${tmpMainAudio}'\nfile '${tmpSilence}'\n`);
execFileSync(FFMPEG_BIN, ["-y", "-f", "concat", "-safe", "0", "-i", tmpAudioList, "-c:a", "aac", tmpAudio], { stdio: ["ignore", "pipe", "pipe"] });
execFileSync(FFMPEG_BIN, [
"-y", "-i", tmpVideo, "-i", tmpAudio,
"-c:v", "copy", "-c:a", "aac", "-b:a", "128k", "-shortest", "-movflags", "+faststart",
FINAL_VIDEO,
], { stdio: ["ignore", "pipe", "pipe"] });
} else {
execFileSync(FFMPEG_BIN, ["-y", "-i", tmpVideo, "-c:v", "copy", "-movflags", "+faststart", FINAL_VIDEO], { stdio: ["ignore", "pipe", "pipe"] });
}
}
function ffmpegDurationSeconds(videoPath) {
try {
execFileSync(FFMPEG_BIN, ["-i", videoPath], { stdio: ["ignore", "pipe", "pipe"] });
return null;
} catch (e) {
const stderr = String(e.stderr ?? "");
const match = stderr.match(/Duration: (\d+):(\d+):(\d+\.\d+)/);
if (!match) return null;
const [, h, m, s] = match;
return Number(h) * 3600 + Number(m) * 60 + Number(s);
}
}
async function main() {
mkdirSync(EVIDENCE_DIR, { recursive: true });
const onlyScene = process.argv.includes("--main-only")
? "main"
: process.argv.includes("--assembly-only")
? "assembly"
: undefined;
const vite = await startVite();
let mainScene;
let assemblyScene;
try {
if (onlyScene !== "assembly") mainScene = await recordMainScene();
if (onlyScene !== "main") assemblyScene = await recordAssemblySyncScene();
} finally {
await vite.close();
}
if (onlyScene) {
console.log(`\n===== DEBUG RUN (${onlyScene} only) DONE, skipping composite/concat =====`);
if (mainScene) console.log(`main video: ${mainScene.videoPath}, beats: ${mainScene.beats.length}`);
if (assemblyScene) console.log(`assembly videos: ${assemblyScene.videoPathA} / ${assemblyScene.videoPathB}, beats: ${assemblyScene.beats.length}`);
return;
}
console.log("\nCompositing Assembly two-device scene side-by-side...");
const assemblyComposite = resolve(VIDEO_TMP_DIR, "assembly-sync-composite.mp4");
compositeSideBySide(assemblyScene.videoPathA, assemblyScene.videoPathB, assemblyComposite);
console.log("Concatenating main scene + Assembly sync scene into the final video...");
concatToFinal(mainScene.videoPath, assemblyComposite);
const finalDuration = ffmpegDurationSeconds(FINAL_VIDEO);
const allBeats = [...mainScene.beats, ...assemblyScene.beats];
writeFileSync(
resolve(EVIDENCE_DIR, "beat-log.json"),
JSON.stringify(
{
recordedAt: new Date().toISOString(),
finalVideoPath: FINAL_VIDEO,
durationSeconds: finalDuration,
mainSceneBeatCount: mainScene.beats.length,
assemblySceneBeatCount: assemblyScene.beats.length,
beats: allBeats,
},
null,
2,
),
);
console.log(`\n===== DONE =====`);
console.log(`Final video: ${FINAL_VIDEO}`);
console.log(`Duration: ${finalDuration ? finalDuration.toFixed(1) + "s" : "unknown"}`);
console.log(`Total beats captured: ${allBeats.length}`);
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});