Skip to content

Commit 52c4c08

Browse files
wpfleger96Duncan
andauthored
fix(sidebar): converge stale-at-open state across devices (sections/sort/stars/mutes) (#7805)
Adds bounded-backoff recovery reads to all four sidebar sync hooks (sections, sort, stars and mutes). A stale relay read at app open now converges without a user edit or a reconnect. ## What this does **Shared recovery hook (`useStaleReaderRecovery`).** All four hooks use one retry effect. It reads immediately on mount, then at 5, 10, 30 and 60 s, staying at 60 s after that. A change of `visibilityState` to `visible` triggers an immediate read. Reads are single-flight. The effect restarts whenever `pubkey` or `relayUrl` changes, so a hook that stays mounted while switching relays drops the old relay's in-flight reads. **Guards that stop a recovery read from rolling back a local edit:** 1. **Skip the read while an edit is pending.** If an edit is pending when a tick starts, the tick skips its read and just schedules the next one. Without this, the read could return the pre-edit blob after the edit published and pending cleared. At that point neither apply-time guard could reject it. 2. **Pending check inside the state updater.** `hasPending()` and the effect lifetime are re-read inside `setStore(prev => ...)`. That way the check runs when React executes the updater, not when the response arrives. 3. **Local-mutation revision.** Each hook counts its local edits. The count is snapshotted when a read starts and checked again at apply time. If an edit landed while the read was in flight, the response is discarded. 4. **Head advanced only after a successful cache write.** A failed `write*Store()` leaves the same head retryable on the next tick. **Ownership-aware pending clear.** Each sync manager's `doPublish(store)` now clears `pendingStore` only while it still holds that same `store`, on both the identical-payload early return and the success path. Before, an older publish that finished after a newer edit had replaced `pendingStore` wiped the newer edit's pending marker, so a recovery read before the newer debounce could apply the older relay head over it. `destroy()` still clears unconditionally. ## Scope Reader-side recovery plus the ownership-aware pending clear. No outboxes, arbitration or replay changes. It applies to `useChannelSections`, `useChannelSortPreference`, `useChannelStars` and `useChannelMutes`. Related: [#7806](#7806) --------- Signed-off-by: Will Pfleger <[email protected]> Signed-off-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
1 parent f7ff429 commit 52c4c08

29 files changed

Lines changed: 2749 additions & 2280 deletions

‎desktop/src/features/sidebar/lib/channelMutesSync.ts‎

Lines changed: 60 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,11 @@ export class ChannelMuteSyncManager {
4646
private lastRemoteCreatedAt: number;
4747
private pendingStore: ChannelMuteStore | null = null;
4848
private lastPublishedStore: ChannelMuteStore | null = null;
49+
/** The bootstrap first-copy seed; retired once any relay head is observed. */
50+
private seedStore: ChannelMuteStore | null = null;
51+
/** Decoded heads, LWW-merged within the 500-entry bound, for each attempt. */
52+
private remoteStore: ChannelMuteStore | null = null;
53+
private remoteRev = 0;
4954
private destroyed = false;
5055

5156
constructor(pubkey: string, relayUrl: string) {
@@ -71,6 +76,7 @@ export class ChannelMuteSyncManager {
7176
if (!result) {
7277
return { status: "failed", createdAt: event.created_at };
7378
}
79+
this.remember(result.store);
7480
return {
7581
status: "found",
7682
data: result,
@@ -87,6 +93,22 @@ export class ChannelMuteSyncManager {
8793
this.lastRemoteCreatedAt = createdAt;
8894
}
8995
advanceWatermark(this.pubkey, BLOB_TYPE, this.relayUrl, createdAt);
96+
// A seed only fills a relay believed empty; any head supersedes it, even
97+
// one whose payload a concurrent reader drops or cannot decrypt.
98+
if (this.seedStore && this.pendingStore === this.seedStore) {
99+
this.cancelPendingMutePublish();
100+
this.pendingStore = null;
101+
}
102+
this.seedStore = null;
103+
}
104+
105+
private remember(store: ChannelMuteStore): void {
106+
const next = this.remoteStore
107+
? mergeStores(this.remoteStore, store)
108+
: store;
109+
// Only a changed winner invalidates in-flight attempts.
110+
if (!this.sameEntries(this.remoteStore, next)) this.remoteRev++;
111+
this.remoteStore = next;
90112
}
91113

92114
cancelPendingMutePublish(): void {
@@ -127,19 +149,21 @@ export class ChannelMuteSyncManager {
127149
this.recordRemoteHead(event.created_at);
128150
const remote = await decryptAndParse(event);
129151
if (!remote) return store;
130-
return mergeStores(store, remote.store);
152+
this.remember(remote.store);
153+
return store;
131154
} catch {
132155
return store;
133156
}
134157
}
135158

136-
private isIdenticalToLastPublished(store: ChannelMuteStore): boolean {
137-
if (!this.lastPublishedStore) return false;
138-
const lastKeys = Object.keys(this.lastPublishedStore.channels);
159+
/** Same winners (IDs, `muted`, `updatedAt`), ignoring key order. */
160+
private sameEntries(prev: ChannelMuteStore | null, store: ChannelMuteStore) {
161+
if (!prev) return false;
162+
const lastKeys = Object.keys(prev.channels);
139163
const currentKeys = Object.keys(store.channels);
140164
if (lastKeys.length !== currentKeys.length) return false;
141165
for (const key of currentKeys) {
142-
const last = this.lastPublishedStore.channels[key];
166+
const last = prev.channels[key];
143167
const current = store.channels[key];
144168
if (
145169
!last ||
@@ -152,14 +176,29 @@ export class ChannelMuteSyncManager {
152176
}
153177

154178
private async doPublish(store: ChannelMuteStore): Promise<void> {
179+
// A seed retired while acquired (preflight, crypto or socket wait) aborts.
180+
const seed = store === this.seedStore;
181+
let rev = this.remoteRev; // a changed winner before dispatch voids it
182+
const stale = () =>
183+
this.destroyed ||
184+
(seed && this.seedStore !== store) ||
185+
rev !== this.remoteRev;
186+
// Only the attempt that still owns `pendingStore` may clear it.
187+
const release = () => {
188+
if (this.pendingStore === store) this.pendingStore = null;
189+
};
155190
try {
156-
const merged = await this.fetchOwnBlobBeforePublish(store);
191+
const pre = await this.fetchOwnBlobBeforePublish(store);
192+
const merged = this.remoteStore
193+
? mergeStores(pre, this.remoteStore)
194+
: pre;
195+
rev = this.remoteRev;
157196
// Guard: manager may have been destroyed while fetchOwnBlobBeforePublish
158197
// was awaited (community switch during in-flight fetch). If so, abort
159198
// before touching the relay.
160-
if (this.destroyed) return;
161-
if (this.isIdenticalToLastPublished(merged)) {
162-
this.pendingStore = null;
199+
if (stale()) return;
200+
if (this.sameEntries(this.lastPublishedStore, merged)) {
201+
release();
163202
return;
164203
}
165204
const payload = {
@@ -180,17 +219,21 @@ export class ChannelMuteSyncManager {
180219
["t", D_TAG], // relay discoverability; not used in our filters
181220
],
182221
});
183-
if (this.destroyed) return;
222+
if (stale()) return;
184223
await relayClient.publishEvent(
185224
event,
186225
"Timed out publishing channel mutes.",
187226
"Failed to publish channel mutes.",
227+
() => !stale(),
188228
);
189229
this.recordRemoteHead(event.created_at);
190230
this.lastPublishedStore = merged;
191-
this.pendingStore = null;
231+
release();
192232
} catch (error) {
193233
console.warn("[channelMutesSync] publish failed:", error);
234+
} finally {
235+
const owned = !this.destroyed && this.pendingStore === store;
236+
if (owned && rev !== this.remoteRev) this.publishMutes(store);
194237
}
195238
}
196239

@@ -210,7 +253,8 @@ export class ChannelMuteSyncManager {
210253
// still advances the watermark and blocks future seed-publish.
211254
this.recordRemoteHead(event.created_at);
212255
void decryptAndParse(event).then((result) => {
213-
if (result) {
256+
if (result && !this.destroyed) {
257+
this.remember(result.store);
214258
onUpdate(result);
215259
}
216260
});
@@ -229,7 +273,10 @@ export class ChannelMuteSyncManager {
229273
lastHead: this.lastRemoteCreatedAt,
230274
localStore,
231275
isLocalNonEmpty: (s) => Object.keys(s.channels).length > 0,
232-
publishFn: (s) => this.publishMutes(s),
276+
publishFn: (s) => {
277+
this.seedStore = s;
278+
this.publishMutes(s);
279+
},
233280
});
234281
}
235282

‎desktop/src/features/sidebar/lib/channelSectionsHelpers.test.mjs‎

Lines changed: 0 additions & 79 deletions
This file was deleted.

‎desktop/src/features/sidebar/lib/channelSectionsHelpers.ts‎

Lines changed: 0 additions & 21 deletions
This file was deleted.

0 commit comments

Comments
 (0)