Files
patriothacks/e2e/demoRecording.e2e.mjs

531 lines
23 KiB
JavaScript

// Demo video recording for plan todo 60: scripted + mechanically recorded,
// <=180s, covering the honesty-anchor chain (todo 19) and the Assembly
// partition-heal demo (todo 23) as mandatory beats, plus a tour of the
// remaining 11 shipped mini-apps.
//
// Self-contained Playwright runner, same shape as e2e/assemblyPartition.e2e.mjs
// and e2e/installShare.e2e.mjs. Two recording "scenes" (two Playwright
// contexts, each with contextOptions.recordVideo):
//
// Scene A ("live"): the actual deployed build (todo 57), reachable at
// record time - confirmed by `curl` before this script runs. Covers the
// home tour, admin "Load Hollow demo" seed, the full honesty-anchor
// chain (Water Watch -> Fair Share), Fair Draw, and 9 of the remaining
// mini-apps.
//
// Scene B ("assembly"): a local Vite dev server serving the exact
// `demo/assembly-sync.html` harness that e2e/assemblyPartition.e2e.mjs
// already proved todo 23's acceptance criteria against. The deployed
// build does not route that harness page as a distinct page (no
// multi-page `rollupOptions.input` entry in vite.config.ts - it 200s
// there only via the SPA's own index.html fallback), and the shipped
// AssemblyScreen mini-app itself never wires a WebrtcProvider (confirmed
// by reading src/miniapps/assembly/useAssemblyEngine.ts) - so the one
// genuine place this beat can be shown live is this harness, run
// locally. Each "device" is its own Playwright browser CONTEXT (not an
// iframe pair in one context) - y-webrtc silently falls back to a
// same-origin BroadcastChannel transport when two same-room documents
// share one storage partition, which would make peerCount()/the
// genuine-partition proof meaningless; two isolated contexts (exactly
// what the already-passing e2e/assemblyPartition.e2e.mjs uses) forces
// the real WebRTC path. Each context records its own video; the two are
// composited side-by-side (ffmpeg hstack, "Device A" | "Device B") into
// one Scene B clip after recording.
//
// All scene video is concatenated (scaled/padded to a common 1280x720
// canvas) into the final artifact with ffmpeg. Every beat's wall-clock
// timestamp (both scene-relative and, after concatenation, offset into the
// final video) is logged to
// .omo/evidence/the-commons-hollow/task-60-beat-timestamps.json, plus a
// screenshot taken at the moment each mandatory beat's key UI state first
// appears - the automated frame-check / DOM-state correlation this todo's
// acceptance criteria calls for.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { spawn, execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync, existsSync } 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/the-commons-hollow");
const VIDEO_TMP_DIR = resolve(ROOT, ".tmp/demo-video");
const FINAL_VIDEO = resolve(EVIDENCE_DIR, "task-60-the-commons-hollow.mp4");
const LIVE_URL = process.env.DEMO_LIVE_URL ?? "https://agile-citrine-45o1qv9.tmp.now";
const FFMPEG_BIN = process.env.FFMPEG_BIN;
const FFPROBE_BIN = process.env.FFPROBE_BIN;
if (!FFMPEG_BIN || !FFPROBE_BIN) {
throw new Error("Set FFMPEG_BIN and FFPROBE_BIN env vars to the ffmpeg-static / ffprobe-static binaries.");
}
const SIG_PORT = 40000 + Math.floor(Math.random() * 20000);
const VITE_PORT = 41000 + Math.floor(Math.random() * 20000);
const SIG = `ws://127.0.0.1:${SIG_PORT}`;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function waitFor(fn, label, timeoutMs = 20000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const v = await fn();
if (v) return v;
await sleep(150);
}
throw new Error(`timeout waiting for: ${label}`);
}
/** Collects (label, sceneRelativeMs, note) beats as they happen, plus an
* optional screenshot path, for the final cross-reference evidence file. */
function makeBeatLog(sceneName, sceneStartRef) {
const beats = [];
return {
beats,
async log(label, note, page) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
let screenshot;
if (page) {
screenshot = resolve(EVIDENCE_DIR, `task-60-beat-${sceneName}-${beats.length}-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await page.screenshot({ path: screenshot });
}
beats.push({ scene: sceneName, label, note, sceneRelativeMs, screenshot });
console.log(`[${sceneName} +${(sceneRelativeMs / 1000).toFixed(1)}s] ${label}: ${note}`);
},
};
}
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}`)));
});
}
/** Generic mini-app tour step: go home, open the tile, wait for its own
* aria-label region to mount, hold briefly for a readable video frame. */
async function tourMiniapp(page, label, beatLog) {
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByRole("button", { name: label }).click();
await page.locator(`[aria-label="${label}"]`).first().waitFor({ state: "visible", timeout: 10000 });
await beatLog.log(`tour:${label}`, `${label} mini-app mounted and visible`, page);
await sleep(1800);
}
async function recordSceneA() {
console.log("\n=== Scene A: live deployed build ===");
const videoDir = resolve(VIDEO_TMP_DIR, "sceneA");
mkdirSync(videoDir, { recursive: true });
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const context = await browser.newContext({
viewport: { width: 414, height: 896 },
recordVideo: { dir: videoDir, size: { width: 414, height: 896 } },
});
const page = await context.newPage();
const sceneStartRef = { value: Date.now() };
const beatLog = makeBeatLog("A-live", sceneStartRef);
try {
// --- Home grid tour ---
await page.goto(`${LIVE_URL}/`, { waitUntil: "load", timeout: 30000 });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await beatLog.log("home", "home grid + wallet card loaded from the live deployed build", page);
await sleep(1400);
// --- Admin: Load Hollow demo (todo 9's cold-visitor seed) ---
await page.goto(`${LIVE_URL}/admin`, { waitUntil: "load" });
await page.getByRole("button", { name: "Load Hollow demo" }).click();
await waitFor(
async () => (await page.getByTestId("demo-load-status").textContent())?.trim().length > 0,
"demo seed load status",
);
await beatLog.log("seed", "Load Hollow demo clicked - signed seed.* events appended", page);
await sleep(900);
await page.goto(`${LIVE_URL}/`, { waitUntil: "load" });
await page.getByRole("grid", { name: "Miniapps" }).waitFor({ state: "visible" });
await sleep(900);
// --- MANDATORY BEAT 1: honesty-anchor chain (todo 19) ---
await page.getByRole("button", { name: "Water Watch" }).click();
await page.locator('[aria-label="Water Watch"]').waitFor({ state: "visible" });
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 reportReading("sensor-A", 50);
await waitFor(
async () => (await page.getByTestId("device-monitor-status-light-pH").getAttribute("data-state")) === "corroborating",
"pH channel reaches corroborating",
);
await beatLog.log(
"honesty-anchor:corroborating",
"sensor-A alone recorded but uncorroborated - gate holds at corroborating",
page,
);
await sleep(1200);
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 (corroborated)",
);
await beatLog.log(
"honesty-anchor:alert",
"independent sensor-B corroborated the spike - real signed credit event + CEEI re-solve triggered",
page,
);
await sleep(1200);
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByRole("button", { name: "Fair Share" }).click();
await page.locator('[aria-label="Fair Share"]').waitFor({ state: "visible" });
await waitFor(
async () => {
const text = await page.getByTestId("tile-water-allocation").textContent();
return text !== null && text.trim().length > 0 && text !== "No allocation yet";
},
"Fair Share water tile shows a real re-solved allocation",
);
await beatLog.log(
"honesty-anchor:fairshare-updated",
"Fair Share water tile reflects the re-solved CEEI allocation - chain complete end to end",
page,
);
await sleep(1800);
// --- Fair Draw tour ---
await page.getByRole("link", { name: "Back to home" }).click();
await page.getByRole("button", { name: "Fair Draw" }).click();
await page.locator('[aria-label="Fair Draw"]').waitFor({ state: "visible" });
await page.getByRole("button", { name: "Start Draw" }).click();
await page.getByRole("button", { name: "Reveal" }).click();
await waitFor(
async () => (await page.getByTestId("reveal-draw-badge").getAttribute("data-state")) !== null,
"Fair Draw reveal badge renders",
);
await beatLog.log("fairdraw", "real commit -> reveal -> verify cycle, verified badge shown", page);
await sleep(1500);
// --- Remaining mini-app tour (9 of the 13; Assembly covered in Scene B) ---
for (const label of [
"Tunnel Safety",
"Housing",
"Find Family",
"Health Post",
"Light Clock",
"Farms",
"The Climb",
"Mentor",
"Sky",
]) {
await tourMiniapp(page, label, beatLog);
}
} finally {
await context.close();
await browser.close();
}
const videoPath = await page.video().path();
const sceneDurationMs = Date.now() - sceneStartRef.value;
console.log(`Scene A recorded: ${videoPath} (${(sceneDurationMs / 1000).toFixed(1)}s wall-clock)`);
return { videoPath, beats: beatLog.beats };
}
async function recordSceneB() {
console.log("\n=== Scene B: Assembly partition-heal (local harness, two isolated contexts) ===");
const videoDirA = resolve(VIDEO_TMP_DIR, "sceneB-deviceA");
const videoDirB = resolve(VIDEO_TMP_DIR, "sceneB-deviceB");
mkdirSync(videoDirA, { recursive: true });
mkdirSync(videoDirB, { recursive: true });
const sig = await startSignaling();
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();
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const HARNESS_URL = `${APP_URL}/demo/assembly-sync.html`;
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const paneSize = { width: 640, height: 720 };
const ctxA = await browser.newContext({ viewport: paneSize, recordVideo: { dir: videoDirA, size: paneSize } });
const ctxB = await browser.newContext({ viewport: paneSize, recordVideo: { dir: videoDirB, size: paneSize } });
// Mirrors e2e/assemblyPartition.e2e.mjs exactly: two ISOLATED contexts (no
// shared storage partition, so no y-webrtc BroadcastChannel shortcut is
// even possible - this is what forces the real WebRTC path) plus a
// signaling-route block so the partition can be made genuine rather than
// relying on setOffline() alone (which does not tear an already-open
// RTCDataChannel over loopback).
const state = { blockSig: false };
for (const ctx of [ctxA, ctxB]) {
await ctx.routeWebSocket(new RegExp(`127\\.0\\.0\\.1:${SIG_PORT}`), (ws) => {
if (state.blockSig) {
ws.close();
return;
}
ws.connectToServer();
});
}
const pageA = await ctxA.newPage();
const pageB = await ctxB.newPage();
const sceneStartRef = { value: Date.now() };
const beatLog = makeBeatLog("B-assembly", sceneStartRef);
const room = `demo-${Math.random().toString(36).slice(2)}`;
async function dualBeat(label, note) {
const sceneRelativeMs = Date.now() - sceneStartRef.value;
const shotA = resolve(EVIDENCE_DIR, `task-60-beat-B-assembly-${beatLog.beats.length}-deviceA-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
const shotB = resolve(EVIDENCE_DIR, `task-60-beat-B-assembly-${beatLog.beats.length}-deviceB-${label.replace(/[^a-z0-9]+/gi, "-")}.png`);
await pageA.screenshot({ path: shotA });
await pageB.screenshot({ path: shotB });
beatLog.beats.push({ scene: "B-assembly", label, note, sceneRelativeMs, screenshot: shotA, screenshotDeviceB: shotB });
console.log(`[B-assembly +${(sceneRelativeMs / 1000).toFixed(1)}s] ${label}: ${note}`);
}
try {
await pageA.goto(HARNESS_URL, { waitUntil: "load" });
await pageB.goto(HARNESS_URL, { waitUntil: "load" });
const initArg = { room, signaling: [SIG] };
await pageA.evaluate((o) => window.commons.init(o), initArg);
await pageB.evaluate((o) => window.commons.init(o), initArg);
await dualBeat("boot", "both isolated-context devices initialized against the same room");
// 1. Connect + prove the live transport genuinely works.
await waitFor(() => pageA.evaluate(() => window.commons.peerCount() > 0), "Device A connects");
await waitFor(() => pageB.evaluate(() => window.commons.peerCount() > 0), "Device B connects");
await pageA.evaluate(() => window.commons.vote("prop", "warmup-voter", "yes"));
await waitFor(() => pageB.evaluate(() => window.commons.voteCount() >= 1), "warmup vote propagates A->B");
await dualBeat("connected", "real WebRTC transport connected (two isolated storage partitions), warm-up vote propagated A -> B");
// 2. MANDATORY BEAT 2: genuine partition (todo 23).
state.blockSig = true;
await ctxA.setOffline(true);
await ctxB.setOffline(true);
await pageA.evaluate(() => window.commons.setConnected(false));
await pageB.evaluate(() => window.commons.setConnected(false));
await waitFor(() => pageA.evaluate(() => window.commons.peerCount() === 0), "Device A isolated");
await waitFor(() => pageB.evaluate(() => window.commons.peerCount() === 0), "Device B isolated");
const countBeforeA = await pageA.evaluate(() => window.commons.voteCount());
const countBeforeB = await pageB.evaluate(() => window.commons.voteCount());
await pageA.evaluate((v) => window.commons.vote(v.p, v.voter, v.choice), { p: "prop", voter: "bob", choice: "yes" });
await pageB.evaluate((v) => window.commons.vote(v.p, v.voter, v.choice), { p: "prop", voter: "carol", choice: "no" });
let leaked = false;
for (let i = 0; i < 10; i++) {
const ac = await pageA.evaluate(() => window.commons.voteCount());
const bc = await pageB.evaluate(() => window.commons.voteCount());
if (ac > countBeforeA + 1 || bc > countBeforeB + 1) {
leaked = true;
break;
}
await sleep(200);
}
if (leaked) throw new Error("votes leaked during partition - not a genuine partition, aborting recording");
await sleep(600);
await dualBeat(
"partition-heal:partitioned",
"both devices genuinely isolated (peerCount=0, RTCDataChannel torn down, signaling route blocked, context offline) - independent votes cast with zero propagation",
);
// 3. Heal + converge.
state.blockSig = false;
await ctxA.setOffline(false);
await ctxB.setOffline(false);
await pageA.evaluate(() => window.commons.setConnected(true));
await pageB.evaluate(() => window.commons.setConnected(true));
await waitFor(() => pageA.evaluate(() => window.commons.voteCount() >= 3), "Device A converges");
await waitFor(() => pageB.evaluate(() => window.commons.voteCount() >= 3), "Device B converges");
const tallyA = await pageA.evaluate(() => window.commons.tally("prop"));
const tallyB = await pageB.evaluate(() => window.commons.tally("prop"));
if (JSON.stringify(tallyA) !== JSON.stringify(tallyB)) {
throw new Error(`post-heal tallies differ: A=${JSON.stringify(tallyA)} B=${JSON.stringify(tallyB)}`);
}
await dualBeat(
"partition-heal:converged",
`reconnect merged both independent votes - identical tally on both devices: ${JSON.stringify(tallyA)}`,
);
await sleep(1500);
} finally {
await ctxA.close();
await ctxB.close();
await browser.close();
await vite.close();
sig.kill("SIGKILL");
}
const videoPathA = await pageA.video().path();
const videoPathB = await pageB.video().path();
const sceneDurationMs = Date.now() - sceneStartRef.value;
console.log(`Scene B recorded: deviceA=${videoPathA} deviceB=${videoPathB} (${(sceneDurationMs / 1000).toFixed(1)}s wall-clock)`);
return { videoPathA, videoPathB, beats: beatLog.beats };
}
/** Composites two same-duration-ish device videos side-by-side (ffmpeg
* hstack) into one "Device A | Device B" clip for Scene B. */
function compositeSideBySide(videoPathA, videoPathB, outPath) {
mkdirSync(dirname(outPath), { recursive: true });
const filter =
"[0:v]scale=640:720,setsar=1,fps=25[v0];" +
"[1:v]scale=640:720,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 ffprobeDurationSeconds(videoPath) {
const out = execFileSync(FFPROBE_BIN, [
"-v", "error",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1",
videoPath,
]).toString().trim();
return Number(out);
}
function concatToFinal(videoAPath, videoBPath) {
mkdirSync(dirname(FINAL_VIDEO), { recursive: true });
const filter =
"[0:v]scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=25[v0];" +
"[1:v]scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(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", videoAPath,
"-i", videoBPath,
"-filter_complex", filter,
"-map", "[v]",
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-movflags", "+faststart",
FINAL_VIDEO,
], { stdio: ["ignore", "pipe", "pipe"] });
}
async function main() {
mkdirSync(EVIDENCE_DIR, { recursive: true });
const sceneA = await recordSceneA();
const sceneB = await recordSceneB();
const sceneBComposite = resolve(VIDEO_TMP_DIR, "sceneB-composite.mp4");
compositeSideBySide(sceneB.videoPathA, sceneB.videoPathB, sceneBComposite);
const durationAWebm = ffprobeDurationSeconds(sceneA.videoPath);
const durationBWebm = ffprobeDurationSeconds(sceneBComposite);
console.log(`\nScene A webm duration: ${durationAWebm.toFixed(2)}s`);
console.log(`Scene B composite duration: ${durationBWebm.toFixed(2)}s`);
concatToFinal(sceneA.videoPath, sceneBComposite);
const finalDuration = ffprobeDurationSeconds(FINAL_VIDEO);
console.log(`\nFinal concatenated video: ${FINAL_VIDEO}`);
console.log(`Final duration: ${finalDuration.toFixed(2)}s (limit: 180s)`);
// Cross-reference: scene-relative beat timestamps -> offsets into the
// final concatenated video (scene A starts at 0, scene B starts right
// after scene A's real measured webm duration).
const beats = [
...sceneA.beats.map((b) => ({ ...b, finalVideoOffsetSeconds: b.sceneRelativeMs / 1000 })),
...sceneB.beats.map((b) => ({ ...b, finalVideoOffsetSeconds: durationAWebm + b.sceneRelativeMs / 1000 })),
];
const mandatoryBeat1 = beats.find((b) => b.label === "honesty-anchor:fairshare-updated");
const mandatoryBeat2 = beats.find((b) => b.label === "partition-heal:converged");
const bothMandatoryBeatsPresent = Boolean(mandatoryBeat1 && mandatoryBeat2);
const withinDurationLimit = finalDuration <= 180;
const evidence = {
task: "60. Demo video (scripted + mechanically recorded)",
recordedAt: new Date().toISOString(),
liveUrl: LIVE_URL,
finalVideoPath: FINAL_VIDEO,
durationSeconds: finalDuration,
durationLimitSeconds: 180,
withinDurationLimit,
sceneADurationSeconds: durationAWebm,
sceneBDurationSeconds: durationBWebm,
mandatoryBeats: {
honestyAnchorChain: mandatoryBeat1
? { present: true, finalVideoOffsetSeconds: mandatoryBeat1.finalVideoOffsetSeconds, note: mandatoryBeat1.note, screenshot: mandatoryBeat1.screenshot }
: { present: false },
assemblyPartitionHeal: mandatoryBeat2
? { present: true, finalVideoOffsetSeconds: mandatoryBeat2.finalVideoOffsetSeconds, note: mandatoryBeat2.note, screenshot: mandatoryBeat2.screenshot }
: { present: false },
},
allBeats: beats,
pass: withinDurationLimit && bothMandatoryBeatsPresent,
};
writeFileSync(resolve(EVIDENCE_DIR, "task-60-beat-timestamps.json"), JSON.stringify(evidence, null, 2));
writeFileSync(
resolve(EVIDENCE_DIR, "task-60-the-commons-hollow.json"),
JSON.stringify(
{
task: "60. Demo video (scripted + mechanically recorded)",
qa: "happy",
description:
"Scripted Playwright recording covering the honesty-anchor chain (todo 19) and Assembly partition-heal (todo 23) as mandatory beats, plus a tour of the remaining 11 shipped mini-apps.",
tool: "Playwright (chromium), contextOptions.recordVideo, two scenes concatenated with ffmpeg",
run_command: "node e2e/demoRecording.e2e.mjs",
videoPath: FINAL_VIDEO,
durationSeconds: finalDuration,
durationLimitSeconds: 180,
withinDurationLimit,
mandatoryBeatsPresent: bothMandatoryBeatsPresent,
pass: evidence.pass,
},
null,
2,
),
);
console.log(`\n===== RESULT =====`);
console.log(`Duration OK (<=180s): ${withinDurationLimit}`);
console.log(`Honesty-anchor beat present: ${Boolean(mandatoryBeat1)} @ ${mandatoryBeat1?.finalVideoOffsetSeconds.toFixed(1)}s`);
console.log(`Partition-heal beat present: ${Boolean(mandatoryBeat2)} @ ${mandatoryBeat2?.finalVideoOffsetSeconds.toFixed(1)}s`);
if (!evidence.pass) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});