Files
patriothacks/e2e/assemblyQrSneakernet.e2e.mjs
OmO Orchestrator 70a684c238 fix(assembly): wire the QR-sneakernet air-gapped fallback into the shipped screen
The audit (.omo/evidence/coherence-audit/assembly.md) found src/lib/qrSneakernet.ts
fully built and tested (encodeDelta/decodeFrames/FrameCollector/renderFramesToDataURLs/
scanFrameFromImage, real qrcode+jsQR, CRC32-checked chunking) but with zero callers
outside its own test file, and no getUserMedia call anywhere in the app - the
README's claimed "QR-sneakernet air-gapped fallback" third resilience layer was
unreachable from the UI.

Adds QrSneakernetPanel (new component under src/miniapps/assembly/), wired into
AssemblyScreen.tsx alongside (not replacing) the existing WebRTC sync toggle:

- "Export state as QR": encodeAssemblyState -> encodeDelta -> renderFramesToDataURLs,
  cycling frames with a visible "Frame N of M" counter.
- "Scan a device's QR": real getUserMedia camera permission prompt with a clean
  denied/unavailable error UI, <video> + canvas capture loop feeding
  scanFrameFromImage into a FrameCollector, applying the reassembled delta via
  applyAssemblyUpdate once collector.isComplete(), with a "synced via QR, N frames
  received" success state. Camera track.stop() runs on cancel/unmount/completion.

Tests (QrSneakernetPanel.test.tsx, 7 passing): export frame rendering/counter,
getUserMedia denial + no-camera error states, cancel/unmount stop the stream
cleanly, and a genuine round trip - real QR bitmaps decoded via scanFrameFromImage,
reassembled via FrameCollector, applied via applyAssemblyUpdate, with the target
replica's CRDT state proven equal to the source's.

QA (e2e/assemblyQrSneakernet.e2e.mjs, Playwright): the export UI's rendered PNGs
decode via the real scanFrameFromImage and match the transport's own encodeDelta
output; a real camera-permission-denied path renders the error UI in headless
Chromium; and - the strongest evidence - a full device-to-device round trip via
Chrome's --use-file-for-fake-video-capture fed a real Y4M video built (ffmpeg-static)
from the actual PNG bytes the export UI rendered, driving the real "Scan a device's
QR" button end to end and confirming the receiving device's CRDT state matches what
was exported. Evidence: .omo/evidence/coherence-audit/assembly-qr-sneakernet-e2e.json.
2026-11-20 17:51:31 -05:00

450 lines
19 KiB
JavaScript

