Skip to content

fix(mobile): deliver the notifications a reconnect missed, and never persist a watermark past them - #10816

Merged
nwparker merged 7 commits into
mainfrom
nwparker/fix-8591-reconnect-catchup
Jul 28, 2026
Merged

nwparker merged 7 commits into
mainfrom
nwparker/fix-8591-reconnect-catchup

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

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

  1. Epoch-tagged watermark. A seq is stored with the counter lifetime it belongs to. A mismatch on reconnect voids it instead of trusting it.
  2. Atomic pair. Seq and epoch live in one JSON value. Written as two keys, a process death between the writes leaves an epoch from one counter beside a seq from another — internally consistent, silently wrong, and therefore trusted.
  3. Survives the app's own teardown. app/index.tsx tears 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.
  4. Cold-open catch-up keyed on the record's existence, not seq > 0 — a voided watermark reloads as seq 0 and would otherwise look like a first-ever pairing.
  5. Serialized delivery (from review) — see trade-offs.

Fix proof

Full mobile suite: 344 files, 2499 passed, 2 skipped. tsc clean, oxlint clean.

Every mechanism was disabled individually against the unchanged suite. Each kills exactly one test — so nothing is unguarded, and nothing is redundant:

Mechanism disabled Result
Batch-as-one-queue-entry → per-item enqueue ordering test fails
Watermark advance → moved before the await ordering test fails
Seed timeout removed wedged-read test fails
Live-path dedup claim removed concurrent-dedup test fails
Replay-path dedup claim removed cross-path dedup test fails

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:

  • Watermark could outrun delivery. The advance happened before the local notification was shown, and replay + live delivery ran concurrently. 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. Confirmed with a disposable probe (expected 11 to be less than 7) before writing any fix.
  • Unbounded seed. Every delivery awaits the persisted read, so an AsyncStorage read that never settled disabled the host's notifications for the entire app lifetime. 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.

One real behavioral trade-off: serializing deliveries removed an overlap the duplicate-suppression relied on. showLocalNotification deduped 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 — sendRequest waits up to 30s, and holding the chain for that would stall live delivery on a slow link.

Accepted: delivery is at-least-once. saveWatermark is 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.

nwparker and others added 7 commits July 26, 2026 15:23
…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]>
…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.
@coderabbitai

coderabbitai Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the bug and fix, but it does not follow the required template sections or include screenshots, testing, review, security, or notes. Rewrite it with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections, including the checklist items requested.
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: reconnect catch-up notifications and watermark handling.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (8)
mobile/src/notifications/mobile-notifications.test.ts (1)

76-84: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Macrotask flush is the right call here. Note the second flushAsync later 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 value

The 3100 ms advance encodes an implicit production timeout. If the seed watchdog duration in notification-reconnect-catchup.ts ever 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 value

Four copies of flushAsync with two different delays. The three new suites also repeat the same expo-notifications / react-native / preferences mock blocks and an in-memory AsyncStorage Map. Extract them into one fixture module with a concrete domain name (e.g. notification-test-doubles.ts — not helpers/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 shared flushAsync and the shared AsyncStorage/expo mock factory instead of redeclaring them.
  • mobile/src/notifications/notification-reconnect-teardown.test.ts#L38-L42: same — drop the local flushAsync and 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 local flushAsync definitions 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, or shared-stuff for files, folders, or modules."

Source: Coding guidelines

mobile/src/notifications/notification-reconnect-teardown.test.ts (1)

47-77: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

missedQueue is declared after the closure that captures it. No TDZ at runtime since sendRequest only runs post-return, but moving the let missedQueue: unknown[] = [] above the client literal removes the head-scratch.

mobile/src/transport/host-removal-lifecycle.test.ts (1)

78-90: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

The await Promise.resolve() isn't load-bearing. clearWatermark issues both removeItem calls synchronously before its first await, so they've already landed when removeHostAndCloseClient resolves. 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 value

Consider awaiting clearWatermark rather than voiding it. It never rejects (each removeItem has 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 win

Condense 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

enqueueHostDelivery returns a rejecting promise to callers.

The tail is protected, but run is handed back unguarded, so callers that fire-and-forget it (see mobile-notifications.ts Lines 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

📥 Commits

Reviewing files that changed from the base of the PR and between 29c40e3 and 5274388.

📒 Files selected for processing (14)
  • mobile/src/notifications/local-notification-scheduling.ts
  • mobile/src/notifications/mobile-notifications.test.ts
  • mobile/src/notifications/mobile-notifications.ts
  • mobile/src/notifications/notification-delivery-ordering.test.ts
  • mobile/src/notifications/notification-permissions.ts
  • mobile/src/notifications/notification-reconnect-catchup.ts
  • mobile/src/notifications/notification-reconnect-teardown.test.ts
  • mobile/src/notifications/notification-watermark-seed-race.test.ts
  • mobile/src/transport/host-removal-lifecycle.test.ts
  • mobile/src/transport/host-removal-lifecycle.ts
  • src/main/runtime/mobile-notification-replay.test.ts
  • src/main/runtime/mobile-notification-replay.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/notifications.ts

Comment on lines +65 to +74
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'
})
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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(() => {})
}
}

