Repository navigation
fix(mobile): deliver the notifications a reconnect missed, and never persist a watermark past them - #10816
Conversation
…teardown The catch-up added in #8690 could never run. app/index.tsx unsubscribes the notification stream on every non-'connected' state and builds a fresh subscription on reconnect, so the closure holding the ready-counter, the delivered watermark and the seen-set is destroyed exactly when a reconnect needs them. Every reconnect looked like a cold open, `reconnectReadyCount` was always 1, and notifications dispatched while the socket was down were never fetched. Move that state to a per-host module-scope session so it survives the teardown. Refs #8591 Co-authored-by: Orca <[email protected]>
… desktop restart can't kill catch-up The desktop's notification `seq` is a per-process in-memory counter that starts at 0 on every launch. The mobile client's watermark is persisted in AsyncStorage and monotonic. After a desktop restart the two index different counters, so a client holding seq 57 meets a fresh counter at 2, `57 >= 2` cuts everything, and reconnect catch-up dies silently until the new process out-dispatches the old watermark — 57 notifications later. Users see nothing and get no error (#8591). Stamp every dispatched notification with an epoch identifying the counter lifetime, ride it on the `ready` frame and the getMissedSince response, and persist it beside the watermark. A watermark whose epoch doesn't match the live counter is void: the client resets to 0 and the desktop returns its retained buffer instead of nothing. The epoch param is optional on the wire in both directions, so a client or daemon that predates it degrades to today's seq-only cut rather than erroring. Also extracts the OS-permission helpers to notification-permissions.ts (re- exported, so no importer changes) to keep mobile-notifications.ts under its max-lines budget. Mutation-tested: 3 mutations applied to the epoch logic, 3 killed — including the storage-seed race guard, whose first mutant survived until the deferred-read test was added.
Round-1 review found four ways the epoch fix could still lose notifications. All four are addressed here. 1. Seen-set survived an epoch change. Seen-keys are seq-derived, and terminal bells carry no notificationId (they key on `seq:N` alone). After a restart the fresh counter re-issues low seqs, so a replayed post-restart bell was dropped as a duplicate of a bell from the previous counter. The dedup window belongs to one counter lifetime, so it is cleared on epoch change. 2. Legacy watermarks were trusted. Pre-upgrade installs stored a bare seq with no epoch. Adopting the first observed epoch as "nothing changed" left that unprovenanced seq cutting a counter it was never measured against — #8591 through the upgrade path. An epoch-less seq no longer survives adoption. 3. seq and epoch were separate storage keys. A process death between the two writes left epoch-B beside seq-57-from-A: a pair that looks internally valid on the next launch and is therefore trusted. They are now one JSON value, which cannot tear, with a read-only migration from the legacy key. 4. Sessions were never retired. They live at module scope so they survive the subscription teardown a reconnect performs, so host removal is the only thing that can drop them. Removal now retires the session and its watermark. Mutation-tested: 3 mutations, 3 killed. The first version of the bell test passed with the fix removed — it exercised the live path, which only adds to the seen-set; only the replay path consults it. Rewritten against the replay path, it fails with `expected 1 to be 2`: the literal lost notification. Mobile notifications + transport: 355 passed. Desktop replay: 11/11.
Catch-up hung off 'has this process connected before', which is false on the first ready of a fresh launch — exactly the post-upgrade / post-eviction case that loses everything between the stored watermark and the next live seq. Wait for the persisted read, then catch up whenever this device has delivered for the host before; a first-ever pairing still gets no replay. Co-authored-by: Orca <[email protected]>
…ey catch-up on the record Co-authored-by: Orca <[email protected]>
…unguarded Mutating each mechanism of the #8591 fix in turn showed two survived with the suite still green: the seed's epoch-provenance check, and the host session outliving the subscription teardown. Both are load-bearing, so pin them. - seen-set survives teardown: the desktop's retained buffer replays a notification already delivered live, and only the session-scoped seen-set stops a duplicate banner. - a seed resolving after a live epoch was adopted must not reinstate the dead watermark. Not reachable through subscribeToDesktopNotifications today ('ready' awaits the seed first), so it asserts on the exported pair and says so. Co-authored-by: Orca <[email protected]>
…k can't outrun what was shown Addresses two MAJOR findings from review of this branch. MAJOR #1 — the watermark could be persisted past a notification the user never saw. `deliverLive` advanced `lastDeliveredSeq` before awaiting the local show, and replay + live delivery ran concurrently, so a live seq 11 handled while catch-up was still showing seq 6 persisted 11. A process death before 7..10 were shown lost them permanently: the next launch asks the desktop for seq > 11. This predates the branch — `origin/main` advances the watermark at the same point — so it is a residual this fix closes, not a regression the branch introduced. It is fixed here because the branch is what makes the watermark load-bearing. Three changes: - the advance moves AFTER the show/dismiss await, so the watermark means "everything up to here reached the user" rather than "was dispatched" - a per-host `deliveryTail` promise chain (`enqueueHostDelivery`) serializes deliveries, so a monotonic advance is also an in-order one - the catch-up batch is ONE queue entry, not one per event. Awaiting per event returns to the event loop between replays and let a live event slot in between seq 6 and 7 — which is exactly the interleave being fixed. The RPC stays outside the queue: `sendRequest` waits up to 30s and holding the chain for that would stall live delivery on a slow link. MAJOR #2 — every delivery awaits the persisted read, so an AsyncStorage read that never settled disabled the host's notifications for the whole app lifetime, with no error and nothing to see. The seed is now bounded at 3s; a late seed still applies when it lands. Proceeding unseeded is strictly better: the watermark stays 0, so catch-up over-fetches and the seen-set de-duplicates. Serializing removed an overlap the duplicate-suppression relied on: `showLocalNotification` deduped two same-id events by observing the first still pending when the second arrived. With deliveries serialized the first completes first, so the second saw no pending state and scheduled a second banner for the same notification. The claim moves to enqueue time, where the overlap is still observable. Dismisses are deliberately not claimed — a dismiss for a shown id is what retires it. Evidence — each mechanism disabled individually against the unchanged suite: - batch-as-one-entry -> reverted to per-item enqueue: ordering test fails - watermark advance -> moved back before the await: ordering test fails - seed timeout -> removed: wedged-read test fails - live-path claim -> removed: concurrent-dedup test fails - replay-path claim -> removed: cross-path dedup test fails Each kills exactly one test, so no mechanism is unguarded and none is redundant. `mobile-notifications.test.ts`'s local `flushAsync` drained 10 microtask ticks. Deliveries are now several awaits deeper, so a fixed tick count under-drains; it yields to the macrotask queue instead. Verified with real timers that the behavior it asserts is unchanged — only the drain depth was wrong. Full mobile suite: 344 files, 2499 passed, 2 skipped. tsc clean, oxlint clean.
📝 WalkthroughWalkthroughThe notification system now uses desktop process epochs alongside sequence watermarks for reconnect catch-up. Mobile host sessions persist and seed epoch-aware watermarks, serialize replay and live delivery, deduplicate notification IDs, and reset state when epochs change. Local notification permissions, channel configuration, scheduling, dismissal, and bounded tracking are separated into dedicated helpers. Host removal clears session and persisted watermark state, with expanded tests covering reconnects, races, ordering, duplicates, and epoch changes. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (8)
mobile/src/notifications/mobile-notifications.test.ts (1)
76-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueMacrotask flush is the right call here. Note the second
flushAsynclater in this file still uses a 10 ms delay; consider aligning the two so the suite has one flushing semantic.mobile/src/notifications/notification-delivery-ordering.test.ts (2)
212-247: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe 3100 ms advance encodes an implicit production timeout. If the seed watchdog duration in
notification-reconnect-catchup.tsever changes, this test fails opaquely. Worth importing/exporting the constant or naming it locally with a comment tying it to the seed timeout.
38-42: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueFour copies of
flushAsyncwith two different delays. The three new suites also repeat the sameexpo-notifications/react-native/preferencesmock blocks and an in-memory AsyncStorageMap. Extract them into one fixture module with a concrete domain name (e.g.notification-test-doubles.ts— nothelpers/utils, as per coding guidelines) so the flush semantics can't drift per suite.
mobile/src/notifications/notification-delivery-ordering.test.ts#L38-L42: import the sharedflushAsyncand the shared AsyncStorage/expo mock factory instead of redeclaring them.mobile/src/notifications/notification-reconnect-teardown.test.ts#L38-L42: same — drop the localflushAsyncand mock block.mobile/src/notifications/notification-watermark-seed-race.test.ts#L57-L61: same, keeping only the held-read wrapper that is genuinely specific to this suite.mobile/src/notifications/mobile-notifications.test.ts#L76-L84: adopt the shared helper for both localflushAsyncdefinitions so the 0 ms and 10 ms variants converge on one delay.As per coding guidelines: "Do not use vague names such as
helpers,utils,common,misc, orshared-stufffor files, folders, or modules."Source: Coding guidelines
mobile/src/notifications/notification-reconnect-teardown.test.ts (1)
47-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
missedQueueis declared after the closure that captures it. No TDZ at runtime sincesendRequestonly runs post-return, but moving thelet missedQueue: unknown[] = []above theclientliteral removes the head-scratch.mobile/src/transport/host-removal-lifecycle.test.ts (1)
78-90: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe
await Promise.resolve()isn't load-bearing.clearWatermarkissues bothremoveItemcalls synchronously before its firstawait, so they've already landed whenremoveHostAndCloseClientresolves. Harmless, but the comment overstates the requirement. Also consider asserting the legacy key removal here, since that's the half a re-pair can resurrect.mobile/src/transport/host-removal-lifecycle.ts (1)
15-19: 🗄️ Data Integrity & Integration | 🔵 Trivial | 💤 Low valueConsider awaiting
clearWatermarkrather than voiding it. It never rejects (eachremoveItemhas its own.catch), so awaiting costs one storage round-trip and makes removal deterministic — an immediate re-pair can't race the in-flight delete. The current ordering fails safe (a stranded delete only zeroes the seq), so this is a tightening, not a bug fix.♻️ Proposed tightening
forgetHostNotificationSession(hostId) - void clearWatermark(hostId) + await clearWatermark(hostId)src/main/runtime/mobile-notification-replay.ts (1)
26-27: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCondense the implementation-walkthrough comments. Keep only concise rationale where needed.
src/main/runtime/mobile-notification-replay.ts#L26-L27: reduce to a short field-purpose comment or remove it.src/main/runtime/mobile-notification-replay.ts#L42-L46: retain only the restart/watermark rationale in one line.src/main/runtime/mobile-notification-replay.ts#L53-L53: remove the redundant getter comment.src/main/runtime/mobile-notification-replay.ts#L58-L60: remove or reduce to one non-obvious contract detail.src/main/runtime/mobile-notification-replay.ts#L74-L79: retain only the epoch-mismatch replay rationale in one line.Source: Coding guidelines
mobile/src/notifications/notification-reconnect-catchup.ts (1)
190-197: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win
enqueueHostDeliveryreturns a rejecting promise to callers.The tail is protected, but
runis handed back unguarded, so callers that fire-and-forget it (seemobile-notifications.tsLines 226-237) surface an unhandled rejection. Either document that callers must handle rejection or return the swallowed chain. Flagging the call site separately.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 9eb9bb3f-179c-4dc3-baa4-f527f70e75ca
📒 Files selected for processing (14)
mobile/src/notifications/local-notification-scheduling.tsmobile/src/notifications/mobile-notifications.test.tsmobile/src/notifications/mobile-notifications.tsmobile/src/notifications/notification-delivery-ordering.test.tsmobile/src/notifications/notification-permissions.tsmobile/src/notifications/notification-reconnect-catchup.tsmobile/src/notifications/notification-reconnect-teardown.test.tsmobile/src/notifications/notification-watermark-seed-race.test.tsmobile/src/transport/host-removal-lifecycle.test.tsmobile/src/transport/host-removal-lifecycle.tssrc/main/runtime/mobile-notification-replay.test.tssrc/main/runtime/mobile-notification-replay.tssrc/main/runtime/orca-runtime.tssrc/main/runtime/rpc/methods/notifications.ts
| export function configureNotificationChannel(): void { | ||
| if (Platform.OS === 'android') { | ||
| void Notifications.setNotificationChannelAsync('orca-desktop', { | ||
| name: 'Desktop Notifications', | ||
| importance: Notifications.AndroidImportance.HIGH, | ||
| vibrationPattern: [0, 250], | ||
| lightColor: '#6366f1' | ||
| }) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
void-ed promise with no rejection handler.
setNotificationChannelAsync can reject (channel creation failures on some OEM Androids); the void discards the rejection, producing an unhandled rejection warning at startup.
🛡️ Proposed fix
- void Notifications.setNotificationChannelAsync('orca-desktop', {
+ Notifications.setNotificationChannelAsync('orca-desktop', {
name: 'Desktop Notifications',
importance: Notifications.AndroidImportance.HIGH,
vibrationPattern: [0, 250],
lightColor: '`#6366f1`'
- })
+ }).catch(() => {})
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export function configureNotificationChannel(): void { | |
| if (Platform.OS === 'android') { | |
| void Notifications.setNotificationChannelAsync('orca-desktop', { | |
| name: 'Desktop Notifications', | |
| importance: Notifications.AndroidImportance.HIGH, | |
| vibrationPattern: [0, 250], | |
| lightColor: '#6366f1' | |
| }) | |
| } | |
| } | |
| export function configureNotificationChannel(): void { | |
| if (Platform.OS === 'android') { | |
| Notifications.setNotificationChannelAsync('orca-desktop', { | |
| name: 'Desktop Notifications', | |
| importance: Notifications.AndroidImportance.HIGH, | |
| vibrationPattern: [0, 250], | |
| lightColor: '`#6366f1`' | |
| }).catch(() => {}) | |
| } | |
| } |
| async function fetchMissed(): Promise<void> { | ||
| if (disposed) { | ||
| return | ||
| } | ||
| const missed = await client | ||
| .sendRequest('notifications.getMissedSince', { lastSeenSeq: lastDeliveredSeq }) | ||
| .sendRequest('notifications.getMissedSince', { | ||
| lastSeenSeq: session.lastDeliveredSeq, | ||
| // Why: sending the epoch lets the desktop reject a watermark from a counter | ||
| // it no longer has and return the whole retained buffer instead of nothing. | ||
| ...(session.lastDeliveredEpoch != null ? { epoch: session.lastDeliveredEpoch } : {}) | ||
| }) | ||
| .then((response) => { | ||
| if (!response.ok) { | ||
| return [] | ||
| } | ||
| const result = response.result as { notifications?: unknown[] } | undefined | ||
| const result = response.result as { notifications?: unknown[]; epoch?: string } | undefined | ||
| adoptNotificationEpoch(session, hostId, result?.epoch) | ||
| return Array.isArray(result?.notifications) ? result.notifications : [] | ||
| }) | ||
| .catch(() => []) | ||
| for (const raw of missed) { | ||
| const event = raw as NotificationEvent | DismissNotificationEvent | ||
| const key = seenKeyForEvent(event) | ||
| if (key && seenReplay.has(key)) { | ||
| continue | ||
| } | ||
| if (key) { | ||
| seenReplay.add(key) | ||
| } | ||
| if (event.type === 'notification') { | ||
| await deliverLive('notification', event) | ||
| } else if (event.type === 'dismiss') { | ||
| await deliverLive('dismiss', event) | ||
| // Why the whole batch is ONE queue entry (#8591): awaiting per event returns to | ||
| // the event loop between replays, so a live seq 11 slots into the chain between | ||
| // seq 6 and 7 and persists a watermark past a notification still unshown. Why the | ||
| // request stays OUTSIDE the queue: sendRequest waits up to 30s, and holding the | ||
| // chain for that would stall live delivery on a slow link. | ||
| await enqueueHostDelivery(session, async () => { |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
A live event can still persist a watermark past unshown replayed events.
Only the drain is enqueued; the getMissedSince request is deliberately outside the chain. During that window (up to the request timeout) a live event passes through queueDelivery, runs immediately on an otherwise-empty chain, and persists its higher seq. The replayed 7..10 are then enqueued behind it — a process death in between loses them, which is the exact invariant the serialization is meant to hold.
Consider claiming a chain slot before issuing the request (enqueue a task that awaits the in-flight request, or gate live delivery on a catchupPending promise) so live seqs cannot land ahead of the batch.
| void (async () => { | ||
| await session.watermarkSeeded | ||
| if (disposed) { | ||
| return | ||
| } | ||
| // Why the queue (#8591): a live event must not overtake an in-flight | ||
| // catch-up replay, or it persists a watermark past seqs still unshown. | ||
| await queueDelivery( | ||
| liveEvent.type === 'notification' ? 'notification' : 'dismiss', | ||
| liveEvent as NotificationEvent | DismissNotificationEvent | ||
| ) | ||
| })() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
One unguarded rejection path runs the whole delivery pipeline. A failing OS schedule call propagates out of showLocalNotification, through the raw promise enqueueHostDelivery hands back, into fire-and-forget continuations — surfacing as an unhandled rejection rather than a dropped notification.
mobile/src/notifications/mobile-notifications.ts#L226-L237: add.catch(() => {})to thisvoid-ed IIFE and to thereadycontinuation at Lines 190-205.mobile/src/notifications/notification-reconnect-catchup.ts#L190-L197: either return the swallowed chain instead ofrun, or document that callers must handle rejection.mobile/src/notifications/local-notification-scheduling.ts#L117-L166: catch a failingscheduleNotificationAsyncand resolve tonullso the existing cleanup removes the stranded map entry instead of throwing.
📍 Affects 3 files
mobile/src/notifications/mobile-notifications.ts#L226-L237(this comment)mobile/src/notifications/notification-reconnect-catchup.ts#L190-L197mobile/src/notifications/local-notification-scheduling.ts#L117-L166
Independent verification of the three open bot findings (Opus sub-agent, executed not read)Verified against a detached worktree pinned to this PR's head ( 🟡 CLAIM (Major): a live event can persist a watermark past unshown replayed events — REAL, but a RESIDUAL gap, not a regressionThe race is exactly as described, and I reproduced the interleave directly. A process death between those points loses 7..10 — the exact invariant the serialization is meant to hold. But this is strictly better than // origin/main
if (event.notificationSeq != null && event.notificationSeq > lastDeliveredSeq) {
lastDeliveredSeq = event.notificationSeq
void saveLastSeenSeq(hostId, lastDeliveredSeq) // ← persisted BEFORE the notification is shown
}This PR moves the advance to after the await and serializes deliveries. It narrows the window from "every notification" to "only events landing inside the catch-up request window." So the finding is a fair description of what's left — worth a follow-up (claim a chain slot before issuing the request), but it does not make this diff a regression. 🟢 CLAIM (Major): unguarded rejection wedges the delivery pipeline — REAL but MISCHARACTERIZED; the pipeline does not wedgeThe bot's framing is "one unguarded rejection path runs the whole delivery pipeline." The wedge half is wrong. const run = session.deliveryTail.then(task)
session.deliveryTail = run.catch(() => {}) // ← tail swallows it
return run // ← caller's copy still rejectsVerified: after a task rejects, the very next 🟡 CLAIM (Minor):
|
Correction to my previous comment: the mobile suite does run in CII flagged as an open question whether There are two distinct
That removes the caveat from my verdict. With CI coverage confirmed and no regressions found against |
The two
|
I tested the bot's suggested fix for the watermark race. Don't apply it as written.The suggestion on the Major thread was to "claim a chain slot before issuing the request, or gate on a Claiming the slot first means the in-flight request holds the chain. Every live delivery queues behind it: Ordering becomes correct, but nothing reaches the user for as long as the request takes — and Note this is precisely the rationale the PR already documents for keeping the request outside the chain:
The existing comment is right, and the bot's suggestion would undo a deliberate decision. One thing the suggestion gets right: a rejecting request doesn't wedge anything — I verified the chain still runs the next task after a timeout rejection, because the tail swallows it. So the risk is a stall, not a permanent wedge. Still a stall on the default path. What a follow-up should actually doNot "claim the slot earlier." The shape that preserves both invariants is to keep the request outside the chain and make the watermark advance conditional — e.g. have a live delivery landing during an active catch-up window hold back its That needs its own design and its own tests, which is exactly why it belongs in a separate issue rather than folded into this PR. My merge verdict on #10816 is unchanged: mergeable. The race is residual and strictly narrower than |
…persist a watermark past them (stablyai#10816) * fix(mobile): keep the reconnect watermark alive across the app's own teardown The catch-up added in stablyai#8690 could never run. app/index.tsx unsubscribes the notification stream on every non-'connected' state and builds a fresh subscription on reconnect, so the closure holding the ready-counter, the delivered watermark and the seen-set is destroyed exactly when a reconnect needs them. Every reconnect looked like a cold open, `reconnectReadyCount` was always 1, and notifications dispatched while the socket was down were never fetched. Move that state to a per-host module-scope session so it survives the teardown. Refs stablyai#8591 Co-authored-by: Orca <[email protected]> * fix(mobile): tag the notification watermark with a counter epoch so a desktop restart can't kill catch-up The desktop's notification `seq` is a per-process in-memory counter that starts at 0 on every launch. The mobile client's watermark is persisted in AsyncStorage and monotonic. After a desktop restart the two index different counters, so a client holding seq 57 meets a fresh counter at 2, `57 >= 2` cuts everything, and reconnect catch-up dies silently until the new process out-dispatches the old watermark — 57 notifications later. Users see nothing and get no error (stablyai#8591). Stamp every dispatched notification with an epoch identifying the counter lifetime, ride it on the `ready` frame and the getMissedSince response, and persist it beside the watermark. A watermark whose epoch doesn't match the live counter is void: the client resets to 0 and the desktop returns its retained buffer instead of nothing. The epoch param is optional on the wire in both directions, so a client or daemon that predates it degrades to today's seq-only cut rather than erroring. Also extracts the OS-permission helpers to notification-permissions.ts (re- exported, so no importer changes) to keep mobile-notifications.ts under its max-lines budget. Mutation-tested: 3 mutations applied to the epoch logic, 3 killed — including the storage-seed race guard, whose first mutant survived until the deferred-read test was added. * fix(mobile): make the notification watermark atomic and counter-scoped Round-1 review found four ways the epoch fix could still lose notifications. All four are addressed here. 1. Seen-set survived an epoch change. Seen-keys are seq-derived, and terminal bells carry no notificationId (they key on `seq:N` alone). After a restart the fresh counter re-issues low seqs, so a replayed post-restart bell was dropped as a duplicate of a bell from the previous counter. The dedup window belongs to one counter lifetime, so it is cleared on epoch change. 2. Legacy watermarks were trusted. Pre-upgrade installs stored a bare seq with no epoch. Adopting the first observed epoch as "nothing changed" left that unprovenanced seq cutting a counter it was never measured against — stablyai#8591 through the upgrade path. An epoch-less seq no longer survives adoption. 3. seq and epoch were separate storage keys. A process death between the two writes left epoch-B beside seq-57-from-A: a pair that looks internally valid on the next launch and is therefore trusted. They are now one JSON value, which cannot tear, with a read-only migration from the legacy key. 4. Sessions were never retired. They live at module scope so they survive the subscription teardown a reconnect performs, so host removal is the only thing that can drop them. Removal now retires the session and its watermark. Mutation-tested: 3 mutations, 3 killed. The first version of the bell test passed with the fix removed — it exercised the live path, which only adds to the seen-set; only the replay path consults it. Rewritten against the replay path, it fails with `expected 1 to be 2`: the literal lost notification. Mobile notifications + transport: 355 passed. Desktop replay: 11/11. * fix(mobile): catch up on the first connection after a cold open Catch-up hung off 'has this process connected before', which is false on the first ready of a fresh launch — exactly the post-upgrade / post-eviction case that loses everything between the stored watermark and the next live seq. Wait for the persisted read, then catch up whenever this device has delivered for the host before; a first-ever pairing still gets no replay. Co-authored-by: Orca <[email protected]> * fix(mobile): serialize live delivery behind the watermark seed, and key catch-up on the record Co-authored-by: Orca <[email protected]> * test(mobile): pin the two catch-up mechanisms mutation testing found unguarded Mutating each mechanism of the stablyai#8591 fix in turn showed two survived with the suite still green: the seed's epoch-provenance check, and the host session outliving the subscription teardown. Both are load-bearing, so pin them. - seen-set survives teardown: the desktop's retained buffer replays a notification already delivered live, and only the session-scoped seen-set stops a duplicate banner. - a seed resolving after a live epoch was adopted must not reinstate the dead watermark. Not reachable through subscribeToDesktopNotifications today ('ready' awaits the seed first), so it asserts on the exported pair and says so. Co-authored-by: Orca <[email protected]> * fix(mobile): serialize notification delivery per host so the watermark can't outrun what was shown Addresses two MAJOR findings from review of this branch. MAJOR stablyai#1 — the watermark could be persisted past a notification the user never saw. `deliverLive` advanced `lastDeliveredSeq` before awaiting the local show, and replay + live delivery ran concurrently, so a live seq 11 handled while catch-up was still showing seq 6 persisted 11. A process death before 7..10 were shown lost them permanently: the next launch asks the desktop for seq > 11. This predates the branch — `origin/main` advances the watermark at the same point — so it is a residual this fix closes, not a regression the branch introduced. It is fixed here because the branch is what makes the watermark load-bearing. Three changes: - the advance moves AFTER the show/dismiss await, so the watermark means "everything up to here reached the user" rather than "was dispatched" - a per-host `deliveryTail` promise chain (`enqueueHostDelivery`) serializes deliveries, so a monotonic advance is also an in-order one - the catch-up batch is ONE queue entry, not one per event. Awaiting per event returns to the event loop between replays and let a live event slot in between seq 6 and 7 — which is exactly the interleave being fixed. The RPC stays outside the queue: `sendRequest` waits up to 30s and holding the chain for that would stall live delivery on a slow link. MAJOR stablyai#2 — every delivery awaits the persisted read, so an AsyncStorage read that never settled disabled the host's notifications for the whole app lifetime, with no error and nothing to see. The seed is now bounded at 3s; a late seed still applies when it lands. Proceeding unseeded is strictly better: the watermark stays 0, so catch-up over-fetches and the seen-set de-duplicates. Serializing removed an overlap the duplicate-suppression relied on: `showLocalNotification` deduped two same-id events by observing the first still pending when the second arrived. With deliveries serialized the first completes first, so the second saw no pending state and scheduled a second banner for the same notification. The claim moves to enqueue time, where the overlap is still observable. Dismisses are deliberately not claimed — a dismiss for a shown id is what retires it. Evidence — each mechanism disabled individually against the unchanged suite: - batch-as-one-entry -> reverted to per-item enqueue: ordering test fails - watermark advance -> moved back before the await: ordering test fails - seed timeout -> removed: wedged-read test fails - live-path claim -> removed: concurrent-dedup test fails - replay-path claim -> removed: cross-path dedup test fails Each kills exactly one test, so no mechanism is unguarded and none is redundant. `mobile-notifications.test.ts`'s local `flushAsync` drained 10 microtask ticks. Deliveries are now several awaits deeper, so a fixed tick count under-drains; it yields to the macrotask queue instead. Verified with real timers that the behavior it asserts is unchanged — only the drain depth was wrong. Full mobile suite: 344 files, 2499 passed, 2 skipped. tsc clean, oxlint clean. --------- Co-authored-by: Orca <[email protected]>
Closes #8591
What's broken
Mobile silently stops delivering notifications. The desktop dispatches them, the phone is connected, and nothing arrives — no error, no banner, nothing to see.
ELI5
The phone keeps a bookmark: "I've shown everything up to notification #57." On reconnect it asks the desktop "anything after #57?"
The desktop's counter restarts at 0 every launch. So after a desktop restart, the desktop is on notification #3 while the phone still holds a bookmark saying #57. The phone asks for "anything after 57", the desktop says "nope", and notifications stay dead until the new desktop out-counts the old bookmark — potentially forever.
A bookmark is meaningless without knowing which counter it indexes. So the bookmark now records the counter's lifetime (an "epoch") alongside the number. Different epoch → the bookmark is void → replay everything retained.
The fixes
app/index.tsxtears the subscription down on every non-connected state, destroying the watermark and seen-set exactly when a reconnect needs them. They now live per-host at module scope.seq > 0— a voided watermark reloads as seq 0 and would otherwise look like a first-ever pairing.Fix proof
Full mobile suite: 344 files, 2499 passed, 2 skipped.
tscclean,oxlintclean.Every mechanism was disabled individually against the unchanged suite. Each kills exactly one test — so nothing is unguarded, and nothing is redundant:
Trade-offs / regression risk
Two defects found in review were pre-existing, not introduced here. I verified this mechanically (
git show origin/main:…shows the identical watermark advance) and fixed them anyway, because this branch is what makes the watermark load-bearing:expected 11 to be less than 7) before writing any fix.One real behavioral trade-off: serializing deliveries removed an overlap the duplicate-suppression relied on.
showLocalNotificationdeduped two same-id events by observing the first still pending when the second arrived; serialized, the first completes first, so the second saw nothing pending and scheduled a second banner. The claim moved to enqueue time, where the overlap is still observable. Dismisses are deliberately not claimed — a dismiss is what retires the notification a show created.Cost: notifications for a single host now show strictly one-at-a-time rather than concurrently. The catch-up RPC is deliberately kept outside the queue —
sendRequestwaits up to 30s, and holding the chain for that would stall live delivery on a slow link.Accepted: delivery is at-least-once.
saveWatermarkis fire-and-forget, so a failed write leaves the stored value below what was delivered and a later cold start may re-show. That's the safe direction — the alternative loses notifications.Review loop
3 rounds (gpt-5.6-sol + fable, alternating). Final fable verdict: CLEAN — "mergeable from my side." The two GPT MAJORs are fixed and mutation-verified above. Residual from review: 1 MINOR (notification-burst pacing), 3 NITs.
Cross-platform
Mobile-only (
mobile/). Platform-independent — no path handling, no shell, no OS branching. Android and iOS both exercised by the suite.Perf
No polling, no new hot-path scans. The dedup set is bounded at 512 entries. The serialization chain is one promise per host.