Files
buzz/desktop/src/shared/lib/localStorageQuota.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

242 lines
8.3 KiB
JavaScript

import assert from "node:assert/strict";
import test from "node:test";
import {
recoverLocalStorageQuotaOnStartup,
setLocalStorageItemWithRecovery,
} from "./localStorageQuota.ts";
function makeQuotaLocalStorage({ maxEntries }) {
const store = new Map();
return {
store,
get length() {
return store.size;
},
key: (i) => [...store.keys()][i] ?? null,
getItem: (key) => store.get(key) ?? null,
setItem(key, value) {
if (!store.has(key) && store.size >= maxEntries) {
throw new Error("QuotaExceededError");
}
store.set(key, value);
},
removeItem: (key) => store.delete(key),
};
}
function install(ls) {
if (typeof globalThis.window === "undefined") {
globalThis.window = {};
}
globalThis.window.localStorage = ls;
globalThis.localStorage = ls;
}
test("startup recovery removes disposable caches but preserves user state", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 6 });
install(ls);
ls.store.set("buzz-channel-messages.v1:relay:chan", "big");
ls.store.set("buzz-channels.v1:relay", "big");
ls.store.set("buzz-timeline-skeleton-shape.v1:chan", "small");
ls.store.set("buzz-sidebar-skeleton-shape.v1:community:user", "small");
ls.store.set("buzz-user-labels.v1:relay", "small");
ls.store.set("buzz-communities", "keep");
recoverLocalStorageQuotaOnStartup();
assert.equal(ls.getItem("buzz-channel-messages.v1:relay:chan"), null);
assert.equal(ls.getItem("buzz-channels.v1:relay"), null);
assert.equal(ls.getItem("buzz-timeline-skeleton-shape.v1:chan"), null);
assert.equal(
ls.getItem("buzz-sidebar-skeleton-shape.v1:community:user"),
null,
);
assert.equal(ls.getItem("buzz-user-labels.v1:relay"), null);
assert.equal(ls.getItem("buzz-communities"), "keep");
assert.equal(ls.getItem("buzz-local-storage-quota-recovery.v1"), "1");
});
test("healthy startup preserves disposable caches", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 10 });
install(ls);
ls.store.set("buzz-channel-messages.v1:relay:new", "snapshot");
recoverLocalStorageQuotaOnStartup();
assert.equal(ls.getItem("buzz-channel-messages.v1:relay:new"), "snapshot");
assert.equal(ls.getItem("buzz-local-storage-quota-recovery.v1"), "1");
});
test("startup recovery does not remove namespace near misses", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 2 });
install(ls);
ls.store.set("buzz-channels.v10:durable", "keep");
ls.store.set("buzz-channel-messages.v1-durable", "keep");
recoverLocalStorageQuotaOnStartup();
assert.equal(ls.getItem("buzz-channels.v10:durable"), "keep");
assert.equal(ls.getItem("buzz-channel-messages.v1-durable"), "keep");
assert.equal(ls.getItem("buzz-local-storage-quota-recovery.v1"), null);
});
test("startup recovery runs only once", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 10 });
install(ls);
recoverLocalStorageQuotaOnStartup();
ls.store.set("buzz-channel-messages.v1:relay:new", "new snapshot");
recoverLocalStorageQuotaOnStartup();
assert.equal(
ls.getItem("buzz-channel-messages.v1:relay:new"),
"new snapshot",
);
});
test("startup recovery retries after marker write fails", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 1 });
install(ls);
ls.store.set("buzz-communities", "keep");
recoverLocalStorageQuotaOnStartup();
assert.equal(ls.getItem("buzz-local-storage-quota-recovery.v1"), null);
ls.store.delete("buzz-communities");
ls.store.set("buzz-channel-messages.v1:relay:chan", "big");
recoverLocalStorageQuotaOnStartup();
assert.equal(ls.getItem("buzz-channel-messages.v1:relay:chan"), null);
assert.equal(ls.getItem("buzz-local-storage-quota-recovery.v1"), "1");
});
test("global cache byte budget evicts only oldest entries needed", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 20 });
install(ls);
ls.store.set("buzz-communities", "keep");
const snapshot = (updatedAt) =>
JSON.stringify({ updatedAt, payload: "x".repeat(400_000) });
const oldestKey = "buzz-channel-messages.v1:relay:oldest";
const newerKey = "buzz-channels.v1:relay-newer";
const newestKey = "buzz-channel-messages.v1:relay:newest";
assert.equal(setLocalStorageItemWithRecovery(oldestKey, snapshot(1)), true);
assert.equal(setLocalStorageItemWithRecovery(newerKey, snapshot(2)), true);
assert.equal(setLocalStorageItemWithRecovery(newestKey, snapshot(3)), true);
assert.equal(ls.getItem(oldestKey), null);
assert.notEqual(ls.getItem(newerKey), null);
assert.notEqual(ls.getItem(newestKey), null);
assert.equal(ls.getItem("buzz-communities"), "keep");
});
test("global cache byte budget spans relays and preserves durable state", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 20 });
install(ls);
ls.store.set("buzz-communities", "keep");
const largeSnapshot = "x".repeat(600_000);
assert.equal(
setLocalStorageItemWithRecovery(
"buzz-channel-messages.v1:relay-one:chan",
largeSnapshot,
),
true,
);
assert.equal(
setLocalStorageItemWithRecovery(
"buzz-channel-messages.v1:relay-two:chan",
largeSnapshot,
),
true,
);
assert.equal(ls.getItem("buzz-channel-messages.v1:relay-one:chan"), null);
assert.equal(
ls.getItem("buzz-channel-messages.v1:relay-two:chan"),
largeSnapshot,
);
assert.equal(ls.getItem("buzz-communities"), "keep");
});
test("rejects a single cache entry larger than the global byte budget", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 10 });
install(ls);
const key = "buzz-channel-messages.v1:relay:oversized";
ls.store.set(key, "previous snapshot");
assert.equal(
setLocalStorageItemWithRecovery(key, "x".repeat(1_100_000)),
false,
);
assert.equal(ls.getItem(key), null);
});
test("writes normally when under quota", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 10 });
install(ls);
assert.equal(setLocalStorageItemWithRecovery("k", "v"), true);
assert.equal(ls.getItem("k"), "v");
});
test("evicts pure caches and retries on quota failure", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 2 });
install(ls);
ls.store.set("buzz-channel-messages.v1:relay:chan", "big");
ls.store.set("buzz-channels.v1:relay", "big");
assert.equal(setLocalStorageItemWithRecovery("k", "v"), true);
assert.equal(ls.getItem("k"), "v");
assert.equal(ls.getItem("buzz-channel-messages.v1:relay:chan"), null);
assert.equal(ls.getItem("buzz-channels.v1:relay"), null);
});
test("returns false when eviction frees nothing", () => {
const ls = makeQuotaLocalStorage({ maxEntries: 2 });
install(ls);
ls.store.set("buzz-workspaces", "keep");
ls.store.set("buzz-active-workspace-id", "keep");
assert.equal(setLocalStorageItemWithRecovery("k", "v"), false);
assert.equal(ls.getItem("k"), null);
assert.equal(ls.getItem("buzz-workspaces"), "keep");
});
test("buzz-observed-unread.v1: prefix participates in LRU eviction and durable state survives", () => {
// Sentinel: fails if buzz-observed-unread.v1: is removed from PURE_CACHE_KEY_PREFIXES —
// the bucket becomes invisible to LRU and the wrong entry is evicted instead.
const ls = makeQuotaLocalStorage({ maxEntries: 20 });
install(ls);
ls.store.set("buzz-communities", "keep");
const snapshot = (updatedAt) =>
JSON.stringify({ updatedAt, payload: "x".repeat(400_000) });
const observedKey = "buzz-observed-unread.v1:wss://relay.example.com:pk1";
const olderKey = "buzz-channel-messages.v1:relay:older";
const newestKey = "buzz-channel-messages.v1:relay:newest";
// Seed observed-unread (oldest updatedAt=1) and a sibling channel-messages entry (updatedAt=2).
assert.equal(setLocalStorageItemWithRecovery(observedKey, snapshot(1)), true);
assert.equal(setLocalStorageItemWithRecovery(olderKey, snapshot(2)), true);
// Writing a third pure-cache entry (updatedAt=3) pushes the total above the 2 MiB budget.
// The observed-unread entry must be evicted first (oldest LRU); the sibling survives.
assert.equal(setLocalStorageItemWithRecovery(newestKey, snapshot(3)), true);
assert.equal(
ls.getItem(observedKey),
null,
"observed-unread bucket must be evicted as the oldest LRU pure-cache entry",
);
assert.notEqual(
ls.getItem(olderKey),
null,
"channel-messages bucket with newer updatedAt must survive",
);
assert.equal(
ls.getItem("buzz-communities"),
"keep",
"durable state must survive",
);
});