// Assembly QR-sneakernet air-gapped fallback acceptance test (coherence
// audit fix: .omo/evidence/coherence-audit/assembly.md, gap 2(c)/3).
//
// Drives the REAL shipped Assembly screen (/miniapp/assembly) through its
// own rendered "Export state as QR" / "Scan a device's QR" controls only -
// no `window`-level bypass of the UI for the behavior under test. Two
// genuinely separate browser instances stand in for two separate physical
// devices (separate profiles - separate IndexedDB, separate identity).
//
// Scenario A (export renders real, scannable QR images): seeds a proposal
// + roster entry on device A via the real `putProposal`/`putRosterEntry`
// production functions, clicks the real "Export state as QR" button, reads
// every cycled frame's rendered `<img>` data URL straight off the DOM, and
// decodes each one THROUGH THE REAL `scanFrameFromImage` (the exact
// function the scan side uses) run inside the same browser page - proving
// the export UI emits genuinely scannable QR codes, not just "an image
// appeared".
//
// Scenario B (the camera round trip, device A -> device B): takes the real
// PNG bytes captured in Scenario A, assembles them into a raw YUV4MPEG2
// video (via the `ffmpeg-static` dependency already in this project) where
// each QR frame is held on screen for ~2s, then launches a SECOND, separate
// Chromium instance for device B with Chrome's
// `--use-file-for-fake-video-capture=<y4m>` flag - the standard mechanism
// for deterministic fake-camera-feed testing this task calls for. Device B
// clicks the real "Scan a device's QR" button, which requests
// `getUserMedia` (auto-granted via `--use-fake-ui-for-media-stream` +
// `context.grantPermissions`), gets the synthetic video feed as its
// "camera", and runs the real `<video>` -> canvas -> `scanFrameFromImage`
// -> `FrameCollector` -> `applyAssemblyUpdate` pipeline with ZERO test-only
// bypass. Success is read off the real `assembly-qr-scan-success` UI text,
// and device B's own CRDT state (read back via the same
// `getAssemblyEngineForTesting` test seam `assemblyScreenSync.e2e.mjs`
// already uses) is confirmed to contain exactly the record seeded on
// device A (device B also runs the app's own unrelated demo auto-seed on
// first mount, so its state is a superset, not a byte-identical set).
//
// Scenario C (permission denied): a third, separate browser context never
// grants camera permission and omits the fake-UI auto-accept flag, so
// Chromium's real permission-prompt path auto-rejects in headless mode -
// confirms the real "permission was denied" error UI renders instead of
// hanging or crashing.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { spawn } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, writeFileSync, rmSync } from "node:fs";
import { dirname, resolve, join } from "node:path";
import { fileURLToPath } from "node:url";
import { tmpdir } from "node:os";
import ffmpegPath from "ffmpeg-static";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const VITE_PORT = 44000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
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`;
const QR_LIB_URL = `${APP_URL}/src/lib/qrSneakernet.ts`;
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) {
if (await fn()) return;
await sleep(200);
}
throw new Error(`timeout waiting for: ${label}`);
}
function run(cmd, args) {
return new Promise((resolvePromise, reject) => {
const child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] });
let stderr = "";
child.stderr.on("data", (b) => (stderr += String(b)));
child.on("exit", (code) => {
if (code === 0) resolvePromise();
else reject(new Error(`${cmd} exited ${code}: ${stderr.slice(-2000)}`));
});
});
}
/** Deep-sorts object keys so two structurally-equal values compare equal by
* `JSON.stringify` regardless of key insertion order - needed because a
* value round-tripped through `Y.applyUpdate` is a freshly-decoded plain
* object, not the original reference, and Yjs does not guarantee key order
* is preserved through that decode. */
function canonicalize(value) {
if (Array.isArray(value)) return value.map(canonicalize);
if (value && typeof value === "object") {
const sorted = {};
for (const key of Object.keys(value).sort()) sorted[key] = canonicalize(value[key]);
return sorted;
}
return value;
}
async function seedAssembly(page, { proposal, roster }) {
await page.evaluate(
async ({ engineUrl, libUrl, proposal, roster }) => {
const engineMod = await import(/* @vite-ignore */ engineUrl);
const libMod = await import(/* @vite-ignore */ libUrl);
const { assembly } = engineMod.getAssemblyEngineForTesting(engineMod.DEFAULT_ASSEMBLY_DB_NAME);
for (const entry of roster) libMod.putRosterEntry(assembly, entry);
for (const p of proposal) libMod.putProposal(assembly, p);
},
{ engineUrl: ENGINE_MODULE_URL, libUrl: ASSEMBLY_LIB_URL, proposal, roster },
);
}
async function readAssemblyState(page) {
return page.evaluate(
async ({ engineUrl, libUrl }) => {
const engineMod = await import(/* @vite-ignore */ engineUrl);
const libMod = await import(/* @vite-ignore */ libUrl);
const { assembly } = engineMod.getAssemblyEngineForTesting(engineMod.DEFAULT_ASSEMBLY_DB_NAME);
return {
proposals: libMod.listProposals(assembly),
roster: libMod.listRoster(assembly),
};
},
{ engineUrl: ENGINE_MODULE_URL, libUrl: ASSEMBLY_LIB_URL },
);
}
/** Decodes a data-URL QR frame image THROUGH THE REAL `scanFrameFromImage`
* (same function the scan side's capture loop calls), run inside the
* browser page itself via `<canvas>.getImageData` - the exact pixel path a
* `<video>` -> canvas capture would produce. */
async function decodeFrameDataUrl(page, dataUrl) {
return page.evaluate(
async ({ src, libUrl }) => {
const img = new Image();
await new Promise((resolvePromise, reject) => {
img.onload = () => resolvePromise(undefined);
img.onerror = () => reject(new Error("image failed to load"));
img.src = src;
});
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const mod = await import(/* @vite-ignore */ libUrl);
return mod.scanFrameFromImage(imageData);
},
{ src: dataUrl, libUrl: QR_LIB_URL },
);
}
async function main() {
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 results = {};
let failed = false;
const workDir = mkdtempSync(join(tmpdir(), "assembly-qr-e2e-"));
const seedContent = {
roster: [
{ id: "r1", residentId: "r1", displayName: "Resident One", joinedAt: 1000, active: true },
],
proposal: [
{
id: "p1",
title: "Repair the community well pump",
description: "Pump noise has been reported for a week.",
authorId: "r1",
createdAt: 2000,
status: "open",
},
],
};
// ---------------------------------------------------------------
// Scenario A: export renders real, scannable QR frames.
// ---------------------------------------------------------------
const scenarioA = { scenario: "export-real-qr", steps: {} };
let framePngPaths = [];
const browserA = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
try {
const ctxA = await browserA.newContext();
const pageA = await ctxA.newPage();
await pageA.goto(ASSEMBLY_URL);
await pageA.getByTestId("assembly-qr-export-start").waitFor({ state: "visible" });
await seedAssembly(pageA, seedContent);
await pageA.getByTestId("assembly-qr-export-start").click();
await pageA.getByTestId("assembly-qr-export-counter").waitFor({ state: "visible" });
const counterText = (await pageA.getByTestId("assembly-qr-export-counter").textContent()) ?? "";
const match = counterText.match(/Frame 1 of (\d+)/);
if (!match) throw new Error(`unexpected counter text: "${counterText}"`);
const frameCount = Number(match[1]);
scenarioA.steps.frameCount = frameCount;
const dataUrls = [];
for (let i = 1; i <= frameCount; i++) {
await waitFor(
async () =>
((await pageA.getByTestId("assembly-qr-export-counter").textContent()) ?? "").startsWith(
`Frame ${i} of`,
),
`export counter reaches frame ${i}`,
);
const src = await pageA.getByTestId("assembly-qr-export-frame").getAttribute("src");
if (!src || !src.startsWith("data:image/png;base64,")) {
throw new Error(`frame ${i}: not a real PNG data URL`);
}
dataUrls.push(src);
}
// Decode every rendered frame through the real scanFrameFromImage -
// proves these are genuinely scannable QR codes, not placeholder art.
const decoded = [];
for (const dataUrl of dataUrls) {
const frame = await decodeFrameDataUrl(pageA, dataUrl);
if (frame === null) throw new Error("a rendered export frame failed to decode via scanFrameFromImage");
decoded.push(frame);
}
scenarioA.steps.allFramesDecoded = decoded.length === frameCount;
// Cross-check against the exact frames the production transport itself
// would produce for this state (encodeAssemblyState + encodeDelta) -
// the rendered QR images carry the REAL current state, not stale data.
const expectedFrames = await pageA.evaluate(
async ({ engineUrl, libUrl, qrLibUrl }) => {
const engineMod = await import(/* @vite-ignore */ engineUrl);
const libMod = await import(/* @vite-ignore */ libUrl);
const qrMod = await import(/* @vite-ignore */ qrLibUrl);
const { assembly } = engineMod.getAssemblyEngineForTesting(engineMod.DEFAULT_ASSEMBLY_DB_NAME);
return qrMod.encodeDelta(libMod.encodeAssemblyState(assembly));
},
{ engineUrl: ENGINE_MODULE_URL, libUrl: ASSEMBLY_LIB_URL, qrLibUrl: QR_LIB_URL },
);
scenarioA.steps.decodedMatchesExpected =
decoded.length === expectedFrames.length && decoded.every((f, i) => f === expectedFrames[i]);
if (!scenarioA.steps.decodedMatchesExpected) {
throw new Error("decoded frames did not match the real transport's own encodeDelta output");
}
// Save the real PNG bytes to disk for Scenario B's fake-camera feed.
mkdirSync(workDir, { recursive: true });
framePngPaths = dataUrls.map((dataUrl, i) => {
const b64 = dataUrl.slice("data:image/png;base64,".length);
const p = join(workDir, `frame_${String(i).padStart(3, "0")}.png`);
writeFileSync(p, Buffer.from(b64, "base64"));
return p;
});
scenarioA.pass = true;
results.exportRealQr = scenarioA;
} catch (err) {
failed = true;
scenarioA.pass = false;
scenarioA.error = String(err && err.message ? err.message : err);
results.exportRealQr = scenarioA;
} finally {
await browserA.close();
}
// ---------------------------------------------------------------
// Scenario B: the real camera round trip via a Chrome fake-file video
// capture device, through device B's real scan UI end to end.
// ---------------------------------------------------------------
const scenarioB = { scenario: "camera-round-trip", steps: {} };
if (framePngPaths.length > 0) {
const seqDir = join(workDir, "seq");
mkdirSync(seqDir, { recursive: true });
const FPS = 5;
const SECONDS_PER_FRAME = 2;
const REPEAT = FPS * SECONDS_PER_FRAME;
let seqIndex = 0;
try {
for (const framePath of framePngPaths) {
for (let r = 0; r < REPEAT; r++) {
const dest = join(seqDir, `img_${String(seqIndex).padStart(5, "0")}.png`);
writeFileSync(dest, readFileSync(framePath));
seqIndex++;
}
}
const y4mPath = join(workDir, "camera-feed.y4m");
await run(ffmpegPath, [
"-y",
"-framerate",
String(FPS),
"-i",
join(seqDir, "img_%05d.png"),
"-vf",
"scale=480:480:flags=neighbor,format=yuv420p",
y4mPath,
]);
scenarioB.steps.videoBuilt = true;
const browserB = await chromium.launch({
headless: true,
args: [
"--no-sandbox",
"--use-fake-device-for-media-stream",
"--use-fake-ui-for-media-stream",
`--use-file-for-fake-video-capture=${y4mPath}`,
],
});
try {
const ctxB = await browserB.newContext();
await ctxB.grantPermissions(["camera"], { origin: APP_URL });
const pageB = await ctxB.newPage();
await pageB.goto(ASSEMBLY_URL);
await pageB.getByTestId("assembly-qr-scan-start").waitFor({ state: "visible" });
await pageB.getByTestId("assembly-qr-scan-start").click();
await pageB.getByTestId("assembly-qr-scan-video").waitFor({ state: "visible" });
await waitFor(
async () => (await pageB.getByTestId("assembly-qr-scan-success").count()) > 0,
"device B's scan reports success",
60000,
);
const successText = (await pageB.getByTestId("assembly-qr-scan-success").textContent()) ?? "";
scenarioB.steps.successText = successText;
scenarioB.steps.reportedFrameCount = successText.includes(
`${framePngPaths.length} frame${framePngPaths.length === 1 ? "" : "s"} received`,
);
// Device B is a fresh profile that also runs the app's own
// unrelated demo auto-seed (src/admin/seedEvents.ts) the moment the
// screen first mounts, so its roster/proposal lists are a superset
// of what device A exported - the genuine proof is that EXACTLY the
// record seeded on device A is present among them, not that the
// two lists are identical sets.
const deviceBState = await readAssemblyState(pageB);
const canonicalProposals = canonicalize(deviceBState.proposals);
const canonicalRoster = canonicalize(deviceBState.roster);
const expectedProposal = JSON.stringify(canonicalize(seedContent.proposal[0]));
const expectedRoster = JSON.stringify(canonicalize(seedContent.roster[0]));
scenarioB.steps.proposalsMatch = canonicalProposals.some(
(p) => JSON.stringify(p) === expectedProposal,
);
scenarioB.steps.rosterMatches = canonicalRoster.some((r) => JSON.stringify(r) === expectedRoster);
if (!scenarioB.steps.proposalsMatch || !scenarioB.steps.rosterMatches) {
scenarioB.steps.deviceBState = deviceBState;
}
if (!scenarioB.steps.reportedFrameCount) {
throw new Error(`unexpected success text: "${successText}"`);
}
if (!scenarioB.steps.proposalsMatch || !scenarioB.steps.rosterMatches) {
throw new Error("device B's applied CRDT state did not match what device A exported");
}
scenarioB.pass = true;
results.cameraRoundTrip = scenarioB;
} finally {
await browserB.close();
}
} catch (err) {
failed = true;
scenarioB.pass = false;
scenarioB.error = String(err && err.message ? err.message : err);
results.cameraRoundTrip = scenarioB;
}
} else {
scenarioB.pass = false;
scenarioB.error = "skipped: scenario A produced no frames to feed the fake camera";
results.cameraRoundTrip = scenarioB;
failed = true;
}
// ---------------------------------------------------------------
// Scenario C: permission denied - no fake-ui flag, no granted
// permission, so Chromium's real headless permission path auto-rejects.
// ---------------------------------------------------------------
const scenarioC = { scenario: "permission-denied", steps: {} };
const browserC = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
try {
const ctxC = await browserC.newContext();
const pageC = await ctxC.newPage();
await pageC.goto(ASSEMBLY_URL);
await pageC.getByTestId("assembly-qr-scan-start").waitFor({ state: "visible" });
await pageC.getByTestId("assembly-qr-scan-start").click();
await waitFor(
async () => (await pageC.getByTestId("assembly-qr-scan-error").count()) > 0,
"device C shows a camera error",
15000,
);
const errorText = (await pageC.getByTestId("assembly-qr-scan-error").textContent()) ?? "";
scenarioC.steps.errorText = errorText;
scenarioC.steps.noVideoElement = (await pageC.getByTestId("assembly-qr-scan-video").count()) === 0;
scenarioC.pass = scenarioC.steps.noVideoElement && errorText.length > 0;
if (!scenarioC.pass) throw new Error(`unexpected state: errorText="${errorText}"`);
results.permissionDenied = scenarioC;
} catch (err) {
failed = true;
scenarioC.pass = false;
scenarioC.error = String(err && err.message ? err.message : err);
results.permissionDenied = scenarioC;
} finally {
await browserC.close();
}
await vite.close();
try {
rmSync(workDir, { recursive: true, force: true });
} catch {
// best-effort cleanup of the scratch dir
}
const evDir = resolve(ROOT, ".omo/evidence/coherence-audit");
mkdirSync(evDir, { recursive: true });
writeFileSync(
resolve(evDir, "assembly-qr-sneakernet-e2e.json"),
JSON.stringify(
{
task: "Assembly coherence gap: wire the QR-sneakernet air-gapped fallback into the shipped screen",
tool:
"Playwright (chromium), real shipped Assembly screen UI; camera round trip via Chrome --use-file-for-fake-video-capture fed a real Y4M video built (via ffmpeg-static) from the real PNG bytes the export UI rendered",
run_command: "node e2e/assemblyQrSneakernet.e2e.mjs",
timestamp: new Date().toISOString(),
results,
pass: !failed,
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(results, null, 2));
console.log(
`\nSUMMARY: exportRealQr=${results.exportRealQr?.pass ? "PASS" : "FAIL"} cameraRoundTrip=${
results.cameraRoundTrip?.pass ? "PASS" : "FAIL"
} permissionDenied=${results.permissionDenied?.pass ? "PASS" : "FAIL"}`,
);
if (failed) process.exitCode = 1;
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});