Comment on lines 104 to +129
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 () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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.

Comment on lines +226 to +237
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
)
})()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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 this void-ed IIFE and to the ready continuation at Lines 190-205.
  • mobile/src/notifications/notification-reconnect-catchup.ts#L190-L197: either return the swallowed chain instead of run, or document that callers must handle rejection.
  • mobile/src/notifications/local-notification-scheduling.ts#L117-L166: catch a failing scheduleNotificationAsync and resolve to null so 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-L197
  • mobile/src/notifications/local-notification-scheduling.ts#L117-L166

@nwparker

Copy link
Copy Markdown
Contributor Author

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 (5274388819), A/B'd against origin/main. Same discriminator as always: does origin/main handle this correctly? If not, the finding describes a residual gap, not a regression this PR introduces.

🟡 CLAIM (Major): a live event can persist a watermark past unshown replayed events — REAL, but a RESIDUAL gap, not a regression

The race is exactly as described, and I reproduced the interleave directly. getMissedSince sits outside the serialization chain (deliberately — it waits up to 30s and holding the chain would stall live delivery). During that window the chain is empty, so a live event runs immediately and persists its higher seq; the replayed 7..10 then enqueue behind it. Observed order:

live-11-persists-seq  →  request-returned  →  replay-7..10

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, not worse. On main there is no chain at all and the watermark advances before showLocalNotification is awaited:

// 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 wedge

The bot's framing is "one unguarded rejection path runs the whole delivery pipeline." The wedge half is wrong. enqueueHostDelivery already sheds the failure from the chain tail:

const run = session.deliveryTail.then(task)
session.deliveryTail = run.catch(() => {})   // ← tail swallows it
return run                                    // ← caller's copy still rejects

Verified: after a task rejects, the very next enqueueHostDelivery still runs. The chain survives. What's actually true is the narrower claim — the returned promise rejects, and the void-ed IIFE at L226-237 doesn't catch it, so a failing OS schedule call surfaces as an unhandled rejection warning. That's cosmetic-to-log-noise, not a dropped-notification or wedged-queue defect. A .catch(() => {}) is still worth adding, but the severity is Minor, not Major.

🟡 CLAIM (Minor): void-ed setNotificationChannelAsync — REAL, cosmetic

Accurate as written. Android channel creation can reject on some OEMs and the void discards it into an unhandled-rejection warning at startup. One-line fix, no behavioral risk.


Verdict

No regressions found. The two Majors are one residual gap and one overstated severity. The committed suite is green — 45 tests across 6 files, all passing.

The honest caveat on merge confidence isn't the bot findings, it's coverage: mobile/ is a separate package with its own vitest config, and this PR's CI ran only the verify job. I could not confirm from the check names that the mobile suite executes in CI at all. Someone should verify that before merging, because if it doesn't, these 45 tests are passing only on developer machines.

Recommendation: mergeable on the merits once (a) the mobile suite is confirmed to run in CI, and (b) ideally the two one-line .catch() additions go in, since they're free. The catch-up-window race deserves its own follow-up issue rather than being folded in here — the fix (claiming a chain slot before the request, or gating on a catchupPending promise) needs its own timeout-deadlock analysis, since the request can hang for 30s.

Verification was read-only against a pinned detached worktree; nothing was pushed and no PR was merged.

@nwparker

Copy link
Copy Markdown
Contributor Author

Correction to my previous comment: the mobile suite does run in CI

I flagged as an open question whether mobile/'s separate vitest package actually executes in CI. It does — I checked rather than leaving it hanging.

