Skip to content

feat: mobile background push notifications — pending user validation - #19204

Closed
Jinwoo-H wants to merge 33 commits into
mainfrom
feat/mobile-push-user-validation
Closed

Jinwoo-H wants to merge 33 commits into
mainfrom
feat/mobile-push-user-validation

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 107 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​9799 $\color{#cf222e}{\Huge{\mathbf{−}}}$​2061 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7738
Prod 187 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​10042 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1438 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​8604

ELI5

Receive agent alerts on your phone when you are away from Orca on desktop, and remove stale alerts when their work is handled. Mobile follows desktop alert categories; Apple/Google push is the sole source of phone OS banners.

Ready for owner review after validation. Do not merge until the owner finishes hands-on testing and explicitly approves.

What Changed

  • Away-only delivery starts after three minutes without keyboard/mouse activity, or when the connected desktop is locked. A focused pane left open while idle does not acknowledge its alerts. Normal remote work measures activity on the connected desktop client.
  • Phone controls cover enablement, away-only delivery, sound, and suppression for the workspace open on mobile. Categories always follow desktop settings, including while the phone sleeps. Registrations pause after seven days without foreground mobile use.
  • Each event keeps its own content, destination and dismissal identity. iOS groups by desktop; Android uses individual replacement tags with platform-owned grouping. Custom burst summaries and the three-second batching delay are removed.
  • The encrypted socket updates app state and carries dismissal/reconciliation traffic. It never creates ordinary OS banners, including during reconnect or without push connectivity.
  • The gateway durably accepts work, deduplication and quota accounting together. Leased workers retry transient failures within the original five-minute deadline. Allowances remain 300 logical alerts and separately 300 dismissals per host per rolling 15 minutes, counted once across phones.
  • Native iOS dismissal and reconnect tray reconciliation retain host/epoch/sequence fences. Every delivered push has one identity. No summary compatibility, batch splitting, or old-worker storage workarounds remain; this unpublished feature does not preserve earlier test summaries.

Why

One category policy, one banner delivery route, and one event per delivery remove overlapping scheduling/replay machinery while retaining durable delivery and timely stale-alert cleanup.

Linked Issue

Follow-up to the revert in #19203; original feature tracking #8129.

Visual Proof

Previous category controls (earlier simulator capture):

Before: independent mobile notification categories

Updated settings (current iOS QA simulator):

After: desktop categories with phone presentation controls

Testing

  • Current iOS simulator: settings rendering and old-preference compatibility; socket events create no banners or push claims; duplicate and ID-less bell suppression; viewing suppression; paired-host validation; persisted native socket dismissal; dismissal during a delayed preference read.
  • Two injected remote iOS notifications appeared independently with the same host grouping key; dismissing one preserved the other. Temporary tray fixtures cleaned.
  • Full mobile suite: 4,292 passed, 3 skipped. Post-merge desktop push/lifecycle/away-policy: 122 passed; earlier RPC/fanout: 10 passed. Full gateway suite against isolated PostgreSQL 16: 134 passed. Post-merge root/mobile typechecks, gateway typecheck, and changed-code quality passed. Final focused mobile notification suite: 113 passed. Reliability/workflow suites: 99 passed plus 24 push workflow tests; 113-gate manifest valid.
  • Regression coverage updated for independent delivery, individual queue persistence, quotas, deduplication, retry/deadline/dismissal behavior, authoritative desktop categories, and native-push-only presentation.
  • Final review follow-ups resolved; main synced and conflicts resolved. Previous head fc9a7c22a9a passed 28 CI checks. The summary-compatibility removal is locally verified; CI is running on f1c83e2b3e0.

Simulator injection and controlled native-ledger tests verify application behavior; they do not prove live APNs delivery or background wakeup. Android physical testing remains deferred at the owner's request. Earlier physical-iPad/provider evidence belongs to deployed source e53b95e26a25af674c6c9129dd458b2e2713cd92, not these simplifications.

Review

Three Codex implementation lanes and independent cross-reviews cover gateway, desktop policy/settings, and mobile delivery. Coordinator independently runs integrated tests and simulator checks. Review covers queue fairness, ID-less bell identity, fail-closed foreground safety checks, and individual dismissal. Legacy summary branches and tests have been removed at the owner’s request. The first simplification commit removes 4,400 net lines; removing unpublished summary compatibility removes another 423 net lines, including tests and documentation.

Agent skill upstream boundary

  • Not applicable: no upstream skill-installer implementation or artifacts copied.

Notes

These review and simplification changes are not deployed to production. Keep the existing dedicated 2-vCPU HA push database; no schema migration is needed. Before deploying this incompatible queue encoding, stop all old gateway revisions and clear unpublished push delivery fixtures plus old summary notifications on test devices. Preserve registrations and unrelated data; no production cleanup or deployment has been performed in this pass. Before production rollout, the dedicated deployment identity/foundation grant in https://github.com/stablyai/orca-cloud/pull/480 and PRODUCTION_GCP_PUSH_DEPLOY_WORKLOAD_IDENTITY_PROVIDER / PRODUCTION_GCP_PUSH_DEPLOY_SERVICE_ACCOUNT must be activated as previously documented. The deployment workflow must be available on main.

Apple background delivery is best effort, so persisted reconnect recovery remains necessary. FCM notification messages may collapse offline; individual tags do not make the tray an event log, and socket replay does not recreate missed banners. Local-only connectivity still updates app state but cannot supply OS banners without provider delivery. Autonomous headless event generation and multi-desktop presence aggregation remain outside scope.

Checklist

  • Small PR: this feature spans desktop, mobile and cloud; scope remains substantial.
  • Explained final behavior and rationale.
  • Before/after settings screenshots attached.
  • Cross-platform, SSH/remote and mixed-version impact considered.
  • Independent reviews complete; CI on f1c83e2b3e0 pending.

Owner hands-on acceptance and explicit merge approval remain open.

@Jinwoo-H
Jinwoo-H marked this pull request as ready for review September 7, 2026 20:57
@greptile-apps

greptile-apps Bot commented Sep 7, 2026 •

Copy link
Copy Markdown

Too many files changed for review (294 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@pullfrog pullfrog 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.

ℹ️ One minor suggestion inline — the gateway's graceful shutdown never actually drains its delivery queue.

Reviewed changes

A large, carefully-tested restoration of mobile background push: a standalone push gateway (cloud/apps/push) plus its wire contract (cloud/packages/push-contract), the desktop host's client/session/challenge machinery, per-device notification preferences and dismissal-fence persistence, and the mobile React-Native/native-iOS delivery and reconciliation paths.

  • Push gateway — Hono service with host challenge/auth (X25519 sealed-box proof), per-host sessions, a device registry, a durable PostgreSQL/SQLite store for quota + coalescing + lease-based delivery, APNs/HTTP2 and FCM senders, per-IP/per-host rate limits, readiness/health, a blue/green deploy workflow with rollback, and a shared Cloud SQL connection-budget slot.
  • Wire contract — push-contract zod schemas and the host-proof transcript, a postgres-schema package extracted from the relay, and a shared challenge-envelope module factored out of relay-host-proof.
  • Desktop host — DesktopPushService (registration, durable unregister outbox, dispatch fan-out), PushGatewayClient/PushGatewaySession (challenge handshake, 401 re-auth, refusal caching), notification preferences/filters, desktop-away detection, and dismissal-fence persistence.
  • Renderer — notification dispatch now offers attention-only completions to main for independent mobile delivery; auto-ack of viewed agents is gated on real presence (away state).
  • Mobile + iOS native — push registration, token handoff, lease renewal, background dismissal via a native subscriber module (orca-notification-dismissal) with a persisted ledger, and catch-up reconciliation over the existing RPC.
  • Operational — Terraform for the gateway and its dedicated database, deploy/verify workflows, runbooks, and the Cloud SQL connection-budget accounting.

I verified the additive RPC field changes and the notifications.subscribe params change from null to an optional object are backward-compatible: parseRpcRequestParams coerces a missing/null params to {}, which the new optional schema accepts, so older clients are unaffected.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread cloud/apps/push/src/index.ts Resolved

@pullfrog pullfrog 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.

✅ No new issues found in the merge delta.

Reviewed changes

5d4faa5efa is a merge of main plus integration-conflict resolution; no new PR-authored behavior. The only PR-touching deltas are:

  • Shared postgres-schema — applyPostgresSchema now treats ALTER TABLE … ADD CONSTRAINT hitting Postgres 42710 (constraint already present) as already-applied rather than retrying a terminal error, matching main's relay constraint-addition needs.
  • Relay-status refactor pulled in from main — the main-process-relay-status.ts extraction (getDesktopRelayStatus / publishDesktopRelayStatus) and its wiring in main-process-runtime-launch.ts / main-process-state.ts, reconciled with the push startup added earlier.
  • Test/ops bookkeeping — workflow census counts (24→25), push-deploy.yml added to the retirement-identity boundary list, and the headless-linux-server.md fetch-audit table.

I confirmed the merge did not alter cloud/apps/push/src/index.ts, so the graceful-shutdown flush note from the prior review still applies unchanged.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

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
📝 Walkthrough

Walkthrough

This PR adds a standalone Cloud Run push gateway service (orca-cloud-push) with its own database, host-challenge authentication, APNs/FCM delivery, coalescing, and a durable retry worker. It adds a shared push-contract package and a shared postgres-schema package. It adds Terraform infrastructure, a production deploy workflow, and connection-budget updates. The desktop main process gains push registration, dispatch, and RPC methods. The mobile app gains push registration, delivery preferences, foreground and background receive handling, and tray dismissal reconciliation.

Merge Risk: 🟠 High · up to 35864

The push stack still has unresolved risks affecting secure transport, notification correctness, registration and dismissal recovery, Cloud SQL rollout capacity, and production deployment recovery. Hands-on validation and corrective changes are still required before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 175 functions across 119 files. (6 skippe… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly identifies the main change as mobile background push notifications and accurately notes that user validation remains pending.
Description check ✅ Passed The description covers the required sections, explains the behavior and rationale, includes linked issue references, visual proof, testing details, scope notes, and pending approval status.
Full details: Docstring Coverage

Explanation

Docstring coverage is 17.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 175 functions across 119 files. (6 skipped: 6 unsupported.)

✨ Finishing Touches 💡 1
📝 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: 11

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
mobile/src/storage/preferences.ts (1)

37-37: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Handle malformed stored preference records.

JSON.parse() throws for malformed legacy and current records. The rejection propagates through refreshSettings() and allowsLocalNotification() instead of using DEFAULT_NOTIFICATION_DELIVERY. Wrap both parsing paths in the same fallback that returns the default preferences.

Proposed fix
 export async function loadNotificationDeliveryPreferences(): Promise<NotificationDeliveryPreferences> {
-  const raw = await AsyncStorage.getItem(KEY)
+  try {
+    const raw = await AsyncStorage.getItem(KEY)
+    // Keep the existing load and migration logic here.
+  } catch {
+    return { ...DEFAULT_NOTIFICATION_DELIVERY }
+  }
-  // existing load and migration logic
 }

Also applies to: 49-49

🟡 Minor comments (15)
cloud/dev/scripts/relay-cloud-sql-connection-budget.mjs-80-80 (1)

80-80: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Count the tagged push candidate once in the rollout overlap.

configuredMaximum already includes pushDraw for the serving revision. The tagged candidate adds one more pushDraw. Line 80 counts the serving revision again, so the reported pushCandidate is four connections too high. This can reject a valid capacity configuration when the push rollout becomes the maximum overlap.

  • cloud/dev/scripts/relay-cloud-sql-connection-budget.mjs#L80-L80: set pushCandidate to retainedDirectorRollback + pushDraw.
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs#L25-L25: expect pushCandidate to equal 19.
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs#L89-L91: expect pushCandidate to equal 19.
docs/reference/headless-linux-server.md-394-394 (1)

394-394: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Fix the wording in this troubleshooting note.

Change “which serve mode never starts” to “because serve mode never starts” or “where serve mode never starts.” The current phrase has incorrect subject-verb agreement.

Source: Linters/SAST tools

docs/reference/mobile-push-contract.md-191-203 (1)

191-203: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Document the kind-specific dismissal payload contract.

The implementation sends dismissals as APNs background payloads with content-available: 1 and FCM data-only payloads. This section currently documents only the visible alert shape. Define separate payloads for kind: "alert" and kind: "dismiss" so future implementations do not add notification, aps.alert, or sound fields to dismissal messages.

cloud/docs/push-gateway.md-342-344 (1)

342-344: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Correct the cutover state guarantee.

Line 344 requires preservation of device registrations and durable queue state. cloud/docs/push-database-cutover.md states that the current initial activation is a state reset and transfers neither. State that this runbook discards current state, or document a migration procedure that preserves it.

src/main/runtime/push/desktop-push-service.ts-167-167 (1)

167-167: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Flush the unregister outbox when the registry update fails.

If DeviceRegistry.setPushRegistration() throws on Line 167, this method exits before it starts the queued gateway deletion. The registration can remain active until restart, after the user disables push. Start flushUnregisterOutbox() in a finally block after outbox.enqueue().

Proposed fix
     this.outbox.enqueue({ registrationId, deviceId })
-    this.registry.setPushRegistration(deviceId, null)
-    void this.flushUnregisterOutbox()
+    try {
+      this.registry.setPushRegistration(deviceId, null)
+    } finally {
+      void this.flushUnregisterOutbox()
+    }
     return { unregistered: true }
src/main/ipc/notification-options.ts-71-78 (1)

71-78: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Localize the new notification status text.

The new raw English strings bypass the notification localization path. Use intent-named localization IDs for "needs input", "working", and "stopped".

Based on learnings: “For newly added user-facing strings in stablyai/orca TypeScript and TSX files, follow config/i18n-translation-source.md: use intent-named localization IDs with named interpolation placeholders.”

Source: Learnings

src/shared/mobile-notification-policy.ts-27-27 (1)

27-27: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Require a confirmed away state.

When onlyWhenDesktopAway is true and event.desktopAway is undefined, this condition permits the notification. This bypasses the selected delivery preference whenever an event lacks presence data. Reject the event unless desktopAway === true.

-  if (filter.onlyWhenDesktopAway && event.desktopAway === false) {
+  if (filter.onlyWhenDesktopAway && event.desktopAway !== true) {
src/shared/cloud-service-url.ts-15-15 (1)

15-15: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Restrict the loopback exception to HTTP.

Line 15 accepts ftp://localhost, file://localhost, and other non-HTTPS schemes when allowLoopbackHttp is true. This contradicts the helper contract and allows invalid endpoint configuration to pass validation.

Proposed fix
-    if (parsed.protocol !== 'https:' && !(loopbackHost && allowLoopbackHttp)) {
+    if (
+      parsed.protocol !== 'https:' &&
+      !(parsed.protocol === 'http:' && loopbackHost && allowLoopbackHttp)
+    ) {
src/main/runtime/push/push-gateway-client.ts-108-108 (1)

108-108: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Handle HTTP 404 before the failure return.

Response.ok is false for HTTP 404. Line 108 returns { deleted: false, retryable: true } before line 113 can classify the missing registration as deleted. The unregister outbox will retain and retry registrations that the gateway already removed.

Proposed fix
-    if (!response.ok) {
+    if (!response.ok && response.response.status !== 404) {
       return { deleted: false, retryable: true }
     }
mobile/src/notifications/push-socket-dismissal.ts-16-16 (1)

16-16: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve ID-only dismissal for legacy events.

Line 16 always passes event as a fence. dismissPresentedPushNotification rejects a matching tray entry when that fence lacks notificationEpoch or notificationSeq. The caller in mobile/src/notifications/local-notification-scheduling.ts:195-204 only requires notificationId, so a legacy dismissal event cannot clear a remote push that was shown while the app was closed.

Pass undefined as the fence when the event does not contain both fence fields. Add a regression test for an event with only notificationId.

Proposed fix
-  await dismissPresentedPushNotification(event.notificationId, fingerprint, event)
+  const fence =
+    event.notificationEpoch && event.notificationSeq !== undefined ? event : undefined
+  await dismissPresentedPushNotification(event.notificationId, fingerprint, fence)
mobile/src/notifications/mobile-notifications.ts-87-91 (1)

87-91: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Prevent a waiting show handoff from blocking dismissals.

queueDelivery serializes notifications and dismissals. While waitForSocketPushHandoff waits for app activation, a later dismissal cannot call dismissLocalNotification, so an OS notification can remain visible. Let dismissals bypass a pending show handoff and add a regression test for this inactive-app sequence.

mobile/src/notifications/desktop-notification-channel.ts-15-15 (1)

15-15: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Await channel creation before push registration. ensureDesktopNotificationChannel() starts setNotificationChannelAsync() without returning its promise. The connected callback can call attachPushRegistration() before Android creates orca-desktop, so Android may drop the first push that targets this channel. Return and await channel creation before registration, and add a delayed-creation regression test.

cloud/apps/push/src/push-send-idempotency.test.ts-26-26 (1)

26-26: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Coerce the COUNT(*) result before comparison.

toBe(1) requires a JS number. The Postgres driver returns COUNT(*) as a string, so this assertion fails when the suite runs against Postgres. The store code already guards this, for example Number(count?.total ?? 0) in durable-push-store.ts at Line 56.

💚 Proposed fix
-  expect((await h.database.query('SELECT COUNT(*) AS count FROM push_events'))[0]?.count).toBe(1)
+  expect(
+    Number((await h.database.query('SELECT COUNT(*) AS count FROM push_events'))[0]?.count)
+  ).toBe(1)
cloud/apps/push/src/push-server.ts-99-99 (1)

99-99: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Remove the unused coalescer timer options.

DurablePushWorker accepts only store, dispatcher, and now. Its start() method uses setInterval directly, so setTimer, clearTimer, and PushCoalescerTimerFactory have no effect. Remove these options from PushServerOptions and the test harness.

cloud/apps/push/src/client-ip-rate-limit.ts-33-33 (1)

33-33: 🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟡 Minor | ⚡ Quick win

Other (CWE-807)

Reachability: External · Exploitability: Difficult

Do not key the limiter on x-real-ip.

x-real-ip is caller-controlled unless a front end explicitly overwrites it. When trustedProxyHops exceeds the available x-forwarded-for depth, rotating this header creates a fresh bucket for each request and bypasses throttling. Return UNKNOWN_CLIENT_IP directly for an untrusted depth. Update the test that currently expects the x-real-ip fallback.

🛡️ Proposed fix
   const client = hops[hops.length - 1 - trustedProxyHops]
-  if (client) return client
-  return context.req.header('x-real-ip')?.trim() || UNKNOWN_CLIENT_IP
+  // No trusted appender at the configured depth: use the shared bucket rather
+  // than a header the caller can rotate.
+  return client ?? UNKNOWN_CLIENT_IP
 }
🧹 Nitpick comments (5)
mobile/src/notifications/push-registration.ts (1)

91-93: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Bound the capability probe like the other two requests.

sendRegister and sendUnregister both pass timeoutMs and failWhenDisconnected: true. status.get passes no options, so it falls back to the client default. The probe runs inside the serialized per-host chain, so a slow or silent host delays every later reconcile for that host, including token-roll and filter updates.

♻️ Proposed change
-    const response = await client.sendRequest('status.get')
+    const response = await client.sendRequest('status.get', undefined, {
+      timeoutMs: REQUEST_TIMEOUT_MS,
+      failWhenDisconnected: true
+    })
cloud/apps/push/src/apns-client.test.ts (1)

184-191: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the background headers on the dismissal path.

The test proves that a dismissal omits apns-collapse-id. It does not prove the two headers that decide whether Apple wakes the app silently or shows a banner. apns-client.ts sets apns-push-type: 'background' and apns-priority: '5' for kind === 'dismiss'. A regression to alert and '10' would show a spurious banner on every dismissal, and this test would still pass.

♻️ Proposed assertions
-  expect(fake.requests[0]?.headers).not.toHaveProperty('apns-collapse-id')
+  expect(fake.requests[0]?.headers).not.toHaveProperty('apns-collapse-id')
+  expect(fake.requests[0]?.headers).toMatchObject({
+    'apns-push-type': 'background',
+    'apns-priority': '5'
+  })
+  expect(JSON.parse(fake.requests[0]!.body).aps).toEqual({ 'content-available': 1 })
cloud/apps/push/src/durable-push-worker.ts (1)

38-43: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

flush can return without doing forced work.

run returns early when another run is in flight. It awaits that run and ignores the new force and registrationId values. The background timer at Line 22 starts a non-forced run every second. If a tick is in flight, flush(registrationId) and flushAll() await that non-forced run, which skips batches whose due_at is still in the future. The caller then observes no delivery.

Queue a follow-up run when the in-flight run is not forced.

♻️ Proposed change
   private async run(registrationId: string | undefined, force: boolean): Promise<void> {
     if (this.running) {
-      await this.running
-      return
+      const inFlight = this.running
+      await inFlight.catch(() => {})
+      if (!force) return
+      if (this.running) return this.run(registrationId, force)
     }
     if (this.stopped) return
cloud/apps/push/src/push-observability.ts (1)

1-18: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Derive the counter union from COUNTER_NAMES.

The union and the array repeat the same 17 names. A name added to the union but not to the array still type-checks. record() accepts it, consume() omits it from the snapshot, and the map reset discards the value, so the metric is lost with no error.

♻️ Proposed refactor
-type PushCounterName =
-  | 'ip_rate_limited'
-  | 'request_error'
-  ...
-const COUNTER_NAMES: PushCounterName[] = [
+const COUNTER_NAMES = [
   'ip_rate_limited',
   'request_error',
   ...
-]
+] as const
+
+type PushCounterName = (typeof COUNTER_NAMES)[number]
cloud/apps/push/src/config.ts (1)

12-12: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Normalize blank environment values before applying defaults.

Zod 3.25.76 applies .default() only to undefined. loadPushConfig passes environment values directly to EnvSchema.parse, so blank PORT, ORCA_PUSH_APNS_TOPIC, ORCA_PUSH_FCM_PROJECT_ID, ORCA_PUSH_DATA_DIR, and ORCA_PUSH_DATABASE_POOL_MAX fail validation. Blank ORCA_PUSH_COALESCE_MS is coerced to 0, bypassing its configured default.

The existing blank-value preprocessing handles only the optional text fields. Extend it to every defaulted schema, including ORCA_PUSH_DATA_DIR, and to optional ORCA_PUSH_DATABASE_POOL_MAX. Add regression coverage for blank values.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: e0217493-d8d2-45eb-868a-edce033bb235

📥 Commits

Reviewing files that changed from the base of the PR and between d0506bf and 5d4faa5.

⛔ Files ignored due to path filters (3)
  • cloud/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • mobile/assets/notification-icon.png is excluded by !**/*.png
  • mobile/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (258)
  • .github/workflows/cloud-verify.yml
  • .github/workflows/mobile-ios-release.yml
  • .gitignore
  • cloud/README.md
  • cloud/apps/push/Dockerfile
  • cloud/apps/push/package.json
  • cloud/apps/push/src/apns-authentication-token.ts
  • cloud/apps/push/src/apns-client.test.ts
  • cloud/apps/push/src/apns-client.ts
  • cloud/apps/push/src/apns-http2-transport.ts
  • cloud/apps/push/src/apns-session-replacement.test.ts
  • cloud/apps/push/src/apns-stream-response.test.ts
  • cloud/apps/push/src/apns-stream-response.ts
  • cloud/apps/push/src/canonical-base64.ts
  • cloud/apps/push/src/client-ip-rate-limit.test.ts
  • cloud/apps/push/src/client-ip-rate-limit.ts
  • cloud/apps/push/src/coalescer.test.ts
  • cloud/apps/push/src/coalescer.ts
  • cloud/apps/push/src/config.test.ts
  • cloud/apps/push/src/config.ts
  • cloud/apps/push/src/desktop-host-proof-interop.test.ts
  • cloud/apps/push/src/device-registry-store.test.ts
  • cloud/apps/push/src/device-registry-store.ts
  • cloud/apps/push/src/durable-push-schema.ts
  • cloud/apps/push/src/durable-push-store.test.ts
  • cloud/apps/push/src/durable-push-store.ts
  • cloud/apps/push/src/durable-push-worker.ts
  • cloud/apps/push/src/fcm-access-token.ts
  • cloud/apps/push/src/fcm-client.test.ts
  • cloud/apps/push/src/fcm-client.ts
  • cloud/apps/push/src/host-challenge-answering.test-fixture.ts
  • cloud/apps/push/src/host-challenge-store.test.ts
  • cloud/apps/push/src/host-challenge-store.ts
  • cloud/apps/push/src/host-fingerprint.ts
  • cloud/apps/push/src/host-session-store.test.ts
  • cloud/apps/push/src/host-session-store.ts
  • cloud/apps/push/src/index.ts
  • cloud/apps/push/src/provider-retry-delay.ts
  • cloud/apps/push/src/push-auth-admission.ts
  • cloud/apps/push/src/push-database-postgres-startup.test.ts
  • cloud/apps/push/src/push-database.ts
  • cloud/apps/push/src/push-delivery-lifecycle.test.ts
  • cloud/apps/push/src/push-delivery-message.ts
  • cloud/apps/push/src/push-dismissal-provider.test.ts
  • cloud/apps/push/src/push-dispatcher.ts
  • cloud/apps/push/src/push-notification-sound.test.ts
  • cloud/apps/push/src/push-observability.ts
  • cloud/apps/push/src/push-provider-outcome.ts
  • cloud/apps/push/src/push-queued-dismissal.ts
  • cloud/apps/push/src/push-readiness.ts
  • cloud/apps/push/src/push-request-drain.ts
  • cloud/apps/push/src/push-schema.ts
  • cloud/apps/push/src/push-send-idempotency.test.ts
  • cloud/apps/push/src/push-server-auth.test.ts
  • cloud/apps/push/src/push-server-harness.test-fixture.ts
  • cloud/apps/push/src/push-server-limits.test.ts
  • cloud/apps/push/src/push-server-send.test.ts
  • cloud/apps/push/src/push-server.ts
  • cloud/apps/push/src/push-session-concurrency.test.ts
  • cloud/apps/push/src/push-session-schema.ts
  • cloud/apps/push/src/push-summary-members.test.ts
  • cloud/apps/push/src/push-summary-members.ts
  • cloud/apps/push/tsconfig.build.json
  • cloud/apps/push/tsconfig.json
  • cloud/apps/push/vitest.config.ts
  • cloud/apps/relay/Dockerfile
  • cloud/apps/relay/package.json
  • cloud/apps/relay/src/postgres-schema-startup.ts
  • cloud/dev/fixtures/terraform-root-partition/families.json
  • cloud/dev/scripts/push-gateway-recovery.test.mjs
  • cloud/dev/scripts/push-gateway-workflow.test.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs
  • cloud/dev/scripts/workload-identity-attribute-conditions.test.mjs
  • cloud/docs/push-database-cutover.md
  • cloud/docs/push-gateway.md
  • cloud/docs/relay-workflows.md
  • cloud/infra/terraform/environments/production.tfvars
  • cloud/infra/terraform/environments/staging.tfvars
  • cloud/infra/terraform/outputs.tf
  • cloud/infra/terraform/push-dedicated-database.tf
  • cloud/infra/terraform/push-gateway.tf
  • cloud/infra/terraform/relay-github-actions.tf
  • cloud/infra/terraform/variables.tf
  • cloud/package.json
  • cloud/packages/postgres-schema/package.json
  • cloud/packages/postgres-schema/src/index.ts
  • cloud/packages/postgres-schema/tsconfig.build.json
  • cloud/packages/postgres-schema/tsconfig.json
  • cloud/packages/push-contract/package.json
  • cloud/packages/push-contract/src/apns-token-length.test.ts
  • cloud/packages/push-contract/src/contract.test.ts
  • cloud/packages/push-contract/src/device-registration-messages.ts
  • cloud/packages/push-contract/src/host-auth-messages.ts
  • cloud/packages/push-contract/src/index.ts
  • cloud/packages/push-contract/src/notification-identity-limits.test.ts
  • cloud/packages/push-contract/src/push-host-proof-transcript.test.ts
  • cloud/packages/push-contract/src/push-host-proof-transcript.ts
  • cloud/packages/push-contract/src/push-host-proof-vector.json
  • cloud/packages/push-contract/src/push-limits.ts
  • cloud/packages/push-contract/src/send-messages.test.ts
  • cloud/packages/push-contract/src/send-messages.ts
  • cloud/packages/push-contract/src/wire-scalars.ts
  • cloud/packages/push-contract/tsconfig.build.json
  • cloud/packages/push-contract/tsconfig.json
  • config/reliability-gates.jsonc
  • docs/reference/headless-linux-server.md
  • docs/reference/mobile-push-contract.md
  • docs/site/content/docs/mobile.mdx
  • docs/site/content/docs/notifications.mdx
  • mobile/app.config.js
  • mobile/app.json
  • mobile/app/_layout.tsx
  • mobile/app/notifications.tsx
  • mobile/google-services.json
  • mobile/modules/orca-notification-dismissal/expo-module.config.json
  • mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissal.podspec
  • mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalModule.swift
  • mobile/modules/orca-notification-dismissal/ios/OrcaNotificationDismissalSubscriber.swift
  • mobile/modules/orca-notification-dismissal/ios/PushDismissalLedger.swift
  • mobile/modules/orca-notification-dismissal/package.json
  • mobile/modules/orca-notification-dismissal/tests/PushDismissalLedgerChecks.swift
  • mobile/package.json
  • mobile/src/home/use-mobile-home-host-connections.ts
  • mobile/src/notifications/NotificationDeliverySection.test.tsx
  • mobile/src/notifications/NotificationDeliverySection.tsx
  • mobile/src/notifications/desktop-notification-channel.test.ts
  • mobile/src/notifications/desktop-notification-channel.ts
  • mobile/src/notifications/local-notification-scheduling.ts
  • mobile/src/notifications/mobile-notifications.test.ts
  • mobile/src/notifications/mobile-notifications.ts
  • mobile/src/notifications/mobile-push-lease-renewal.test.ts
  • mobile/src/notifications/mobile-push-lease-renewal.ts
  • mobile/src/notifications/native-notification-data.test.ts
  • mobile/src/notifications/native-notification-data.ts
  • mobile/src/notifications/native-push-dismissal.native.ts
  • mobile/src/notifications/native-push-dismissal.ts
  • mobile/src/notifications/notification-catchup-failure-quarantine.test.ts
  • mobile/src/notifications/notification-consent-events.ts
  • mobile/src/notifications/notification-delivery-ordering.test.ts
  • mobile/src/notifications/notification-delivery-preferences.test.ts
  • mobile/src/notifications/notification-delivery-preferences.ts
  • mobile/src/notifications/notification-local-delivery.test.ts
  • mobile/src/notifications/notification-local-dismissal.test.ts
  • mobile/src/notifications/notification-reconnect-teardown.test.ts
  • mobile/src/notifications/notification-reopen-push-duplicate.test.ts
  • mobile/src/notifications/notification-viewing-policy.ts
  • mobile/src/notifications/notification-watermark-seed-race.test.ts
  • mobile/src/notifications/push-background-dismissal.test.ts
  • mobile/src/notifications/push-background-dismissal.ts
  • mobile/src/notifications/push-dismissal-reconciliation.test.ts
  • mobile/src/notifications/push-dismissal-reconciliation.ts
  • mobile/src/notifications/push-dismissal-watermarks.test.ts
  • mobile/src/notifications/push-dismissal-watermarks.ts
  • mobile/src/notifications/push-host-fingerprint.test.ts
  • mobile/src/notifications/push-host-fingerprint.ts
  • mobile/src/notifications/push-payload.ts
  • mobile/src/notifications/push-preference-update.test.ts
  • mobile/src/notifications/push-receive.test.ts
  • mobile/src/notifications/push-receive.ts
  • mobile/src/notifications/push-registration.test.ts
  • mobile/src/notifications/push-registration.ts
  • mobile/src/notifications/push-socket-dismissal.test.ts
  • mobile/src/notifications/push-socket-dismissal.ts
  • mobile/src/notifications/push-summary-dismissal.test.ts
  • mobile/src/notifications/push-summary-members.ts
  • mobile/src/notifications/push-token.test.ts
  • mobile/src/notifications/push-token.ts
  • mobile/src/notifications/push-tray-dismissal.test.ts
  • mobile/src/notifications/push-tray-dismissal.ts
  • mobile/src/notifications/push-tray-seen-seed.test.ts
  • mobile/src/notifications/push-tray-seen-seed.ts
  • mobile/src/notifications/socket-push-delivery-handoff.test.ts
  • mobile/src/notifications/socket-push-delivery-handoff.ts
  • mobile/src/notifications/use-remote-push-capable-hosts.test.tsx
  • mobile/src/notifications/use-remote-push-capable-hosts.ts
  • mobile/src/storage/preferences.ts
  • mobile/src/transport/host-removal-lifecycle.test.ts
  • mobile/src/transport/host-removal-lifecycle.ts
  • src/main/global-fetch-call-site-audit.test.ts
  • src/main/host/electron-runtime-desktop-surface.ts
  • src/main/ipc/notification-burst-cooldown.ts
  • src/main/ipc/notification-options.ts
  • src/main/ipc/notifications-message-formatting.test.ts
  • src/main/ipc/notifications-mobile-fanout.test.ts
  • src/main/ipc/notifications.ts
  • src/main/notifications/desktop-away-state.test.ts
  • src/main/notifications/desktop-away-state.ts
  • src/main/orca-profiles/profile-cloud-auth-config.ts
  • src/main/orcad/orcad-entry.ts
  • src/main/orcad/orcad-push-startup.test.ts
  • src/main/runtime/device-registry.ts
  • src/main/runtime/host-challenge-envelope.ts
  • src/main/runtime/mobile-notification-dismissal-store.test.ts
  • src/main/runtime/mobile-notification-dismissal-store.ts
  • src/main/runtime/push/desktop-push-service.test.ts
  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/push-agent-state.test.ts
  • src/main/runtime/push/push-cleanup-auth-expiry.test.ts
  • src/main/runtime/push/push-delivery-policy.test.ts
  • src/main/runtime/push/push-device-registration-persistence.test.ts
  • src/main/runtime/push/push-dispatcher.test-fixture.ts
  • src/main/runtime/push/push-dispatcher.test.ts
  • src/main/runtime/push/push-dispatcher.ts
  • src/main/runtime/push/push-gateway-client.test.ts
  • src/main/runtime/push/push-gateway-client.ts
  • src/main/runtime/push/push-gateway-origin.ts
  • src/main/runtime/push/push-gateway-response.ts
  • src/main/runtime/push/push-gateway-session.test.ts
  • src/main/runtime/push/push-gateway-session.ts
  • src/main/runtime/push/push-host-challenge-fixtures.ts
  • src/main/runtime/push/push-host-proof-vector.test.ts
  • src/main/runtime/push/push-host-proof.test.ts
  • src/main/runtime/push/push-host-proof.ts
  • src/main/runtime/push/push-outcome-counters.test.ts
  • src/main/runtime/push/push-outcome-counters.ts
  • src/main/runtime/push/push-policy-pipeline.integration.test.ts
  • src/main/runtime/push/push-preferences.test.ts
  • src/main/runtime/push/push-register-throttle.ts
  • src/main/runtime/push/push-registration-races.test.ts
  • src/main/runtime/push/push-registration-rpc.test.ts
  • src/main/runtime/push/push-unregister-outbox.test.ts
  • src/main/runtime/push/push-unregister-outbox.ts
  • src/main/runtime/relay/relay-host-proof.ts
  • src/main/runtime/rpc/methods/notification-preferences.test.ts
  • src/main/runtime/rpc/methods/notification-stream-policy.ts
  • src/main/runtime/rpc/methods/notifications.ts
  • src/main/runtime/runtime-desktop-surface.ts
  • src/main/runtime/runtime-mobile-notification-controller.ts
  • src/main/runtime/runtime-rpc-mobile-method-allowlist-fixtures.ts
  • src/main/runtime/runtime-rpc/runtime-rpc-mobile-method-allowlist.ts
  • src/main/runtime/runtime-rpc/runtime-rpc-pairing.ts
  • src/main/runtime/runtime-rpc/runtime-rpc-state.ts
  • src/main/runtime/runtime-service-command-surface.ts
  • src/main/startup/main-process-push-startup.ts
  • src/main/startup/main-process-quit.ts
  • src/main/startup/main-process-relay-status.ts
  • src/main/startup/main-process-runtime-launch.ts
  • src/main/startup/main-process-state.ts
  • src/preload/api/notifications-bridge.ts
  • src/preload/api/os-permission-api.ts
  • src/renderer/src/components/terminal-pane/agent-task-complete-policy.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/hooks/agent-auto-ack-presence.ts
  • src/renderer/src/hooks/agent-auto-ack-targets.ts
  • src/renderer/src/hooks/useAutoAckViewedAgent.away.test.ts
  • src/renderer/src/hooks/useAutoAckViewedAgent.clock-skew.test.ts
  • src/renderer/src/hooks/useAutoAckViewedAgent.floating-panel.test.ts
  • src/renderer/src/hooks/useAutoAckViewedAgent.ts
  • src/renderer/src/web/preload-api/web-notifications-api.ts
  • src/shared/cloud-service-url.ts
  • src/shared/mobile-notification-policy.test.ts
  • src/shared/mobile-notification-policy.ts
  • src/shared/mobile-push-contract.ts
  • src/shared/notification-burst-cooldown.ts
  • src/shared/protocol-version.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment thread cloud/apps/push/package.json Resolved
Comment on lines +44 to +46
...(delivery.orca.kind === 'dismiss'
? {}
: { notification: { title: delivery.title, body: delivery.body } }),

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🌐 Web query:

According to the official Firebase Cloud Messaging REST v1 documentation, does android.collapse_key affect a message that includes message.notification, and how are multiple offline notification messages retained per registration token?

💡 Result:

According to the official Firebase Cloud Messaging (FCM) documentation, the android.collapse_key parameter does not affect messages that include a message.notification payload. Notification messages are treated as collapsible by default and will ignore any provided collapse_key [1][2]. Regarding the retention of offline notification messages per registration token: 1. Pending Message Limit: Firebase servers can store up to 100 pending messages for a single app instance if the device is disconnected [3]. 2. Collapsible Messages: FCM allows for a maximum of 4 different collapse keys per device at any given time [4][1]. For messages marked as collapsible, if more than 4 are sent while a device is offline, FCM will retain only 4, discarding others with no deterministic factor for which are kept [1]. 3. Message Expiration and Dropping: If the storage limit (for non-collapsible messages) or the collapse key limit is exceeded, or if a device remains inactive for an extended period, messages may be dropped [3]. If a device reconnects after being offline for too long (or if messages were dropped due to hitting limits), the Firebase SDK on the client side will invoke the onDeletedMessages method, signaling the app to perform a full sync with your server as it may have missed important updates [3].

Citations:


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target file ---'
sed -n '1,180p' cloud/apps/push/src/fcm-client.ts
printf '%s\n' '--- related symbols ---'
rg -n --glob '!node_modules' 'collapse_key|collapseKey|createPushServer|PushDelivery|orca.kind|notification:' cloud/apps/push cloud/apps | head -200

Repository: stablyai/orca

Length of output: 25910


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 11393


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- delivery model ---'
sed -n '1,150p' cloud/apps/push/src/push-delivery-message.ts
printf '%s\n' '--- FCM tests ---'
sed -n '1,150p' cloud/apps/push/src/fcm-client.test.ts
printf '%s\n' '--- dispatcher/coalescing path ---'
sed -n '1,150p' cloud/apps/push/src/coalescer.ts
sed -n '1,120p' cloud/apps/push/src/push-dispatcher.ts

Repository: stablyai/orca

Length of output: 16801


Do not rely on android.collapse_key for non-dismiss FCM messages.

When delivery.orca.kind !== 'dismiss', fcmMessageBody emits message.notification and sets message.android.collapse_key from delivery.collapseId. FCM ignores collapse_key for notification messages. Distinct offline deliveries can therefore be collapsed before the device receives their notificationId values.

Use data-only messages with local notifications, or coalesce intentionally and provide catch-up reconciliation.

Comment thread cloud/apps/push/src/push-readiness.ts Resolved
Comment thread cloud/docs/relay-workflows.md Resolved
import { cleanCloudServiceOrigin } from '../../../shared/cloud-service-url'

export function resolvePushGatewayOrigin(env: NodeJS.ProcessEnv, packaged: boolean): string {
return cleanCloudServiceOrigin(env.ORCA_PUSH_GATEWAY_URL, !packaged) ?? 'https://push.onorca.dev'

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.

🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟠 Major | 🏗️ Heavy lift

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n -C 4 'ORCA_PUSH_GATEWAY_URL|resolvePushGatewayOrigin|authorization: `Bearer|redirect: .error.' \
  src/main/runtime/push src/main/orca-profiles

Repository: stablyai/orca

Length of output: 6649


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '--- shared URL validation ---'
ast-grep outline src/shared/cloud-service-url.ts
sed -n '1,140p' src/shared/cloud-service-url.ts

printf '%s\n' '--- push client authorization path ---'
ast-grep outline src/main/runtime/push/push-gateway-client.ts
sed -n '135,180p' src/main/runtime/push/push-gateway-client.ts

printf '%s\n' '--- session-token creation and origin consumers ---'
rg -n -C 3 'session\.token|new PushGatewayClient|PushGatewayClient|getOrcaPushGatewayUrl' \
  src/main/runtime/push src/main/orca-profiles

Repository: stablyai/orca

Length of output: 21033


Sensitive Data Exposure (CWE-319): Cleartext Transmission of Sensitive Information

Exploitability: Difficult

Do not permit a Bearer session over loopback HTTP.

When an unpackaged build accepts a loopback HTTP value from ORCA_PUSH_GATEWAY_URL, PushGatewayClient sends its Authorization: Bearer session token without transport encryption. Require HTTPS before sending session credentials, or withhold credentials for HTTP origins.

Comment thread src/main/startup/main-process-quit.ts Resolved
@@ -352,7 +352,7 @@ describe('dispatchTerminalNotification', () => {
expect(mockState.markWorktreeUnread).toHaveBeenCalledWith('wt-primary')
expect(mockState.markTerminalTabUnread).toHaveBeenCalledWith('tab-1')
expect(mockState.markTerminalPaneUnread).toHaveBeenCalledWith(paneKey)
expect(window.api.notifications.dispatch).not.toHaveBeenCalled()
expect(window.api.notifications.dispatch).toHaveBeenCalled()

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve suppressOsNotification through IPC.

The new dispatch path does not forward event.suppressOsNotification to notifications:dispatch. The main-process handler also has no suppression branch. If desktop notifications are enabled, an attention-only completion can now produce a native OS notification.

Forward the flag, dispatch mobile delivery first, then skip desktop delivery when it is set. Update this assertion to require the forwarded flag.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

A single commit that simplifies the push-gateway delivery path and unifies mobile foreground dedup with socket delivery.

  • Delivery path consolidated onto the durable store/worker — removed the in-memory PushCoalescer and PushDispatcher's in-process retry loop; coalescing (accept merging into open push_delivery_batches windows), persisted retry backoff (finish(batch, retryAfterMs)), and lease-based delivery now live entirely in DurablePushStore/DurablePushWorker.
  • Graceful shutdown now joins in-flight work — index.ts awaits worker.stop() (which awaits the running drain) alongside request drain and HTTP close, replacing the prior dead coalescer.stop() + flushAll() sequence; unclaimed batches fall through to durable lease recovery.
  • push_send_log scaffolding removed — the unused table, its quota/prune references, and sendLogRetentionMs are dropped.
  • Mobile foreground dedup serialized — shouldSuppressForegroundPush and socket delivery now claim the same seen-key through enqueueHostDelivery, and deliverLive consults the shared seen-set before showing, so a foreground push and its live socket event no longer double-banner.
  • Completion tracking decoupled from desktop-only toggles — the renderer tracks agent-task completion once settings hydrate and delegates per-surface filtering to main (desktopAllowed) and mobile, retiring the redundant renderer suppressOsNotification flag.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

A single follow-up commit hardening the two registration/removal races.

  • Cancelled mobile registrations are fenced — unregisterPushForRemovedHost now drops the host's state before awaiting the best-effort unregister, and reconcileHost re-checks an isCurrent() guard plus the consent generation after each await, so a late register response cannot resurrect a removed host or register against stale consent.
  • Unregister drain race closed — flushUnregisterOutbox returns early once stopped and clears flushLoop synchronously inside runFlushLoop's finally, so a cleanup queued while an empty flush is completing starts a fresh drain instead of being dropped.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: d8e084af-fbd2-47ef-b6e4-61f2a66508bd

📥 Commits

Reviewing files that changed from the base of the PR and between 5d4faa5 and eac2a9d.

📒 Files selected for processing (40)
  • cloud/apps/push/src/apns-stream-response.ts
  • cloud/apps/push/src/durable-push-store.ts
  • cloud/apps/push/src/durable-push-worker.test.ts
  • cloud/apps/push/src/durable-push-worker.ts
  • cloud/apps/push/src/index.ts
  • cloud/apps/push/src/push-delivery-lifecycle.test.ts
  • cloud/apps/push/src/push-delivery-message.ts
  • cloud/apps/push/src/push-dispatcher.ts
  • cloud/apps/push/src/push-schema.ts
  • cloud/apps/push/src/push-send-idempotency.test.ts
  • cloud/apps/push/src/push-server-auth.test.ts
  • cloud/apps/push/src/push-server-harness.test-fixture.ts
  • cloud/apps/push/src/push-server-limits.test.ts
  • cloud/apps/push/src/push-server-send.test.ts
  • cloud/apps/push/src/push-server.ts
  • cloud/apps/push/src/push-summary-members.test.ts
  • cloud/packages/push-contract/src/contract.test.ts
  • cloud/packages/push-contract/src/push-limits.ts
  • docs/reference/mobile-push-contract.md
  • mobile/src/notifications/mobile-notifications.ts
  • mobile/src/notifications/notification-reconnect-catchup.ts
  • mobile/src/notifications/push-receive.ts
  • mobile/src/notifications/push-registration-cancellation.test.ts
  • mobile/src/notifications/push-registration.ts
  • mobile/src/notifications/push-socket-foreground-ordering.test.ts
  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/push-registration-races.test.ts
  • src/renderer/src/components/terminal-pane/agent-task-complete-policy.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
  • src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
  • src/renderer/src/components/terminal-pane/pty-connection-notification-settings-gating.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/pty-connection/agent-task-complete-notify.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.test.ts
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/hooks/agent-hook-completion-notifications.test.ts
  • src/renderer/src/hooks/agent-hook-completion-notifications.ts
  • src/renderer/src/hooks/agent-hook-completion-store-sync.test.ts
  • src/renderer/src/hooks/agent-hook-completion-store-sync.ts
💤 Files with no reviewable changes (7)
  • src/renderer/src/components/terminal-pane/use-notification-dispatch.ts
  • src/renderer/src/components/terminal-pane/pty-connection-types.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-lifecycle-types.ts
  • cloud/packages/push-contract/src/contract.test.ts
  • cloud/apps/push/src/push-dispatcher.ts
  • cloud/apps/push/src/push-schema.ts
  • cloud/packages/push-contract/src/push-limits.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • cloud/apps/push/src/push-delivery-lifecycle.test.ts
  • src/main/runtime/push/push-registration-races.test.ts
  • cloud/apps/push/src/apns-stream-response.ts
  • mobile/src/notifications/push-registration.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment on lines +136 to +137
? `${count} agents need attention`
: `${count} updates`

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.

🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

Do not serialize English summary text in the gateway.

summaryBody sends English text in the provider payload. APNs and FCM can display this body before the client can translate it. Localized devices will receive English grouped notifications.

Send an intent-named localization ID with a named count argument. Resolve it through the provider-specific localization fields or the client delivery contract.

Based on learnings, newly added user-facing strings must use intent-named localization IDs with named interpolation placeholders.

Source: Learnings

settings: object | null
}): boolean {
// Mobile delivery can remain enabled when desktop banners and attention are off.
return state.settings !== null

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- target helper ---'
sed -n '1,120p' src/renderer/src/components/terminal-pane/agent-task-complete-policy.ts
printf '%s\n' '--- parked watcher references ---'
rg -n -C 8 'isAgentTaskCompleteTrackingEnabledFromState|onAgentBecameIdle|settings|hydrate|hydration' src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
printf '%s\n' '--- related callers and settings initialization ---'
rg -n -C 5 'onAgentBecameIdle|isAgentTaskCompleteTrackingEnabledFromState|settings\s*[:=]|set.*settings|hydrate.*settings|settings.*hydrate' src/renderer/src/components/terminal-pane src/renderer/src | head -n 300

Repository: stablyai/orca

Length of output: 38447


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 37294


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- candidate file list ---'
git ls-files 'src/renderer/src/components/terminal-pane/*'
printf '%s\n' '--- watcher outline ---'
ast-grep outline src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts --view expanded

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- watcher implementation ---'
sed -n '1,240p' src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
printf '%s\n' '--- watcher tests involving settings, idle, and notification ---'
rg -n -C 10 'settings|onAgentBecameIdle|notification|hydrate|subscribe|setState' src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
printf '%s\n' '--- store settings hydration bindings ---'
rg -n -C 8 'settings:\s*(null|undefined)|setState\(\{\s*settings|fetchSettings|getSync|settings\.get|settings\.onChanged' src/renderer/src/store src/renderer/src | head -n 240

Repository: stablyai/orca

Length of output: 49850


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- exact test and watcher file sizes ---'
wc -l src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts
printf '%s\n' '--- completion-related tests ---'
rg -l 'parked-terminal-byte-watcher|settings.*null|settings.*hydrate|agentTaskComplete|onAgentBecameIdle' src/renderer/src/components/terminal-pane \
  | grep -E '(parked-terminal-byte-watcher|task-complete|completion|notification|settings)' | head -n 80

Repository: stablyai/orca

Length of output: 1405


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- watcher registration and remaining lifecycle ---'
sed -n '220,340p' src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.ts
rg -n -C 12 'startParkedTerminalByteWatcher|ParkedTerminalByteWatcher' src/renderer/src --glob '*.{ts,tsx}'
printf '%s\n' '--- renderer settings bootstrap ---'
rg -n -C 10 'settings:\s*null|fetchSettings|window\.api\.settings\.(get|getSync|onChanged)|setSettings|setState\(\{[^}]*settings' src/renderer/src --glob '*.{ts,tsx}' | head -n 320

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- completion policy tests ---'
rg -n -C 8 'isAgentTaskCompleteTrackingEnabledFromState|settings.*null|hydr' src/renderer/src/components/terminal-pane/*test* src/renderer/src/hooks/*test* --glob '*.{ts,tsx}' | head -n 260
printf '%s\n' '--- watcher test setup and start helper ---'
sed -n '1,150p' src/renderer/src/components/terminal-pane/parked-terminal-byte-watcher.test.ts

Repository: stablyai/orca

Length of output: 32877


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- parked watcher caller files ---'
rg -l 'startParkedTerminalByteWatcher' src/renderer/src --glob '*.{ts,tsx}' | sort
printf '%s\n' '--- caller context ---'
for f in $(rg -l 'startParkedTerminalByteWatcher' src/renderer/src --glob '*.{ts,tsx}' | grep -v '\.test\.'); do
  echo "### $f"
  rg -n -C 14 'startParkedTerminalByteWatcher|useAppStore\.subscribe|settings' "$f"
done
printf '%s\n' '--- settings initialization in store ---'
rg -n -C 8 'settings\s*:' src/renderer/src/store --glob '*.{ts,tsx}' | head -n 220

Repository: stablyai/orca

Length of output: 29472


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- narrow hydration/replay search in terminal parking code ---'
rg -n -C 8 'settings|hydrate|replay|idle|agent' src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers.ts src/renderer/src/components/terminal-pane/terminal-parked-tab-watchers*.ts src/renderer/src/components/terminal-pane/pty-side-effect* 2>/dev/null | head -n 320

Repository: stablyai/orca

Length of output: 24825


Retain idle events during settings hydration

When settings is null, isAgentTaskCompleteTrackingEnabledFromState returns false. The parked watcher then exits before creating the completion timer and does not re-evaluate the idle event when settings hydrate. Retain the idle event or replay it after hydration so the agent does not lose its completion notification.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior Pullfrog review (ff4e8d10 "fix(push): address review races and isolate deployment authority") that closes a set of flagged races and migrates deploy authority to a dedicated identity:

  • Dedicated push deploy identity — cloud-push-deploy.yml now authenticates via PRODUCTION_GCP_PUSH_DEPLOY_WORKLOAD_IDENTITY_PROVIDER/SERVICE_ACCOUNT; the new push-deploy-identity.tf maps a distinct attribute.push_deploy principal (and deliberately not attribute.repository) so the workflow can no longer assume the shared Relay deploy account, and push-deploy.yml was removed from the Relay provider allowlist.
  • Device registration delete/insert race closed — deleteOwned now acquires the per-host DEVICE_CAP_LOCK_PREFIX lock inside its transaction, so a delete serializes against a concurrent upsert that already read its row (new isolated-PostgreSQL race test).
  • Readiness single-flight + failure caching — createPushReadiness coalesces concurrent checks behind one in-flight query and caches failures for the cache window; /ready is now behind limitUnauthenticatedIp so unauthenticated probes can't amplify database round-trips.
  • Client-IP limiter no longer trusts x-real-ip — falls back to the shared UNKNOWN_CLIENT_IP bucket rather than a caller-rotatable header.
  • Config and dependencies — blank environment values are normalized to undefined before zod parse; hono → 4.13.7 and @hono/node-server → 1.19.17; APNs dismissal test now asserts the apns-push-type: background / priority 5 / content-available: 1 headers.
  • Mobile delivery hardening — Android notification-channel creation is awaited before token registration (failure propagates so registration retries); foreground dismissals fire independently of the serialized show queue; the socket handoff re-checks the dismissal watermark so a dismissed alert is not resurrected on foreground; legacy ID-only dismissals preserve host isolation; malformed stored preferences fall back to defaults.
  • Desktop polish — the unregister outbox flushes in a finally even when clearing the local registration throws; the loopback-URL exception is restricted to the http: scheme; the connection-budget script counts the tagged push candidate once.

I traced the deliverLive eager-dismissal refactor (the dismissal promise is created once and awaited inside the queue task, so there is no double-dismiss), the readiness single-flight (pending reset in finally, failure-cached for cacheMs), and the deleteOwned lock (matches the existing upsert locking pattern), and confirmed the new Workload Identity condition pins the exact cloud-push-deploy.yml dispatch workflow on main/production. No new issues.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cloud/infra/terraform/push-gateway.tf (1)

303-304: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Include both revisions in the shared SQL budget.

template.scaling.max_instance_count limits each Cloud Run revision. The --no-traffic candidate boots while the serving revision remains active. The current condition can therefore allow two pools of four connections, exceeding the shared four-connection allocation. Apply the same two-revision bound used by the dedicated-database precondition.

Source: MCP tools

🧹 Nitpick comments (1)
cloud/dev/scripts/push-gateway-workflow.test.mjs (1)

303-309: 🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🔵 Trivial | ⚡ Quick win

Security Misconfiguration (CWE-284)

Reachability: External · Exploitability: Theoretical

Assert the push provider's repository and workflow scope.

The provider currently enforces accepted-repository claims and exact push-deploy.yml@refs/heads/main workflow references. Add positive assertions for these conditions so future changes cannot remove the restriction without failing this test.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 1b7b8665-7cd4-475e-9629-4badf17f32bd

📥 Commits

Reviewing files that changed from the base of the PR and between eac2a9d and 761d2a0.

⛔ Files ignored due to path filters (1)
  • cloud/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (56)
  • .github/workflows/cloud-push-deploy.yml
  • cloud/apps/push/package.json
  • cloud/apps/push/src/apns-client.test.ts
  • cloud/apps/push/src/client-ip-rate-limit.test.ts
  • cloud/apps/push/src/client-ip-rate-limit.ts
  • cloud/apps/push/src/config.test.ts
  • cloud/apps/push/src/config.ts
  • cloud/apps/push/src/device-registration-delete-race.test.ts
  • cloud/apps/push/src/device-registry-store.ts
  • cloud/apps/push/src/push-observability.ts
  • cloud/apps/push/src/push-readiness.test.ts
  • cloud/apps/push/src/push-readiness.ts
  • cloud/apps/push/src/push-send-idempotency.test.ts
  • cloud/apps/push/src/push-server.ts
  • cloud/dev/fixtures/terraform-root-partition/families.json
  • cloud/dev/scripts/push-gateway-workflow.test.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs
  • cloud/dev/scripts/relay-production-identity-boundaries.test.mjs
  • cloud/dev/scripts/render-workload-identity-conditions.mjs
  • cloud/dev/scripts/workload-identity-attribute-conditions.test.mjs
  • cloud/docs/push-gateway.md
  • cloud/docs/relay-workflows.md
  • cloud/infra/terraform/push-deploy-identity.tf
  • cloud/infra/terraform/push-gateway.tf
  • cloud/infra/terraform/relay-github-actions.tf
  • cloud/infra/terraform/relay-github-workflow-trust.tf
  • docs/reference/headless-linux-server.md
  • docs/reference/mobile-push-contract.md
  • mobile/app/_layout.tsx
  • mobile/src/notifications/desktop-notification-channel.test.ts
  • mobile/src/notifications/desktop-notification-channel.ts
  • mobile/src/notifications/mobile-notifications.ts
  • mobile/src/notifications/notification-delivery-preferences.test.ts
  • mobile/src/notifications/notification-delivery-preferences.ts
  • mobile/src/notifications/push-preference-update.test.ts
  • mobile/src/notifications/push-registration-cancellation.test.ts
  • mobile/src/notifications/push-registration.test.ts
  • mobile/src/notifications/push-registration.ts
  • mobile/src/notifications/push-socket-dismissal.test.ts
  • mobile/src/notifications/push-socket-dismissal.ts
  • mobile/src/notifications/push-socket-foreground-ordering.test.ts
  • mobile/src/notifications/socket-push-delivery-handoff.test.ts
  • mobile/src/notifications/socket-push-delivery-handoff.ts
  • src/main/ipc/notification-options.ts
  • src/main/runtime/push/desktop-push-service.ts
  • src/main/runtime/push/push-registration-races.test.ts
  • src/main/runtime/remote-runtime-close-intent.integration.test.ts
  • src/main/runtime/remote-runtime-request-connection.integration.test.ts
  • src/main/runtime/runtime-rpc-mobile-terminal-streaming.test.ts
  • src/main/runtime/runtime-rpc-request-authorization.test.ts
  • src/main/runtime/runtime-rpc-websocket-long-poll-caps.test.ts
  • src/main/startup/main-process-quit.ts
  • src/renderer/src/i18n/locales/en.json
  • src/shared/cloud-service-url.test.ts
  • src/shared/cloud-service-url.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • docs/reference/headless-linux-server.md
  • src/main/ipc/notification-options.ts
  • docs/reference/mobile-push-contract.md
  • cloud/apps/push/package.json
  • cloud/apps/push/src/push-observability.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.

Comment thread cloud/apps/push/src/config.ts Outdated
export function loadPushConfig(env: NodeJS.ProcessEnv = process.env): PushConfig {
const parsed = EnvSchema.parse(
Object.fromEntries(
Object.entries(env).map(([key, value]) => [key, value?.trim() === '' ? undefined : value])

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Trim retained environment values.

Line 98 converts whitespace-only values to undefined, but it preserves whitespace on every non-empty value. For example, ORCA_PUSH_PUBLIC_URL=" https://push.example " fails validation instead of loading the valid origin. Normalize the retained value before parsing.

Proposed fix
-      Object.entries(env).map(([key, value]) => [key, value?.trim() === '' ? undefined : value])
+      Object.entries(env).map(([key, value]) => {
+        const trimmed = value?.trim()
+        return [key, trimmed === '' ? undefined : trimmed]
+      })
📝 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
Object.entries(env).map(([key, value]) => [key, value?.trim() === '' ? undefined : value])
Object.entries(env).map(([key, value]) => {
const trimmed = value?.trim()
return [key, trimmed === '' ? undefined : trimmed]
})

)
github_push_workflow_clauses = [
for prefix in local.relay_github_workflow_ref_prefixes :
"assertion.workflow_ref == '${prefix}push-deploy.yml@refs/heads/main' && assertion.job_workflow_ref == '${prefix}push-deploy.yml@refs/heads/main'"

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🔎 Supported by static analysis

🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 42980


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- changed file ---'
sed -n '1,120p' cloud/infra/terraform/push-deploy-identity.tf
printf '%s\n' '--- workflow files ---'
find .github/workflows -maxdepth 1 -type f -print | sort
printf '%s\n' '--- workflow references ---'
rg -n -C 3 'push-deploy|cloud-push-deploy|workflow_ref|job_workflow_ref|google-github-actions/auth' cloud .github/workflows

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
python3 - <<'PY'
from pathlib import Path
p = Path('cloud/infra/terraform/push-deploy-identity.tf')
print(p.read_text())
for name in ['.github/workflows/cloud-push-deploy.yml', '.github/workflows/push-deploy.yml']:
    q = Path(name)
    print(f'--- {name}: {q.exists()} ---')
    if q.exists():
        print(q.read_text())
PY

Repository: stablyai/orca

Length of output: 20885


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- Terraform identity ---'
sed -n '1,120p' cloud/infra/terraform/push-deploy-identity.tf
printf '%s\n' '--- workflow files ---'
find .github/workflows -maxdepth 1 -type f -print | sort
printf '%s\n' '--- relevant references ---'
rg -n -C 3 'push-deploy|cloud-push-deploy|workflow_ref|job_workflow_ref|google-github-actions/auth' cloud .github/workflows

Repository: stablyai/orca

Length of output: 50369


🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions

Length of output: 25273


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- push workflow condition bindings ---'
rg -n -C 8 'github_push_workflow_clauses|github_push|relay_github_workflow_conditions' cloud/infra/terraform cloud/dev/scripts
printf '%s\n' '--- relevant Terraform definitions ---'
sed -n '1,230p' cloud/infra/terraform/relay-github-actions.tf
printf '%s\n' '--- push identity checks ---'
sed -n '80,180p' cloud/dev/scripts/relay-production-identity-boundaries.test.mjs
sed -n '1,80p' cloud/dev/scripts/push-gateway-recovery.test.mjs

Repository: stablyai/orca

Length of output: 50369


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- push condition references ---'
rg -n -C 6 'github_push_workflow_clauses|relay_github_workflow_conditions|github_push' cloud/infra/terraform
printf '%s\n' '--- identity tests ---'
sed -n '90,145p' cloud/dev/scripts/relay-production-identity-boundaries.test.mjs
sed -n '1,35p' cloud/dev/scripts/push-gateway-recovery.test.mjs

Repository: stablyai/orca

Length of output: 21990


🌐 Web query:

site:docs.github.com actions OIDC job_workflow_ref claim reusable workflow direct workflow

💡 Result:

When using reusable workflows in GitHub Actions, the OIDC token generated for a job includes a custom claim called job_workflow_ref [1][2][3]. This claim specifically identifies the called (reusable) workflow, providing its repository path, file path, and reference (e.g., octo-org/octo-automation/.github/workflows/oidc.yml@refs/heads/main) [1][2][3]. For cloud providers that support custom OIDC claims (such as Google Cloud Platform and HashiCorp Vault), you can use job_workflow_ref directly in your trust conditions to enforce security policies that require specific reusable workflows to be used for deployments [1][2]. For cloud providers that do not natively support custom claims, you can use the GitHub REST API to customize the OIDC subject (sub) claim [1][4][5]. By applying a customization template, you can include the job_workflow_ref within the sub claim itself [4][5][6]. This allows you to enforce requirements on the reusable workflow path by setting a condition in your cloud provider's OIDC configuration that verifies the sub claim matches the expected path format [4][5][7]. In summary, the job_workflow_ref claim allows organizations to ensure that only authorized, standardized reusable workflows can authenticate with their cloud infrastructure [1][2].

Citations:


Correct the push workflow condition.

github_push_workflow_clauses feeds the provider condition, but it requires push-deploy.yml for both claims. The supported direct workflow is .github/workflows/cloud-push-deploy.yml. It also does not provide the reusable-workflow-only job_workflow_ref claim. Use cloud-push-deploy.yml for workflow_ref and remove the job_workflow_ref comparison.

}
} else {
await dismissLocalNotification(event as DismissNotificationEvent, hostId)
await (dismissal ?? dismissLocalNotification(event as DismissNotificationEvent, hostId))

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Run dismissal cleanup again after the host queue.

When a preceding notification waits in waitForSocketPushHandoff, Lines 67-71 can finish dismissLocalNotification before showLocalNotification creates its local state. Line 105 then only awaits the completed promise. The queued dismissal does not remove the later notification, so it can remain visible after its dismiss event.

Keep the early cleanup for prompt tray removal. Run dismissLocalNotification again after the preceding queue work completes.

Proposed fix
     } else {
-      await (dismissal ?? dismissLocalNotification(event as DismissNotificationEvent, hostId))
+      if (dismissal) {
+        await dismissal
+      }
+      await dismissLocalNotification(event as DismissNotificationEvent, hostId)
     }

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One PR-authored commit plus a main merge since the prior review at 8fd9947c:

  • Reworked Cloud Run recovery to be successor-first — because Cloud Run refuses to delete the latest created revision, activation now deploys the active successor (a<run>-<attempt>) before removing the validation tag and deleting validation; the recovery path deploys a tagged known-good successor, verifies its template/runtime/secret shape against the captured push-rollback-revision.json, promotes it, and public-checks it before retiring rejected/previous consumers.
  • Added a preflight admission gate — the deploy now requires exactly one serving revision resource and refuses leftover revisions, keeping every rollout within the three-revision budget.
  • Committed the serving revision on public verification — ROLLOUT_VERIFIED is set only after public checks pass, so post-verification cleanup failures no longer trigger rollback; a new Retire previous consumers after public checks step clears tags and deletes obsolete revisions.
  • Raised the connection budget to three simultaneous pools — pushCandidate overlap moved to pushDraw * 2 and the Terraform precondition to * 3 <= 64, matching the serving + validation/rejected + successor shape.
  • Pinned single-manifest builds — --platform linux/amd64 --provenance=false so the build metadata records the same digest Cloud Run resolves.
  • Introduced an executable fake-gcloud model — push-cloud-run-model.mjs enforces the latest/traffic deletion constraints, and the recovery tests were rewritten around it (25 scenarios) with updated workflow/validation/budget assertions.
  • Merged main — resolving main's hono 4.13.7 / @hono/node-server 1.19.17 bump against the PR's @orca-cloud/postgres-schema workspace dependency.

I traced the success path (candidate → activate → shift → public → retire leaves a single serving revision) and the failure paths (validation/activation/describe/delete/deploy failures, ambiguous traffic shift, failed public check, failed recovery promotion), and confirmed the shape jq comparison, the ROLLOUT_VERIFIED rollback gate, and the three-pool budget are consistent with the Terraform precondition and the connection-budget script. All changed test suites pass locally (25 recovery, 32 workflow/validation/budget).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@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

🧹 Nitpick comments (1)
cloud/dev/scripts/push-cloud-run-model.mjs (1)

7-7: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

option returns the wrong token when the flag is absent.

args.indexOf(name) returns -1 for a missing flag, so option(name) returns args[0]. Every caller then reads a plausible-looking string instead of failing.

This matters for a harness whose purpose is to catch workflow defects. If a future edit drops --revision-suffix or --image, line 44 builds a revision name from args[0] and line 50 sets the image to 'run', and the test can still pass. Fail instead.

♻️ Proposed fix: refuse a missing flag
-const option = (name) => args[args.indexOf(name) + 1]
+const option = (name) => {
+  const index = args.indexOf(name)
+  if (index === -1 || index + 1 >= args.length) fail(`missing option ${name}`)
+  return args[index + 1]
+}
 const has = (name) => args.includes(name)
 const fail = (message) => {
   throw new Error(message)
 }

fail is declared after option, so move the fail declaration above option to avoid a temporal dead zone at call time.

Line 111 relies on the current fallback (?? option('--format')), so give it an explicit default when you change this.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 326c9dcd-0fef-436b-8c3a-f17a2bdc1a79

📥 Commits

Reviewing files that changed from the base of the PR and between 8fd9947 and 35864ab.

⛔ Files ignored due to path filters (2)
  • cloud/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • mobile/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • .github/workflows/cloud-push-deploy.yml
  • cloud/apps/relay/package.json
  • cloud/dev/scripts/push-cloud-run-model.mjs
  • cloud/dev/scripts/push-gateway-recovery.test.mjs
  • cloud/dev/scripts/push-gateway-workflow.test.mjs
  • cloud/dev/scripts/push-validation-workflow.test.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.mjs
  • cloud/dev/scripts/relay-cloud-sql-connection-budget.test.mjs
  • cloud/docs/push-database-cutover.md
  • cloud/docs/push-gateway.md
  • cloud/infra/terraform/push-gateway.tf
  • src/renderer/src/i18n/locales/en.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/i18n/locales/en.json

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

Comment on lines +283 to +284
/env\.RECOVERY_VERIFIED == 'true'/,
'cleanup must wait for verified recovery traffic and public checks'

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

Assert the rejected-revision step’s own guard.

The assertion searches the full slice from Delete the rejected candidate revision through Drop the candidate traffic tag. It can pass when env.RECOVERY_VERIFIED == 'true' appears in another step or shell command while the delete step remains unconditional. Extract the deletion step and assert its exact if: condition contains the recovery marker.

assert.match(workflow.slice(deploy, activation), /\.mode == "validation"/)
assert.ok(position('Prove the runtime identity can reach FCM') < activation)
const active = workflow.slice(activation, shift)
assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete'))

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

This ordering assertion passes when gcloud run deploy is absent.

String.prototype.indexOf returns -1 for missing text. If the activation span loses gcloud run deploy, the comparison becomes -1 < <positive>, which is true.

Successor-first ordering is the exact property this PR adds, so require both markers to exist before comparing them.

💚 Proposed fix: require both markers
-  assert.ok(active.indexOf('gcloud run deploy') < active.indexOf('gcloud run revisions delete'))
+  const deployAt = active.indexOf('gcloud run deploy')
+  const deleteAt = active.indexOf('gcloud run revisions delete')
+  assert.ok(deployAt !== -1 && deleteAt !== -1)
+  assert.ok(deployAt < deleteAt)

The earlier review raised the same indexOf weakness for the other ordering checks in this file. Apply one shared helper to all of them.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Since the prior review at 35864ab0, one PR-authored commit (2c0dcc83d1 "Simplify mobile push delivery and mirror desktop notification categories") plus a main merge (fc9a7c22a9):

  • Gateway sends each event as its own notification — DurablePushStore.accept now inserts one immediately-due push_delivery_batches row per event (a one-element JSON envelope readable by an overlapping old worker), claim() returns a single QueuedPushDelivery (replacing DeliveryBatch), and coalesceMs/ORCA_PUSH_COALESCE_MS, canCoalescePushNotifications, summaryBody, and the gateway push-summary-members module are deleted. Collapse identity is sha256([host, notificationId | [epoch, seq]]) for every event, with APNs thread-id = host and a per-event Android tag replacing the host-wide collapse id.
  • Rolling-deploy queue compatibility — new rows carry due_at = 0 so an old writer's attempts = 0 AND due_at > now coalescing lookup skips them; claim() atomically splits a pre-deployment multi-event row into :legacy:NN singletons (bounded at 32) preserving expiry/attempts; removeDismissedAlerts/reconcileQueuedDismissal now scope by host.
  • Socket stops creating OS banners — subscribeToDesktopNotifications is reduced to handling ready (tray reconciliation via getMissedSince + deliveredPushes) and dismiss; the whole #8591 watermark/replay/seen-set/catch-up machinery (notification-reconnect-catchup.ts, local-notification-scheduling.ts, push-tray-seen-seed.ts, socket-push-delivery-handoff.ts) and their tests are deleted. APNs/FCM is the sole banner path.
  • Desktop categories are authoritative — PushDispatcher drops the shared allowsMobileNotification (mobile-notification-policy.ts deleted) for a local allowsPushDelivery gated on desktopAllowed !== false plus the phone-specific onlyWhenDesktopAway/sound settings; followDesktop and per-category phone overrides are retired and the mobile settings screen shows only phone controls.
  • Foreground push dedup + dismissal simplified — shouldSuppressForegroundPush now uses a bounded process-local identity claim (claimForegroundPush) plus persisted dismissal fences, with legacy summary expansion narrowed to areLegacySummaryPushesDismissed for tray entries delivered during the transition.

I traced the legacy-split claim() ordering (due retries sort before fresh first attempts; attempts/expiresAt are preserved across the split), the allowsPushDelivery authoritative-category gate, and confirmed the deleted watermark/scheduling modules leave no dangling imports anywhere in mobile/ or src/.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior review at fc9a7c22a9:

  • Removed the rolling-deploy summary compatibility layer — DurablePushStore.accept now persists a single notification object (due_at = now, no due_at = 0 sentinel), claim() drops the :legacy: split of pre-deployment multi-event rows and the LEGACY_BATCH_MAX_NOTIFICATIONS cap, and removeDismissedAlerts is replaced by a single-notification isDismissedAlert behind a new parsePushDeliveryPayload guard that rejects array payloads.
  • Aligned the dismissal fence comparison — reconcileQueuedDismissal now treats an event at exactly the recorded dismissal sequence as already dismissed (>=, matching isDismissedAlert), so a re-queued alert at the same identity/sequence is dropped at accept time instead of surviving to the worker.
  • Deleted the mobile summary expansion — push-summary-members.ts and areLegacySummaryPushesDismissed are removed; readPushNotificationIdentity replaces readPushIdentity, and push-payload.ts drops summaryMembers/coalescedCount. Reconciliation paging, tray dismissal and shouldSuppressForegroundPush operate on individual identities, and the iOS PushDismissalLedger drops its legacy summary branch.
  • Updated tests and docs — legacy summary tests are deleted, an individual-identity paging test (288 identities across two 256-identity pages) is added, and the contract/gateway docs now state the incompatible-queue deploy prerequisite (stop old revisions, clear fixtures) instead of describing the removed transition.

I traced the paging arithmetic (256 + 32 → 288 dismissals), the >= edge cases on the dismissal fence, and the due_at/ordering simplification, and confirmed no dangling references to the removed symbols remain.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior Pullfrog review at f1c83e2b (a4fead9cb4 "Simplify push policy and remove unpublished compatibility paths") that strips the remaining per-device category machinery and hardens dismissal storage ownership:

  • Removed category filters end-to-end — PushNotificationFilter and the filter_json column are dropped from push-contract, the push_devices schema, and device-registry-store.ts; POST /v1/devices and notifications.registerPush now carry only onlyWhenDesktopAway/sound.
  • Made the seven-day lease unconditional — MobilePushRegistration.expiresAt is required on every persisted registration, parseMobilePushRegistration rejects rows without a finite expiry, and PushDispatcher drops its expiresAt === undefined guard.
  • Moved the one-session-per-host invariant into the initial schema — push-session-schema.ts and its duplicate-session repair migration are deleted in favor of a CREATE UNIQUE INDEX … push_sessions_host statement; the upgrade prerequisite is documented.
  • iOS dismissal uses the native ledger exclusively — native-push-dismissal.native.ts becomes .ios.ts backed by requireNativeModule (a missing module is a build defect), Android/web use AsyncStorage, and tray/storage failures now propagate to callers instead of silently falling back.

I confirmed no dangling references to the removed PushNotificationFilter, filter_json, ensurePushSessionIndex, or requireOptionalNativeModule symbols remain, traced the expiresAt-required change through desktop-push-service.ts, push-dispatcher.ts, and the shared parseMobilePushRegistration, and verified the dismissal-failure propagation is safe (the reconciliation catchup caller at mobile-notifications.ts:39 catches, and the dismissal ledger is persisted before tray cleanup). The dropped filter_json column and cleared push_sessions are the only deploy prerequisites, and they are captured in the contract reference and the PR notes for this unpublished, reset-only rollout.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior Pullfrog review (a4fead9cb4): bba1b53447 removes the gateway's redundant shared-Cloud-SQL attachment and commits it fully to its dedicated database.

  • push_hosts and challenge bloat removed — the push_hosts table, its host_public_key/transcript columns, rememberHost, and pruneStaleHosts are deleted. The challenge store persists only (challenge_id, host_fingerprint, secret_hash, expires_at, consumed_at); proof verification still consumes once under the consumed_at IS NULL predicate, and host ownership rides the fingerprint that sessions/devices/events already key on.
  • Delivery identity and lease fencing hardened — accept now normalizes kind into the content fingerprint so an omitted kind and an explicit kind: "alert" collapse to one event, and renew/finish fence on state = 'pending' so a late renew/finish cannot resurrect a delivery that claim/prune flipped to dismissed/expired.
  • Dedicated rollout serialization — cloud-push-deploy.yml moves to a production-push-rollout concurrency group and terraform/state/push-rollout/production.lock lease object (with a narrowly-scoped github_push_rollout_lease objectAdmin grant), and builds the image before taking the lease.
  • Shared-store resources and budget removed — the shared push database/user/secret resources and the push draw from relay-cloud-sql-connection-budget are gone; the dedicated instance provisions on push_gateway_count and the pool precondition is now instances × pool × 3 ≤ 64.
  • Runbook rewritten — push-database-cutover.md covers legacy-resource ownership, the schema-preparation prerequisite (the new image's challenge INSERT omits the old NOT NULL columns, so an old internal DB needs a reviewed drop job first), and the lock-namespace transition.

I traced the challenge-store simplification (nothing reads the removed host row or columns; the transcript is re-derived by the client and only its HMAC digest is stored), the fingerprint normalization (matches the already-normalized eventId kind), and the renew/finish fencing (guarded by both lease_token and state), and confirmed the census test still classifies push-deploy.yml correctly via NOT_A_CLOUD_SQL_CANDIDATE with no dangling references to the removed symbols.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Two commits since the prior Pullfrog review (bba1b53447): a consolidation of the remaining redundant client state and replay options, plus a one-line Terraform ordering fix.

  • Consent single-sourced — savePushNotificationsEnabled no longer mirrors consent to the orca:remotePushEnabled key; loadRemotePushEnabled/saveRemotePushEnabled and the REMOTE_PUSH_KEY are deleted, so orca:pushNotificationsEnabled is the sole consent source. readPushNotificationsPreference never consults the obsolete key (the preference test now proves an obsolete key alone does not grant consent).
  • Reconciliation simplified — requestNotificationCatchup(client, hostId, isDisposed) drops the params/replay/epoch/includeDesktopSuppressed arguments and returns void; it always sends lastSeenSeq: Number.MAX_SAFE_INTEGER, pages the native tray 256 identities at a time, skips the RPC entirely when the tray holds no alerts for the host, and continues past a host that omits the dismissedPushes array. New tests cover the empty-tray skip, paging without requesting historical events, and stopping after a second-page failure/disconnect without removing unconfirmed alerts.
  • Capability consolidation — notifications.delivery-preferences.v1 and notifications.delivery-policy.v1 are removed from RUNTIME_CAPABILITIES; notifications.remote-push.v1 is now the single push capability, useRemotePushCapableHosts drops its policySupported field, and the "Update your paired desktops" hint is deleted. No references to the removed constants remain anywhere in the tree.
  • Dead client surface deleted — buildLocalNotificationData and its DesktopNotification{Source,Event}/LocalNotificationData types plus wasHostPushDismissed are removed (their last callers were already gone after the earlier simplification).
  • deleteDevice boolean collapse — PushGatewayClient.deleteDevice returns a plain boolean instead of { deleted, retryable }; the old retryable was always !deleted, so the collapse is lossless (404 and surviving-401 paths behave identically), with caller and test updates in lockstep.
  • Deploy identity ordering fix — push_deploy_member now references one(google_service_account.github_push_deploy[*].member) instead of a hand-built serviceAccount:<prefix>-gha-push@… string (same member value, but now a real resource dependency so Terraform orders the grants correctly against count).
  • New native-dismissal CI job — mobile.yml compiles and runs the Swift dismissal-ledger checks on macos-15.

I verified the four removed symbols/capabilities (loadRemotePushEnabled/saveRemotePushEnabled, wasHostPushDismissed, buildLocalNotificationData, and both retired capability constants) leave no dangling references, traced the deleteDevice boolean collapse and the requestNotificationCatchup paging/continue rewrite against their tests, and confirmed the Terraform one(...) reference is well-formed against the counted github_push_deploy resource.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior Pullfrog review (3be752984c), hardening unregister recovery against storage failures and removing the last of the dead push-contract surface.

  • Unregister recovery survives a failed pending-record write — setRemotePushEnabled now reconciles hosts in a finally, and reconcileHost gains a consent-off branch that sends notifications.unregisterPush directly (instead of relying solely on the persisted pending set), so a disable persists through a "disk full" write and an app restart. mutateRecords no longer swallows its save error, and enqueueReconcile now logs failures.
  • Unregister outbox no longer overwrites an unreadable file — PushUnregisterOutbox mirrors relay-revoke-outbox: it flags isUnreadableError reads and refuses to save over them, preserving pending token deletions until the file is readable again (the unused createdAt field is dropped).
  • Tray dismissal now requires the host fingerprint — dismissPresentedPushNotification takes hostFingerprint as a required argument (all callers already passed it), always filtering on host identity.
  • Dead push-contract schemas removed — PushErrorResponseSchema/PUSH_ERROR_CODES, PushDevice{Registration,List}ResponseSchema, PushSendResponseSchema, and CanonicalHttpsOriginSchema (plus the unused PushGatewayClient.hostFingerprint field), with docs/comments updated to match.

I traced the recovery path (the desktop unregisterCurrent returns { unregistered: false } without touching the outbox when no registration exists, so the per-reconcile unregister is idempotent), confirmed the outbox change reproduces relay-revoke-outbox.ts exactly, and verified via grep that none of the deleted schemas have any remaining references. The two new tests are meaningful — the "disk full" recovery test fails without the fix, and the unreadable-outbox test asserts the original file bytes are preserved.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior review at 90c143b436 (e3b63ed063 "fix(push): preserve registration lifecycle and simplify delivery contracts"):

  • Absolute delivery deadline — PushDelivery.expiresAt is now required; the worker forwards queued.expiresAt into buildPushDelivery, and APNs apns-expiration / FCM ttl derive from that absolute value rather than a per-send now + TTL fallback. Retries therefore shrink the remaining TTL, and an expired delivery is refused (reason: 'expired') before any provider round-trip. The now-dead FCM validateOnly option (the deploy probe posts validate_only via a raw curl) and the PushReadinessOptions.observe latency callback are removed.
  • Compare-and-set dead-token retirement — DeviceRegistryStore.markDead now takes the observed registration and fences the UPDATE on token/platform/apns_environment, so a token that rotated mid-send can no longer retire the new registration.
  • Mobile registration ownership — push-registration.ts moves the client under a connection object (a detach only clears the connection it owns), bounds token acquisition to a 2s timeout, and returns a restore callback from unregisterPushForRemovedHost; removeHostAndCloseClient re-restores the registration when host metadata removal fails, without reviving stale registration work.
  • Single delivery snapshot — foregroundNotificationBehavior reads preferences once and passes suppressWhileViewing to the now-synchronous shouldSuppressNotificationWhileViewing, so sound and viewing decisions can no longer diverge.
  • Unreadable outbox refuses registration — PushUnregisterOutbox.isUnreadable() plus the registerAfterCleanup guard return registration_storage_failed before any delete or register, so a host never registers over a cleanup state it cannot reliably settle.
  • Dead-field cleanup — MobilePushRegistration.registeredAt is dropped (parsing tolerates the obsolete field), PushTarget.registrationId collapses onto registration, and OrcaPushPayload/route data drop the unused source/agentState fields. Durable-store Postgres tests now isolate each case behind a random search_path schema.

I traced the absolute deadline end-to-end (store accept clamps expiresAt to now + notificationTtlSeconds; claim/finish fence on expires_at; finish drops a retry whose retryAt lands past the deadline), confirmed markDead's new predicate is a compare-and-set against the device read at send time, and verified the registration-restore path (unregisterPushForRemovedHost deletes the host before awaiting its chain, so in-flight reconciles fail their isCurrent() guard) with no dangling callers of the changed signatures.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior review at e3b63ed063 (317680a9cc "refactor(push): centralize consent and unregister drain ownership"):

  • Consent mutation centralized — the notification-consent-events pub/sub is deleted; setRemotePushEnabled is now the sole consent mutation, persisting consent + cleanup intent and then scheduling reconciliation in the background (void reconcileAllHosts() in a finally) instead of awaiting it, so Settings, onboarding, and the new notification-opt-in-gate all complete on local persistence.
  • Opt-in gate routes through the owner — shouldPresentNotificationOptIn (auto-adopt an existing grant / skip a denied device) and onboarding now call setRemotePushEnabled rather than savePushNotificationsEnabled, so permission-derived decisions also register/unregister.
  • Unregister drain processes one snapshot per pass — DesktopPushService.drainPending iterates a single outbox.pending() snapshot and relies on the "every enqueue requests a flush" invariant for the outer loop to re-snapshot mid-pass work, closing the ordering gap the prior per-item re-read handled.

I traced the consent fence (consentGeneration) against the fire-and-forget reconcile, the serialized per-host chain, and the drain's enqueue-flush invariant (all three enqueue sites trigger flushUnregisterOutbox; the outbox swaps this.items on remove(), so iterating the entry-time snapshot is safe), and confirmed the new tests exercise the failure paths (failed consent/records writes, mid-drain enqueue ordering, stop-leaves-later-work-durable). No new issues.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

One commit since the prior Pullfrog review at 317680a9cc (8eea3ee9d5 "refactor(push): remove redundant platform state and require gateway mode"):

  • platform dropped from the persisted desktop registration — MobilePushRegistration no longer stores platform, which was written on register but never read on the desktop. Routing still rides the gateway's push_devices.platform (supplied via MobilePushRegisterInput.platform, still validated at the RPC boundary by MOBILE_PUSH_PLATFORMS), and parseMobilePushRegistration now tolerates old rows that carry the field, so existing registrations survive the upgrade.
  • PushConfig.mode is now required — loadPushConfig always populated it (ORCA_PUSH_MODE defaults to 'active'), so the /health endpoint's config.mode ?? 'active' fallback was dead and is now a direct read; the test fixture and contract docs were updated to match.

I traced the data flow: platform is still forwarded through push-gateway-client.ts to the gateway's device registry (APNs/FCM routing), no desktop code reads the persisted field, and no PushConfig literal is left without mode. No behavioral change.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@mmarabel

Copy link
Copy Markdown
Contributor

Physical-device field report against the latest released Orca Mobile and desktop apps (not a build from this PR):

  • Device: iPhone on iOS 26.6.1
  • Connection: Tailscale
  • Orca Mobile remained open but backgrounded; it was not force-quit.
  • No agent-activity notifications arrived while it was backgrounded.
  • On returning to Orca, multiple notifications were delivered together.
  • The replay included stale agent turns that had already been handled on desktop in two distinct ways:
    1. turns I had read and replied to, and
    2. turns whose agent activity I had opened and read on desktop but had not replied to yet.
  • Exact background duration was not measured.

This is consistent with iOS suspending the background socket, but the stale replay is the more important UX detail: reconnect catch-up appears to use the phone delivery watermark without reconciling desktop-resolved or desktop-viewed state. The desired behavior is aligned with this PR's direction: native away/locked delivery rather than reconnect-created banners, plus reconciliation so already handled alerts do not reappear. It would be useful to cover both “replied/resolved on desktop” and “opened/read on desktop” in physical-device validation because they may use different acknowledgement paths.

@OrcaWin

OrcaWin commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Closing as superseded by the merged split implementation:

I reviewed this PR’s full description and complete 294-file intended diff at 8eea3ee9d59281040c457090841e4c9aced34fbe, compared it with the split implementation, and checked the surviving behavior on main at 067c61476433c15ef684ef608a5a141549969519. The successors cover the durable per-event queue/quota/retry pipeline, authenticated registration and cleanup, authoritative desktop categories, native-only banners, mobile preferences, and host/epoch/sequence dismissal recovery. Differences include subsequent fixes such as preserving registrations after failed local unpair, explicit push-service consent, and retaining live dismissal fences beyond 512 entries.

The deployment workflow, dedicated database/IAM resources and recovery contracts also landed through #19912; #31792 subsequently moved deployment ownership to stablyai/orca-cloud, as documented in the current cloud/README.md. Their removal from this repository is therefore not missing implementation.

No independent implementation scope remains in this combined reference PR. Closing it does not claim that the original hands-on/provider acceptance gaps were completed, and does not approve a deployment or merge this old branch.

@OrcaWin OrcaWin closed this Oct 27, 2026
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.

3 participants