Skip to content

Commit 37d4658

Browse files
wesbillmanCarl
andcommitted
fix(desktop): replay unread markers after native open
Queue read-marker advances per observed-unread scope while native persistence is opening, then ingest them once the scope is ready. Keep newer advances intact when an older queued batch settles. Co-authored-by: Carl <c7ebe626f000404285d3686e1dc74cc07cc60a9754a150041ba132e14bd3e2ec@buzz.block.builderlab.xyz> Signed-off-by: Wes <[email protected]>
1 parent bad1dbf commit 37d4658

2 files changed

Lines changed: 139 additions & 42 deletions

File tree

‎desktop/src/features/channels/observedUnreadNative.test.mjs‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,50 @@ async function settle() {
5656
});
5757
}
5858

59+
test("marker advances queued before native readiness are ingested after open", async () => {
60+
installFreshStorage();
61+
let harness;
62+
let releaseOpen;
63+
const openGate = new Promise((resolve) => {
64+
releaseOpen = resolve;
65+
});
66+
const rig = installNativeRig();
67+
const invoke = globalThis.window.__TAURI_INTERNALS__.invoke;
68+
globalThis.window.__TAURI_INTERNALS__.invoke = async (command, args) => {
69+
if (command === "observed_unread_open_scope") await openGate;
70+
return invoke(command, args);
71+
};
72+
try {
73+
harness = await mountHook(
74+
{
75+
...DEFAULT_PROPS,
76+
pubkey: "pk-delayed-open-marker",
77+
getTs: () => NOW_S,
78+
},
79+
makeRefs(),
80+
);
81+
82+
harness.api.syncMarkers(["channel-before-ready"]);
83+
assert.equal(
84+
rig.requests("observed_unread_ingest").length,
85+
0,
86+
"the marker cannot be ingested before the native scope opens",
87+
);
88+
89+
releaseOpen();
90+
await settle();
91+
await settle();
92+
93+
assert.deepEqual(rig.markerUpdates(), [
94+
{ contextId: "channel-before-ready", readAt: NOW_S },
95+
]);
96+
} finally {
97+
releaseOpen?.();
98+
await harness?.unmount();
99+
rig.restore();
100+
}
101+
});
102+
59103
test("native no-op marker delta does not notify the renderer", async () => {
60104
installFreshStorage();
61105
let harness;

‎desktop/src/features/channels/useObservedUnreadPersistence.ts‎

Lines changed: 95 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,12 @@ export function useObservedUnreadPersistence(
9999
const nativeFailedRef = React.useRef(false);
100100
const timerRef = React.useRef<ReturnType<typeof setTimeout> | null>(null);
101101
const queueRef = React.useRef<QueuedObservedUnreadEvent[]>([]);
102+
const pendingMarkersRef = React.useRef(
103+
new Map<
104+
string,
105+
Map<string, { contextId: string; readAt: number | null }>
106+
>(),
107+
);
102108
const chainRef = React.useRef(Promise.resolve());
103109
const persistRefs = React.useRef<ObservedUnreadRefs>({
104110
eventsRef: observedUnreadEventsByChannelRef,
@@ -323,48 +329,95 @@ export function useObservedUnreadPersistence(
323329
}, []);
324330

325331
const enqueueNative = React.useCallback(
326-
(state: NativeState, mutation: NativeMutation) => {
332+
(state: NativeState, mutation: NativeMutation, onSettled?: () => void) => {
327333
flushNative();
328334
chainRef.current = chainRef.current.then(async () => {
329-
const ingest = async () => {
330-
const current = nativeRef.current;
331-
if (
332-
!current ||
333-
current.scope.pubkey !== state.scope.pubkey ||
334-
current.scope.relayUrl !== state.scope.relayUrl
335-
)
335+
try {
336+
const ingest = async () => {
337+
const current = nativeRef.current;
338+
if (
339+
!current ||
340+
current.scope.pubkey !== state.scope.pubkey ||
341+
current.scope.relayUrl !== state.scope.relayUrl
342+
)
343+
return true;
344+
const response = await ingestObservedUnread({
345+
scope: current.scope,
346+
sequence: current.sequence + 1,
347+
baseRevision: current.revision,
348+
...mutation,
349+
});
350+
if (response.kind === "snapshotRequired") return false;
351+
apply(response);
336352
return true;
337-
const response = await ingestObservedUnread({
338-
scope: current.scope,
339-
sequence: current.sequence + 1,
340-
baseRevision: current.revision,
341-
...mutation,
342-
});
343-
if (response.kind === "snapshotRequired") return false;
344-
apply(response);
345-
return true;
346-
};
353+
};
347354

348-
try {
349-
if (await ingest()) return;
350-
} catch {}
355+
try {
356+
if (await ingest()) return;
357+
} catch {}
351358

352-
try {
353-
await reopen(state.scope);
354-
if (await ingest()) return;
355-
} catch {}
359+
try {
360+
await reopen(state.scope);
361+
if (await ingest()) return;
362+
} catch {}
356363

357-
if (
358-
activityScopeKey(state.scope.pubkey, state.scope.relayUrl) ===
359-
scopeLoadedRef.current
360-
) {
361-
seedFallback(mutation);
364+
if (
365+
activityScopeKey(state.scope.pubkey, state.scope.relayUrl) ===
366+
scopeLoadedRef.current
367+
) {
368+
seedFallback(mutation);
369+
}
370+
} finally {
371+
onSettled?.();
362372
}
363373
});
364374
},
365375
[apply, flushNative, reopen, seedFallback],
366376
);
367377

378+
const flushPendingMarkers = React.useCallback(
379+
(scopeKey: string) => {
380+
const pending = pendingMarkersRef.current.get(scopeKey);
381+
if (!pending || pending.size === 0) return;
382+
const markers = [...pending.values()];
383+
const state = nativeRef.current;
384+
if (!state) {
385+
// The fallback reads markers directly from ReadStateManager and prunes
386+
// through the read-state effect below; replaying this native delta into
387+
// fallback would collapse its top-level-only semantics.
388+
if (nativeFailedRef.current && scopeLoadedRef.current === scopeKey)
389+
pendingMarkersRef.current.delete(scopeKey);
390+
return;
391+
}
392+
if (
393+
activityScopeKey(state.scope.pubkey, state.scope.relayUrl) !== scopeKey
394+
)
395+
return;
396+
enqueueNative(
397+
state,
398+
{
399+
events: [],
400+
channelLatest: [],
401+
markers,
402+
membership: [],
403+
clearChannels: [],
404+
clearAll: false,
405+
},
406+
() => {
407+
if (scopeLoadedRef.current !== scopeKey) return;
408+
const current = pendingMarkersRef.current.get(scopeKey);
409+
if (!current) return;
410+
for (const marker of markers) {
411+
if (current.get(marker.contextId) === marker)
412+
current.delete(marker.contextId);
413+
}
414+
if (current.size === 0) pendingMarkersRef.current.delete(scopeKey);
415+
},
416+
);
417+
},
418+
[enqueueNative],
419+
);
420+
368421
React.useEffect(() => {
369422
const onPageHide = () => {
370423
flushNative();
@@ -414,6 +467,7 @@ export function useObservedUnreadPersistence(
414467
};
415468
scopeLoadedRef.current = currentScope;
416469
apply(response);
470+
flushPendingMarkers(currentScope);
417471
if (response.migrationComplete) {
418472
try {
419473
window.localStorage.removeItem(key);
@@ -432,22 +486,22 @@ export function useObservedUnreadPersistence(
432486
latestByChannelRef.current = deriveLatestByChannel(stored);
433487
}
434488
scopeLoadedRef.current = currentScope;
489+
flushPendingMarkers(currentScope);
435490
optionsRef.current.onPruned?.();
436491
});
437492
return () => {
438493
active = false;
439494
flushNative();
440495
flushObservedUnreadWrite(persistRefs.current);
441496
};
442-
}, [normalizedPubkey, normalizedRelayUrl]);
497+
}, [normalizedPubkey, normalizedRelayUrl, flushPendingMarkers]);
443498

444499
const syncMarkers = React.useCallback(
445500
(
446501
contextIds: Iterable<string>,
447502
explicitReadAt?: ReadonlyMap<string, number>,
448503
) => {
449-
const state = nativeRef.current;
450-
if (!state) return;
504+
if (!currentScope) return;
451505
const markers = [...new Set(contextIds)].map((contextId) => ({
452506
contextId,
453507
readAt:
@@ -457,16 +511,15 @@ export function useObservedUnreadPersistence(
457511
: getEffectiveTimestamp(contextId)),
458512
}));
459513
if (markers.length === 0) return;
460-
enqueueNative(state, {
461-
events: [],
462-
channelLatest: [],
463-
markers,
464-
membership: [],
465-
clearChannels: [],
466-
clearAll: false,
467-
});
514+
let pending = pendingMarkersRef.current.get(currentScope);
515+
if (!pending) {
516+
pending = new Map();
517+
pendingMarkersRef.current.set(currentScope, pending);
518+
}
519+
for (const marker of markers) pending.set(marker.contextId, marker);
520+
flushPendingMarkers(currentScope);
468521
},
469-
[enqueueNative, getEffectiveTimestamp, getOwnTimestamp],
522+
[currentScope, flushPendingMarkers, getEffectiveTimestamp, getOwnTimestamp],
470523
);
471524

472525
// A read-state revision only needs to send the contexts that changed. Native

0 commit comments

Comments
 (0)