There are two distinct verify jobs on this PR, from different workflows, and the check-name collision is what made it ambiguous:

Mobile Checks / verify   SUCCESS   ← .github/workflows/mobile.yml
PR Checks / verify       SUCCESS   ← the desktop suite
Track Community PRs      SUCCESS

.github/workflows/mobile.yml triggers on paths: ['mobile/**'] — which is precisely this PR's diff — runs with working-directory: mobile, and executes pnpm test (plus pnpm lint). So the 45 mobile tests genuinely ran on this head, on CI, not just locally.

That removes the caveat from my verdict. With CI coverage confirmed and no regressions found against origin/main, the merge blocker I raised is gone. What remains is optional polish: the two one-line .catch(() => {}) additions, and a follow-up issue for the catch-up-window race (which, to restate, is narrower on this branch than on main).

@nwparker

Copy link
Copy Markdown
Contributor Author

The two .catch() additions, made concrete

I called these "free" in my verdict; here they are precisely, so nobody has to re-derive them. Both are the same one-line shape on a void (async () => {…})() whose body can reject.

1. mobile-notifications.ts L227-237 — the live-event continuation:

     void (async () => {
       await session.watermarkSeeded
       if (disposed) {
         return
       }
       await queueDelivery(
         liveEvent.type === 'notification' ? 'notification' : 'dismiss',
         liveEvent as NotificationEvent | DismissNotificationEvent
       )
-    })()
+    })().catch(() => {})

2. mobile-notifications.ts L190-205 — the ready continuation, same shape, where fetchMissed() is the rejecting call.

3. local-notification-scheduling.ts L74 — void Notifications.setNotificationChannelAsync(...) → append .catch(() => {}). Android channel creation rejects on some OEMs.

What these do and don't fix

To restate the correction from my earlier comment, since "add a catch" invites the assumption that something was broken without it: the delivery chain does not wedge today. enqueueHostDelivery already sheds the failure from the tail —

session.deliveryTail = run.catch(() => {})   // tail is protected
return run                                    // caller's copy still rejects

— and I verified a subsequent delivery still runs after a task rejects. So these three lines suppress unhandled-rejection warnings, nothing more. They're worth taking because they're zero-risk and quiet the logs, not because they close a defect. The bot's "one unguarded rejection path runs the whole delivery pipeline" framing overstates it.

I have not pushed these — this isn't my branch, and the change is small enough that whoever owns the PR should just take it directly.

Still the one open item worth a follow-up issue

The catch-up-window race (a live event persisting a watermark while getMissedSince is in flight outside the chain). Real, reproduced, but narrower on this branch than on origin/main, which has no chain at all and advances the watermark before awaiting showLocalNotification. It needs its own timeout-deadlock analysis before anyone claims a chain slot ahead of a request that can hang for 30s — which is exactly why it doesn't belong in this diff.

@nwparker

Copy link
Copy Markdown
Contributor Author

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 catchupPending promise." That closes the race, but I modelled it against the real enqueueHostDelivery semantics and it introduces a worse problem than the one it fixes.

Claiming the slot first means the in-flight request holds the chain. Every live delivery queues behind it:

enqueue(chain, async () => { await getMissedSince(); replay() })   // slot claimed first
enqueue(chain, async () => { deliverLive() })                      // arrives during the request
→ after 20ms: []          ← nothing delivered; live notification is BLOCKED
→ after release: ['replay', 'live']

Ordering becomes correct, but nothing reaches the user for as long as the request takes — and sendRequest waits up to 30 seconds. On a slow or flaky link that is a guaranteed half-minute of dead notifications on every reconnect, in exchange for closing a race that requires a process death inside a narrow window. That trade is bad in the common case.

Note this is precisely the rationale the PR already documents for keeping the request outside the chain:

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.

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 do

Not "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 saveWatermark until the replay drains, rather than blocking the delivery itself. The user still sees the notification immediately; only the persisted seq waits.

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 origin/main, which has no chain at all and persists the watermark before the notification is shown.

@nwparker
nwparker merged commit d547e27 into main Jul 28, 2026
3 checks passed
@nwparker
nwparker deleted the nwparker/fix-8591-reconnect-catchup branch July 28, 2026 00:18
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mobile reconnect is socket-only: missed notifications, stuck terminal driver, stale worktree list (#8129 #4500 #8498 #6784)

1 participant