Skip to content

fix(push): send one push per phone token when a phone has several pairing rows - #52203

Merged
nwparker merged 2 commits into
stablyai:mainfrom
zifengjiang:fix/push-dedupe-by-token
Nov 29, 2026
Merged

nwparker merged 2 commits into
stablyai:mainfrom
zifengjiang:fix/push-dedupe-by-token

Conversation

@zifengjiang

@zifengjiang zifengjiang commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

If you paired your phone with the same computer more than once (for example over your home network and again over Tailscale), Orca kept a separate pairing for each, and every notification reached your phone once per pairing. Your phone buzzed twice for the same thing. Now Orca sees that those pairings belong to one phone and sends each notification once, using the phone's latest settings.

What Changed

Before: Each pairing creates its own device row. The phone registers its push token on every host row it connects to, so two rows end up with gateway registrations for the same native token and share one tokenDigest. PushDispatcher built one push target per row, and the gateway's /v1/send queues one delivery per registration ID without deduping by token. Alerts, dismissals and badge pushes all went out twice. Burst cooldown slots were keyed per deviceId, so the two rows also kept separate cooldowns.

After:

  • New livePushTargets() in src/main/runtime/push/push-dispatcher.ts makes one O(N) pass. It drops expired registrations and keeps one target per tokenDigest: the one with the latest expiresAt, which is the newest registration and carries the phone's current filter. Rows without a digest (older registrations) are all kept, as before.
  • Alerts, dismissals, the cross-host coverage ask and badge pushes (PushBadgeSync.sendChangedCount) all go through livePushTargets(). Dedupe runs first, so the newest row's filter decides.
  • Burst slots are held per phone through pushBurstHolder(): digest:<tokenDigest>, or device:<deviceId> for a row without a digest. A phone's rows share one cooldown even when the newest row changes. coveredDigests looks up the same digest: key and returns each digest it was asked about at most once.
  • DesktopPushService.flushUnregisterOutbox now calls badgeSync.request(). Badges reach only the newest row, so when that row is removed the remaining row gets the current unread count and doesn't keep a stale one at the gateway.
  • PushDispatcherOptions.client is narrowed to Pick<PushGatewayClient, 'send'>, because the dispatcher only calls send. This lets the test skip a cast.

Why

The original PR deduped when a registration was written: it cleared other rows with the same digest and queued their gateway IDs for deletion. This version dedupes when a push is sent instead, for three reasons:

  • Mobile registers on every connected host each time it attaches or a preference changes. A newest-wins rule at the registry would flip-flop, adding a gateway register plus a delete on every foreground.
  • Mobile sends unregister only to the host being removed. Unpairing the row that registered last would leave the other pairing with no registration, so the phone would get nothing until it next attached.
  • Write-time dedupe also needs a disk refresh, outbox ordering and restore-on-removal handling. Send-time dedupe needs none of that.

With this approach, registry data and gateway registrations are unchanged. Unpairing either row still leaves the phone reachable through the other. An older duplicate row goes away when its 7-day lease expires.

Linked Issue

Fixes #52202

Original fix and investigation by @zifengjiang in #52203.

Visual Proof

N/A. Nothing in the desktop UI changes. The visible effect is on a phone's lock screen and needs a real paired iPhone plus the push gateway, so I checked the behavior with tests that drive the real PushDispatcher against a fake gateway client (see Testing).

