Files
buzz/desktop/src/features/channels/useUnreadChannels.test.mjs
Will Pfleger 0afeac8a7c feat(desktop): persist sidebar observed-unread across webview reload (#3976)
## Problem

`Command+R` (webview reload) wipes the two in-memory refs driving
sidebar channel unread badges: `observedUnreadEventsByChannelRef` and
`latestByChannelRef`. The boot catch-up REQ can only fetch events newer
than each channel's NIP-RS frontier, so thread replies that arrived
before the frontier was passively advanced (the common case) are never
re-discovered.

Inbox is unaffected because it rebuilds candidates from a relay feed
query and checks fine-grained `thread:`/`msg:` markers. The sidebar
badge path lacks an equivalent recovery mechanism.

## Solution

Persist the sidebar's per-event candidate set to localStorage as a
disposable, versioned projection cache
(`buzz-observed-unread.v1:<relay>:<pubkey>`) and hydrate it on boot
before the catch-up REQ runs.

### New files

**`observedUnreadStorage.ts`** — storage module for the cache:
- Keyed
`buzz-observed-unread.v1:<normalizedRelayUrl>:<normalizedPubkey>`
(relay-scoped to prevent cross-community leakage, matching
`threadActivityStorage`)
- Stores validated per-event `ObservedUnreadEvent` rows;
`latestByChannel` is derived at hydration — no divergent dual aggregate
- Age pruning (7d = `READ_STATE_HORIZON_SECONDS`), per-channel cap
(1000), global cap (5000) across all channels in a scope bucket
- Payload `updatedAt` for LRU ordering; registered in
`PURE_CACHE_KEY_PREFIXES` for 2 MiB eviction budget
- Field-level validation on decode; write failure is non-fatal
(session-only degradation)
- Snapshot-owning timers: `scheduleObservedUnreadWrite` deep-clones the
events map at schedule time — a late A-scope timer can never read B's
mutable refs or write under B's key

**`useObservedUnreadPersistence.ts`** — hook that owns all persistence
lifecycle:
- Scope fence: `normalized pubkey + normalized relay` identity;
`isScopeLoaded()` callback guards both projection (`rawUnread`) and
every **observed-cache mutation** (`recordUnreadEvent`, `removeChannel`,
`clearAll`) before touching refs or storage. Note: stale-scope calls to
`markChannelRead`/`markAllChannelsRead` can still affect
`forcedUnreadRef` and NIP-RS markers, which are pre-existing on `main`
and deferred to the NIP-RS arc (see Deferred below).
- Synchronous `pagehide` flush closes the Cmd+R timing gap
(`useReloadShortcut.ts` reloads within 500ms of teardown, before the
1-second debounce fires)
- Identity-reset effect: flushes old scope, resets refs, hydrates from
storage, stamps loaded scope — all atomic; cleanup flushes on unmount
- `clearAll` cancels the pending timer, resets both in-memory refs, and
clears storage in a single transactional operation; `removeChannel`
deletes the channel from both refs and replaces any pending snapshot
with the current full map — never cancel-without-replacement, preserving
sibling-channel events on reload
- Marker-prune effect on `readStateVersion`: evaluates each retained
event with `observedUnreadEventReadAt()` (the same evaluator used by the
projection memo) and removes covered events, rederiving per-channel
latest — never clears a whole channel for a single thread/msg marker
- Returns a stable `useMemo`-wrapped API object keyed on actual deps so
unrelated re-renders do not restart the catch-up REQ
- `isScopeLoaded` is a `useCallback` (not a memoized boolean) — always
reads the ref at call time, never stale

### Modified files

**`useUnreadChannels.ts`** — hook integration:
- Calls `useObservedUnreadPersistence` with all persistence wired
through the returned API
- `rawUnread`: `isScopeLoaded()` guard suppresses A-scope refs from
projecting under B
- `recordUnreadEvent`: `isScopeLoaded()` fence before touching refs;
schedules a debounced write on each successful record
- `markChannelRead` clearObserved path: calls `removeChannel` so the
cleared state survives reload
- `markAllChannelsRead`: delegates to the owner's fenced `clearAll` —
the parent does not reset the observed refs directly; `clearAll` owns
the transactional clear of both refs and storage, preventing a stale
scope-A callback from corrupting scope B

**`localStorageQuota.ts`** — registers `buzz-observed-unread.v1:` in
`PURE_CACHE_KEY_PREFIXES`

## Design constraints

The cache is a **disposable projection**: versioned key, read-through
only, safe to delete wholesale. It does not touch `ReadStateManager`,
marker semantics, or `forcedUnreadStore`. Zero overlap with the NIP-RS
manual mark-read/unread protocol work in progress in another channel;
migration path when that lands is "stop reading the key."

## Test coverage

**`observedUnreadStorage.test.mjs`** covers storage primitives:
- Key normalization, relay-scoped isolation, round-trip correctness
- Age-prune and per-channel cap on read and write; global cap across
channels
- `deriveLatestByChannel` correctness
- Thread-marker prune leaves sibling thread events persisted and lit
- Scope-isolation state machine: A rows visible in A, absent in B,
restored on A again; late A-scope write does not overwrite B's bucket
- Malformed structures/fields, relay/pubkey isolation, quota failure
degradation

**`useObservedUnreadPersistence.test.mjs`** exercises the real hook via
`createRoot` + `act`:
- pagehide flush: event recorded within debounce window survives reload
(headline regression)
- Unmount with pending write flushes before teardown
- `clearAll` cancels pending debounce so no resurrection after reload
- `removeChannel` replaces pending snapshot so sibling channel B
survives reload (two-channel repro)
- Marker prune: thread and channel markers prune covered events; sibling
channels survive
- `isScopeLoaded` returns false before identity-reset effect commits,
true after
- A→B scope switch: pending A-timer is cancelled by flush, A data
persisted synchronously (hydration round-trip)
- Stale `clearAll` from scope A rejects after scope B loads
(observed-cache scope fence)
- Stale `removeChannel` from scope A rejects after scope B loads
(observed-cache scope fence)
- API object identity stable across unrelated re-renders (catch-up
stability)

**`useUnreadChannels.test.mjs`** exercises the full parent-to-owner seam
with real hook mounts:
- Stale `markChannelRead` from scope A does not corrupt B's observed
bucket after flush
- Stale `markAllChannelsRead` from scope A does not overwrite B's bucket
after flush

## Deferred

Issues deferred to the NIP-RS arc (`#unread-messages-ux`) or future
hardening — not regressions introduced by this PR:

- **Stale-scope `forcedUnreadRef` / `markContextRead` exposure**: a
stale scope-A `markChannelRead` or `markAllChannelsRead` still deletes
B's `forcedUnreadRef` entries and advances B's NIP-RS markers via
`markContextRead` before the observed-cache fence rejects. This is
pre-existing on `origin/main` (identical shape at lines 316/330). Fix
requires touching `forcedUnreadStore` and marker paths — out of scope
for Fix A. Deferred to the NIP-RS work.
- **`isScopeLoaded` empty-scope hardening**: `isScopeLoaded()` returns
`true` when `pubkey` and `relay` are empty strings (no active session).
A guard could assert non-empty identity before stamping scope-loaded.
Low risk in practice since the hook is only mounted after auth, but
could be tightened.
- **Catch-up batch scheduling**: `handleChannelMessage` and the catch-up
loop each clone the full events map per event via
`scheduleObservedUnreadWrite`. For channels with large backlogs this
produces O(n) snapshot clones per catch-up batch. A batch-schedule API
(single snapshot at end of batch) would reduce allocations. Not
observable in normal use; deferred as a performance optimization.

---------

Signed-off-by: Will Pfleger <pfleger.will@gmail.com>
Signed-off-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
2026-08-04 12:44:24 -04:00

176 lines
6.1 KiB
JavaScript

/**
* Boundary tests for useUnreadChannels — exercises the real parent-to-owner
* boundary between useUnreadChannels and useObservedUnreadPersistence.
*
* These tests mount the FULL production hook (via createRoot + act) to verify
* that markChannelRead and markAllChannelsRead are scope-safe: a stale callback
* captured under scope A cannot corrupt scope B's refs or storage after a
* scope switch. Coverage for both happy paths (current scope mutates correctly)
* and stale paths (scope-A callback rejects after B loads) is included.
*/
import assert from "node:assert/strict";
import test from "node:test";
import {
installDOMShim,
installFreshStorage,
seedStorage,
mountUnreadChannels,
} from "./observedUnreadTestHarness.mjs";
// DOM shim must run before any React import (harness imports React at parse time).
installDOMShim();
installFreshStorage();
import { readObservedUnreadFromStorage } from "./observedUnreadStorage.ts";
import { act } from "react";
// ── Helpers ───────────────────────────────────────────────────────────────────
const RELAY = "wss://relay.example.com";
// ── Tests ─────────────────────────────────────────────────────────────────────
test("markChannelRead happy path: current scope removes channel from observed refs and persists snapshot", async () => {
installFreshStorage();
const PUBKEY = "pubkey-happy-mcr";
const readAt = seedStorage(PUBKEY, RELAY, "channel-1");
const harness = await mountUnreadChannels({ pubkey: PUBKEY });
// markChannelRead with readAt >= observed latest triggers clearObserved,
// which delegates to observedPersistence.removeChannel. act() needed because
// markChannelRead calls bumpLatestVersion (useReducer).
await act(async () => {
harness.markChannelRead("channel-1", readAt);
});
harness.flushStorage();
const stored = readObservedUnreadFromStorage(PUBKEY, RELAY);
assert.ok(
stored === null || !stored.has("channel-1"),
"channel-1 must be absent from storage after markChannelRead under current scope",
);
await harness.unmount();
});
test("markChannelRead happy path: topLevelOnly=true leaves observed refs intact (no clearObserved)", async () => {
installFreshStorage();
const PUBKEY = "pubkey-happy-mcr-tlo";
const readAt = seedStorage(PUBKEY, RELAY, "channel-tlo");
const harness = await mountUnreadChannels({ pubkey: PUBKEY });
// topLevelOnly=true passes observedLatest as undefined, so clearObserved stays false.
await act(async () => {
harness.markChannelRead("channel-tlo", readAt, { topLevelOnly: true });
});
harness.flushStorage();
const stored = readObservedUnreadFromStorage(PUBKEY, RELAY);
assert.ok(
stored?.has("channel-tlo"),
"channel-tlo must remain in storage when topLevelOnly=true",
);
await harness.unmount();
});
test("markChannelRead stale: scope-A callback rejects after scope B loads — B storage survives flush", async () => {
installFreshStorage();
const PUBKEY_A = "pubkey-a-mcr";
const PUBKEY_B = "pubkey-b-mcr";
// Shared channel ensures stale A callback targets a channel present in B's hydrated refs.
const SHARED_CHANNEL = "channel-shared";
const readAtA = seedStorage(PUBKEY_A, RELAY, SHARED_CHANNEL, "evt-a");
seedStorage(PUBKEY_B, RELAY, SHARED_CHANNEL, "evt-b");
const harness = await mountUnreadChannels({ pubkey: PUBKEY_A });
const staleMarkChannelRead = harness.markChannelRead;
// Switch to B; hydration flushes A and loads B's storage.
await harness.render(PUBKEY_B);
assert.ok(
readObservedUnreadFromStorage(PUBKEY_B, RELAY)?.has(SHARED_CHANNEL),
"B's channel-shared must be present before the stale call",
);
// Stale A call must be rejected by the scope fence; B's refs stay intact.
await act(async () => {
staleMarkChannelRead(SHARED_CHANNEL, readAtA);
});
harness.flushStorage();
const storedBAfter = readObservedUnreadFromStorage(PUBKEY_B, RELAY);
assert.ok(
storedBAfter?.has(SHARED_CHANNEL),
"B's channel-shared must survive the post-stale-call flush (stale scope-A markChannelRead must not corrupt B's refs)",
);
await harness.unmount();
});
test("markAllChannelsRead happy path: current scope clears all observed refs and clears storage bucket", async () => {
installFreshStorage();
const PUBKEY = "pubkey-happy-mar";
seedStorage(PUBKEY, RELAY, "channel-1");
const harness = await mountUnreadChannels({ pubkey: PUBKEY });
// clearAll cancels any pending write and removes the storage bucket.
await act(async () => {
harness.markAllChannelsRead();
});
const stored = readObservedUnreadFromStorage(PUBKEY, RELAY);
assert.ok(
stored === null || stored.size === 0,
"storage bucket must be empty after markAllChannelsRead under current scope",
);
await harness.unmount();
});
test("markAllChannelsRead stale: scope-A callback rejects after scope B loads — B storage survives flush", async () => {
installFreshStorage();
const PUBKEY_A = "pubkey-a-mar";
const PUBKEY_B = "pubkey-b-mar";
seedStorage(PUBKEY_A, RELAY, "channel-1");
seedStorage(PUBKEY_B, RELAY, "channel-2");
const harness = await mountUnreadChannels({ pubkey: PUBKEY_A });
const staleMarkAllChannelsRead = harness.markAllChannelsRead;
// Switch to B; hydration flushes A and loads B's storage (channel-2).
await harness.render(PUBKEY_B);
assert.ok(
readObservedUnreadFromStorage(PUBKEY_B, RELAY)?.has("channel-2"),
"B's channel-2 must be present before the stale call",
);
// Stale A call must be rejected by the scope fence; B's refs stay intact.
await act(async () => {
staleMarkAllChannelsRead();
});
harness.flushStorage();
const storedBAfter = readObservedUnreadFromStorage(PUBKEY_B, RELAY);
assert.ok(
storedBAfter?.has("channel-2"),
"B's channel-2 must survive the post-stale-call flush (stale scope-A markAllChannelsRead must not wipe B's refs)",
);
await harness.unmount();
});