From d02f436d8d16efcdebf48c97d0d06b67e71068c9 Mon Sep 17 00:00:00 2001 From: OmO Orchestrator Date: Wed, 18 Nov 2026 04:04:37 -0500 Subject: [PATCH] fix(identity): make concurrent init() calls idempotent so a fresh identity never gets stuck unresolved --- .../task-23-the-commons-hollow-polish.json | 52 ++++++ e2e/identityInitRace.e2e.mjs | 150 ++++++++++++++++++ src/lib/identity.test.ts | 19 +++ src/lib/identity.ts | 23 ++- 4 files changed, 243 insertions(+), 1 deletion(-) create mode 100644 .omo/evidence/the-commons-hollow-polish/task-23-the-commons-hollow-polish.json create mode 100644 e2e/identityInitRace.e2e.mjs diff --git a/.omo/evidence/the-commons-hollow-polish/task-23-the-commons-hollow-polish.json b/.omo/evidence/the-commons-hollow-polish/task-23-the-commons-hollow-polish.json new file mode 100644 index 0000000..efc9244 --- /dev/null +++ b/.omo/evidence/the-commons-hollow-polish/task-23-the-commons-hollow-polish.json @@ -0,0 +1,52 @@ +{ + "task": "23. Fix the StrictMode identity-init race that leaves a fresh visitor's wallet stuck on 'Balance --' forever", + "qa": "happy - 2 independent fresh browser profiles, real StrictMode (not disabled), no identity pre-seed", + "description": "Two independent fresh Playwright browser contexts (separate IndexedDB storage, no pre-seeded identity) each navigate cold to '/' under the app's real wrapper (src/main.tsx, untouched). Confirms the WalletCard balance genuinely starts at '--' (unresolved accountId, proving the race window is real) and resolves to 'No balance yet' within 8s on BOTH profiles, with zero console/page errors (no unhandled ConstraintError rejection).", + "tool": "Playwright (chromium), real Vite dev server, real app UI ('/' -> WalletCard), real ", + "run_command": "node e2e/identityInitRace.e2e.mjs", + "selectors_used": [ + "wallet-balance" + ], + "timestamp": "2026-11-18T09:04:16.836Z", + "result": { + "profileA": { + "scenario": "happy", + "profile": "A", + "steps": { + "initialBalanceWasUnresolved": { + "initialBalance": "--", + "wasDash": true + }, + "resolvedWithinTimeout": { + "resolvedBalance": "No balance yet", + "resolvedAfterMs": 826, + "neverStuckOnDash": true + }, + "consoleErrors": { + "consoleErrors": [] + } + }, + "pass": true + }, + "profileB": { + "scenario": "happy", + "profile": "B", + "steps": { + "initialBalanceWasUnresolved": { + "initialBalance": "--", + "wasDash": true + }, + "resolvedWithinTimeout": { + "resolvedBalance": "No balance yet", + "resolvedAfterMs": 365, + "neverStuckOnDash": true + }, + "consoleErrors": { + "consoleErrors": [] + } + }, + "pass": true + } + }, + "pass": true +} \ No newline at end of file diff --git a/e2e/identityInitRace.e2e.mjs b/e2e/identityInitRace.e2e.mjs new file mode 100644 index 0000000..f5b8076 --- /dev/null +++ b/e2e/identityInitRace.e2e.mjs @@ -0,0 +1,150 @@ +// StrictMode identity-init race acceptance test (plan todo 23). Self- +// contained Playwright runner, same shape as e2e/transactionHistorySignature.e2e.mjs, +// but deliberately does NOT pre-seed the identity record - the whole point +// of this test is to exercise the real cold-start path (identity.init() +// racing itself under React 19 StrictMode's dev double effect-invocation) +// against a genuinely fresh browser profile, with NO StrictMode override. +// +// HAPPY: 2 independent fresh browser contexts each navigate to "/" cold. +// Both must reach a resolved WalletCard balance ("No balance yet" for a +// never-before-seen identity, never a fabricated "0") within a few +// seconds - never stuck on "--" forever. +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 = 8000; + +async function runFreshProfile(browser, profileLabel) { + // Each call gets its own isolated context (separate IndexedDB origin + // storage) - a genuinely fresh profile, never reusing another run's + // identity. + const context = await browser.newContext(); + const evidence = { scenario: "happy", profile: profileLabel, steps: {} }; + try { + 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))); + + const navigatedAt = Date.now(); + await page.goto(`${APP_URL}/`); + + // Confirm the balance genuinely starts at "--" (unresolved accountId) - + // proves this is testing the real cold-start race window, not a + // no-op. + const initialBalance = await page.getByTestId("wallet-balance").innerText(); + evidence.steps.initialBalanceWasUnresolved = { initialBalance, wasDash: initialBalance === "--" }; + + await page.waitForFunction( + () => document.querySelector('[data-testid="wallet-balance"]')?.textContent !== "--", + { timeout: RESOLUTION_TIMEOUT_MS }, + ); + const resolvedBalance = await page.getByTestId("wallet-balance").innerText(); + const resolvedAfterMs = Date.now() - navigatedAt; + evidence.steps.resolvedWithinTimeout = { + resolvedBalance, + resolvedAfterMs, + neverStuckOnDash: resolvedBalance !== "--", + }; + + if (resolvedBalance !== "No balance yet") { + throw new Error(`expected a fresh identity to resolve to "No balance yet", got "${resolvedBalance}"`); + } + + evidence.steps.consoleErrors = { consoleErrors }; + if (consoleErrors.length > 0) { + throw new Error(`expected zero console/page errors (no unhandled rejection), got: ${JSON.stringify(consoleErrors)}`); + } + + evidence.pass = true; + return evidence; + } catch (err) { + evidence.pass = false; + evidence.error = String(err && err.message ? err.message : err); + throw Object.assign(err, { evidence }); + } finally { + await context.close(); + } +} + +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 results = {}; + let failed = false; + try { + try { + results.profileA = await runFreshProfile(browser, "A"); + } catch (e) { + failed = true; + results.profileA = e.evidence ?? { scenario: "happy", profile: "A", pass: false, error: String(e) }; + } + + try { + results.profileB = await runFreshProfile(browser, "B"); + } catch (e) { + failed = true; + results.profileB = e.evidence ?? { scenario: "happy", profile: "B", pass: false, error: String(e) }; + } + } finally { + await browser.close(); + await vite.close(); + } + + const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow-polish"); + mkdirSync(evDir, { recursive: true }); + const now = new Date().toISOString(); + + writeFileSync( + resolve(evDir, "task-23-the-commons-hollow-polish.json"), + JSON.stringify( + { + task: "23. Fix the StrictMode identity-init race that leaves a fresh visitor's wallet stuck on 'Balance --' forever", + qa: "happy - 2 independent fresh browser profiles, real StrictMode (not disabled), no identity pre-seed", + description: + "Two independent fresh Playwright browser contexts (separate IndexedDB storage, no pre-seeded identity) each navigate cold to '/' under the app's real wrapper (src/main.tsx, untouched). Confirms the WalletCard balance genuinely starts at '--' (unresolved accountId, proving the race window is real) and resolves to 'No balance yet' within 8s on BOTH profiles, with zero console/page errors (no unhandled ConstraintError rejection).", + tool: "Playwright (chromium), real Vite dev server, real app UI ('/' -> WalletCard), real ", + run_command: "node e2e/identityInitRace.e2e.mjs", + selectors_used: ["wallet-balance"], + timestamp: now, + result: results, + pass: Boolean(results.profileA && results.profileA.pass && results.profileB && results.profileB.pass), + }, + null, + 2, + ), + ); + + console.log("\n===== e2e RESULTS ====="); + console.log(JSON.stringify(results, null, 2)); + console.log( + `\nSUMMARY: profileA=${results.profileA && results.profileA.pass ? "PASS" : "FAIL"} profileB=${ + results.profileB && results.profileB.pass ? "PASS" : "FAIL" + }`, + ); + if (failed || !(results.profileA && results.profileA.pass) || !(results.profileB && results.profileB.pass)) { + process.exitCode = 1; + } +} + +main().catch((e) => { + console.error("FATAL", e); + process.exitCode = 1; +}); diff --git a/src/lib/identity.test.ts b/src/lib/identity.test.ts index 4bb992b..6ecccf5 100644 --- a/src/lib/identity.test.ts +++ b/src/lib/identity.test.ts @@ -30,6 +30,25 @@ describe("identity", () => { expect(await db.identity.count()).toBe(1); }); + it("resolves two concurrent init() calls against a fresh identity table to the SAME account, with no unhandled rejection (StrictMode double-effect regression)", async () => { + const unhandled: unknown[] = []; + const onUnhandledRejection = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandledRejection); + + try { + const [first, second] = await Promise.all([init(), init()]); + + expect(second.publicKey).toEqual(first.publicKey); + expect(await db.identity.count()).toBe(1); + + // Give any unhandled rejection from a losing racer's write a tick to surface. + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandledRejection); + } + }); + it("signs a message and verifies it against the persisted public key", async () => { await init(); const message = new TextEncoder().encode("the-commons-hollow"); diff --git a/src/lib/identity.ts b/src/lib/identity.ts index 8a012b7..d708406 100644 --- a/src/lib/identity.ts +++ b/src/lib/identity.ts @@ -16,7 +16,7 @@ async function loadExisting(): Promise { return db.identity.get("local"); } -export async function init(): Promise { +async function initUncached(): Promise { const existing = await loadExisting(); if (existing) { return { publicKey: existing.publicKey }; @@ -33,6 +33,27 @@ export async function init(): Promise { return { publicKey }; } +/** + * Caches the in-flight `init()` promise so two concurrent callers (e.g. + * React StrictMode's double effect-invocation in dev) await the SAME + * promise instead of racing two `db.identity.add()` writes against an + * empty identity table - the loser of that race would throw an unhandled + * Dexie `ConstraintError` and its caller's state setter would never run, + * leaving a fresh visitor's wallet stuck unresolved forever. Cleared once + * settled (success or failure) so a later genuine re-init still re-checks + * the database rather than replaying a stale result. + */ +let inFlightInit: Promise | undefined; + +export function init(): Promise { + if (!inFlightInit) { + inFlightInit = initUncached().finally(() => { + inFlightInit = undefined; + }); + } + return inFlightInit; +} + export async function getPublicKey(): Promise { const record = await loadExisting(); if (!record) throw new IdentityMissingError();