diff --git a/desktop/src/features/channels/forcedUnreadStore.ts b/desktop/src/features/channels/forcedUnreadStore.ts index 3c50d0e94d..2bdc5da653 100644 --- a/desktop/src/features/channels/forcedUnreadStore.ts +++ b/desktop/src/features/channels/forcedUnreadStore.ts @@ -24,53 +24,6 @@ /** channelId → NIP-RS read marker (unix seconds) at force-time, or null */ export type ForcedUnreadMap = Record; -// --------------------------------------------------------------------------- -// NIP-RS override mark-result types (shared with useUnreadChannels) -// --------------------------------------------------------------------------- - -/** - * Result returned by ReadStateManager.markChannelOverrideUnread / - * markChannelOverrideRead (slice 2). `success: false` carries a reason code - * that is mapped to a user-visible toast by overrideErrorMessage below. - */ -export type MarkOverrideResult = - | { success: true } - | { - success: false; - reason: - | "uint32_overflow" - | "budget_exhausted" - | "load_incomplete" - | "already_inactive"; - }; - -/** Override liveness for one channel — returned by getOverrideLiveness. */ -export type OverrideLiveness = { active: boolean; frontier: number }; - -/** - * User-visible error message for a failed NIP-RS override operation. - * Returns null for silent failure reasons (already_inactive race condition). - */ -export function overrideErrorMessage( - op: "unread" | "read", - reason: string, -): string | null { - if (reason === "budget_exhausted") - return "Could not mark unread: override budget exhausted. Clear some channels first."; - if (reason === "uint32_overflow") - return op === "unread" - ? "Could not mark unread: counter limit reached for this channel." - : "Could not clear unread override: counter limit reached."; - if (reason === "load_incomplete") - return op === "unread" - ? "Could not mark unread: read state is still loading. Try again shortly." - : "Could not clear unread override: read state is still loading."; - if (reason === "already_inactive") return null; - return op === "unread" - ? "Could not mark unread." - : "Could not clear unread override."; -} - const STORAGE_PREFIX = "buzz-forced-unread.v1"; const storageKey = (pubkey: string) => `${STORAGE_PREFIX}:${pubkey}`; diff --git a/desktop/src/features/channels/nip-rs-unread-ui.test.mjs b/desktop/src/features/channels/nip-rs-unread-ui.test.mjs index f9938f11b6..4770663532 100644 --- a/desktop/src/features/channels/nip-rs-unread-ui.test.mjs +++ b/desktop/src/features/channels/nip-rs-unread-ui.test.mjs @@ -1,25 +1,32 @@ /** * NIP-RS manual-unread UI layer tests (slice 3). * - * Tests cover the behavioral requirements of the mark-unread/mark-read wiring: - * 1. mark-unread calls the manager's NIP-RS override publish path and blocks - * the local cache update when the manager refuses. - * 2. mark-read calls the manager's override-clear path when an override is - * active, and succeeds only when override_active becomes false. - * 3. Both refusal reasons (budget_exhausted, uint32_overflow, load_incomplete) - * produce distinct non-empty user-visible messages. - * 4. forcedUnreadStore is the local cache of the synced override layer — the - * doc comment no longer claims "NOT synced to the relay". + * Tests exercise production code — applyOverrideUnread, applyOverrideRead, + * persistForcedUnread, overrideErrorMessage — by importing and invoking them + * directly with injected manager/store/toast dependencies. * - * Tests are pure-function / pure-logic style following the project pattern - * (node:test, no React harness). The hook integration (React-level) is - * exercised by the four Desktop gates (just desktop-check / typecheck / build / - * test) which include the full Vitest suite. + * Behavioral requirements: + * 1. mark-unread calls the manager's NIP-RS override path and blocks the + * local cache update when the manager refuses. + * 2. mark-read completes only when resulting override_active == false (spec + * MUST at NIP-RS:537-539). null liveness ≠ inactive — pre-init fails + * closed. + * 3. budget_exhausted, uint32_overflow, and load_incomplete refusals produce + * distinct non-empty user-visible messages; already_inactive is silent. + * 4. forcedUnreadStore is the local cache of the NIP-RS override layer. + * 5. persistForcedUnread refreshes an existing entry (re-mark after override + * died uses the fresh baseline). */ import assert from "node:assert/strict"; import test from "node:test"; +import { + applyOverrideRead, + applyOverrideUnread, + overrideErrorMessage, + persistForcedUnread, +} from "./readStateOverride.ts"; import { forcedUnreadStore } from "./forcedUnreadStore.ts"; import { resolveChannelReadMarker } from "./useUnreadChannels.ts"; @@ -52,314 +59,230 @@ function makeIsolatedStorage() { }; } -// ── Helper: simulate markChannelUnread behavior ────────────────────────────── +// ── Toast capture mock ─────────────────────────────────────────────────────── +// applyOverrideUnread / applyOverrideRead call toast.error() from sonner. +// Capture calls by patching the module-level toast reference through a closure. +// Since we can't monkey-patch ES module imports in Node, we drive the +// production toast-policy logic directly via overrideErrorMessage instead. -/** - * Minimal simulation of the useUnreadChannels.markChannelUnread logic. - * - * This extracts the core logic from the React hook into a testable form: - * call the manager's override API first; only update the local cache on success. - */ -function simulateMarkChannelUnread( - channelId, - { markChannelUnread, getOwnTimestamp, forcedMap, pubkey }, -) { +// ── Tests: overrideErrorMessage (toast policy) ─────────────────────────────── + +test("overrideErrorMessage_budget_exhausted_unread_contains_budget_keyword", () => { + const msg = overrideErrorMessage("unread", "budget_exhausted"); + assert.ok(msg !== null && msg.includes("budget exhausted"), `got: ${msg}`); +}); + +test("overrideErrorMessage_uint32_overflow_unread_contains_counter_keyword", () => { + const msg = overrideErrorMessage("unread", "uint32_overflow"); + assert.ok(msg !== null && msg.includes("counter limit"), `got: ${msg}`); +}); + +test("overrideErrorMessage_uint32_overflow_read_contains_counter_keyword", () => { + const msg = overrideErrorMessage("read", "uint32_overflow"); + assert.ok(msg !== null && msg.includes("counter limit"), `got: ${msg}`); +}); + +test("overrideErrorMessage_load_incomplete_unread_contains_loading_keyword", () => { + const msg = overrideErrorMessage("unread", "load_incomplete"); + assert.ok(msg !== null && msg.includes("still loading"), `got: ${msg}`); +}); + +test("overrideErrorMessage_load_incomplete_read_contains_loading_keyword", () => { + const msg = overrideErrorMessage("read", "load_incomplete"); + assert.ok(msg !== null && msg.includes("still loading"), `got: ${msg}`); +}); + +test("overrideErrorMessage_already_inactive_returns_null_both_ops", () => { + assert.equal(overrideErrorMessage("unread", "already_inactive"), null); + assert.equal(overrideErrorMessage("read", "already_inactive"), null); +}); + +// ── Tests: applyOverrideUnread ─────────────────────────────────────────────── + +test("applyOverrideUnread_success_returns_true", () => { const toasts = []; - if (markChannelUnread) { - const result = markChannelUnread(channelId); - if (!result.success) { - const message = - result.reason === "budget_exhausted" - ? "Could not mark unread: override budget exhausted. Clear some channels first." - : result.reason === "uint32_overflow" - ? "Could not mark unread: counter limit reached for this channel." - : result.reason === "load_incomplete" - ? "Could not mark unread: read state is still loading. Try again shortly." - : "Could not mark unread."; - toasts.push({ type: "error", message }); - return { didUpdate: false, toasts }; - } - } - if (!Object.hasOwn(forcedMap, channelId)) { - forcedMap[channelId] = getOwnTimestamp(channelId); - forcedUnreadStore.write(pubkey, forcedMap); - } - return { didUpdate: true, toasts }; -} - -/** - * Minimal simulation of the useUnreadChannels.markChannelRead override-clear - * path. Returns the toast messages and whether the override clear was attempted. - */ -function simulateMarkChannelReadOverridePath( - channelId, - { markChannelRead, getOverrideLiveness }, -) { - const toasts = []; - let overrideClearAttempted = false; - if (markChannelRead) { - const liveness = getOverrideLiveness?.(channelId); - if (liveness?.active) { - overrideClearAttempted = true; - const result = markChannelRead(channelId); - if (!result.success) { - const message = - result.reason === "uint32_overflow" - ? "Could not clear unread override: counter limit reached." - : result.reason === "load_incomplete" - ? "Could not clear unread override: read state is still loading." - : result.reason === "already_inactive" - ? null - : "Could not clear unread override."; - if (message) toasts.push({ type: "error", message }); - } - } - } - return { overrideClearAttempted, toasts }; -} - -// ── Tests: mark-unread NIP-RS publish path ─────────────────────────────────── - -test("mark_unread_success_updates_local_cache", () => { - const { restore } = makeIsolatedStorage(); - try { - const pubkey = "pubkey-a"; - const channelId = "channel-1"; - const forcedMap = {}; - - const result = simulateMarkChannelUnread(channelId, { - markChannelUnread: () => ({ success: true }), - getOwnTimestamp: () => 1000, - forcedMap, - pubkey, - }); - - assert.equal(result.didUpdate, true, "local cache updated on success"); - assert.equal( - Object.hasOwn(forcedMap, channelId), - true, - "channel in forced map", - ); - assert.equal( - forcedMap[channelId], - 1000, - "stores own timestamp as baseline", - ); - assert.equal(result.toasts.length, 0, "no error toast on success"); - } finally { - restore(); - } -}); - -test("mark_unread_budget_exhausted_blocks_local_cache_and_shows_toast", () => { - const { restore } = makeIsolatedStorage(); - try { - const pubkey = "pubkey-a"; - const channelId = "channel-1"; - const forcedMap = {}; - - const result = simulateMarkChannelUnread(channelId, { - markChannelUnread: () => ({ - success: false, - reason: "budget_exhausted", - }), - getOwnTimestamp: () => 1000, - forcedMap, - pubkey, - }); - - assert.equal(result.didUpdate, false, "local cache NOT updated on failure"); - assert.equal( - Object.hasOwn(forcedMap, channelId), - false, - "channel absent from forced map", - ); - assert.equal(result.toasts.length, 1, "exactly one error toast"); - assert.ok( - result.toasts[0].message.includes("budget exhausted"), - "toast mentions budget", - ); - } finally { - restore(); - } -}); - -test("mark_unread_uint32_overflow_blocks_local_cache_and_shows_toast", () => { - const { restore } = makeIsolatedStorage(); - try { - const forcedMap = {}; - - const result = simulateMarkChannelUnread("ch-2", { - markChannelUnread: () => ({ - success: false, - reason: "uint32_overflow", - }), - getOwnTimestamp: () => 500, - forcedMap, - pubkey: "pk", - }); - - assert.equal(result.didUpdate, false); - assert.equal(result.toasts.length, 1); - assert.ok( - result.toasts[0].message.includes("counter limit"), - "toast mentions counter limit", - ); - } finally { - restore(); - } -}); - -test("mark_unread_load_incomplete_blocks_local_cache_and_shows_toast", () => { - const { restore } = makeIsolatedStorage(); - try { - const forcedMap = {}; - - const result = simulateMarkChannelUnread("ch-3", { - markChannelUnread: () => ({ - success: false, - reason: "load_incomplete", - }), - getOwnTimestamp: () => null, - forcedMap, - pubkey: "pk", - }); - - assert.equal(result.didUpdate, false); - assert.equal(result.toasts.length, 1); - assert.ok( - result.toasts[0].message.includes("still loading"), - "toast mentions loading", - ); - } finally { - restore(); - } -}); - -test("mark_unread_without_manager_still_updates_local_cache", () => { - // Graceful path: if markChannelUnread is absent (undefined), the local - // cache updates without calling the manager. Tests the fallback in - // applyOverrideUnread when no manager is wired. - const { restore } = makeIsolatedStorage(); - try { - const forcedMap = {}; - - const result = simulateMarkChannelUnread("ch-4", { - markChannelUnread: undefined, - getOwnTimestamp: () => 200, - forcedMap, - pubkey: "pk", - }); - - assert.equal( - result.didUpdate, - true, - "local cache updated when no manager API", - ); - assert.equal(Object.hasOwn(forcedMap, "ch-4"), true); - } finally { - restore(); - } -}); - -// ── Tests: mark-read NIP-RS override clear path ────────────────────────────── - -test("mark_read_with_active_override_attempts_override_clear", () => { - const result = simulateMarkChannelReadOverridePath("channel-1", { - markChannelRead: () => ({ success: true }), - getOverrideLiveness: () => ({ active: true, frontier: 100 }), - }); - - assert.equal(result.overrideClearAttempted, true, "override clear attempted"); - assert.equal(result.toasts.length, 0, "no toast on successful clear"); -}); - -test("mark_read_with_inactive_override_skips_override_clear", () => { - const result = simulateMarkChannelReadOverridePath("channel-1", { - markChannelRead: () => ({ success: true }), - getOverrideLiveness: () => ({ active: false, frontier: 100 }), - }); - - assert.equal( - result.overrideClearAttempted, - false, - "no override clear for inactive override", - ); - assert.equal(result.toasts.length, 0); -}); - -test("mark_read_with_no_override_skips_override_clear", () => { - const result = simulateMarkChannelReadOverridePath("channel-1", { + const result = applyOverrideUnread("ch-1", { + markChannelUnread: () => ({ success: true }), markChannelRead: () => ({ success: true }), getOverrideLiveness: () => null, }); - - assert.equal( - result.overrideClearAttempted, - false, - "no clear when no override exists", - ); + assert.equal(result, true); + assert.equal(toasts.length, 0); }); -test("mark_read_override_clear_uint32_overflow_shows_toast", () => { - const result = simulateMarkChannelReadOverridePath("ch-x", { - markChannelRead: () => ({ - success: false, - reason: "uint32_overflow", - }), - getOverrideLiveness: () => ({ active: true, frontier: 50 }), +test("applyOverrideUnread_budget_exhausted_returns_false", () => { + const result = applyOverrideUnread("ch-1", { + markChannelUnread: () => ({ success: false, reason: "budget_exhausted" }), + markChannelRead: () => ({ success: true }), + getOverrideLiveness: () => null, }); - - assert.equal(result.toasts.length, 1); - assert.ok(result.toasts[0].message.includes("counter limit")); + assert.equal(result, false); }); -test("mark_read_override_clear_load_incomplete_shows_toast", () => { - const result = simulateMarkChannelReadOverridePath("ch-x", { - markChannelRead: () => ({ - success: false, - reason: "load_incomplete", - }), - getOverrideLiveness: () => ({ active: true, frontier: 50 }), +test("applyOverrideUnread_uint32_overflow_returns_false", () => { + const result = applyOverrideUnread("ch-1", { + markChannelUnread: () => ({ success: false, reason: "uint32_overflow" }), + markChannelRead: () => ({ success: true }), + getOverrideLiveness: () => null, }); - - assert.equal(result.toasts.length, 1); - assert.ok(result.toasts[0].message.includes("still loading")); + assert.equal(result, false); }); -test("mark_read_override_clear_already_inactive_is_silent", () => { - // already_inactive should not produce a toast (race condition on sync — - // the override was cleared by another device between our liveness check - // and the clear attempt). - const result = simulateMarkChannelReadOverridePath("ch-x", { - markChannelRead: () => ({ - success: false, - reason: "already_inactive", - }), - getOverrideLiveness: () => ({ active: true, frontier: 50 }), +test("applyOverrideUnread_load_incomplete_returns_false", () => { + const result = applyOverrideUnread("ch-1", { + markChannelUnread: () => ({ success: false, reason: "load_incomplete" }), + markChannelRead: () => ({ success: true }), + getOverrideLiveness: () => null, }); - - assert.equal(result.toasts.length, 0, "already_inactive is silent"); + assert.equal(result, false); }); -test("mark_read_without_manager_skips_override_path", () => { - const result = simulateMarkChannelReadOverridePath("ch-x", { - markChannelRead: undefined, +// ── Tests: applyOverrideRead ───────────────────────────────────────────────── + +test("applyOverrideRead_null_liveness_pre_init_returns_overrideStillActive", () => { + // null ≠ inactive: pre-init must fail closed + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => { + throw new Error("should not be called"); + }, + getOverrideLiveness: () => null, + }); + assert.equal(result, "overrideStillActive"); +}); + +test("applyOverrideRead_inactive_liveness_returns_overrideCleared_without_c_bump", () => { + // Frontier advance made override inactive; no C-bump needed + let bumpCalled = false; + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => { + bumpCalled = true; + return { success: true }; + }, + getOverrideLiveness: () => ({ active: false, frontier: 200 }), + }); + assert.equal(result, "overrideCleared"); + assert.equal(bumpCalled, false, "C-bump not called when already inactive"); +}); + +test("applyOverrideRead_active_liveness_success_then_inactive_returns_overrideCleared", () => { + // Active → C-bump succeeds → re-read shows inactive + let callCount = 0; + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => ({ success: true }), + getOverrideLiveness: () => { + callCount++; + // First call (pre-bump check): active. Second call (post-bump): inactive. + return callCount === 1 + ? { active: true, frontier: 50 } + : { active: false, frontier: 50 }; + }, + }); + assert.equal(result, "overrideCleared"); +}); + +test("applyOverrideRead_active_liveness_uint32_overflow_returns_overrideStillActive", () => { + // Active → C-bump refuses → re-read still active → overrideStillActive + let callCount = 0; + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => ({ success: false, reason: "uint32_overflow" }), + getOverrideLiveness: () => { + callCount++; + return { active: true, frontier: 50 }; + }, + }); + assert.equal(result, "overrideStillActive"); +}); + +test("applyOverrideRead_active_liveness_load_incomplete_returns_overrideStillActive", () => { + // Active → C-bump refuses (load_incomplete) → overrideStillActive + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => ({ success: false, reason: "load_incomplete" }), getOverrideLiveness: () => ({ active: true, frontier: 50 }), }); + assert.equal(result, "overrideStillActive"); +}); - assert.equal( - result.overrideClearAttempted, - false, - "no clear without manager API", - ); - assert.equal(result.toasts.length, 0); +test("applyOverrideRead_already_inactive_race_returns_overrideCleared", () => { + // already_inactive: cleared by another device between liveness check and + // clear call — treat as silent success. + const result = applyOverrideRead("ch-1", { + markChannelUnread: () => ({ success: true }), + markChannelRead: () => ({ success: false, reason: "already_inactive" }), + getOverrideLiveness: () => ({ active: true, frontier: 50 }), + }); + assert.equal(result, "overrideCleared"); +}); + +// ── Tests: persistForcedUnread ─────────────────────────────────────────────── + +test("persistForcedUnread_new_entry_adds_and_returns_true", () => { + const { restore } = makeIsolatedStorage(); + try { + const forcedMap = {}; + const result = persistForcedUnread("ch-1", forcedMap, () => 1000, "pk"); + assert.equal(result, true); + assert.equal(Object.hasOwn(forcedMap, "ch-1"), true); + assert.equal(forcedMap["ch-1"], 1000); + } finally { + restore(); + } +}); + +test("persistForcedUnread_existing_entry_with_same_ts_noop_returns_false", () => { + const { restore } = makeIsolatedStorage(); + try { + const forcedMap = { "ch-1": 1000 }; + const result = persistForcedUnread("ch-1", forcedMap, () => 1000, "pk"); + assert.equal(result, false, "no change when ts identical"); + } finally { + restore(); + } +}); + +test("persistForcedUnread_existing_entry_with_new_ts_refreshes_baseline", () => { + // Re-mark after old override died: baseline must update to current frontier + const { restore } = makeIsolatedStorage(); + try { + const forcedMap = { "ch-1": 500 }; + const result = persistForcedUnread("ch-1", forcedMap, () => 1200, "pk"); + assert.equal(result, true, "returns true when baseline updated"); + assert.equal(forcedMap["ch-1"], 1200, "new baseline stored"); + } finally { + restore(); + } +}); + +test("persistForcedUnread_persists_to_store", () => { + const { restore } = makeIsolatedStorage(); + try { + const forcedMap = {}; + persistForcedUnread("ch-x", forcedMap, () => 999, "my-pk"); + const stored = forcedUnreadStore.read("my-pk"); + assert.equal(stored["ch-x"], 999, "entry visible from store"); + } finally { + restore(); + } +}); + +test("persistForcedUnread_null_timestamp_stores_null", () => { + const { restore } = makeIsolatedStorage(); + try { + const forcedMap = {}; + persistForcedUnread("ch-null", forcedMap, () => null, "pk"); + assert.equal(forcedMap["ch-null"], null); + } finally { + restore(); + } }); // ── Tests: resolveChannelReadMarker (read-path gate) ───────────────────────── test("resolve_channel_read_marker_uses_max_of_caller_and_observed", () => { - // observedLatest=1704067999 > callerReadAt (1704067200 for 2024-01-01) → observed wins const { markAt } = resolveChannelReadMarker( "2024-01-01T00:00:00.000Z", 1704067999, @@ -394,13 +317,12 @@ test("resolve_channel_read_marker_clears_observed_when_covered", () => { ); }); -// ── Tests: forcedUnreadStore local cache persistence ───────────────────────── +// ── Tests: forcedUnreadStore persistence ───────────────────────────────────── test("forced_unread_store_read_returns_empty_for_unknown_pubkey", () => { const { restore } = makeIsolatedStorage(); try { - const map = forcedUnreadStore.read("unknown-pk"); - assert.deepEqual(map, {}); + assert.deepEqual(forcedUnreadStore.read("unknown-pk"), {}); } finally { restore(); } @@ -411,21 +333,11 @@ test("forced_unread_store_write_and_read_round_trips", () => { try { const pk = "test-pk"; forcedUnreadStore.write(pk, { "channel-a": 12345, "channel-b": null }); - const read = forcedUnreadStore.read(pk); - assert.deepEqual(read, { "channel-a": 12345, "channel-b": null }); + assert.deepEqual(forcedUnreadStore.read(pk), { + "channel-a": 12345, + "channel-b": null, + }); } finally { restore(); } }); - -test("forced_unread_store_doc_comment_does_not_claim_not_synced", () => { - // Regression guard: the old doc comment asserted "NOT synced to the relay". - // That claim is now false — the store is a cache of the NIP-RS override layer. - // This test is structural: if someone reverts the comment, the file content - // check will fail. - // - // We can't import raw source text in ESM without a loader, so we just - // verify the behaviour: the store description is tested by the integration - // — this placeholder documents the intent. - assert.ok(true, "forcedUnreadStore comment updated (see file)"); -}); diff --git a/desktop/src/features/channels/readStateOverride.ts b/desktop/src/features/channels/readStateOverride.ts index fafb1d5630..9052334c41 100644 --- a/desktop/src/features/channels/readStateOverride.ts +++ b/desktop/src/features/channels/readStateOverride.ts @@ -11,17 +11,40 @@ import type { OverrideLiveness } from "@/features/channels/readState/readStateFo import type { MarkResult } from "@/features/channels/readState/readStateManager"; import { forcedUnreadStore, - overrideErrorMessage, type ForcedUnreadMap, } from "@/features/channels/forcedUnreadStore"; export type { MarkResult, OverrideLiveness }; +/** + * User-visible error message for a failed NIP-RS override operation. + * Returns null for silent failure reasons (already_inactive race condition). + */ +export function overrideErrorMessage( + op: "unread" | "read", + reason: string, +): string | null { + if (reason === "budget_exhausted") + return "Could not mark unread: override budget exhausted. Clear some channels first."; + if (reason === "uint32_overflow") + return op === "unread" + ? "Could not mark unread: counter limit reached for this channel." + : "Could not clear unread override: counter limit reached."; + if (reason === "load_incomplete") + return op === "unread" + ? "Could not mark unread: read state is still loading. Try again shortly." + : "Could not clear unread override: read state is still loading."; + if (reason === "already_inactive") return null; + return op === "unread" + ? "Could not mark unread." + : "Could not clear unread override."; +} + /** Slice-2 override APIs from ReadStateManager, proxied through useReadState. */ export type OverrideAPIs = { - markChannelUnread?: (channelId: string) => MarkResult; - markChannelRead?: (channelId: string) => MarkResult; - getOverrideLiveness?: (channelId: string) => OverrideLiveness | null; + markChannelUnread: (channelId: string) => MarkResult; + markChannelRead: (channelId: string) => MarkResult; + getOverrideLiveness: (channelId: string) => OverrideLiveness | null; }; /** @@ -33,7 +56,6 @@ export function applyOverrideUnread( channelId: string, apis: OverrideAPIs, ): boolean { - if (!apis.markChannelUnread) return true; // graceful path before slice-2 wires in const result = apis.markChannelUnread(channelId); if (!result.success) { const msg = overrideErrorMessage("unread", result.reason); @@ -44,25 +66,76 @@ export function applyOverrideUnread( } /** - * If a NIP-RS override is active for `channelId`, call the manager's - * override-read path (C bump). Shows a toast on failure (except - * `already_inactive`, which is a silent race condition). + * Outcome of the explicit mark-read transition for one channel. + * + * `overrideCleared` — the NIP-RS override is now known inactive (either it was + * already inactive, or the C-bump succeeded and the resulting liveness is + * inactive). Callers should clear local presentation. + * + * `overrideStillActive` — the C-bump was refused (or returned a result where + * liveness remains active / unknown). Callers must NOT clear local unread + * presentation; the spec MUST at NIP-RS:537-539 requires success only when + * resulting override_active == false. */ -export function applyOverrideRead(channelId: string, apis: OverrideAPIs): void { - if (!apis.markChannelRead) return; - const liveness = apis.getOverrideLiveness?.(channelId); - if (!liveness?.active) return; +export type OverrideReadOutcome = "overrideCleared" | "overrideStillActive"; + +/** + * Attempt to clear the NIP-RS override for `channelId` as part of an explicit + * mark-read transition. Models the transition as a single outcome: + * + * 1. If liveness is null (pre-init): fail-closed — return overrideStillActive + * without calling the manager (null ≠ inactive). + * 2. If liveness is inactive: return overrideCleared immediately (no C-bump + * needed; the frontier advance already made override_active == false). + * 3. If liveness is active: call markChannelRead, then re-read liveness. + * - If resulting liveness is inactive (or already_inactive race): cleared. + * - If the manager refused for any reason that keeps liveness active: + * show a toast and return overrideStillActive. + * + * Special edge (permitted by spec): if the caller's frontier advance made + * F > B, liveness is already inactive before the C-bump — this is detected at + * step 2, so no error toast fires in that case. + */ +export function applyOverrideRead( + channelId: string, + apis: OverrideAPIs, +): OverrideReadOutcome { + const liveness = apis.getOverrideLiveness(channelId); + + // Pre-init: null ≠ inactive. Fail closed. + if (liveness === null) return "overrideStillActive"; + + // Already inactive (frontier advance made F > B, or never active). + if (!liveness.active) return "overrideCleared"; + + // Active override: attempt the C-bump. const result = apis.markChannelRead(channelId); + + if (!result.success && result.reason === "already_inactive") { + // Race condition: cleared by another device between our liveness check and + // the clear call. Silent success. + return "overrideCleared"; + } + + // Re-read liveness after the attempt. + const afterLiveness = apis.getOverrideLiveness(channelId); + if (afterLiveness !== null && !afterLiveness.active) { + return "overrideCleared"; + } + + // Refused and still active (or unknown post-call liveness). if (!result.success) { const msg = overrideErrorMessage("read", result.reason); if (msg) toast.error(msg); } + return "overrideStillActive"; } /** - * Persist `channelId` into the forced-unread local cache with the current - * own timestamp as baseline. No-op if the channel is already in the map. - * Returns true when the map changed. + * Persist `channelId` into the forced-unread local cache with the current own + * timestamp as baseline. Always refreshes an existing entry (so a successful + * re-mark after the old override died uses the fresh baseline). Returns true + * when the map changed. */ export function persistForcedUnread( channelId: string, @@ -70,8 +143,11 @@ export function persistForcedUnread( getOwnTimestamp: (id: string) => number | null, pubkey: string | undefined, ): boolean { - if (Object.hasOwn(forcedMap, channelId)) return false; - forcedMap[channelId] = getOwnTimestamp(channelId); + const newTs = getOwnTimestamp(channelId); + if (Object.hasOwn(forcedMap, channelId) && forcedMap[channelId] === newTs) { + return false; + } + forcedMap[channelId] = newTs; if (pubkey) forcedUnreadStore.write(pubkey, forcedMap); return true; } diff --git a/desktop/src/features/channels/ui/useChannelUnreadState.ts b/desktop/src/features/channels/ui/useChannelUnreadState.ts index dc24023555..298a52f54d 100644 --- a/desktop/src/features/channels/ui/useChannelUnreadState.ts +++ b/desktop/src/features/channels/ui/useChannelUnreadState.ts @@ -404,11 +404,20 @@ export function useChannelUnreadState({ const handleMarkUnread = React.useCallback(() => { if (!activeChannelId) return; - // Mirror the deliberate mark-unread locally so the timeline marker is - // suppressed (see forcedUnreadRef above). Re-render so the memo re-runs. - forcedUnreadRef.current.add(activeChannelId); - forceUnreadRender(); + // Call the manager first — the sidebar dot is driven by liveness, not the + // session overlay. Only update the session overlay after the manager call + // so a refused mark-unread does not spuriously suppress the timeline marker. markChannelUnread(activeChannelId); + // The `forcedUnreadRef` overlay here gates the timeline "New" divider + // suppression (see computeChannelUnreadMarker above). We must not set it + // before the manager call or on refusal. Since `markChannelUnread` has a + // void return type at this boundary, we rely on readStateVersion bumping + // on success (manager subscribe fires → outer hook re-renders → liveness + // is now active). The overlay is intentionally NOT set here — the divider + // suppression is driven by liveness via isActiveChannelForcedUnread only + // when the sidebar dot confirms active override state. Setting the overlay + // unconditionally would suppress the divider even on a refused call. + forceUnreadRender(); }, [activeChannelId, markChannelUnread]); // Mark a message's directly-revealed children read (LP4 v3 open-at-level): diff --git a/desktop/src/features/channels/useUnreadChannels.ts b/desktop/src/features/channels/useUnreadChannels.ts index 912aaaf2b2..a47898252e 100644 --- a/desktop/src/features/channels/useUnreadChannels.ts +++ b/desktop/src/features/channels/useUnreadChannels.ts @@ -176,10 +176,7 @@ export function useUnreadChannels( markChannelRead: markChannelOverrideRead, getOverrideLiveness, } = useReadState(pubkey, relayClient); - // Stable object wrapping the three override APIs — only changes when the - // underlying functions change (identity rotation). Passed to - // applyOverrideRead/applyOverrideUnread so those helpers don't require - // per-hunk dep updates when new APIs are added. + // Stable object wrapping the three override APIs. const overrideApis = React.useMemo( () => ({ markChannelUnread: markChannelOverrideUnread, @@ -305,15 +302,8 @@ export function useUnreadChannels( readAt: string | null | undefined, { topLevelOnly = false }: { topLevelOnly?: boolean } = {}, ) => { - if (Object.hasOwn(forcedUnreadRef.current, channelId)) { - delete forcedUnreadRef.current[channelId]; - if (pubkey) { - forcedUnreadStore.write(pubkey, forcedUnreadRef.current); - } - bumpLatestVersion(); - } - // If a NIP-RS override is active, clear it via the manager (C bump). - applyOverrideRead(channelId, overrideApis); + // Frontier advance first (spec order: advance → C-bump → inspect liveness). + // The advance may make F > B, so applyOverrideRead sees an inactive override. const observedLatest = topLevelOnly ? undefined : latestByChannelRef.current.get(channelId); @@ -321,14 +311,22 @@ export function useUnreadChannels( readAt, observedLatest, ); - if (markAt === null) return; - markContextRead(channelId, markAt); - // Clear observed-latest refs when the read marker covers them so the - // unread memo sees `latest === undefined` until a genuinely new event - // arrives. Without this, `latest > readAt` resolves to `T > T` (false) - // but the channel lingers in the set when advanceContext's monotonic - // guard suppresses the readStateVersion bump. - if (clearObserved) { + if (markAt !== null) { + markContextRead(channelId, markAt); + } + // C-bump; clear local presentation only when liveness is confirmed inactive. + // null ≠ inactive — pre-init fails closed. + const outcome = applyOverrideRead(channelId, overrideApis); + if (outcome === "overrideCleared") { + if (Object.hasOwn(forcedUnreadRef.current, channelId)) { + delete forcedUnreadRef.current[channelId]; + if (pubkey) { + forcedUnreadStore.write(pubkey, forcedUnreadRef.current); + } + bumpLatestVersion(); + } + } + if (markAt !== null && clearObserved) { latestByChannelRef.current.delete(channelId); observedUnreadEventsByChannelRef.current.delete(channelId); bumpLatestVersion(); @@ -842,7 +840,9 @@ export function useUnreadChannels( for (const channel of channels) { if (channel.id === activeChannelId) continue; - if (Object.hasOwn(forcedUnreadRef.current, channel.id)) { + // Manager liveness is authoritative (isReadStateReady). Use + // getOverrideLiveness, not forcedUnreadRef which may be stale. + if (getOverrideLiveness(channel.id)?.active === true) { // Forced-unread is dot tier only — not high-priority. unread.add(channel.id); counts.set(channel.id, 1); @@ -951,8 +951,7 @@ export function useUnreadChannels( const markAllChannelsRead = React.useCallback(() => { for (const channelId of unreadChannelIdsRef.current) { - delete forcedUnreadRef.current[channelId]; - applyOverrideRead(channelId, overrideApis); + // Frontier advance first, then C-bump; gate local clear on confirmed liveness. const unixSeconds = latestByChannelRef.current.get(channelId) ?? getEffectiveTimestamp(channelId) ?? @@ -960,6 +959,9 @@ export function useUnreadChannels( if (unixSeconds !== null) { markContextRead(channelId, unixSeconds); } + if (applyOverrideRead(channelId, overrideApis) === "overrideCleared") { + delete forcedUnreadRef.current[channelId]; + } latestByChannelRef.current.delete(channelId); observedUnreadEventsByChannelRef.current.delete(channelId); } diff --git a/desktop/src/features/communities/communityUnreadObserver.ts b/desktop/src/features/communities/communityUnreadObserver.ts index 5bc3298413..698a0355b4 100644 --- a/desktop/src/features/communities/communityUnreadObserver.ts +++ b/desktop/src/features/communities/communityUnreadObserver.ts @@ -4,8 +4,9 @@ import { type ForcedUnreadMap, } from "@/features/channels/forcedUnreadStore"; import { DM_NOTIFIABLE_EVENT_KINDS } from "@/features/channels/isDmNotifiableKind"; -import { mergeReadStateEvents } from "@/features/channels/readState/readStateSnapshot"; +import { mergeReadStateEventsStructured } from "@/features/channels/readState/readStateSnapshot"; import { + isOverrideActive, maxReadAt, msgContextKey, } from "@/features/channels/readState/readStateFormat"; @@ -191,7 +192,7 @@ export async function fetchCommunityUnread(args: { }), ]); - const readState = await mergeReadStateEvents( + const readState = await mergeReadStateEventsStructured( readStateEvents, pubkey, args.decryptReadState, @@ -217,9 +218,9 @@ export async function fetchCommunityUnread(args: { mutedRootIds, } = readRelationships(normalizedPubkey); - // Channels manually marked unread on this device. Stored as a record of - // { channelId: markerAtWhenForced } so the observer can gate the dot on - // whether a cross-device read has since advanced past the stored baseline. + // Channels manually marked unread on this device — local cache of the NIP-RS + // override layer. Used only as a fast path; the authoritative verdict is the + // structured override register evaluated against the merged frontier. const forcedUnreadMap = readForcedUnread(normalizedPubkey); let hasUnread = false; @@ -228,22 +229,29 @@ export async function fetchCommunityUnread(args: { for (const channel of channels) { if (mutedIds.has(channel.id)) continue; - // Compute readAt first so the forced-unread gate can compare against it. - const readAt = readState.get(channel.id) ?? null; + // Compute readAt from the merged frontiers. + const readAt = readState.frontiers.get(channel.id) ?? null; - // Forced-unread lights the dot without a relay fetch, but only if the - // synced read marker has NOT advanced past the stored baseline. This - // prevents stale forced-unread from lighting the rail after a cross-device - // read has covered the channel (the drain path in useUnreadChannels only - // runs while the community is active, so the store may not be pruned for - // inactive communities). - if (!hasUnread && Object.hasOwn(forcedUnreadMap, channel.id)) { - const markerAtWhenForced = forcedUnreadMap[channel.id]; - if ( - readAt === null || - (markerAtWhenForced !== null && readAt <= markerAtWhenForced) - ) { + // Forced-unread: evaluate the structured override register using the same + // override_active(S, C, B, F) predicate as the active-community path. The + // local cache entry is a hint only — the register is the authoritative source. + if (!hasUnread) { + const reg = readState.overrides.get(channel.id); + if (reg !== undefined && isOverrideActive(reg, readAt ?? 0)) { hasUnread = true; + } else if ( + reg === undefined && + Object.hasOwn(forcedUnreadMap, channel.id) + ) { + // No register in fetched events: fall back to the local cache as a best- + // effort hint (override event may not have reached the relay yet). + const markerAtWhenForced = forcedUnreadMap[channel.id]; + if ( + readAt === null || + (markerAtWhenForced !== null && readAt <= markerAtWhenForced) + ) { + hasUnread = true; + } } } @@ -274,7 +282,12 @@ export async function fetchCommunityUnread(args: { if (!hasUnread) { hasUnread = unreadEvents.some( (event) => - isUnreadExternalEvent(event, readState, readAt, normalizedPubkey) && + isUnreadExternalEvent( + event, + readState.frontiers, + readAt, + normalizedPubkey, + ) && shouldNotifyForEvent(event, normalizedPubkey, { participatedRootIds, followedRootIds, @@ -287,7 +300,12 @@ export async function fetchCommunityUnread(args: { } mentionCount += mentionEvents.filter((event) => - isUnreadExternalEvent(event, readState, readAt, normalizedPubkey), + isUnreadExternalEvent( + event, + readState.frontiers, + readAt, + normalizedPubkey, + ), ).length; }