From 387fa66c6a63dfaffc09c034a8d1fdabdd00eebe Mon Sep 17 00:00:00 2001 From: OmO Orchestrator Date: Wed, 18 Nov 2026 23:57:04 -0500 Subject: [PATCH] feat(sync): wire HIGH-tier multiplayer mini-apps to the backend relay --- .../task-3-backend-service-expansion.md | 184 ++++++++++++++++++ src/lib/fairshare.test.ts | 41 +++- src/lib/fairshare.ts | 7 +- src/lib/housing.ts | 7 +- src/lib/skyMemoryWall.test.ts | 33 +++- src/lib/skyMemoryWall.ts | 7 +- src/lib/skyMorale.test.ts | 32 ++- src/lib/skyMorale.ts | 7 +- src/miniapps/fairdraw/RevealDraw.test.tsx | 45 ++++- src/miniapps/fairdraw/RevealDraw.tsx | 18 +- src/miniapps/fairshare/ResourceTiles.tsx | 8 + src/miniapps/fairshare/TrendChart.tsx | 8 + .../healthpost/HealthPostScreen.test.tsx | 22 ++- src/miniapps/healthpost/HealthPostScreen.tsx | 8 + .../healthpost/healthpostEvents.test.ts | 58 +++++- src/miniapps/healthpost/healthpostEvents.ts | 13 +- src/miniapps/housing/FloorPlanScreen.test.tsx | 37 +++- src/miniapps/housing/FloorPlanScreen.tsx | 10 +- src/miniapps/sky/SkyScreen.test.tsx | 25 ++- src/miniapps/sky/SkyScreen.tsx | 10 + src/miniapps/theclimb/TheClimbScreen.test.tsx | 24 ++- src/miniapps/theclimb/TheClimbScreen.tsx | 9 + .../tunnelsafety/ReportHazardForm.tsx | 4 + .../tunnelsafety/TunnelSafetyScreen.test.tsx | 35 +++- .../tunnelsafety/TunnelSafetyScreen.tsx | 9 +- src/shell/TransactionHistory.test.tsx | 22 ++- src/shell/TransactionHistory.tsx | 9 + src/shell/WalletCard.test.tsx | 28 ++- src/shell/WalletCard.tsx | 10 + 29 files changed, 700 insertions(+), 30 deletions(-) create mode 100644 .omo/evidence/backend-service-expansion/task-3-backend-service-expansion.md diff --git a/.omo/evidence/backend-service-expansion/task-3-backend-service-expansion.md b/.omo/evidence/backend-service-expansion/task-3-backend-service-expansion.md new file mode 100644 index 0000000..317cd39 --- /dev/null +++ b/.omo/evidence/backend-service-expansion/task-3-backend-service-expansion.md @@ -0,0 +1,184 @@ +# Todo 3 - Wire the 8 HIGH-tier multiplayer mini-apps to the relay + +Plan: `.omo/plans/backend-service-expansion.md`, todo 3. +Worktree: `backend-service-expansion-wave2` (branch `backend-service-expansion-wave2`). + +## What changed + +Every write wires `trySyncWithBackend()` (from `src/lib/sync.ts`) fire-and-forget +(`void trySyncWithBackend();`) immediately after the real local `append()`/`appendFn()` +call resolves, and never awaits/returns it - so the local-first write's own +result and the component's render are never delayed or reordered by it. +`trySyncWithBackend()` itself is already a no-throw, catch-everything helper +(per its own doc comment in `sync.ts`), so no app-level try/catch was added +around the fire-and-forget calls. + +Every mount wires it via `useEffect(() => { void trySyncWithBackend(); }, [])` +(empty deps - fires once per mount, never re-fires on every render). + +| App | Write-path file(s) | Mount file(s) | +|---|---|---| +| Fair Share | `src/lib/fairshare.ts` (`postFairshareFloor`) | `src/miniapps/fairshare/ResourceTiles.tsx`, `TrendChart.tsx` | +| Tunnel Safety | `src/miniapps/tunnelsafety/ReportHazardForm.tsx` (after `reportHazard()`) | `src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx` | +| Housing | `src/lib/housing.ts` (`reportIdleSpace`) | `src/miniapps/housing/FloorPlanScreen.tsx` | +| Health Post | `src/miniapps/healthpost/healthpostEvents.ts` (`postSymptomReport`, `postReferral`) | `src/miniapps/healthpost/HealthPostScreen.tsx` | +| Fair Draw | `src/miniapps/fairdraw/RevealDraw.tsx` (after the commit-publish `append()` and after the reveal `append()`) | `src/miniapps/fairdraw/RevealDraw.tsx` (same component, mount effect) | +| The Climb | **none - see below** | `src/miniapps/theclimb/TheClimbScreen.tsx` | +| Wallet | **none - see below** | `src/shell/WalletCard.tsx`, `src/shell/TransactionHistory.tsx` | +| Sky | `src/lib/skyMemoryWall.ts` (`postMemoryWallEntry`), `src/lib/skyMorale.ts` (`postMoralePulse`) | `src/miniapps/sky/SkyScreen.tsx` | + +### The Climb - genuinely read-only today, mount pull only (as instructed) + +Verified by reading every file in `src/miniapps/theclimb/` and grepping for +`append(` across that directory: zero matches. `TheClimbScreen.tsx`'s +schedule/congestion/wave-demand state is pure local `useState`, never +persisted to the signed Event Log (not even read from it via +`useEventLogEntries`). This mini-app has no resident-facing write into the +log at all, so per the task's own instruction I did **not** invent a write +hook - I wired a mount-time pull only, with a comment in the source +explaining why. + +### Wallet - no transfer UI exists today, mount pull only (as instructed) + +Confirmed: `wallet.transfer` is only ever constructed in admin seed data +(`src/admin/seedEvents.ts`) and tests - there is no send/transfer screen in +`src/shell/` or `src/miniapps/`. Per the task's explicit instruction, I wired +`trySyncWithBackend()` on mount in `WalletCard.tsx` and +`TransactionHistory.tsx` only, and did not invent a transfer UI. + +### Sky - `useSkyPresence.ts` deliberately untouched + +Per the task's explicit instruction, `src/miniapps/sky/useSkyPresence.ts` +(the live WebRTC/Yjs Awareness presence counter, shared transport with +Assembly) was not touched or double-wired. The mount-time sync lives in +`SkyScreen.tsx` next to the memory-wall/morale-pulse state, with a comment +explaining the separation. + +## Automated verification + +``` +$ npm run test + Test Files 87 passed (87) + Tests 668 passed (668) + Duration 8.51s + +$ npm run build +✓ 290 modules transformed. +✓ built in 595ms +PWA v2.0.0 — precache 20 entries (1119.38 KiB), files generated + +$ npm run lint +exit 0 (warnings only; every warning on a line I did not touch - see below) +``` + +Full, unmodified existing suite (668 tests, 87 files across the whole repo, +not just the 8 touched mini-apps) stays green. `tsc -b --noEmit` was also run +standalone before the full `build` and passed with no output. + +### Lint warnings are pre-existing, not introduced by this change + +`npm run lint` exits 0 (oxlint only fails the command on errors). Two of the +printed `set-state-in-effect` warnings land in files this todo touched +(`TheClimbScreen.tsx:37`, `SkyScreen.tsx:57`) - both verified by reading the +exact lines to be inside the *pre-existing* `useEffect` blocks (the schedule +computation effect and the clock-tick effect respectively), not the new +mount-sync `useEffect` this todo added. Every other listed warning is in a +file this todo never touched (`AdminAggregatePanel.tsx`, +`useAssemblyEngine.ts`, `findfamily/SearchScreen.tsx`, `mentor/MentorScreen.tsx`, +`MountedMiniapp.tsx`, `InstallMiniappScreen.tsx`, `InstalledMiniappScreen.tsx`, +`e2e/demoRecording.e2e.mjs`). + +## Manual-QA evidence (adversarial QA classes) + +### Rigorous tests (3 of 8 apps, mocking `fetch` and asserting observable sync calls) + +**Fair Share** - `src/lib/fairshare.test.ts`, describe +`"postFairshareFloor backend sync wiring (plan todo 3)"`: +- asserts `fetch` is called exactly once with `"/api/sync"` / `POST` after + `postFairshareFloor()` resolves, while the local `append()`'s own stored + entry and `readAll()` count are verified unaffected by the (rejected) + relay call. +- asserts the write still resolves normally (never throws into the caller) + when the relay is unreachable. + +**Health Post** - `src/miniapps/healthpost/healthpostEvents.test.ts`, describe +`"postSymptomReport / postReferral backend sync wiring (plan todo 3)"` +(both write sites), plus `src/miniapps/healthpost/HealthPostScreen.test.tsx`, +describe `"HealthPostScreen backend sync wiring (plan todo 3, mount-time pull)"` +asserting the mount-time call fires without altering the honest +"No symptom reports yet" empty render. + +**Sky** - `src/lib/skyMemoryWall.test.ts` (`postMemoryWallEntry`) and +`src/lib/skyMorale.test.ts` (`postMoralePulse`), both with the same +called-once / local-write-unaffected / never-throws shape, plus +`src/miniapps/sky/SkyScreen.test.tsx` describe +`"SkyScreen backend sync wiring (plan todo 3, mount-time pull)"` asserting +the mount call fires without touching `useSkyPresence`'s own transport. + +### Simpler assertions (remaining 5 apps - sync call wired + existing tests still pass) + +- **Tunnel Safety** - `TunnelSafetyScreen.test.tsx`: mount call (1) then a + second call (2) after a real hazard report submitted through + `ReportHazardForm`, with the form's own "Hazard reported." success text + still rendering. +- **Housing** - `FloorPlanScreen.test.tsx`: mount call (1) then a second + call (2) after a real `housing.space.report` submitted through + `ReportSpaceForm`, with the entry still present via `readAll()`. +- **Fair Draw** - `RevealDraw.test.tsx`: mount call (1), a second call after + the commit `append()` (2), a third after the reveal `append()` (3), with + exactly one real `fairdraw.commit`/`fairdraw.reveal` pair still recorded. +- **The Climb** - `TheClimbScreen.test.tsx`: mount call (1), with the honest + "no schedule yet" empty state still rendering. +- **Wallet** - `WalletCard.test.tsx` (asserts 2 calls - `WalletCard`'s own + mount effect plus the nested `TransactionHistory`'s) and + `TransactionHistory.test.tsx` (1 call, standalone), both with the honest + empty-state renders unaffected. + +All of the above await the real mocked-`fetch` promise/DOM update via +`waitFor` - no `setTimeout`/sleep/timing waits anywhere in the new assertions. + +## Adversarial QA classes + +- **malformed input**: n/a - this todo adds no new input parsing; every + write path's existing validation (e.g. `InvalidFairshareFloorError`, + `InvalidHousingSpaceReportError`, `SkyMoraleValidationError`) is + untouched and still runs *before* `append()`/`trySyncWithBackend()` are + ever reached. +- **stale/cached artifacts**: verified directly - in every wired write path, + `trySyncWithBackend()` is called *after* `append()` has already resolved + and is never `await`ed by the caller, so the local-first optimistic + update can never wait on, or be reordered by, the sync call. Proven by + the "unaffected local result" assertions above, all of which pass with + the mocked relay rejecting every call. +- **flaky tests**: every new assertion awaits the real mocked-`fetch` + promise chain via vitest `waitFor`/already-awaited calls; no + `setTimeout`/sleep. Ran `npm run test` to completion (not a subset) to + confirm determinism under full-suite load - 668/668 passed. +- **misleading success output**: the `npm run test` / `npm run build` / + `npm run lint` output quoted above is the literal command output (exit + codes and tail), not a paraphrase. One failing assertion was found and + fixed during this todo (`WalletCard`'s new mount test initially expected + 1 `fetch` call but `WalletCard` also mounts `TransactionHistory`, which + independently sync-wires - updated the assertion to 2, matching the real + nested-component behavior) - reported here rather than silently + discarded. +- Other adversarial classes (auth bypass, injection, race conditions + beyond the stale-artifact check above) are not applicable: this todo + adds no new input surface, no new auth, and no new mutable shared state - + it only adds fire-and-forget calls into an already-reviewed, + already-tested helper (`sync.ts`, todo 2). + +## Scope discipline + +- Touched only the 8 apps' own files (write-path lib/component + + mount-time component) plus their co-located `*.test.ts(x)` files. No + changes to `api/**`, `src/lib/eventlog.ts`, `src/lib/sync.ts` itself, + `src/admin/**`, or any mini-app outside the 8 listed (Water Watch, + Mentor, Farms are untouched - todo 4's scope). +- No existing test's asserted behavior was changed - only new + describe/it blocks were added, plus the single `WalletCard` assertion + fix described above (which corrects a wrong expectation in a test I + wrote myself in this same todo, not a pre-existing test). +- No business logic, payload shape, or UI behavior was changed - only a + fire-and-forget `trySyncWithBackend()` call was added at each write site + and each mount point. diff --git a/src/lib/fairshare.test.ts b/src/lib/fairshare.test.ts index 1cb73e4..b629c28 100644 --- a/src/lib/fairshare.test.ts +++ b/src/lib/fairshare.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "./db"; import { init } from "./identity"; import { append, readAll } from "./eventlog"; @@ -17,6 +17,10 @@ beforeEach(async () => { await init(); }); +afterEach(() => { + vi.unstubAllGlobals(); +}); + async function seedResource(resource: string, value: number): Promise { await append({ type: `seed.resource.${resource}`, resource, value }); } @@ -255,6 +259,41 @@ describe("postFairshareFloor (survival floor ahead of the CEEI solve)", () => { }); }); +describe("postFairshareFloor backend sync wiring (plan todo 3)", () => { + it("observably calls trySyncWithBackend() after the write, without delaying or altering the local-first append", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + const stored = await postFairshareFloor("power", 10); + + // The local-first write's own result is unaffected by the sync call + // (same value whether or not the relay is reachable) and was never + // reordered/delayed by it - the append() above already resolved before + // postFairshareFloor returned. + expect(stored.payload).toMatchObject({ type: "fairshare.floor", resource: "power", perAgentFloor: 10 }); + const entries = await readAll(); + expect(entries).toHaveLength(1); + + // trySyncWithBackend() is fire-and-forget (not awaited by + // postFairshareFloor), so give its microtask a turn to run before + // asserting the relay was actually invoked. + await Promise.resolve(); + await Promise.resolve(); + + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: "POST" }); + }); + + it("never throws into the caller when the relay is unreachable - the write still resolves normally", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down"))); + + await expect(postFairshareFloor("water", 5)).resolves.toMatchObject({ + payload: { type: "fairshare.floor", resource: "water", perAgentFloor: 5 }, + }); + }); +}); + describe("computeAllocationTrend", () => { it("reports 'no trend yet' at exactly 1 history entry", async () => { await append({ type: "fairshare.allocation.cycle", resource: "food", totalAllocated: 50 }); diff --git a/src/lib/fairshare.ts b/src/lib/fairshare.ts index 704c812..a79089c 100644 --- a/src/lib/fairshare.ts +++ b/src/lib/fairshare.ts @@ -2,6 +2,7 @@ import type { StoredEventLogEntry } from "./eventlog"; import { append } from "./eventlog"; import { sortForReplay } from "./ledger"; import { solveCeeiWaterFilling } from "./ceeiSpike"; +import { trySyncWithBackend } from "./sync"; /** * Production ma-fairshare allocation engine (plan todo 14). @@ -163,11 +164,15 @@ export async function postFairshareFloor( if (!isValidFloorValue(perAgentFloor)) { throw new InvalidFairshareFloorError(perAgentFloor); } - return append({ + const entry = await append({ type: "fairshare.floor", resource, perAgentFloor, } satisfies FairshareFloorPayload); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write this entry already completed. + void trySyncWithBackend(); + return entry; } function isAllocationCyclePayload( diff --git a/src/lib/housing.ts b/src/lib/housing.ts index e4c67d6..324963d 100644 --- a/src/lib/housing.ts +++ b/src/lib/housing.ts @@ -5,6 +5,7 @@ import solver, { } from "javascript-lp-solver"; import { append, readAll, type StoredEventLogEntry } from "./eventlog"; import { sortForReplay } from "./ledger"; +import { trySyncWithBackend } from "./sync"; /** * Housing: constrained assignment engine with a fairness-debt ledger @@ -236,7 +237,11 @@ export async function reportIdleSpace( idleHoursPerDay: input.idleHoursPerDay, reportedAt: Date.now(), }; - return append(payload); + const entry = await append(payload); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write that just completed above. + void trySyncWithBackend(); + return entry; } /** diff --git a/src/lib/skyMemoryWall.test.ts b/src/lib/skyMemoryWall.test.ts index 569d821..1b76cb7 100644 --- a/src/lib/skyMemoryWall.test.ts +++ b/src/lib/skyMemoryWall.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "./db.ts"; import { init } from "./identity.ts"; import { readAll } from "./eventlog.ts"; @@ -16,6 +16,10 @@ beforeEach(async () => { await init(); }); +afterEach(() => { + vi.unstubAllGlobals(); +}); + describe("isSkyMemoryEntryPayload", () => { it("accepts a well-formed memory wall payload", () => { expect( @@ -71,3 +75,30 @@ describe("postMemoryWallEntry + extractMemoryWallEntries", () => { expect(wall).toHaveLength(2); }); }); + +describe("postMemoryWallEntry backend sync wiring (plan todo 3)", () => { + it("observably calls trySyncWithBackend() after the write, without delaying or altering the local-first append", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + const stored = await postMemoryWallEntry({ text: "sync-wired entry" }, { now: () => 5000 }); + + expect(stored.payload).toMatchObject({ type: "sky.memoryWall.entry", text: "sync-wired entry" }); + expect(await readAll()).toHaveLength(1); + + // Fire-and-forget: give the un-awaited sync call's microtask a turn. + await Promise.resolve(); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(fetchMock.mock.calls[0][1]).toMatchObject({ method: "POST" }); + }); + + it("never throws into the caller when the relay is unreachable - the write still resolves normally", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down"))); + + await expect(postMemoryWallEntry({ text: "still works offline" })).resolves.toMatchObject({ + payload: { type: "sky.memoryWall.entry", text: "still works offline" }, + }); + }); +}); diff --git a/src/lib/skyMemoryWall.ts b/src/lib/skyMemoryWall.ts index 1ff18f1..c7e0090 100644 --- a/src/lib/skyMemoryWall.ts +++ b/src/lib/skyMemoryWall.ts @@ -14,6 +14,7 @@ import { append, type StoredEventLogEntry, } from "./eventlog.ts"; +import { trySyncWithBackend } from "./sync.ts"; export const SKY_MEMORY_ENTRY_PAYLOAD_TYPE = "sky.memoryWall.entry" as const; @@ -101,5 +102,9 @@ export async function postMemoryWallEntry( text, postedAt: now(), }; - return appendFn(payload); + const entry = await appendFn(payload); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write that just completed above. + void trySyncWithBackend(); + return entry; } diff --git a/src/lib/skyMorale.test.ts b/src/lib/skyMorale.test.ts index b128e06..3266950 100644 --- a/src/lib/skyMorale.test.ts +++ b/src/lib/skyMorale.test.ts @@ -1,4 +1,4 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "./db.ts"; import { init } from "./identity.ts"; import { readAll } from "./eventlog.ts"; @@ -18,6 +18,10 @@ beforeEach(async () => { await init(); }); +afterEach(() => { + vi.unstubAllGlobals(); +}); + describe("isSkyMoralePulsePayload", () => { it("accepts a well-formed morale pulse payload, with or without a note", () => { expect( @@ -111,3 +115,29 @@ describe("latestMoralePulse + aggregateMoraleCounts", () => { expect(aggregateMoraleCounts([])).toEqual({ great: 0, good: 0, okay: 0, low: 0, rough: 0 }); }); }); + +describe("postMoralePulse backend sync wiring (plan todo 3)", () => { + it("observably calls trySyncWithBackend() after the write, without delaying or altering the local-first append", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + const stored = await postMoralePulse({ mood: "good" }, { now: () => 5000 }); + + expect(stored.payload).toMatchObject({ type: "sky.morale.pulse", mood: "good" }); + expect(await readAll()).toHaveLength(1); + + // Fire-and-forget: give the un-awaited sync call's microtask a turn. + await Promise.resolve(); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + }); + + it("never throws into the caller when the relay is unreachable - the write still resolves normally", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down"))); + + await expect(postMoralePulse({ mood: "low" })).resolves.toMatchObject({ + payload: { type: "sky.morale.pulse", mood: "low" }, + }); + }); +}); diff --git a/src/lib/skyMorale.ts b/src/lib/skyMorale.ts index bff76d9..27ae5ef 100644 --- a/src/lib/skyMorale.ts +++ b/src/lib/skyMorale.ts @@ -20,6 +20,7 @@ */ import { append, type StoredEventLogEntry } from "./eventlog.ts"; +import { trySyncWithBackend } from "./sync.ts"; export const SKY_MORALE_PULSE_PAYLOAD_TYPE = "sky.morale.pulse" as const; @@ -152,5 +153,9 @@ export async function postMoralePulse( ...(trimmedNote ? { note: trimmedNote } : {}), postedAt: now(), }; - return appendFn(payload); + const entry = await appendFn(payload); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write that just completed above. + void trySyncWithBackend(); + return entry; } diff --git a/src/miniapps/fairdraw/RevealDraw.test.tsx b/src/miniapps/fairdraw/RevealDraw.test.tsx index d1c13ed..d279a83 100644 --- a/src/miniapps/fairdraw/RevealDraw.test.tsx +++ b/src/miniapps/fairdraw/RevealDraw.test.tsx @@ -17,7 +17,10 @@ import { init } from "../../lib/identity"; import { balanceOf, computeBalances } from "../../lib/ledger"; import { FAIR_DRAW_PRIZE_AMOUNT, RevealDraw } from "./RevealDraw"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -347,3 +350,43 @@ describe("RevealDraw append-to-log commit requirement (plan todo 8, require a pu expect(commits[0].lamportTs).toBeLessThan(reveals[0].lamportTs); }); }); + +describe("RevealDraw backend sync wiring (plan todo 3)", () => { + it("calls trySyncWithBackend() on mount, after commit, and after reveal - without altering the real commit/reveal writes", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + await init(); + const user = userEvent.setup(); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + + await act(async () => { + await user.click(screen.getByRole("button", { name: "Start Draw" })); + }); + await waitFor(() => + expect(screen.getByTestId("reveal-draw-commit-hash")).toBeInTheDocument(), + ); + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + + await act(async () => { + await user.click(screen.getByRole("button", { name: "Reveal" })); + }); + await waitFor(() => expect(screen.getByTestId("reveal-draw-revealed")).toBeInTheDocument()); + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(3); + }); + + // The real commit/reveal writes themselves were unaffected by the + // unreachable relay - still exactly one of each, correctly ordered. + const log = await readAll(); + expect(log.filter((e) => isFairDrawCommitPayload(e.payload))).toHaveLength(1); + expect(log.filter((e) => isFairDrawRevealPayload(e.payload))).toHaveLength(1); + }); +}); diff --git a/src/miniapps/fairdraw/RevealDraw.tsx b/src/miniapps/fairdraw/RevealDraw.tsx index 414ae29..149b6b5 100644 --- a/src/miniapps/fairdraw/RevealDraw.tsx +++ b/src/miniapps/fairdraw/RevealDraw.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from "react"; +import { useCallback, useEffect, useState } from "react"; import { append, readAll } from "../../lib/eventlog"; import { commit, @@ -10,6 +10,7 @@ import { type Revealed, } from "../../lib/fairdraw"; import { init as initIdentity } from "../../lib/identity"; +import { trySyncWithBackend } from "../../lib/sync"; import { Icon } from "../../shell/icons"; import { useActiveAccountId } from "../../shell/useActiveAccountId"; import styles from "./RevealDraw.module.css"; @@ -125,6 +126,12 @@ export function RevealDraw({ }: RevealDrawProps) { const [phase, setPhase] = useState({ step: "idle" }); + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render below. + useEffect(() => { + void trySyncWithBackend(); + }, []); + const startDraw = useCallback(async () => { // The commit/reveal primitives sign with the local identity's key via // append()'s real Event Log path (src/lib/eventlog.ts), which throws @@ -170,6 +177,10 @@ export function RevealDraw({ ); } + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first commit write that just completed. + void trySyncWithBackend(); + setPhase({ step: "committed", drawId, commitHash, seed, salt }); }, [generateSeedSalt, participants, appendDrawEvent, readDrawLog]); @@ -220,6 +231,11 @@ export function RevealDraw({ } } + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first reveal/credit writes that just + // completed above. + void trySyncWithBackend(); + setPhase({ step: "revealed", drawId: committed.drawId, diff --git a/src/miniapps/fairshare/ResourceTiles.tsx b/src/miniapps/fairshare/ResourceTiles.tsx index 3d6d5ed..2e13c7e 100644 --- a/src/miniapps/fairshare/ResourceTiles.tsx +++ b/src/miniapps/fairshare/ResourceTiles.tsx @@ -1,5 +1,7 @@ +import { useEffect } from "react"; import { balanceOf, computeBalances } from "../../lib/ledger"; import { computeFairshareAllocation, FAIRSHARE_RESOURCES, type FairshareResource } from "../../lib/fairshare"; +import { trySyncWithBackend } from "../../lib/sync"; import { Icon, type IconId } from "../../shell/icons"; import { useActiveAccountId } from "../../shell/useActiveAccountId"; import { useEventLogEntries } from "../../shell/useEventLogEntries"; @@ -38,6 +40,12 @@ export function ResourceTiles() { const accountId = useActiveAccountId(); const entries = useEventLogEntries(); + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render or the live Event Log subscription above. + useEffect(() => { + void trySyncWithBackend(); + }, []); + const ledgerState = computeBalances(entries); const hasBalanceRecord = accountId !== undefined && accountId in ledgerState.balances; const balance = hasBalanceRecord ? balanceOf(ledgerState, accountId!) : undefined; diff --git a/src/miniapps/fairshare/TrendChart.tsx b/src/miniapps/fairshare/TrendChart.tsx index 20e373d..75b1dd1 100644 --- a/src/miniapps/fairshare/TrendChart.tsx +++ b/src/miniapps/fairshare/TrendChart.tsx @@ -1,8 +1,10 @@ +import { useEffect } from "react"; import { computeAllocationTrend, getAllocationHistory, type FairshareResource, } from "../../lib/fairshare.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { useEventLogEntries } from "../../shell/useEventLogEntries.ts"; import styles from "./TrendChart.module.css"; @@ -59,6 +61,12 @@ export function TrendChart({ resource }: TrendChartProps) { const entries = useEventLogEntries(); const trend = computeAllocationTrend(entries, resource); + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render or the live Event Log subscription above. + useEffect(() => { + void trySyncWithBackend(); + }, []); + if (trend.status === "no-trend-yet") { return (
{ + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -41,6 +44,21 @@ describe("HealthPostScreen (QA happy path - full exam through the chat UI)", () }); }); +describe("HealthPostScreen backend sync wiring (plan todo 3, mount-time pull)", () => { + it("calls trySyncWithBackend() on mount, without blocking or altering the honest empty render", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(screen.getByTestId("healthpost-tally-empty")).toHaveTextContent("No symptom reports yet"); + }); +}); + describe("HealthPostScreen (QA failure path - zero symptom reports seeded)", () => { it("shows an honest 'no reports yet' tally state rather than a fabricated placeholder tally", async () => { render(); diff --git a/src/miniapps/healthpost/HealthPostScreen.tsx b/src/miniapps/healthpost/HealthPostScreen.tsx index c9037fd..1689b6e 100644 --- a/src/miniapps/healthpost/HealthPostScreen.tsx +++ b/src/miniapps/healthpost/HealthPostScreen.tsx @@ -1,9 +1,17 @@ +import { useEffect } from "react"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { ReferralQueue } from "./ReferralQueue.tsx"; import { SymptomTallyDashboard } from "./SymptomTallyDashboard.tsx"; import { TriageChat } from "./TriageChat.tsx"; import styles from "./HealthPostScreen.module.css"; export function HealthPostScreen() { + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render below. + useEffect(() => { + void trySyncWithBackend(); + }, []); + return (
diff --git a/src/miniapps/healthpost/healthpostEvents.test.ts b/src/miniapps/healthpost/healthpostEvents.test.ts index 91ccf5d..2582b55 100644 --- a/src/miniapps/healthpost/healthpostEvents.test.ts +++ b/src/miniapps/healthpost/healthpostEvents.test.ts @@ -1,9 +1,15 @@ -import { beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "../../lib/db.ts"; import { readAll } from "../../lib/eventlog.ts"; import { init } from "../../lib/identity.ts"; import type { TriageResult } from "../../lib/healthpost.ts"; -import { extractReferrals, postReferral, REFERRAL_PAYLOAD_TYPE } from "./healthpostEvents.ts"; +import { + extractReferrals, + postReferral, + postSymptomReport, + REFERRAL_PAYLOAD_TYPE, + SYMPTOM_REPORT_PAYLOAD_TYPE, +} from "./healthpostEvents.ts"; beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -12,6 +18,10 @@ beforeEach(async () => { await init(); }); +afterEach(() => { + vi.unstubAllGlobals(); +}); + const URGENT_RESULT: TriageResult = { ageMonths: 12, dangerSigns: ["lethargic or unconscious"], @@ -85,6 +95,50 @@ describe("extractReferrals (stale-state - cold-replayed log)", () => { }); }); +describe("postSymptomReport / postReferral backend sync wiring (plan todo 3)", () => { + it("observably calls trySyncWithBackend() after a symptom report, without altering the local-first write's own result", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + const stored = await postSymptomReport("fever"); + + expect(stored.payload).toEqual({ type: SYMPTOM_REPORT_PAYLOAD_TYPE, symptom: "fever" }); + expect(await readAll()).toHaveLength(1); + + // Fire-and-forget: give the un-awaited sync call's microtask a turn. + await Promise.resolve(); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + }); + + it("observably calls trySyncWithBackend() after a case relay (referral), without altering the local-first write's own result", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + const stored = await postReferral(URGENT_RESULT); + + expect(stored.payload).toMatchObject({ type: REFERRAL_PAYLOAD_TYPE, status: "open" }); + expect(await readAll()).toHaveLength(1); + + await Promise.resolve(); + await Promise.resolve(); + expect(fetchMock).toHaveBeenCalledTimes(1); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + }); + + it("never throws into the caller when the relay is unreachable - both writes still resolve normally", async () => { + vi.stubGlobal("fetch", vi.fn().mockRejectedValue(new Error("network down"))); + + await expect(postSymptomReport("cough")).resolves.toMatchObject({ + payload: { type: SYMPTOM_REPORT_PAYLOAD_TYPE, symptom: "cough" }, + }); + await expect(postReferral(URGENT_RESULT)).resolves.toMatchObject({ + payload: { type: REFERRAL_PAYLOAD_TYPE, status: "open" }, + }); + }); +}); + describe("extractReferrals (QA failure path - malformed/forged payloads never surface a silent referral)", () => { it("drops an entry whose payload is missing required referral fields", () => { const malformed = [ diff --git a/src/miniapps/healthpost/healthpostEvents.ts b/src/miniapps/healthpost/healthpostEvents.ts index 0030d25..3b7e5c3 100644 --- a/src/miniapps/healthpost/healthpostEvents.ts +++ b/src/miniapps/healthpost/healthpostEvents.ts @@ -2,6 +2,7 @@ import { append, type StoredEventLogEntry } from "../../lib/eventlog.ts"; import type { SymptomCategory, SymptomReport } from "../../lib/healthpostTally.ts"; import { ALL_SYMPTOM_CATEGORIES } from "../../lib/healthpostTally.ts"; import type { TriageResult, Urgency } from "../../lib/healthpost.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; /** * Event Log <-> Health Post tally adapter (plan todo 34). @@ -36,7 +37,11 @@ function isSymptomReportPayload(payload: unknown): payload is SymptomReportPaylo /** Signs and appends one real crowd self-report of `symptom` to the Event Log. */ export async function postSymptomReport(symptom: SymptomCategory): Promise { const payload: SymptomReportPayload = { type: SYMPTOM_REPORT_PAYLOAD_TYPE, symptom }; - return append(payload); + const entry = await append(payload); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write that just completed above. + void trySyncWithBackend(); + return entry; } /** @@ -128,7 +133,11 @@ export async function postReferral(triageResult: TriageResult): Promise { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -215,3 +218,33 @@ describe("FloorPlanScreen > Run assignment cycle", () => { }); }); }); + +describe("FloorPlanScreen backend sync wiring (plan todo 3)", () => { + it("calls trySyncWithBackend() on mount and again after an idle-space report submitted through the real form", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + + fireEvent.change(screen.getByTestId("housing-report-space-id"), { + target: { value: "sync-test-space" }, + }); + fireEvent.change(screen.getByTestId("housing-report-location"), { + target: { value: "Anywhere" }, + }); + fireEvent.submit(screen.getByRole("form", { name: "Report an idle space" })); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + // The local-first write still completed, unaffected by the relay being + // unreachable. + const entries = await readAll(); + expect(entries.some((entry) => isHousingSpaceReportPayload(entry.payload))).toBe(true); + }); +}); diff --git a/src/miniapps/housing/FloorPlanScreen.tsx b/src/miniapps/housing/FloorPlanScreen.tsx index 9c0d67c..d92e337 100644 --- a/src/miniapps/housing/FloorPlanScreen.tsx +++ b/src/miniapps/housing/FloorPlanScreen.tsx @@ -1,4 +1,4 @@ -import { useState, type FormEvent } from "react"; +import { useEffect, useState, type FormEvent } from "react"; import { readAll } from "../../lib/eventlog.ts"; import { discoverAvailableSlots, @@ -9,6 +9,7 @@ import { type HousingAssignment, type HousingPreference, } from "../../lib/housing.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { useActiveAccountId } from "../../shell/useActiveAccountId.ts"; import { useEventLogEntries } from "../../shell/useEventLogEntries.ts"; import styles from "./FloorPlanScreen.module.css"; @@ -197,6 +198,13 @@ function explainAssignment(view: ResidentCycleView): string { export function FloorPlanScreen() { const accountId = useActiveAccountId(); const entries = useEventLogEntries(); + + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render or the live Event Log subscription above. + useEffect(() => { + void trySyncWithBackend(); + }, []); + const cycles = extractHousingCycles(entries); const view = accountId === undefined ? undefined : findLatestResidentCycle(cycles, accountId); diff --git a/src/miniapps/sky/SkyScreen.test.tsx b/src/miniapps/sky/SkyScreen.test.tsx index bb306e1..43e8167 100644 --- a/src/miniapps/sky/SkyScreen.test.tsx +++ b/src/miniapps/sky/SkyScreen.test.tsx @@ -2,7 +2,7 @@ import "@testing-library/jest-dom/vitest"; import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import * as Y from "yjs"; import { Awareness } from "y-protocols/awareness"; import { db } from "../../lib/db.ts"; @@ -12,7 +12,10 @@ import { postMemoryWallEntry } from "../../lib/skyMemoryWall.ts"; import { postMoralePulse } from "../../lib/skyMorale.ts"; import { SkyScreen } from "./SkyScreen.tsx"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -174,3 +177,21 @@ describe("SkyScreen (QA happy path - real sky state, real presence, real memory expect(screen.getByTestId("sky-mood-latest")).toHaveTextContent("Latest pulse: Rough"); }); }); + +describe("SkyScreen backend sync wiring (plan todo 3, mount-time pull)", () => { + it("calls trySyncWithBackend() on mount, without touching useSkyPresence's own WebRTC/Yjs transport", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + const self = new Awareness(new Y.Doc()); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + // The honest "no presence" / "no memories yet" render is unaffected by + // the sync call - it still reflects the real (empty) local state. + expect(screen.getByTestId("sky-memory-empty")).toBeInTheDocument(); + }); +}); diff --git a/src/miniapps/sky/SkyScreen.tsx b/src/miniapps/sky/SkyScreen.tsx index 1f0f916..c344f20 100644 --- a/src/miniapps/sky/SkyScreen.tsx +++ b/src/miniapps/sky/SkyScreen.tsx @@ -10,6 +10,7 @@ import { type SkyMood, } from "../../lib/skyMorale.ts"; import type { PresenceAwareness } from "../../lib/skyPresence.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { useActiveAccountId } from "../../shell/useActiveAccountId.ts"; import { useEventLogEntries } from "../../shell/useEventLogEntries.ts"; import { useSkyPresence } from "./useSkyPresence.ts"; @@ -61,6 +62,15 @@ export function SkyScreen({ const accountId = useActiveAccountId(); const presenceCount = useSkyPresence({ residentId: accountId, awareness: presenceAwareness }); + // Best-effort cross-device sync on mount (plan todo 3) for the memory + // wall / morale pulse signed events below - deliberately NOT touching + // useSkyPresence.ts's own live WebRTC/Yjs Awareness transport above, + // which is a separate real-time channel this sync call must never + // double-wire. Fire-and-forget, never blocks the render. + useEffect(() => { + void trySyncWithBackend(); + }, []); + const entries = useEventLogEntries(); const memoryWall = useMemo(() => extractMemoryWallEntries(entries), [entries]); const moralePulses = useMemo(() => extractMoralePulses(entries), [entries]); diff --git a/src/miniapps/theclimb/TheClimbScreen.test.tsx b/src/miniapps/theclimb/TheClimbScreen.test.tsx index b230cfb..f9b2a91 100644 --- a/src/miniapps/theclimb/TheClimbScreen.test.tsx +++ b/src/miniapps/theclimb/TheClimbScreen.test.tsx @@ -1,11 +1,14 @@ // @vitest-environment happy-dom import "@testing-library/jest-dom/vitest"; -import { cleanup, render, screen } from "@testing-library/react"; +import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, describe, expect, it } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { TheClimbScreen } from "./TheClimbScreen.tsx"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); describe("TheClimbScreen (QA failure path - no schedule data entered)", () => { it("renders the honest no-schedule-yet empty state rather than a fabricated/placeholder schedule", () => { @@ -64,3 +67,18 @@ describe("TheClimbScreen (QA happy path - entered wave/shaft/capacity data produ expect(screen.getByTestId("theclimb-total-wait")).toHaveTextContent("5"); }); }); + +describe("TheClimbScreen backend sync wiring (plan todo 3, mount-time pull only - no write path exists)", () => { + it("calls trySyncWithBackend() on mount, without altering the honest no-schedule-yet render", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(screen.getByTestId("theclimb-no-schedule-yet")).toBeInTheDocument(); + }); +}); diff --git a/src/miniapps/theclimb/TheClimbScreen.tsx b/src/miniapps/theclimb/TheClimbScreen.tsx index 98cf58d..0b9216b 100644 --- a/src/miniapps/theclimb/TheClimbScreen.tsx +++ b/src/miniapps/theclimb/TheClimbScreen.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { computeWaveSchedule, type ScheduleInput, type ShaftEdge, type SurfaceCapacityPeriod, type WaveDemandGroup, type WaveSchedule } from "../../lib/theclimb.ts"; import { simulateCongestion, type CongestionTimeline } from "../../lib/theclimbCongestion.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { CongestionHeatmap } from "./CongestionHeatmap.tsx"; import { ScheduleInputForm } from "./ScheduleInputForm.tsx"; import { ScheduleTimeline } from "./ScheduleTimeline.tsx"; @@ -23,6 +24,14 @@ export function TheClimbScreen() { const [surfaceCapacity, setSurfaceCapacity] = useState([]); const [computation, setComputation] = useState({ status: "no-schedule-yet" }); + // The Climb has no resident-facing write path into the signed Event Log + // today (its schedule/congestion engine is pure local component state, + // never persisted) - so this is a mount-time pull only (plan todo 3), + // best-effort and fire-and-forget. + useEffect(() => { + void trySyncWithBackend(); + }, []); + useEffect(() => { if (shafts.length === 0 || demands.length === 0 || surfaceCapacity.length === 0) { setComputation({ status: "no-schedule-yet" }); diff --git a/src/miniapps/tunnelsafety/ReportHazardForm.tsx b/src/miniapps/tunnelsafety/ReportHazardForm.tsx index 6cda4d3..1554883 100644 --- a/src/miniapps/tunnelsafety/ReportHazardForm.tsx +++ b/src/miniapps/tunnelsafety/ReportHazardForm.tsx @@ -7,6 +7,7 @@ import { reportHazard, type HazardStatus, } from "../../lib/tunnelsafety.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { SEGMENT_LABELS, TUNNEL_GRAPH } from "./tunnelGraph.ts"; import styles from "./ReportHazardForm.module.css"; @@ -83,6 +84,9 @@ export function ReportHazardForm() { status, ...(accelSamples !== undefined ? { accelSamples } : {}), }); + // Best-effort cross-device sync (plan todo 3): fire-and-forget, never + // blocks or affects the local-first write that just completed above. + void trySyncWithBackend(); setSubmitStatus("submitted"); } catch (error) { setSubmitStatus("error"); diff --git a/src/miniapps/tunnelsafety/TunnelSafetyScreen.test.tsx b/src/miniapps/tunnelsafety/TunnelSafetyScreen.test.tsx index 67b016e..19bcd20 100644 --- a/src/miniapps/tunnelsafety/TunnelSafetyScreen.test.tsx +++ b/src/miniapps/tunnelsafety/TunnelSafetyScreen.test.tsx @@ -2,13 +2,16 @@ import "@testing-library/jest-dom/vitest"; import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "../../lib/db.ts"; import { init } from "../../lib/identity.ts"; import { reportHazard } from "../../lib/tunnelsafety.ts"; import { TunnelSafetyScreen } from "./TunnelSafetyScreen.tsx"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -174,3 +177,31 @@ describe("TunnelSafetyScreen (QA failure path - no hazards reported)", () => { ); }); }); + +describe("TunnelSafetyScreen backend sync wiring (plan todo 3)", () => { + it("calls trySyncWithBackend() on mount and again after a hazard report submitted through the real form", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + + await userEvent.selectOptions(screen.getByTestId("tunnel-safety-report-segment"), "seg-south-commons"); + await userEvent.click(screen.getByTestId("tunnel-safety-report-submit")); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + // The local-first report still completed and rendered, unaffected by + // the relay being unreachable. + await waitFor(() => { + expect(screen.getByTestId("tunnel-safety-report-status-text")).toHaveTextContent( + "Hazard reported.", + ); + }); + }); +}); diff --git a/src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx b/src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx index d592a35..0336d40 100644 --- a/src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx +++ b/src/miniapps/tunnelsafety/TunnelSafetyScreen.tsx @@ -1,7 +1,8 @@ -import { useState } from "react"; +import { useEffect, useState } from "react"; import { computeHazardReports } from "../../lib/tunnelsafety.ts"; import type { AccelerometerSample } from "../../lib/tunnelrouting.ts"; import { closedSegmentIdsFromReports, findRoute } from "../../lib/tunnelrouting.ts"; +import { trySyncWithBackend } from "../../lib/sync.ts"; import { useEventLogEntries } from "../../shell/useEventLogEntries.ts"; import { HazardFeed } from "./HazardFeed.tsx"; import { ReportHazardForm } from "./ReportHazardForm.tsx"; @@ -23,6 +24,12 @@ export function TunnelSafetyScreen() { const [end, setEnd] = useState(DEFAULT_END_NODE); const [accessibleOnly, setAccessibleOnly] = useState(false); + // Best-effort cross-device sync on mount (plan todo 3): fire-and-forget, + // never blocks the render or the live Event Log subscription above. + useEffect(() => { + void trySyncWithBackend(); + }, []); + const reports = computeHazardReports(entries); const closedSegmentIds = closedSegmentIdsFromReports(reports); diff --git a/src/shell/TransactionHistory.test.tsx b/src/shell/TransactionHistory.test.tsx index ecf0a49..6c9b967 100644 --- a/src/shell/TransactionHistory.test.tsx +++ b/src/shell/TransactionHistory.test.tsx @@ -2,7 +2,7 @@ import "@testing-library/jest-dom/vitest"; import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "../lib/db"; import { append } from "../lib/eventlog"; import { getPublicKey, init } from "../lib/identity"; @@ -10,7 +10,10 @@ import { toAccountId } from "./accountId"; import { TransactionHistory } from "./TransactionHistory"; import { walletHistoryFor } from "./walletHistory"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -68,3 +71,18 @@ describe("TransactionHistory signature verification", () => { expect(screen.getByText("No transactions yet")).toBeInTheDocument(); }); }); + +describe("TransactionHistory backend sync wiring (plan todo 3, mount-time pull - no transfer UI exists)", () => { + it("calls trySyncWithBackend() on mount, without altering the empty-state render", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(screen.getByText("No transactions yet")).toBeInTheDocument(); + }); +}); diff --git a/src/shell/TransactionHistory.tsx b/src/shell/TransactionHistory.tsx index 6c70761..060737b 100644 --- a/src/shell/TransactionHistory.tsx +++ b/src/shell/TransactionHistory.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { verifyEntrySignature } from "../lib/eventlog"; +import { trySyncWithBackend } from "../lib/sync"; import styles from "./TransactionHistory.module.css"; import type { WalletHistoryEntry } from "./walletHistory"; @@ -56,6 +57,14 @@ export function TransactionHistory({ entries }: TransactionHistoryProps) { const verification = useSignatureVerification(entries); const [expandedId, setExpandedId] = useState(undefined); + // No dedicated send/transfer UI exists in this codebase today (plan todo + // 3) - this is a mount-time pull only, so a resident's history reflects + // peer-synced wallet.issue/wallet.transfer events without needing a + // local write to trigger it. Best-effort, fire-and-forget. + useEffect(() => { + void trySyncWithBackend(); + }, []); + if (entries.length === 0) { return

No transactions yet

; } diff --git a/src/shell/WalletCard.test.tsx b/src/shell/WalletCard.test.tsx index 68ff10e..f3e5e6e 100644 --- a/src/shell/WalletCard.test.tsx +++ b/src/shell/WalletCard.test.tsx @@ -1,14 +1,17 @@ // @vitest-environment happy-dom import "@testing-library/jest-dom/vitest"; import { cleanup, render, screen, waitFor } from "@testing-library/react"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { db } from "../lib/db"; import { append } from "../lib/eventlog"; import { getPublicKey, init } from "../lib/identity"; import { toAccountId } from "./accountId"; import { WalletCard } from "./WalletCard"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); beforeEach(async () => { indexedDB.deleteDatabase(db.name); @@ -82,3 +85,24 @@ describe("WalletCard (failure path - no ledger balance yet)", () => { expect(screen.getByTestId("wallet-balance")).not.toHaveTextContent("No balance yet"); }); }); + +describe("WalletCard backend sync wiring (plan todo 3, mount-time pull - no transfer UI exists)", () => { + it("calls trySyncWithBackend() on mount, without altering the honest 'no balance yet' render", async () => { + const fetchMock = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")); + vi.stubGlobal("fetch", fetchMock); + await init(); + + // WalletCard's non-compact render also mounts TransactionHistory, + // which wires its own mount-time sync call below - so both fire. + render(); + + await waitFor(() => { + expect(fetchMock).toHaveBeenCalledTimes(2); + }); + expect(fetchMock.mock.calls[0][0]).toBe("/api/sync"); + expect(fetchMock.mock.calls[1][0]).toBe("/api/sync"); + await waitFor(() => { + expect(screen.getByTestId("wallet-balance")).toHaveTextContent("No balance yet"); + }); + }); +}); diff --git a/src/shell/WalletCard.tsx b/src/shell/WalletCard.tsx index e273b74..4f0ee85 100644 --- a/src/shell/WalletCard.tsx +++ b/src/shell/WalletCard.tsx @@ -1,4 +1,6 @@ +import { useEffect } from "react"; import { balanceOf, computeBalances } from "../lib/ledger"; +import { trySyncWithBackend } from "../lib/sync"; import { Icon } from "./icons"; import { TransactionHistory } from "./TransactionHistory"; import { useActiveAccountId } from "./useActiveAccountId"; @@ -19,6 +21,14 @@ export function WalletCard({ compact = false }: WalletCardProps = {}) { const accountId = useActiveAccountId(); const entries = useEventLogEntries(); + // No dedicated send/transfer UI exists in this codebase today (plan todo + // 3) - this is a mount-time pull only, so a resident's balance/history + // reflects peer-synced wallet.issue/wallet.transfer events without + // needing a local write to trigger it. Best-effort, fire-and-forget. + useEffect(() => { + void trySyncWithBackend(); + }, []); + // A brand-new identity that has never appeared in a `wallet.issue` or // `wallet.transfer` event has no entry in the ledger's `balances` map // at all - reported honestly as "no balance yet" below, never a