feat(sync): wire HIGH-tier multiplayer mini-apps to the backend relay

This commit is contained in:
OmO Orchestrator committed 2026-11-18 23:57:04 -05:00
1 parent 7f03fd2911
commit 387fa66c6a
29 files changed
+700 -30

No files matched your search

@@ -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.
+40 -1
View File
@@ -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<void> {
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 });
+6 -1
View File
@@ -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(
+6 -1
View File
@@ -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;
}
/**
+32 -1
View File
@@ -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" },
});
});
});
+6 -1
View File
@@ -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;
}
+31 -1
View File
@@ -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" },
});
});
});
+6 -1
View File
@@ -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;
}
+44 -1
View File
@@ -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(<RevealDraw participants={PARTICIPANTS} />);
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);
});
});
+17 -1
View File
@@ -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<Phase>({ 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,
+8
View File
@@ -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;
+8
View File
@@ -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 (
<div
@@ -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 { HealthPostScreen } from "./HealthPostScreen.tsx";
import { TRIAGE_DISCLAIMER_TEXT } from "./TriageChat.tsx";
afterEach(cleanup);
afterEach(() => {
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(<HealthPostScreen />);
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(<HealthPostScreen />);
@@ -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 (
<section className={styles.screen} aria-label="Health Post">
<SymptomTallyDashboard />
@@ -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 = [
+11 -2
View File
@@ -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<StoredEventLogEntry> {
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<StoredEv
overallUrgency: triageResult.overallUrgency,
status: "open",
};
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;
}
/**
+35 -2
View File
@@ -1,7 +1,7 @@
// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, 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 { readAll } from "../../lib/eventlog";
import { getPublicKey, init } from "../../lib/identity";
@@ -13,7 +13,10 @@ import {
import { toAccountId } from "../../shell/accountId";
import { FloorPlanScreen } from "./FloorPlanScreen";
afterEach(cleanup);
afterEach(() => {
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(<FloorPlanScreen />);
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);
});
});
+9 -1
View File
@@ -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);
+23 -2
View File
@@ -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(<SkyScreen presenceAwareness={self} />);
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();
});
});
+10
View File
@@ -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]);
+21 -3
View File
@@ -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(<TheClimbScreen />);
await waitFor(() => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});
expect(fetchMock.mock.calls[0][0]).toBe("/api/sync");
expect(screen.getByTestId("theclimb-no-schedule-yet")).toBeInTheDocument();
});
});
+9
View File
@@ -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<SurfaceCapacityPeriod[]>([]);
const [computation, setComputation] = useState<Computation>({ 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" });
@@ -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");
@@ -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(<TunnelSafetyScreen />);
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.",
);
});
});
});
@@ -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);
+20 -2
View File
@@ -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(<TransactionHistory entries={[]} />);
await waitFor(() => {
expect(fetchMock).toHaveBeenCalledTimes(1);
});
expect(fetchMock.mock.calls[0][0]).toBe("/api/sync");
expect(screen.getByText("No transactions yet")).toBeInTheDocument();
});
});
+9
View File
@@ -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<number | undefined>(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 <p className={styles.empty}>No transactions yet</p>;
}
+26 -2
View File
@@ -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(<WalletCard />);
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");
});
});
});
+10
View File
@@ -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