Repository navigation
feat(mobile): receive native push notifications from paired desktops - #19951
Conversation
There was a problem hiding this comment.
Important
One iOS-only dismissal race: the overtaking-write guard in wasPushDismissed never observes writes made by the native PushDismissalLedger (the silent-push subscriber writes it directly), so a foreground alert decided concurrently with its dismissal can show and persist after the dismissal. Narrow, but it is a documented guarantee this code does not uphold on the platform where it matters most.
Reviewed changes
- Provider-push delivery — replaces the old socket-scheduled local notifications (deleted
local-notification-scheduling.ts/notification-reconnect-catchup.ts) with native APNs/FCM delivery through the already-landed gateway; socket traffic now only reconciles dismissals. - Registration & consent —
push-registration.tsbecomes the single consent owner, probing each host fornotifications.remote-push.v1, registering the native token per paired host, and persisting aregistered/pendingUnregisteroutbox in AsyncStorage. - Dismissal fencing — per-host/epoch/notificationId sequence watermarks in JS (
push-dismissal-watermarks.ts) and a native iOSPushDismissalLedger, with socket, provider-dismiss, background-task, and reconnect-reconciliation dismissal surfaces. - Settings & onboarding — reuses the shared
NotificationsScreenwith phone-only delivery controls (onlyWhenDesktopAway,sound,suppressWhileViewing); onboarding routes consent throughsetRemotePushEnabled. - Build config —
app.config.jsderives the iOSaps-environmententitlement fromORCA_IOS_APS_ENVIRONMENTso production entitlements match the production token; adds theexpo-notificationspatch,google-services.json, and the native dismissal module.
The core sequencing invariants (monotonicity, host/epoch/id isolation, boundary semantics) all check out across the three dismissal surfaces, and the mobile↔desktop fingerprint derivation matches deriveRelayHostId exactly. The registration state machine, consent-generation races, and host-removal restore path are handled carefully and well tested.
ℹ️ Nitpicks
- The dismissal ledger (JS
AsyncStorageand, more relevantly, the iOSUserDefaultssingle JSON blob) has no count cap inside its 24h retention, andnotificationIdis admitted up to 2048 chars. A busy multi-host session could inflate theUserDefaultsvalue well past what that store is meant to hold and rewrite frequently; a high count cap (well above the removed 512) or a tighternotificationIdbound would keep the worst case sane. use-remote-push-capable-hosts.tsresolvedcan settle on "Pair an updated desktop" when a host that never answered its capability probe disconnects while another host has already answered "no push" — the disconnected host's support is silently dropped. Minor UX edge case, since a reconnect re-probes.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| const precedingWrites = writes | ||
| await precedingWrites | ||
| const dismissed = await readDismissal(payload, key) | ||
| if (dismissed || writes === precedingWrites) { |
There was a problem hiding this comment.
On iOS this overtaking-write guard never fires for the dismiss path that actually writes the ledger. OrcaNotificationDismissalSubscriber calls PushDismissalLedger.shared.remember directly on a silent dismiss push, bypassing the JS writes chain, so writes === precedingWrites always holds and a negative snapshot taken mid-dismiss is returned as-is — the foreground banner shows and persists until a later reconnect reconciliation catches it. The dedicated race test only drives a JS-queued native write, so this direct-write path is uncovered.
Technical details
# iOS dismissal re-queue gap
## Affected sites
- mobile/src/notifications/push-dismissal-watermarks.ts:96-103 — `wasPushDismissed` re-checks only when `writes !== precedingWrites`, i.e. only for writes queued through `queueDismissalOperation` (JS `rememberPushDismissal`).
- mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swift:13 — the silent-dismiss handler writes `PushDismissalLedger.shared.remember(fence)` directly, never advancing the JS `writes` chain. This is the primary iOS dismiss path.
- mobile/src/notifications/push-receive.ts:73-109 — `shouldSuppressForegroundPush` awaits `wasPushDismissed` as its final gate before showing the banner.
## Required outcome
- A foreground alert whose dismissal lands during the `shouldSuppressForegroundPush` await chain must be suppressed (or, failing that, the race and its residual banner must be acknowledged as accepted behavior with the guarantee comment narrowed).
## Suggested approach (optional)
- Have the native subscriber surface its write to JS (e.g. an emitted event that bumps `writes`), or re-read the native ledger after a microtask/short delay before returning a negative `wasPushDismissed` on iOS, so a mid-decision native write is observed.
## Open questions for the human (optional)
- Is the residual banner (persisting until the next reconnect reconciliation) acceptable for this narrow foreground window, or should it be closed?|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe mobile app now supports remote push registration, foreground filtering, notification routing, dismissal reconciliation, pane-aware navigation, and delivery preferences. The change adds native iOS dismissal storage, Android Firebase configuration, Expo notification setup, push-token renewal, host capability probing, and registration lifecycle handling. It removes local desktop notification scheduling and watermark-based reconnect catch-up. Tests, workflows, and documentation cover the new push behavior. Priority: ➖ Normal Merge Risk: 🔵 Low · up to Push consent behavior is covered, but a socket-banner regression and some registration test gaps could evade automated validation. These are bounded validation risks rather than a demonstrated user-facing failure. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives detailed scope, rationale, testing results, limitations, and linked issue context. However, it does not follow the required template because the required section headings and checklist are missing, and it provides no Visual Proof attachment or explicit Resolution Rewrite the description using all required template sections. Add the linked issue in the required
✨ Finishing Touches 💡 1📝 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: 1
🧹 Nitpick comments (3)
mobile/src/notifications/push-registration-cancellation.test.ts (1)
91-93: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winFour settle points in this file use fixed real-timer sleeps instead of a condition-bounded wait. The shared root cause is that
await new Promise((resolve) => setTimeout(resolve, n))guesses how long the reconcile chain takes. A guessed duration that is too short fails a positive assertion on slow CI, and a guessed duration that is too short before a negative assertion lets the test pass vacuously. Every other settle point in the same file already usesvi.waitFor.
mobile/src/notifications/push-registration-cancellation.test.ts#L91-L93: replace the 10 ms sleep withvi.waitForwrapping bothrecords()assertions, so the wait ends when cleanup completes.mobile/src/notifications/push-registration-cancellation.test.ts#L104-L107: replace the 10 ms sleep withvi.waitForon the condition that makes the negative meaningful, for example wait untilgetDevicePushTokenhas settled, then assertregisterPushwas not sent.mobile/src/notifications/push-registration-cancellation.test.ts#L202-L203: drain the reconcile chain to quiescence before assertingsendRequestwas not called, or state the one-macrotask assumption in a comment asmobile/src/notifications/push-registration.test.tsLines 50-54 does.mobile/src/notifications/push-registration-cancellation.test.ts#L224-L225: apply the same drain as the previous site before thenot.toHaveBeenCalled()assertion.mobile/src/notifications/notification-opt-in-gate.test.ts (1)
54-54: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winAdd a rejection test for
setRemotePushEnabled.
shouldPresentNotificationOptIn()catches rejections from both the adopt and denied paths and returnsfalse. Add a test for a rejected consent write to preserve the startup guarantee.💚 Proposed additional case
it('does not block startup when storage or permission checks fail', async () => { vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: false }) await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) vi.mocked(getNotificationPermissionState).mockRejectedValue(new Error('unavailable')) await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) }) + + it('does not block startup when adopting system authorization fails to persist', async () => { + vi.mocked(readPushNotificationsPreference).mockResolvedValue({ value: null, loaded: true }) + vi.mocked(getNotificationPermissionState).mockResolvedValue({ + granted: true, + status: 'granted', + canAskAgain: true, + authorizationReflectsUserChoice: true + }) + vi.mocked(setRemotePushEnabled).mockRejectedValue(new Error('consent write failed')) + + await expect(shouldPresentNotificationOptIn()).resolves.toBe(false) + })mobile/src/notifications/push-registration.test.ts (1)
416-419: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winStart token sync and invoke its AppState callback instead of attaching twice.
startPushTokenSync()installs theAppStatelistener that callsreconcileAllHosts()when the app becomes active. This test never starts token sync, so the secondattachPushRegistrationtests a different trigger. Start token sync, capture its callback, invoke it after setting the state to'active', and stop the sync after the test.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 29dd422a-6868-48ef-ae75-f1aaf2faee0b
⛔ Files ignored due to path filters (2)
mobile/assets/notification-icon.pngis excluded by!**/*.pngmobile/pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (85)
.github/workflows/mobile-ios-release.yml.github/workflows/mobile.ymldocs/site/content/docs/mobile.mdxdocs/site/content/docs/notifications.mdxmobile/app.config.jsmobile/app.jsonmobile/app/_layout.tsxmobile/app/mobile-onboarding.tsxmobile/app/notifications.tsxmobile/google-services.jsonmobile/modules/orca-notification-dismissal/expo-module.config.jsonmobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissal.podspecmobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalModule.swiftmobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swiftmobile/modules/orca-notification-dismissal/ios/PushDismissalLedger.swiftmobile/modules/orca-notification-dismissal/package.jsonmobile/modules/orca-notification-dismissal/tests/PushDismissalLedgerChecks.swiftmobile/package.jsonmobile/patches/expo-notifications@55.0.27.patchmobile/pnpm-workspace.yamlmobile/src/home/use-mobile-home-host-connections.tsmobile/src/notifications/NotificationDeliverySection.test.tsxmobile/src/notifications/NotificationDeliverySection.tsxmobile/src/notifications/desktop-notification-channel.test.tsmobile/src/notifications/desktop-notification-channel.tsmobile/src/notifications/desktop-notification-events.tsmobile/src/notifications/expo-native-token-retry.test.tsmobile/src/notifications/local-notification-scheduling.tsmobile/src/notifications/mobile-notifications.test.tsmobile/src/notifications/mobile-notifications.tsmobile/src/notifications/mobile-push-lease-renewal.test.tsmobile/src/notifications/mobile-push-lease-renewal.tsmobile/src/notifications/native-notification-data.test.tsmobile/src/notifications/native-notification-data.tsmobile/src/notifications/native-push-dismissal.ios.tsmobile/src/notifications/native-push-dismissal.test.tsmobile/src/notifications/native-push-dismissal.tsmobile/src/notifications/notification-catchup-failure-quarantine.test.tsmobile/src/notifications/notification-consent-ownership.test.tsmobile/src/notifications/notification-delivery-ordering.test.tsmobile/src/notifications/notification-delivery-preferences.test.tsmobile/src/notifications/notification-delivery-preferences.tsmobile/src/notifications/notification-opt-in-gate.test.tsmobile/src/notifications/notification-opt-in-gate.tsmobile/src/notifications/notification-reconnect-catchup.tsmobile/src/notifications/notification-reconnect-teardown.test.tsmobile/src/notifications/notification-routing.test.tsmobile/src/notifications/notification-routing.tsmobile/src/notifications/notification-viewing-policy.tsmobile/src/notifications/notification-watermark-seed-race.test.tsmobile/src/notifications/push-background-dismissal.test.tsmobile/src/notifications/push-background-dismissal.tsmobile/src/notifications/push-dismissal-native-races.test.tsmobile/src/notifications/push-dismissal-reconciliation.test.tsmobile/src/notifications/push-dismissal-reconciliation.tsmobile/src/notifications/push-dismissal-watermarks.test.tsmobile/src/notifications/push-dismissal-watermarks.tsmobile/src/notifications/push-host-fingerprint.test.tsmobile/src/notifications/push-host-fingerprint.tsmobile/src/notifications/push-notification-identity.test.tsmobile/src/notifications/push-notification-identity.tsmobile/src/notifications/push-payload.tsmobile/src/notifications/push-preference-update.test.tsmobile/src/notifications/push-receive.test.tsmobile/src/notifications/push-receive.tsmobile/src/notifications/push-registration-cancellation.test.tsmobile/src/notifications/push-registration.test.tsmobile/src/notifications/push-registration.tsmobile/src/notifications/push-socket-dismissal.test.tsmobile/src/notifications/push-socket-dismissal.tsmobile/src/notifications/push-token.test.tsmobile/src/notifications/push-token.tsmobile/src/notifications/push-tray-dismissal.test.tsmobile/src/notifications/push-tray-dismissal.tsmobile/src/notifications/use-remote-push-capable-hosts.test.tsxmobile/src/notifications/use-remote-push-capable-hosts.tsmobile/src/onboarding/mobile-onboarding-screen.test.tsmobile/src/settings/native-notification-delivery-settings.test.tsxmobile/src/settings/native-notification-delivery-settings.tsxmobile/src/settings/native-notification-settings-operations.tsmobile/src/settings/notification-settings-screen.tsxmobile/src/storage/preferences.test.tsmobile/src/storage/preferences.tsmobile/src/transport/host-removal-lifecycle.test.tsmobile/src/transport/host-removal-lifecycle.ts
💤 Files with no reviewable changes (8)
- mobile/src/notifications/notification-reconnect-catchup.ts
- mobile/src/notifications/notification-watermark-seed-race.test.ts
- mobile/src/notifications/local-notification-scheduling.ts
- mobile/src/notifications/notification-delivery-ordering.test.ts
- mobile/src/notifications/notification-reconnect-teardown.test.ts
- mobile/src/notifications/notification-catchup-failure-quarantine.test.ts
- mobile/src/notifications/notification-routing.ts
- mobile/src/notifications/notification-routing.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
| it('never presents an OS banner for socket alert or replay events', async () => { | ||
| const rpc = client() | ||
| subscribeToDesktopNotifications(rpc as never, 'host-1') | ||
| rpc.emit({ type: 'ready', subscriptionId: 'sub-1', epoch: 'epoch-1' }) | ||
| rpc.emit({ | ||
| type: 'notification', | ||
| notificationId: 'agent-1', | ||
| title: 'Needs input', | ||
| body: 'Reply', | ||
| source: 'agent-task-complete' | ||
| }) | ||
| await Promise.resolve() | ||
| expect(requestNotificationCatchup).toHaveBeenCalledWith(rpc, 'host-1', expect.any(Function)) | ||
| expect(dismissHostPushNotification).not.toHaveBeenCalled() | ||
| }) |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Assert scheduleNotificationAsync directly.
The socket path has no scheduling call, and its reachable notification APIs only inspect or dismiss presented notifications. Add the explicit mock and import so a future scheduling call can fail this test.
♻️ Proposed assertion on the notification API
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import * as Notifications from 'expo-notifications'
import { subscribeToDesktopNotifications } from './mobile-notifications'
@@
+vi.mock('expo-notifications', () => ({
+ scheduleNotificationAsync: vi.fn(async () => 'scheduled-1')
+}))
vi.mock('./push-socket-dismissal', () => ({
@@
await Promise.resolve()
+ expect(Notifications.scheduleNotificationAsync).not.toHaveBeenCalled()
expect(requestNotificationCatchup).toHaveBeenCalledWith(rpc, 'host-1', expect.any(Function))There was a problem hiding this comment.
Important
No new issues in this delta — the retry-on-failure capability probe is correct and well tested — but the iOS-only dismissal race flagged in the prior review is still open and untouched by this commit, so I'm not approving yet.
Reviewed changes
- Retried push-capability probes —
push-registration.tsnow drivesstatus.getthrough the sharedstartRuntimeCapabilityProbe(already used byuse-remote-push-capable-hosts) instead of a one-shot read, retrying with backoff until a response lands and stopping the probe on re-attach, disconnect, and host removal.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Important
The three follow-up commits are correct and close the probe-lifecycle gaps cleanly, but approval is still held on the previously-flagged iOS dismissal race, which none of these commits touch.
Reviewed changes
- Cancelled retired probes —
attachPushRegistration, host removal, and the removal-restore path now stop and clearcapabilityProbeStop; the detach callback also cancels a probe on the restored state object when the original client disconnects. - Ignored stale reconciliations — the probe start and its completion callback now both guard with
isCurrent(), so a host removed or replaced mid-reconcile can no longer start a probe or setsupportedon a stale state. - Typed the probe at its boundary —
startRuntimeCapabilityProbenow takesPick<RpcClient, 'sendRequest'>instead of the full client.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Too many files changed for review (104 files, 100 file limit). Bypass the limit by tagging |
There was a problem hiding this comment.
Important
No new issues in this delta — the pane-routing path is correct end to end — but the iOS-only dismissal race flagged in the prior review is still open and untouched by this commit, so I'm not approving yet.
Reviewed changes
- Routed push taps to the originating pane — the originating
paneKeynow flows from the desktop dispatcher through the gateway's APNs/FCM payload to mobile, which parses it and selects the exact terminal/split pane instead of the first tab; closed or invalid panes fall back to workspace selection.
The matching logic is sound: the desktop builds paneKey as makePaneKey(parentTabId, leafId), so mobile's (parentTabId ?? id) === tabId && leafId === leafId comparison resolves the correct terminal tab, and the agent-session branch is a safe no-op fallback since agent notifications carry the parent terminal's pane key. The paneKey param is consumed unconditionally so a later tab snapshot can't steal selection, and the terminalsLoaded gate plus setParams({ paneKey: '' }) prevent a stale tab list from firing the switch early or twice.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one minor observation in the nitpicks below.
Reviewed changes
- Required explicit push-service consent on upgrade — renamed the persisted consent key from
orca:pushNotificationsEnabledtoorca:pushServiceNotificationsEnabled, so every existing user (including those who had enabled the old socket notifications) is asked for fresh push-service consent instead of silently inheriting the prior choice; no production code reads the orphaned old key. - Simplified the opt-in gate —
shouldPresentNotificationOptInnow reads only the persisted preference, dropping the OS-permission consultation and the auto-persist/auto-register side effects, leavingsetRemotePushEnabledas the single registration path. - Added onboarding disclosure — the notifications step now states delivery is via Orca's push service and surfaces the default three-minute desktop-away policy.
ℹ️ Nitpicks
- Dropping the gate's
denied/!canAskAgainbranch means an iOS user who permanently denied notification permission now sees the onboarding opt-in, and tapping "Enable" silently recordsfalse—ensureNotificationPermissions()returnsfalsewithout prompting whencanAskAgainis false, andchooseNotificationsadvances with no error or explanation. The removed branch previously skipped the opt-in for exactly this population (with a comment naming Settings as the recovery path); consider restoring that skip or surfacing a "could not enable" message in the onboarding error state.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/notifications/mobile-notifications.test.ts (1)
33-57: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that socket paths never schedule an OS notification.
subscribeToDesktopNotificationsignores socketnotificationevents, and catch-up only reconciles dismissals. These tests mock both helpers, so a futureNotifications.scheduleNotificationAsynccall can pass. Mock that API and assert it is not called for both the socket event and theready/catch-up path. Add the same assertion to the catch-up tests whilerequestNotificationCatchupremains mocked here.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: ba33ca25-226f-444c-9910-5e9fc8a3758c
📒 Files selected for processing (10)
mobile/src/notifications/notification-consent-ownership.test.tsmobile/src/notifications/notification-opt-in-gate.test.tsmobile/src/notifications/notification-opt-in-gate.tsmobile/src/notifications/push-preference-update.test.tsmobile/src/notifications/push-receive.test.tsmobile/src/notifications/push-registration-cancellation.test.tsmobile/src/onboarding/MobileOnboardingPage.tsxmobile/src/onboarding/mobile-onboarding-styles.tsmobile/src/storage/preferences.test.tsmobile/src/storage/preferences.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.

Paired phones can receive agent notifications while Orca is closed. Explicit mobile consent registers the native APNs/FCM token through the paired desktop and the already-landed push gateway. This is the final mobile portion of #19204, following merged cloud #19912 and desktop #19935.
New mobile requires a push-capable desktop for phone banners. Older desktops remain usable, but the new mobile app does not fall back to socket-created OS notifications. Settings explain when an updated desktop is needed. Pairing alone does not opt in; the enable control discloses Orca's push service.
Validation: mobile frozen install, typecheck, lint and formatting pass; 542 test files / 4,357 tests pass (3 skipped), plus three new settings tests. Native Swift checks pass for restart, sequence/host isolation, expiry and more than 512 dismissals. Signed iOS simulator and physical-device builds succeed; Android production bundle export succeeds. On the fresh simulator build, injected remote pushes create two native tray entries; dismissal removes only the older sequence, preserves the newer alert, and remains effective after app restart without suppressing another host. Settings render correctly with enabled controls and with all three controls visible but greyed out when disabled. Fresh physical APNs delivery remains unverified: iPad installation is blocked by the locked device (CoreDevice 10003). Simulator injection does not prove APNs background wakeup. Physical Android testing is deferred. The pane-routing follow-up includes a gateway payload change, deployed through the push-only production workflow; no Terraform changes.
Changed-line breakdown (additions / deletions):
Lockfile churn comes from regeneration with the repository's pinned pnpm 12, including peer-context keys. The new runtime dependency is
expo-task-manager; existing dependency versions are retained.Notification-tap correction: preserve the desktop's optional
paneKeythrough the gateway's APNs/FCM payload and mobile route. Once the workspace tabs load, select the originating terminal/split pane through the existing mobile tab action; closed panes keep normal workspace selection. This adds a small desktop/cloud follow-up to the mobile PR. The gateway must be deployed before using the updated desktop because the send schema rejects unknown fields. Existing workspace-only notifications remain valid.Validation for this correction: full mobile suite 544 files / 4,365 tests passed (3 skipped), desktop fan-out/dispatcher 17 tests passed, gateway 139 tests passed (4 skipped); mobile, desktop-node, and gateway typechecks passed. Standalone Android build succeeded. Gateway deployment succeeded (Actions run 34556955227); authenticated production schema probe accepted paneKey. The standalone Orca Notification Android APK is installed on the connected Samsung. The matching desktop ad hoc build is publishing in run 34557053665. A real provider-delivered tap with the newly built desktop has not yet been exercised.