scripts/record-demo.mjs
import { mkdir, mkdtemp, readFile, writeFile, rm, realpath, rename } from 'node:fs/promises';
import { resolve, sep, relative } from 'node:path';
import { spawnSync } from 'node:child_process';
import { setTimeout as delay } from 'node:timers/promises';
import { root } from './configure.mjs';
import { validateNarration, captionSrt, findFfmpeg, encodeVideo, videoDuration } from './video-tools.mjs';
const args = process.argv.slice(2);
const live = args.includes('--live');
const quick = args.includes('--quick');
const option = name => args.includes(name) ? args[args.indexOf(name) + 1] : undefined;
const base = new URL(option('--url') || 'http://127.0.0.1:4173');
if (!live && !['127.0.0.1', 'localhost'].includes(base.hostname)) throw Error('Rehearsal requires a loopback URL.');
if (base.username || base.password || base.search || base.hash) throw Error('Use a plain app URL with no credentials or query parameters.');
const voiceover = option('--voiceover') ? resolve(root, option('--voiceover')) : undefined;
if (voiceover && (relative(root, voiceover).startsWith('..') || !relative(root, voiceover).startsWith('output' + sep))) throw Error('Put an optional voice-over track under output/ and pass its relative path.');
const shots = JSON.parse(await readFile(resolve(root, 'docs/demo-narration.json'), 'utf8'));
const plannedSeconds = validateNarration(shots);
const ffmpeg = findFfmpeg();
const cache = resolve(root, '.cache');
await mkdir(cache, { recursive: true });
// A unique run folder prevents old videos/reports being mistaken for this run.
const outputBase = resolve(root, 'output/demo'); await mkdir(outputBase, { recursive: true });
const output = await mkdtemp(resolve(outputBase, (live ? 'live-' : 'rehearsal-') + (quick ? 'smoke-' : '')));
process.env.PLAYWRIGHT_BROWSERS_PATH = resolve(cache, 'playwright-video');
const install = spawnSync(process.execPath, [resolve(root, 'node_modules/playwright/cli.js'), 'install', 'ffmpeg'], { env: process.env, stdio: 'pipe', windowsHide: true, timeout: 120000 });
if (install.status !== 0) throw Error('Playwright video encoder setup failed. Retry npm run record:demo; no browser or login is required.');
const { chromium } = await import('playwright');
const profile = await mkdtemp(resolve(cache, 'chrome-demo-'));
const report = { checkedAt: new Date().toISOString(), mode: live ? 'live Firebase' : 'labelled fake-cloud rehearsal', plannedSeconds, quick, captions: 'English narration rendered into recorded pixels; no synthesised audio', profile: 'fresh temporary, no sign-in, deleted after close', shots: [], status: 'failed' };
let context, video, clockStart;
const source = async page => (await page.locator('#route').innerText()).trim();
async function waitText(page, selector, text) {
await page.waitForFunction(({ selector, text }) => document.querySelector(selector)?.textContent?.includes(text), { selector, text }, { timeout: 25000 });
}
try {
context = await chromium.launchPersistentContext(profile, {
executablePath: process.env.CHROME_EXE || 'C:/Program Files/Google/Chrome/Application/chrome.exe',
headless: !args.includes('--headed'), viewport: { width: 1440, height: 1000 },
recordVideo: { dir: output, size: { width: 1440, height: 1000 } }, acceptDownloads: true,
args: ['--no-first-run', '--no-default-browser-check'],
});
// A persistent context's automatically opened page can predate video setup.
// Create the recorded page explicitly; never rely on that startup page.
for (const initial of context.pages()) await initial.close();
const page = await context.newPage(); video = page.video();
const pageErrors = []; page.on('pageerror', () => pageErrors.push('Browser page exception.'));
if (!live) await context.route('**/*', route => { const url = new URL(route.request().url()); return url.protocol.startsWith('http') && url.origin !== base.origin ? route.abort() : route.continue(); });
await page.goto(base.href, { waitUntil: 'networkidle' });
if (live) {
if (await page.locator('#mode option[value="live"]').isDisabled()) throw Error('Live client configuration is missing. Owner: build:live and configure App Check first.');
await page.locator('#mode').selectOption('live');
} else {
await page.locator('#rehearsal summary').click();
await page.locator('#sim-nano').selectOption('unavailable');
}
await page.evaluate(({ live, firstCaption }) => {
const style = document.createElement('style'); style.textContent = `body{padding-bottom:160px}#demo-label{position:fixed;right:18px;top:12px;z-index:1001;background:#183b38;color:#fff;padding:10px 14px;border:2px solid #dfea93;border-radius:7px;font:700 13px/1.4 'Segoe UI',sans-serif;letter-spacing:.4px;pointer-events:none}#demo-caption{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);width:calc(100% - 100px);max-width:1120px;background:#102723f5;color:#fff;border-radius:8px;padding:18px 26px;z-index:1000;text-align:center;font:500 22px/1.5 'Segoe UI',sans-serif;box-shadow:0 4px 24px #0003;pointer-events:none}`;
const label = document.createElement('div'); label.id = 'demo-label'; label.textContent = live ? 'FIREBASE WORKSPACE · CHECK RESULT SOURCE' : 'REHEARSAL · FAKE CLOUD · NO GEMINI REQUESTS';
const caption = document.createElement('div'); caption.id = 'demo-caption'; caption.textContent = firstCaption;
document.head.append(style); document.body.append(label, caption);
}, { live, firstCaption: live ? shots[0].liveText || shots[0].text : shots[0].text });
const view = selector => page.locator(selector).evaluate(el => el.scrollIntoView({ block: 'start', behavior: 'smooth' }));
const run = async () => { await page.locator('#run').click(); await page.waitForFunction(() => !document.querySelector('#run').disabled); };
clockStart = performance.now();
for (const shot of shots) {
const started = performance.now();
await page.locator('#demo-caption').evaluate((el, text) => { el.textContent = text; }, live ? shot.liveText || shot.text : shot.text);
// Force a painted frame even when the shot has no movement (the opening).
await page.screenshot();
const captionBox = await page.locator('#demo-caption').boundingBox();
if (!captionBox || captionBox.x < 0 || captionBox.y < 0 || captionBox.x + captionBox.width > 1440 || captionBox.y + captionBox.height > 1000) throw Error('Caption is clipped; adjust narration or layout before filming.');
switch (shot.id) {
case 'intro': await page.evaluate(() => scrollTo(0, 0)); break;
case 'boundary': await view('.workspace'); break;
case 'local': await run(); await view('.result-panel'); report.localSource = await source(page); break;
case 'evidence': await view('#cards'); break;
case 'permission': await view('.boundary-panel'); await page.locator('#consent').check(); break;
case 'cloud':
await run(); await view('.result-panel'); report.cloudSource = await source(page);
if (!(report.cloudSource.includes(live ? 'Gemini · cloud' : 'Fake cloud'))) throw Error('Expected cloud source was not observed. Local recovery or device output cannot stand in for a cloud recording. Fix setup, or use an unsupported-device session for live cloud.');
await page.screenshot({ path: resolve(output, 'cloud-frame.png') }); break;
case 'edit':
await view('.workspace'); await page.locator('#notes').fill((await page.locator('#notes').inputValue()) + '\nTODO: Share the reviewed handoff.');
if (await page.locator('#consent').isChecked() || !await page.locator('#export').isDisabled()) throw Error('Edit did not revoke permission/export.');
break;
case 'offline':
await page.waitForFunction(() => navigator.serviceWorker?.controller != null);
await context.setOffline(true); await run(); await view('.result-panel');
report.offlineSource = await source(page); if (!report.offlineSource.includes('Local rules') && !report.offlineSource.includes('on device')) throw Error('Offline source was not local.'); break;
case 'failure':
if (!live) { await context.setOffline(false); await page.locator('#cloud-fail').check(); await page.locator('#consent').check(); await run(); await view('.result-panel'); await waitText(page, '#route', 'Local rules'); }
break;
case 'export': {
const download = page.waitForEvent('download'); await page.locator('#export').click(); await (await download).saveAs(resolve(output, 'handoff-sample.md'));
await view('.result-panel'); break;
}
case 'clear': await page.locator('#clear').click(); await view('.workspace'); break;
case 'end': await page.evaluate(() => scrollTo(0, 0)); break;
}
const hold = (quick ? 1600 : shot.seconds * 1000) - (performance.now() - started);
if (hold > 0) await delay(hold);
report.shots.push({ id: shot.id, start: (started - clockStart) / 1000, end: (performance.now() - clockStart) / 1000 });
console.log(`Captured ${shot.id} · ${Math.round((performance.now() - clockStart) / 1000)}s`);
}
if (pageErrors.length) throw Error('Browser exceptions occurred; recording requires review.');
report.status = 'passed';
} catch (error) { report.failure = error.message; process.exitCode = 1; }
finally {
// Resolve the local artifact while its channel is alive. Closing a persistent
// context closes that channel, so saveAs() afterwards is unavailable here.
const generatedVideo = video ? await video.path() : undefined;
if (context) await context.close();
const actual = await realpath(profile); const allowed = await realpath(cache);
if (!actual.startsWith(allowed + sep) || !actual.split(sep).at(-1).startsWith('chrome-demo-')) throw Error('Unexpected temporary-profile location.');
await rm(actual, { recursive: true, force: true, maxRetries: 3, retryDelay: 300 });
if (generatedVideo) {
if (!generatedVideo.startsWith(output + sep) || !generatedVideo.endsWith('.webm')) throw Error('Unexpected recording artifact location.');
const raw = resolve(output, 'capture.webm'); await rename(generatedVideo, raw);
try {
report.durationSeconds = videoDuration(ffmpeg, raw);
if (report.durationSeconds >= 180) throw Error('Recording reached the three-minute cap. Rerun after fixing slow setup; no footage was silently cut.');
await encodeVideo(ffmpeg, raw, resolve(output, 'hushbrief-captioned.mp4'), voiceover);
report.mp4DurationSeconds = videoDuration(ffmpeg, resolve(output, 'hushbrief-captioned.mp4'));
await writeFile(resolve(output, 'captions.srt'), captionSrt(shots, live, report.shots), 'utf8');
await writeFile(resolve(output, 'narration.txt'), shots.map(s => live ? s.liveText || s.text : s.text).join('\n\n') + '\n', 'utf8');
} catch (error) { report.status = 'failed'; report.failure = error.message; process.exitCode = 1; }
}
await writeFile(resolve(output, 'recording-report.json'), JSON.stringify(report, null, 2) + '\n', 'utf8');
await new Promise(done => process.stdout.write(`Recording ${report.status}: ${relative(root, output)} (local only)\n`, done));
if (report.failure) await new Promise(done => process.stderr.write(report.failure + '\n', done));
// All artifact writes, encoder completion, browser close and profile removal
// have been awaited. Terminate this CLI even if a driver timer remains alive.
process.exit(process.exitCode || 0);
}