Skip to content

Commit 2560a59

Browse files
committed
fix(notifications): align cross-device mark-as-unread sync and mobile unread filtering
Desktop's value-monotonic merge (ts > current) rejected rolled-back timestamps from mark-as-unread events arriving from other devices. Port mobile's envelope-based merge (event.created_at comparison) so newer events carrying lower context values are accepted. Mobile bumped lastMessageAt for every relay event including reactions, edits, and non-participant thread replies. Add shouldNotifyForEvent gate matching desktop's kind/self-author/thread-participation filters.
1 parent 81a07a9 commit 2560a59

5 files changed

Lines changed: 108 additions & 35 deletions

File tree

‎desktop/src/features/channels/readState/readStateFormat.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,10 @@ export function localPublishableContextKey(pubkey: string): string {
1818
return `sprout.channel-read-state.publishable.v1:${pubkey}`;
1919
}
2020

21+
export function localSourceCreatedAtKey(pubkey: string): string {
22+
return `sprout.channel-read-state.source-created-at.v1:${pubkey}`;
23+
}
24+
2125
export function isPlainRecord(
2226
value: unknown,
2327
): value is Record<string, unknown> {

‎desktop/src/features/channels/readState/readStateManager.ts‎

Lines changed: 29 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -52,27 +52,16 @@ export class ReadStateManager {
5252
private relayClient: RelayClient;
5353
private clientId: string;
5454
private slotId: string;
55-
56-
// Effective merged state across all blobs
5755
private effectiveState = new Map<string, number>();
58-
59-
// Contexts this client is allowed to include in its published blob. This
60-
// excludes first-load local baselines for channels the user has not opened.
6156
private publishableContextIds = new Set<string>();
62-
63-
// Last-published blob content (for diff to suppress no-op publishes)
6457
private lastPublishedContexts: Record<string, number> = {};
6558
private debounceTimer: number | null = null;
6659
private listeners = new Set<() => void>();
6760
private unsubscribeLive: (() => void) | null = null;
6861
private initialized = false;
69-
70-
// Track the max created_at seen from fetched blobs so publishes can satisfy
71-
// NIP-RS clock-skew monotonicity for our d-tag coordinate.
7262
private maxFetchedCreatedAt = 0;
73-
74-
// Contexts rolled back by mark-unread, protected from merge until next publish.
7563
private forcedContexts = new Set<string>();
64+
private contextSourceCreatedAt = new Map<string, number>();
7665

7766
constructor(pubkey: string, relayClient: RelayClient) {
7867
this.pubkey = pubkey;
@@ -103,16 +92,17 @@ export class ReadStateManager {
10392
markContextRead(contextId: string, unixTimestamp: number): void {
10493
this.forcedContexts.delete(contextId);
10594
this.advanceContext(contextId, unixTimestamp, { publishable: true });
95+
this.contextSourceCreatedAt.set(
96+
contextId,
97+
Math.max(Math.floor(Date.now() / 1_000), this.maxFetchedCreatedAt + 1),
98+
);
10699
}
107100

108101
seedContextRead(contextId: string, unixTimestamp: number): void {
109102
this.advanceContext(contextId, unixTimestamp, { publishable: false });
110103
}
111104

112105
markContextUnread(contextId: string, lastMessageUnix: number): void {
113-
// Roll back the read timestamp to just before the last message so the
114-
// channel appears unread. This is published via NIP-RS and syncs across
115-
// devices.
116106
const rollbackTo = lastMessageUnix - 1;
117107
this.effectiveState.set(contextId, rollbackTo);
118108
this.publishableContextIds.add(contextId);
@@ -128,7 +118,6 @@ export class ReadStateManager {
128118
options: { publishable: boolean },
129119
): void {
130120
const current = this.effectiveState.get(contextId) ?? 0;
131-
// Monotonic: only advance, never lower
132121
if (unixTimestamp <= current) {
133122
if (!options.publishable || this.publishableContextIds.has(contextId)) {
134123
return;
@@ -203,16 +192,13 @@ export class ReadStateManager {
203192
let ownBlobCreatedAt = 0;
204193

205194
for (const event of events) {
206-
// Only process our own events
207195
if (event.pubkey !== this.pubkey) continue;
208196

209-
// Validate d tag (exactly one, with correct prefix)
210197
const dTags = event.tags.filter((t) => t[0] === "d");
211198
if (dTags.length !== 1) continue;
212199
const dTag = dTags[0];
213200
if (!isValidReadStateDTag(dTag[1])) continue;
214201

215-
// Validate t tag (exactly one)
216202
const tTags = event.tags.filter(
217203
(t) => t[0] === "t" && t[1] === "read-state",
218204
);
@@ -237,17 +223,19 @@ export class ReadStateManager {
237223
continue;
238224
}
239225

240-
// Merge into effective state
241226
for (const [ctx, ts] of Object.entries(blob.contexts)) {
242227
if (this.forcedContexts.has(ctx)) continue;
228+
const sourceCreatedAt = this.contextSourceCreatedAt.get(ctx) ?? 0;
243229
const current = this.effectiveState.get(ctx) ?? 0;
244-
if (ts > current) {
230+
if (event.created_at > sourceCreatedAt) {
231+
this.effectiveState.set(ctx, ts);
232+
this.contextSourceCreatedAt.set(ctx, event.created_at);
233+
} else if (event.created_at === sourceCreatedAt && ts > current) {
245234
this.effectiveState.set(ctx, ts);
246235
}
247236
this.publishableContextIds.add(ctx);
248237
}
249238

250-
// Track own blob (most recent event for our client_id)
251239
if (blob.client_id === this.clientId) {
252240
if (event.created_at > ownBlobCreatedAt) {
253241
ownBlob = blob;
@@ -307,13 +295,11 @@ export class ReadStateManager {
307295
private async handleIncomingEvent(event: RelayEvent): Promise<void> {
308296
if (event.pubkey !== this.pubkey) return;
309297

310-
// Validate d tag (exactly one, with correct prefix)
311298
const dTags = event.tags.filter((t) => t[0] === "d");
312299
if (dTags.length !== 1) return;
313300
const dTag = dTags[0];
314301
if (!isValidReadStateDTag(dTag[1])) return;
315302

316-
// Validate t tag (exactly one)
317303
const tTags = event.tags.filter(
318304
(t) => t[0] === "t" && t[1] === "read-state",
319305
);
@@ -338,16 +324,25 @@ export class ReadStateManager {
338324
return;
339325
}
340326

341-
// Merge into effective state
342327
let anyAdvanced = false;
343328
for (const [ctx, ts] of Object.entries(blob.contexts)) {
344329
if (this.forcedContexts.has(ctx)) continue;
330+
const sourceCreatedAt = this.contextSourceCreatedAt.get(ctx) ?? 0;
345331
const current = this.effectiveState.get(ctx) ?? 0;
346-
if (ts > current) {
332+
if (event.created_at > sourceCreatedAt) {
333+
if (this.effectiveState.get(ctx) !== ts) {
334+
this.effectiveState.set(ctx, ts);
335+
anyAdvanced = true;
336+
}
337+
this.contextSourceCreatedAt.set(ctx, event.created_at);
338+
} else if (event.created_at === sourceCreatedAt && ts > current) {
347339
this.effectiveState.set(ctx, ts);
348340
anyAdvanced = true;
349341
}
350-
this.publishableContextIds.add(ctx);
342+
if (!this.publishableContextIds.has(ctx)) {
343+
this.publishableContextIds.add(ctx);
344+
anyAdvanced = true;
345+
}
351346
}
352347

353348
if (anyAdvanced) {
@@ -416,6 +411,9 @@ export class ReadStateManager {
416411

417412
this.lastPublishedContexts = contexts;
418413
this.forcedContexts.clear();
414+
for (const key of Object.keys(contexts)) {
415+
this.contextSourceCreatedAt.set(key, createdAt);
416+
}
419417
this.maxFetchedCreatedAt = Math.max(
420418
this.maxFetchedCreatedAt,
421419
event.created_at,
@@ -473,6 +471,9 @@ export class ReadStateManager {
473471
for (const contextId of stored.publishableContextIds) {
474472
this.publishableContextIds.add(contextId);
475473
}
474+
for (const [contextId, createdAt] of stored.contextSourceCreatedAt) {
475+
this.contextSourceCreatedAt.set(contextId, createdAt);
476+
}
476477
this.persistLocalState();
477478
}
478479

@@ -481,6 +482,7 @@ export class ReadStateManager {
481482
this.pubkey,
482483
this.effectiveState,
483484
this.publishableContextIds,
485+
this.contextSourceCreatedAt,
484486
);
485487
}
486488

‎desktop/src/features/channels/readState/readStateStorage.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,13 @@ import {
33
localIsoToUnixSeconds,
44
localPublishableContextKey,
55
localReadStateKey,
6+
localSourceCreatedAtKey,
67
} from "@/features/channels/readState/readStateFormat";
78

89
export type StoredReadState = {
910
contexts: Map<string, number>;
1011
publishableContextIds: Set<string>;
12+
contextSourceCreatedAt: Map<string, number>;
1113
};
1214

1315
function mergeLocalStorageKey(
@@ -55,20 +57,43 @@ function readPublishableContextIds(pubkey: string): Set<string> {
5557
return result;
5658
}
5759

60+
function readContextSourceCreatedAt(pubkey: string): Map<string, number> {
61+
const result = new Map<string, number>();
62+
const raw = localStorage.getItem(localSourceCreatedAtKey(pubkey));
63+
if (!raw) return result;
64+
65+
try {
66+
const parsed = JSON.parse(raw);
67+
if (!isPlainRecord(parsed)) return result;
68+
69+
for (const [key, value] of Object.entries(parsed)) {
70+
if (typeof value === "number" && Number.isInteger(value) && value >= 0) {
71+
result.set(key, value);
72+
}
73+
}
74+
} catch {
75+
// Corrupt localStorage, ignore.
76+
}
77+
78+
return result;
79+
}
80+
5881
export function readStoredReadState(pubkey: string): StoredReadState {
5982
const contexts = new Map<string, number>();
6083
mergeLocalStorageKey(contexts, localReadStateKey(pubkey));
6184

6285
return {
6386
contexts,
6487
publishableContextIds: readPublishableContextIds(pubkey),
88+
contextSourceCreatedAt: readContextSourceCreatedAt(pubkey),
6589
};
6690
}
6791

6892
export function writeStoredReadState(
6993
pubkey: string,
7094
contexts: ReadonlyMap<string, number>,
7195
publishableContextIds: ReadonlySet<string>,
96+
contextSourceCreatedAt: ReadonlyMap<string, number>,
7297
): void {
7398
const state: Record<string, string> = {};
7499
for (const [contextId, timestamp] of contexts) {
@@ -80,4 +105,13 @@ export function writeStoredReadState(
80105
localPublishableContextKey(pubkey),
81106
JSON.stringify([...publishableContextIds]),
82107
);
108+
109+
const sourceState: Record<string, number> = {};
110+
for (const [contextId, createdAt] of contextSourceCreatedAt) {
111+
sourceState[contextId] = createdAt;
112+
}
113+
localStorage.setItem(
114+
localSourceCreatedAtKey(pubkey),
115+
JSON.stringify(sourceState),
116+
);
83117
}

‎mobile/lib/features/channels/channels_provider.dart‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import 'channel.dart';
1010
import 'channel_management_provider.dart' show channelDetailsProvider;
1111
import 'read_state/read_state_provider.dart';
1212
import 'unread_badge/is_high_priority_event.dart';
13+
import 'unread_badge/should_notify_for_event.dart';
1314

1415
const _channelTypeOrder = {'stream': 0, 'forum': 1, 'dm': 2};
1516

@@ -409,6 +410,7 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
409410
var maxHighPriority = 0;
410411
for (final event in events) {
411412
if (event.pubkey == myPk) continue;
413+
if (!EventKind.channelMessageEventKinds.contains(event.kind)) continue;
412414
if (isHighPriorityEvent(event.tags, myPk) &&
413415
event.createdAt > maxHighPriority) {
414416
maxHighPriority = event.createdAt;
@@ -432,6 +434,8 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
432434
final channelId = event.channelId;
433435
if (channelId == null) return;
434436

437+
final myPk = ref.read(myPubkeyProvider);
438+
435439
state = state.whenData((channels) {
436440
final idx = channels.indexWhere((c) => c.id == channelId);
437441
if (idx == -1) {
@@ -440,16 +444,18 @@ class ChannelsNotifier extends AsyncNotifier<List<Channel>> {
440444
}
441445
final updated = List<Channel>.of(channels);
442446
final channel = updated[idx];
443-
final eventTime = DateTime.fromMillisecondsSinceEpoch(
444-
event.createdAt * 1000,
445-
isUtc: true,
446-
);
447-
if (channel.lastMessageAt == null ||
448-
eventTime.isAfter(channel.lastMessageAt!)) {
449-
updated[idx] = channel.copyWith(lastMessageAt: eventTime);
447+
448+
if (myPk != null && shouldNotifyForEvent(event, myPk)) {
449+
final eventTime = DateTime.fromMillisecondsSinceEpoch(
450+
event.createdAt * 1000,
451+
isUtc: true,
452+
);
453+
if (channel.lastMessageAt == null ||
454+
eventTime.isAfter(channel.lastMessageAt!)) {
455+
updated[idx] = channel.copyWith(lastMessageAt: eventTime);
456+
}
450457
}
451458

452-
final myPk = ref.read(myPubkeyProvider);
453459
if (myPk != null &&
454460
event.pubkey != myPk &&
455461
(channel.isDm || isHighPriorityEvent(event.tags, myPk))) {
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
import '../../../shared/relay/nostr_models.dart';
2+
3+
bool shouldNotifyForEvent(NostrEvent event, String myPubkey) {
4+
if (!EventKind.channelMessageEventKinds.contains(event.kind)) return false;
5+
6+
if (event.pubkey == myPubkey) return false;
7+
8+
final ref = event.threadReference;
9+
if (ref.parentId == null) return true;
10+
11+
for (final tag in event.tags) {
12+
if (tag.length >= 2 && tag[0] == 'broadcast' && tag[1] == '1') {
13+
return true;
14+
}
15+
}
16+
17+
final normalizedPk = myPubkey.toLowerCase();
18+
for (final tag in event.tags) {
19+
if (tag.length >= 2 &&
20+
tag[0] == 'p' &&
21+
tag[1].toLowerCase() == normalizedPk) {
22+
return true;
23+
}
24+
}
25+
26+
return false;
27+
}

0 commit comments

Comments
 (0)