Testing

  • Reproduced on main with a verifier suite that drives the real PushDispatcher through a fake gateway client. A phone with two rows sharing a token digest got two alerts (r-lan and r-ts), two dismissals, and a coverage ask of ['X','X']. An older stale filter still delivered. On main, 6 tests fail: the committed regression test plus cases A (one alert, sent to the newest row), B (re-pairing between two bursts still gives one push), C (the coverage ask lists each digest once), D (the coverage answer comes back once) and F (the newest row's sound:false wins). On this branch, all 31 tests pass.

  • New push-dispatcher.test.ts and push-badge-sync.test.ts cases both fail on main and pass here. The badge test checks that the newest row gets the one badge, and that after that row is removed and request() runs, the count moves to the remaining row. push-burst-slots.test.ts is updated for the new holder keys.

  • vitest run src/main/runtime/push: 7 files, 23 tests pass.

  • Clean on all 7 touched files: oxlint, oxfmt --check, anti-slop oxlint, code-quality native plugins, ast-grep, and the changed-code quality gate.

  • Platforms: unit tests on macOS. The code is platform-neutral main-process logic. I did not test end to end with a real phone, which needs hardware.

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • Every added test fails without this change and avoids the test anti-patterns

Performance

None that matters. planSend runs once per notification event in the main process, and badge sync runs at most once per settle of 1 s or more. Neither is a hot path. There is no new I/O, subprocess work or polling. The extra request() on unregister arms at most one debounced timer, and no renderer or store code changes.

Microbenchmark, time per enqueue (sync part):

Case Main This PR
N=3 2.1-2.3 us 2.0-2.4 us
N=200 71.6-72.2 us 67.6-68.5 us
N=200, every phone paired twice 138.9 us, 200 sends 62.4 us, 100 sends

Badge target selection takes 3.0 us on main and 4.8 us here at N=200 with all phones unique. Every case is far below the 16 ms budget.

Risk

Level: Low

  • Alerts follow only the newest row's filter. That matches how the phone works, since its preferences are global.
  • If the gateway has lost only the newest registration, the phone can miss one alert until it re-registers. This is unlikely.
  • If a phone has both a legacy row without a digest and a new row, it still gets two pushes. Main behaves the same way.
  • Saved data, the gateway protocol and mobile are unchanged, so mixed versions work. A plain revert backs this out completely.

Review

Three reviews approved this with no blocking issues: correctness, breakage-hunting and verification. Their non-blocking notes are fixed here: badge dedupe, prefixed slot keys, and the reserve() doc comment.

Agent skill upstream boundary

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

Ensure no issues in: Security, Cross-platform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • I stated the risk: what could break, for whom, and how to back it out
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@zifengjiang

Copy link
Copy Markdown
Contributor Author

The workflow runs for this PR are waiting for maintainer approval (action_required — first contribution from this fork), so CI has not started yet. Could someone approve the runs? Local pnpm check:changed (format, oxlint, node/web/cli/bot-evals typechecks, targeted tests) passes; full suite and build are left to CI.

@greptile-apps

greptile-apps Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5 · The PR appears safe to merge; no blocking issues remain.RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no blocking issues remain.

Summary

Sends one push per phone token, using the newest live registration and its settings.

  • Each phone token gets pushes through its newest live pairing row.
  • Pairing rows for one phone share a push burst cooldown.
  • Badge updates follow the newest pairing row and move when it is removed.

Reviews (5) · Last reviewed commit: "test(push): use a fixed clock in the dis..." · Reviewed by Greptile

@coderabbitai

coderabbitai Bot commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

Push dispatch and badge synchronization now use live registrations, with duplicate token digests represented by the registration with the latest expiry. Burst-slot reservations use a holder derived from the token digest when available. flushUnregisterOutbox also requests badge synchronization before the outbox drain.

Severity of issue fixed: Medium

Merge Risk: Moderate · up to 5d52c

The change stops duplicate push notifications for a phone with several pairing rows. Earlier review concerns about registration displacement and cleanup, which could remove a working notification route, are still open and unverified at this head. Two smaller edge cases also remain, a lost retry and a stale badge count. Resolve or explicitly accept these before merging.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title names the main change: the push sender now sends one push per phone token when a phone has several pairing rows. The changeset adds send-time dedupe through livePushTargets, pushBurstHolder,…
Description check Passed The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #52202), Visual Proof (N/A with reason), Testing with platforms, Performance with a stated …
Linked Issues check Passed [#52202] requires one push per notification event when one phone has two or more pairing rows. It also requires one notification to remain after either pairing is removed.

The current head uses send-…
Out of Scope Changes check Passed All changed areas connect to one objective: one push per event for a phone with duplicate pairing rows.
- push-dispatcher.ts: livePushTargets() and the narrowed PushDispatcherOptions.client type (Pick…
Full details: Title check

Explanation

The title names the main change: the push sender now sends one push per phone token when a phone has several pairing rows. The changeset adds send-time dedupe through livePushTargets, pushBurstHolder, and related updates, so the title matches the primary fix. It is specific and follows conventional commit style.

Full details: Description check

Explanation

The description follows the repository template closely. It has ELI5, What Changed, Why, Linked Issue (Fixes #52202), Visual Proof (N/A with reason), Testing with platforms, Performance with a stated reason and benchmarks, Risk with level and revert path, AI Disclosure left as a template comment, and the checklists. The Linked Issue section is filled in. The Review section and Agent skill boundary are filled. The Risk section explains what could break and how to back it out. The Testing section reports unit tests on macOS and states that end-to-end testing with a real phone was not done. Minor gaps: the local manual testing box is unchecked, the AI Disclosure section is empty, and the final pnpm checks box is unchecked, which the author explains as CI coverage.

Full details: Linked Issues check

Explanation

[#52202] requires one push per notification event when one phone has two or more pairing rows. It also requires one notification to remain after either pairing is removed.

The current head uses send-time dedupe only. It does not change registry writes or gateway registrations.

  • push-dispatcher.ts: livePushTargets() drops missing and expired registrations. It keeps one target per tokenDigest, the one with the latest expiresAt. Rows without a digest are all kept. Alerts, dismissals, and the coverage ask use these targets, so one gateway send occurs per phone token.
  • push-badge-sync.ts: badge targets use livePushTargets(), so the newest row receives the single badge push.
  • push-burst-slots.ts: pushBurstHolder() keys slots by digest:<tokenDigest>, or device:<deviceId> when no digest exists. Rows for one phone share one cooldown.
  • desktop-push-service.ts: flushUnregisterOutbox() calls badgeSync.request(). After the newest row is removed, the remaining row receives the current unread count.
  • Removing either pairing leaves the other row registered at the gateway. The dispatcher then sends one push for that phone.
  • Tests: push-dispatcher.test.ts covers duplicate digests, legacy rows without digests, and a watch token. push-badge-sync.test.ts covers one badge send for duplicate digests and the remaining row after removal. push-burst-slots.test.ts is updated for holder keys.

Limits: the whole-PR text diff was not read. This verdict relies on the change summary, the PR description, and the listed tests. The previous assessment described registration-write dedupe (planPushRegistration, setPushRegistration, push-unregister-outbox). The current change summary does not list those files. That earlier evidence is therefore not used for this verdict.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to one objective: one push per event for a phone with duplicate pairing rows.

  • push-dispatcher.ts: livePushTargets() and the narrowed PushDispatcherOptions.client type (Pick<PushGatewayClient, 'send'>). The narrowed type supports the test double and does not change behavior.
  • push-burst-slots.ts and push-burst-slots.test.ts: holder keys by digest so duplicate rows share one cooldown. This directly supports the dedupe objective.
  • push-badge-sync.ts and push-badge-sync.test.ts: badge targets reuse livePushTargets(), so badge pushes also collapse per digest.
  • desktop-push-service.ts: the two-line badge request on unregister flush. It keeps the remaining row's badge count current after the newest row is removed. This is adjacent to the objective and is justified in the PR description.
  • push-dispatcher.test.ts: covers the new dedupe behavior.

No pairing, credential, mobile client, registry schema, or gateway protocol change appears in the change summary. The PR description states these are unchanged.

Limits: the whole-PR text diff was not read. This verdict relies on the change summary and the PR description.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 187a3940-f691-4363-8244-2e94d2328ffc
Commits

Reviewing files that changed from the base of the PR and between afae678 and 5d52c14.

Files selected for processing: 1

  • src/main/runtime/push/push-dispatcher.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@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: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: d6c66934-1f75-4cf8-9d33-49060dc9bb71
Commits

Reviewing files that changed from the base of the PR and between d0aeea8 and 5f2b72f.

Files selected for processing: 8

  • src/main/runtime/push/push-burst-slots.test.ts
  • src/main/runtime/push/push-burst-slots.ts
  • src/main/runtime/push/push-dispatcher.ts
  • src/main/runtime/rpc/server/pairing/device-push-registration.ts
  • src/main/runtime/rpc/server/pairing/device-registry-push-dedupe.test.ts
  • src/main/runtime/rpc/server/pairing/device-registry.ts
  • src/main/runtime/rpc/server/runtime-rpc-lifecycle.ts
  • src/main/runtime/rpc/server/runtime-rpc-mobile-devices.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

if (this.getDevice(deviceId)?.scope !== 'mobile') {
return false
}
const plan = planPushRegistration(this.devices, deviceId, registration)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied in 491865a. setPushRegistration now calls this.adoptExternalEdits({ fresh: true }) before the scope guard and planning, so a row removed on disk by another process fails the guard and nothing is cleared or queued. The residual window between the refresh and the save merge is covered by the restore path: if the merge drops the target row, the displaced registrations are put back with a second save. Test: "clears nothing when another writer removed this row before the call".

@zifengjiang
zifengjiang force-pushed the fix/push-dedupe-by-token branch 2 times, most recently from 9409f39 to 491865a Compare November 29, 2026 02:59
if (this.getDevice(deviceId)?.scope !== 'mobile') {
return false
}
const plan = planPushRegistration(this.devices, deviceId, registration)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied in 491865a. setPushRegistration now calls this.adoptExternalEdits({ fresh: true }) before the scope guard and planning, so a row removed on disk by another process fails the guard and nothing is cleared or queued. The residual window between the refresh and the save merge is covered by the restore path: if the merge drops the target row, the displaced registrations are put back with a second save. Test: "clears nothing when another writer removed this row before the call".

@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: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 6a85c22f-04ba-428a-b494-a708912a73ed
Commits

Reviewing files that changed from the base of the PR and between 5f2b72f and 9409f39.

Files selected for processing: 6

  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/mobile-push-registration.ts
  • src/main/runtime/push/push-unregister-outbox.ts
  • src/main/runtime/rpc/server/pairing/device-push-registration.ts
  • src/main/runtime/rpc/server/pairing/device-registry-push-dedupe.test.ts
  • src/main/runtime/rpc/server/pairing/device-registry.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

return false
}
const plan = planPushRegistration(this.devices, deviceId, registration)
beforeReplace?.(plan.displaced)

@coderabbitai coderabbitai Bot Nov 29, 2026 •

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.

Major · Data Integrity & Integration · Heavy lift

Cancel displacement deletes when the displacement rolls back.

If another writer removes the target during saving, Line 211 restores the surviving registration. Its deletion remains in the outbox.

The normal drain preserves that registration. However, the surviving pairing's next registration attempt deletes its queued gateway ID before calling registerDevice. If that gateway registration fails, the surviving pairing retains a local registration whose gateway record has been deleted.

Reconcile the queued deletes when displacement does not commit, including restoration and save failures. Keep the deletes for successful displacements.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in 743098a. beforeReplace now returns an undo: PushUnregisterOutbox.enqueueDisplaced queues the deletions and hands back a callback that removes exactly the items it added. When the save merge drops the target row, the registry restores the displaced registrations and then calls that undo, so no stale delete survives for the surviving pairing to consume on its next registration attempt. The undo is only invoked after the restore save succeeds; a failed restore keeps the deletes queued. The restore test now drives a real outbox and asserts pending() is empty afterwards, and fails if the undo is removed.

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.

Analysis chain

Script executed:

#!/bin/bash
printf 'HEAD: '; git rev-parse HEAD
for f in \
  src/main/runtime/rpc/server/pairing/device-registry.ts \
  src/main/runtime/rpc/server/pairing/device-registry-push-dedupe.test.ts \
  src/main/runtime/rpc/server/pairing/device-push-registration.ts \
  src/main/runtime/push/push-unregister-outbox.ts \
  src/main/runtime/push/desktop-push-service.ts \
  src/main/runtime/push/push-unregister-outbox.test.ts; do
  printf '\n--- OUTLINE %s ---\n' "$f"
  ast-grep outline "$f" --items all 2>&1 | head -130
done
printf '\n--- REGISTRY, OUTBOX, TESTS: RELEVANT MATCHES ---\n'
rg -n -C 7 'setPushRegistration\(|enqueueDisplaced\(|beforeReplace|restorePushRegistrations\(|registerDevice\(|pending\(\)|save failure|save fails|save throws|throw' \
  src/main/runtime/rpc/server/pairing/device-registry.ts \
  src/main/runtime/rpc/server/pairing/device-registry-push-dedupe.test.ts \
  src/main/runtime/rpc/server/pairing/device-push-registration.ts \
  src/main/runtime/push/push-unregister-outbox.ts \
  src/main/runtime/push/desktop-push-service.ts \
  src/main/runtime/push/push-unregister-outbox.test.ts
printf '\n--- REGISTRY SAVE IMPLEMENTATIONS ---\n'
rg -n -C 6 --type ts '(protected|private|public)?\s*save\s*\(|\bsave\([^)]*DeviceEntry' src/main/runtime/rpc/server/pairing

Length of output: 65423


Script executed:

#!/bin/bash
printf '%s\n' '--- DeviceRegistryStore outline and save ---'
ast-grep outline src/main/runtime/rpc/server/pairing/device-registry-store.ts --items all
cat -n src/main/runtime/rpc/server/pairing/device-registry-store.ts | sed -n '108,155p'
printf '%s\n' '--- PushUnregisterOutbox enqueue and undo ---'
cat -n src/main/runtime/push/push-unregister-outbox.ts | sed -n '32,100p'
printf '%s\n' '--- DesktopPushService registration and cleanup ---'
cat -n src/main/runtime/push/desktop-push-service.ts | sed -n '120,220p'
cat -n src/main/runtime/push/desktop-push-service.ts | sed -n '265,330p'
printf '%s\n' '--- Registry writer declarations ---'
rg -n -C 5 --type ts 'class .*Registry.*Writer|write\(before|writer\.write|new .*Writer' src/main/runtime/rpc/server/pairing/device-registry-store.ts src/main/runtime/rpc/server/pairing

Length of output: 20382


@zifengjiang The undo addresses the target-row removal case. The test also checks that the outbox is empty after restoration.

One part of the finding remains: if the initial registry save fails before committing, Line 207 leaves the displacement deletes queued. A later registration attempt can delete the surviving gateway registration before registerDevice fails.

Also, enqueueDisplaced can receive an existing item from enqueue, so its undo can remove a delete it did not add.

Please handle these failure and coalescing cases, and add tests for them. I’m not marking the finding as addressed yet.


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

You are interacting with an AI system.

@zifengjiang
zifengjiang force-pushed the fix/push-dedupe-by-token branch from 491865a to 743098a Compare November 29, 2026 03:07

@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: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0861c4ed-e470-4514-8658-e87ab1b75805
Commits

Reviewing files that changed from the base of the PR and between 9409f39 and 743098a.

Files selected for processing: 5

  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/push-unregister-outbox.ts
  • src/main/runtime/rpc/server/pairing/device-push-registration.ts
  • src/main/runtime/rpc/server/pairing/device-registry-push-dedupe.test.ts
  • src/main/runtime/rpc/server/pairing/device-registry.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

input.deviceId,
mobilePushRegistration(input, registrationId),
// Durable before the save below lets the other rows forget their ids.
this.outbox.enqueueDisplaced.bind(this.outbox)

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.

Minor · Stability & Availability · Quick win

Drop a device's queued delete for the registration ID it stores.

When two rows for the same phone overlap, the losing row can queue a delete for an ID that the winning row later stores. If that early delete fails, the item stays queued. The next registration's pre-cleanup then deletes the ID from the gateway before calling registerDevice. If that registration fails, the local row keeps an ID the gateway no longer has.

After the registration is stored, remove this device's queued deletes for the same registrationId. Deletes for other IDs remain queued.

Suggested fix

--- "a/src/main/runtime/push/desktop-push-service.ts"
+++ "b/src/main/runtime/push/desktop-push-service.ts"
@@ -268,16 +268,24 @@
     input: MobilePushRegisterInput,
     registrationId: string
   ): RegisterStorageFailure | null {
     try {
       const stored = this.registry.setPushRegistration(
         input.deviceId,
         mobilePushRegistration(input, registrationId),
         // Durable before the save below lets the other rows forget their ids.
         this.outbox.enqueueDisplaced.bind(this.outbox)
       )
+      if (stored) {
+        // The row now owns this gateway ID, so a queued delete for it is stale.
+        for (const item of this.outbox
+          .pending()
+          .filter((entry) => entry.deviceId === input.deviceId && entry.registrationId === registrationId)) {
+          this.outbox.remove(item.reqId)
+        }
+      }
       // False means the device was removed or left mobile scope while the gateway
       // call was in flight.
       return stored ? null : 'not_mobile'
     } catch (error) {
       console.warn('[push] Failed to persist a push registration:', error)
       return 'registration_storage_failed'

const stored = this.devices.some((device) => device.deviceId === deviceId)
if (!stored && plan.displaced.length > 0) {
// Another writer removed this row mid-save; the other pairing keeps the phone's push route.
this.devices = this.save(restorePushRegistrations(this.devices, plan.displaced))

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.

Major · Stability & Availability · Heavy lift

Preserve recovery data when the restoration save fails.

If the first save drops the target, it has already committed the removal of the surviving pairing's registration. If this restoration save throws, this.devices still contains that cleared state.

storeRegistration then returns a storage failure. The caller queues the new gateway registration and flushes the outbox. Because neither registration is attached, the drain can delete both gateway registrations. A failed replacement therefore removes the previously working notification route.

Persist recoverable rollback data before the first save, or make target validation and displacement atomic. Cancelling queued deletes alone cannot restore the registration already removed from the registry. Keep cleanup queued for successful displacements.

Based on learnings, an authoritative recovery copy must remain after a failed transfer; this outbox retains only IDs.

Source: Learnings

@zifengjiang

Copy link
Copy Markdown
Contributor Author

Clean obsolete PR work failed on 743098a with a GitHub API 500 from GET /actions/concurrency_groups/pr-checks-52203 (the job only cancels superseded runs). It is unrelated to the diff and cannot be re-run without write access; the next push, or a maintainer re-run, replaces it. CodeRabbit and Greptile both reviewed 743098a and passed.

…ring rows

Pairing the same phone twice with one host (for example over LAN and
then Tailscale) leaves a device row per pairing, each with its own
gateway registration for the same native token. The dispatcher pushed
every row, so the phone showed each alert twice.

livePushTargets() now drops expired registrations and keeps one target
per token digest, the newest one, which carries the phone's current
filter. Alerts, dismissals, the cross-host coverage ask and badge pushes
all use it. Burst slots are held per phone (digest:<d>, or device:<id>
for a legacy row without a digest), so a phone's rows share one
cooldown. Removing a registration re-runs badge sync so the remaining
row gets the current count.

Registrations stay on every row, so unpairing one still leaves the
phone reachable through the other.

Fixes stablyai#52202

Co-authored-by: jeffjiang <[email protected]>
@nwparker
nwparker force-pushed the fix/push-dedupe-by-token branch from 743098a to afae678 Compare November 29, 2026 03:28
@nwparker nwparker changed the title fix(push): dedupe registrations by token digest across pairing rows fix(push): send one push per phone token when a phone has several pairing rows Nov 29, 2026

@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: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 7ce265c7-d152-4dce-bd71-319827347837
Commits

Reviewing files that changed from the base of the PR and between 743098a and afae678.

Files selected for processing: 7

  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/push-badge-sync.test.ts
  • src/main/runtime/push/push-badge-sync.ts
  • src/main/runtime/push/push-burst-slots.test.ts
  • src/main/runtime/push/push-burst-slots.ts
  • src/main/runtime/push/push-dispatcher.test.ts
  • src/main/runtime/push/push-dispatcher.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

? [{ deviceId, registration }]
: []
)
const live = livePushTargets(this.registry.listDevices(), now).filter(

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.

Minor · Functional Correctness · Quick win

Request a badge pass when a dead result removes the selected registration.

sendChangedCount does not schedule another pass after dropDeadPushRegistrations removes a dead row. The dead path leaves retry false. The removal path in DeviceRegistry.setPushRegistration(deviceId, null) requests no badge work. As a result, when the newest row for a phone is removed, the older same-digest row is not sent the current badge count in that pass. It stays stale until a later badge trigger.

Keep the existing exclusion of the older row from this pass. After a dead registration is removed, the badge flow must run again while a live replacement row still lacks the current count. The source does not establish a specific mechanism for this. A retry or a new badge request could satisfy it, so choose the mechanism that keeps the retry bounded and avoids a loop on re-registered rows.

}
const targets = this.registry.listDevices().flatMap((device) => {
const registration = device.pushRegistration
const targets = livePushTargets(this.registry.listDevices(), Date.now()).flatMap((target) => {

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.

Minor · Functional Correctness · Quick win

Retain a retry target when the selected pairing is removed.

If two rows share a digest, this selects only the later-expiring row. If its send returns unreachable, deliver schedules a retry with only that row. If the user removes that pairing before the retry, Lines 227-238 discard the target and send nothing. The other pairing remains live, but this notification is lost. Previously, the retry retained both rows.

When the original target is no longer current, resolve an eligible replacement with the same digest for the retry. Keep the current-registration guard and do not add a fallback after a queued result.

The test-no-wall-clock rule rejects Date.now() in tests.
@nwparker
nwparker merged commit 06fb16c into stablyai:main Nov 29, 2026
56 checks passed
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.

[Bug]: Same phone paired twice with one Mac receives every push notification twice

2 participants