Files
patriothacks/e2e/autoSeedColdLoad.e2e.mjs

210 lines
8.7 KiB
JavaScript

// Real-browser QA for plan todo 5 (auto-seed the Hollow demo fixture on a
// genuinely empty Event Log at shell boot). Self-contained Playwright
// runner, same shape as e2e/identityInitRace.e2e.mjs. Reads the Event Log
// via the raw `indexedDB` API (not a dynamic ES-module re-import, which
// proved unreliable through Vite's dev-server module graph) - the same
// ground truth the real app's own Dexie-backed `readAll()` is built on.
//
// HAPPY: a fresh browser context (separate IndexedDB origin storage, no
// pre-seeded identity/log) navigates straight to `/` - never `/admin` -
// and the wallet balance leaves "--" for a real non-zero number, with the
// 13-tile mini-app grid populated, all without any manual seed step.
// FAILURE (idempotent): reloading the same profile a second time does not
// duplicate the seed.demo.loaded marker or any other seed.* event - this
// also exercises the real app's React 19 <StrictMode> dev double
// effect-invocation path (src/main.tsx), which the in-flight-promise guard
// in src/admin/loadHollowDemo.ts exists specifically to survive.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { mkdirSync, writeFileSync } 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 VITE_PORT = 48000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const RESOLUTION_TIMEOUT_MS = 10000;
const EVIDENCE_DIR = resolve(ROOT, ".omo/evidence/first-place-overhaul");
function readEventLogPayloadTypes() {
return new Promise((res, rej) => {
const req = indexedDB.open("the-commons-hollow");
req.onsuccess = () => {
const database = req.result;
const tx = database.transaction("eventLog", "readonly");
const store = tx.objectStore("eventLog");
const getAllReq = store.getAll();
getAllReq.onsuccess = () => {
res(getAllReq.result.map((e) => (e && e.payload ? e.payload.type : null)));
};
getAllReq.onerror = () => rej(getAllReq.error);
};
req.onerror = () => rej(req.error);
});
}
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 browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const evidence = { scenario: "happy+failure", steps: {} };
let pass = true;
try {
const context = await browser.newContext();
const page = await context.newPage();
const consoleErrors = [];
page.on("console", (msg) => {
if (msg.type() === "error") consoleErrors.push(msg.text());
});
page.on("pageerror", (err) => consoleErrors.push(String(err)));
await page.goto(`${APP_URL}/`);
const initialBalance = await page.getByTestId("wallet-balance").innerText();
evidence.steps.coldStart = { initialBalance, wasDash: initialBalance === "--" };
// Data-completion signal: the marker is the auto-seed's very last
// write, so waiting for it (via the raw IndexedDB store, not the UI)
// proves the full fixture has landed.
async function markerPresent() {
const types = await page.evaluate(readEventLogPayloadTypes);
return types.includes("seed.demo.loaded");
}
const deadline = Date.now() + RESOLUTION_TIMEOUT_MS;
while (!(await markerPresent())) {
if (Date.now() > deadline) {
throw new Error("timed out waiting for the seed.demo.loaded marker to land");
}
await page.waitForTimeout(100);
}
// UI-reactivity signal: WalletCard's own `liveQuery` subscription needs
// its own bounded wait to visually catch up to the now-complete data.
await page.waitForFunction(
() => {
const text = document.querySelector('[data-testid="wallet-balance"]')?.textContent;
return text !== undefined && Number.isFinite(Number(text));
},
{ timeout: RESOLUTION_TIMEOUT_MS },
);
const resolvedBalance = await page.getByTestId("wallet-balance").innerText();
const numericBalance = Number(resolvedBalance);
evidence.steps.autoSeededBalance = {
resolvedBalance,
numericBalance,
isNonZeroNumber: Number.isFinite(numericBalance) && numericBalance > 0,
};
if (!Number.isFinite(numericBalance) || numericBalance <= 0) {
throw new Error(`expected a non-zero auto-seeded balance, got "${resolvedBalance}"`);
}
const tileCount = await page.getByRole("grid", { name: "Miniapps" }).getByRole("button").count();
evidence.steps.tileGrid = { tileCount };
if (tileCount < 13) {
throw new Error(`expected at least 13 populated mini-app tiles, got ${tileCount}`);
}
mkdirSync(EVIDENCE_DIR, { recursive: true });
await page.screenshot({ path: resolve(EVIDENCE_DIR, "task-5-first-place-overhaul-cold-load.png") });
const typesAfterFirstLoad = await page.evaluate(readEventLogPayloadTypes);
const markerCountFirst = typesAfterFirstLoad.filter((t) => t === "seed.demo.loaded").length;
evidence.steps.firstLoadEventLog = {
totalEntries: typesAfterFirstLoad.length,
markerCount: markerCountFirst,
entryCountsByType: Object.fromEntries(
[...new Set(typesAfterFirstLoad)].map((t) => [t, typesAfterFirstLoad.filter((x) => x === t).length]),
),
};
if (markerCountFirst !== 1) {
throw new Error(`expected exactly 1 seed.demo.loaded marker after first load, got ${markerCountFirst}`);
}
// Simulate a reload on the SAME profile (same IndexedDB origin) -
// idempotency must hold: no duplicate seed.* events, including under
// the real app's <StrictMode> double effect-invocation.
await page.reload();
await page.waitForFunction(
() => {
const text = document.querySelector('[data-testid="wallet-balance"]')?.textContent;
return text !== undefined && text !== "--";
},
{ timeout: RESOLUTION_TIMEOUT_MS },
);
const typesAfterReload = await page.evaluate(readEventLogPayloadTypes);
const markerCountSecond = typesAfterReload.filter((t) => t === "seed.demo.loaded").length;
evidence.steps.reloadEventLog = {
totalEntries: typesAfterReload.length,
markerCount: markerCountSecond,
sameTotalAsFirstLoad: typesAfterReload.length === typesAfterFirstLoad.length,
};
if (markerCountSecond !== 1 || typesAfterReload.length !== typesAfterFirstLoad.length) {
throw new Error(
`idempotency violated: first load had ${typesAfterFirstLoad.length} entries/${markerCountFirst} markers, reload had ${typesAfterReload.length} entries/${markerCountSecond} markers`,
);
}
// `trySyncWithBackend()` (src/lib/sync.ts) is a documented silent,
// throw-free no-op against an unreachable backend - this harness runs
// no backend, so its failed resource loads are expected noise, not a
// regression from this change.
const unexpectedConsoleErrors = consoleErrors.filter(
(msg) => !msg.includes("502") && !msg.includes("Bad Gateway"),
);
evidence.steps.consoleErrors = { consoleErrors, unexpectedConsoleErrors };
if (unexpectedConsoleErrors.length > 0) {
throw new Error(
`expected zero UNEXPECTED console/page errors, got: ${JSON.stringify(unexpectedConsoleErrors)}`,
);
}
await context.close();
evidence.pass = true;
} catch (err) {
pass = false;
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
} finally {
await browser.close();
await vite.close();
}
mkdirSync(EVIDENCE_DIR, { recursive: true });
writeFileSync(
resolve(EVIDENCE_DIR, "task-5-first-place-overhaul-browser-qa.json"),
JSON.stringify(
{
task: "5. Auto-seed the Hollow demo fixture on a genuinely empty Event Log at shell boot",
qa:
"happy - fresh browser profile navigates to '/' (never '/admin'), wallet balance leaves '--' for a real non-zero number, 13-tile grid populated; failure - reloading the same profile (exercising the real app's React StrictMode double effect-invocation) does not duplicate seed.* events",
tool: "Playwright (chromium), real Vite dev server, real app UI, real <StrictMode>",
run_command: "node e2e/autoSeedColdLoad.e2e.mjs",
timestamp: new Date().toISOString(),
result: evidence,
pass,
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(evidence, null, 2));
console.log(`\nSUMMARY: ${pass ? "PASS" : "FAIL"}`);
if (!pass) process.exitCode = 1;
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});