Repository navigation
Conversation
There was a problem hiding this comment.
Important
The fix correctly resolves the transient-hiccup case, but it also removes the fail-fast path for a sustained retryable outage — see the inline comment.
Reviewed changes
waitForLiveBrokerwaits through a scheduled retry — aretryScheduledresolvable signal, set byscheduleRetryand resolved by both the retry firing andcancelRetry, lets the waiter sit through the coordinator's own recovery instead of returningnullon the first cold-start failure.- Backoff math extracted to
relay-retry-backoff.ts— purecomputeRetryDelayMsmirrors the existingrelay-drain-retry-schedule.tspattern and keeps the coordinator under the 300-line cap. - Two regression tests added — one asserts
waitForLiveBrokerresolves to the broker after the scheduled retry succeeds; the other guards thecancelRetrywake-up path against a hung waiter.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change centralizes relay retry scheduling with capped exponential backoff and Severity of issue fixed: Medium Merge Risk: 🟠 High · up to Mobile pairing can still fail before an automatic relay retry has time to recover, while exceptional retry paths may delay waiters. These relay recovery issues should be fixed before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Out of Scope Changes checkExplanation The PR includes changes beyond the retry-wait objective in [ Resolution Remove the unrelated diagnostics, offline-reason, and pairing-authorization changes, or split them into separate PRs with linked issues. Keep the retry scheduling, bounded wait behavior, coordinator integration, and directly related tests in this PR.
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 4373ac10-0a84-4b33-9689-bbd1cdfb9eb4
📥 Commits
Reviewing files that changed from the base of the PR and between a278d84 and 2c94b69f6509b6799bc8edb57327daf7d599c80a.
📒 Files selected for processing (3)
src/main/runtime/relay/relay-auth-coordinator-recovery.test.tssrc/main/runtime/relay/relay-auth-coordinator.tssrc/main/runtime/relay/relay-retry-backoff.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
|
Added a follow-up commit on top of the Reasoning: the original version's wait was unbounded — during a genuine, sustained relay outage it would ride the full backoff ladder (up to 5-minute gaps) indefinitely rather than failing clearly. The phone-facing pairing RPC has no timeout of its own, so that path could hang a pairing attempt instead of surfacing a clear error. This starts the budget deliberately long (10 min) so it essentially never triggers on ordinary transient recovery, with room to tighten based on real-world timing data. The pure race-against-deadline logic lives alongside
|
There was a problem hiding this comment.
ℹ️ No critical issues — the prior unbounded-wait concern is now resolved with a 10-minute budget; one minor suggestion inline.
Reviewed changes
- Bounded the wait through scheduled retries —
waitForLiveBroker(budgetMs)now computes a deadline and races each await (the in-flight reconcile and the scheduled retry) against it via a newraceDeadlinehelper, so a sustained outage returnsnullafterLIVE_BROKER_WAIT_BUDGET_MS(10 min) instead of blocking indefinitely. - Added a budget-elapse regression test —
gives up once its wait budget elapses during a sustained outagedriveswaitForLiveBroker(5_000)with fake timers and asserts it resolvesnullwhile the retry ladder keeps firing.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: e6dac85b-4a7d-4f2e-9838-d0f967f9fdc9
📥 Commits
Reviewing files that changed from the base of the PR and between 2c94b69f6509b6799bc8edb57327daf7d599c80a and a7b0646511b47b5d7e23a8eedb97d06de10c55f5.
📒 Files selected for processing (3)
src/main/runtime/relay/relay-auth-coordinator-recovery.test.tssrc/main/runtime/relay/relay-auth-coordinator.tssrc/main/runtime/relay/relay-retry-backoff.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
| export function raceDeadline<T>(promise: Promise<T>, deadline: number): Promise<T | void> { | ||
| return Promise.race([ | ||
| promise, | ||
| new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now()))) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- target file ---'
cat -n src/main/runtime/relay/relay-retry-backoff.ts
printf '%s\n' '--- direct references ---'
rg -n -C 3 'raceDeadline|waitForLiveBroker' src/main test tests 2>/dev/null || trueRepository: stablyai/orca
Length of output: 22466
🤖 get_repo_knowledge executed:
get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/architecture
Length of output: 31742
🏁 Script executed:
#!/bin/bash
set -eu
printf '%s\n' '--- waitForLiveBroker and retry cancellation ---'
cat -n src/main/runtime/relay/relay-auth-coordinator.ts | sed -n '140,170p;320,360p'
printf '%s\n' '--- runtime and test timer policy ---'
rg -n -C 3 'unref\(|clearTimeout\(|setTimeout\(' src/main/runtime/relay src/main/startup | head -240Repository: stablyai/orca
Length of output: 21065
Clear the deadline timer when promise settles first.
raceDeadline() passes a setTimeout() promise to Promise.race() without retaining its timer handle. The reconciliation and retry paths can settle before the deadline, leaving each losing timer referenced until its deadline. Clear the timer in finally.
Proposed fix
export function raceDeadline<T>(promise: Promise<T>, deadline: number): Promise<T | void> {
- return Promise.race([
- promise,
- new Promise<void>((resolve) => setTimeout(resolve, Math.max(0, deadline - Date.now())))
- ])
+ let timer: ReturnType<typeof setTimeout> | undefined
+ return Promise.race([
+ promise,
+ new Promise<void>((resolve) => {
+ timer = setTimeout(resolve, Math.max(0, deadline - Date.now()))
+ })
+ ]).finally(() => {
+ if (timer !== undefined) {
+ clearTimeout(timer)
+ }
+ })
}|
Addressed both review findings in b35500f:
159/159 relay tests, lint, ratchet, and full typecheck pass locally. |
There was a problem hiding this comment.
✅ No new issues found — the prior timer-leak nit is cleanly addressed.
Reviewed changes
- Replaced
raceDeadlinewith the sharedwithTimeout— the timer-leak finding from the prior review is resolved by reusingsrc/shared/promise-timeout-fallback.ts, whose.finallyclears its deadline timer;waitForLiveBrokernow awaits each step viawithTimeout(pending, remainingMs(), undefined), and the now-unusedraceDeadlinehelper was dropped fromrelay-retry-backoff.ts. - Strengthened the canceled-retry regression test — an
await vi.advanceTimersByTimeAsync(0)flush now guarantees the waiter is actually parked on the retry signal beforefenceAndCloseNow()runs, so thecancelRetrywake-up path is genuinely exercised rather than passing regardless.
The restructure is semantically equivalent to the previous revision: the budgetMs default and per-await deadline checks behave identically, and the else if branch preserves the original fail-fast return when no retry is scheduled.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
Problem: every Anywhere/Relay pairing mint failure surfaced to the user as the generic relay_control_not_active code, whether the real cause was a revoked/absent cloud session, a missing relay.use entitlement, or a broker cold-start/transport failure. RelayAuthCoordinator already knew which of these happened on every path that publishes 'offline' but discarded it, so DesktopRelayService.requireActiveBroker() could only throw the one generic code. Fix: RelayAuthCoordinator now records why it last went offline (RelayOfflineReason, reusing the existing RELAY_HOST_CLOSE_REASON wire vocabulary for signed-out rather than inventing a parallel constant) and clears it once it goes back online. requireActiveBroker() maps that reason to relay_signed_out / relay_not_entitled / relay_broker_unavailable via relayOfflineReasonMintFailureCode(), falling back to relay_control_not_active when no reason is known. The code already flowed unchanged through mobileRelayMintFailureFromUnknown into the mobile_pairing_relay_failure payload (verified with a regression test), and neither renderer consumer maps failure.code to UI text today (only .stage and a separate auth-status flag), so no new user-facing strings or localization entries were needed. Also extends the "Copy diagnostics" payload (MobilePage.tsx) with the live relay status and app version via a new pure buildMobileRelayDiagnosticsPayload() builder, deliberately omitting any address (matching the existing LAN/Tailscale-leak precedent) — only relayStatus and appVersion are added. relay-auth-coordinator.ts and desktop-relay-service.ts were already at this repo's 300-line oxlint ceiling, so the offline-reason mapping, the retry-backoff jitter math, and the already independently-tested pairingAuthorizationForContext helper were extracted into their own small files (relay-offline-reason.ts, relay-retry-delay.ts, relay-pairing-authorization.ts) instead of disabling the rule. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The Settings → Mobile pane had its own inline "Copy diagnostics" builder that still wrote the selected address into a payload users are asked to share, and lacked the relay status and app version. Both entry points now call one collectMobileRelayDiagnosticsPayload, so they emit one shape with no network identifier. RelayDrainRetrySchedule reuses relayRetryDelayMs instead of carrying a second copy of the same backoff constants and formula. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…retryable from rejected
- waitForLiveBrokerResult() returns { broker } | { broker: null, offlineReason }
so requireActiveBroker maps the reason the wait actually observed instead of
re-reading coordinator state after the wait returned.
- broker-open failures split three ways by what the failure proves:
auth_unavailable (session read/refresh failed, never reached the relay),
broker_unavailable (relay refused transiently, retry armed),
broker_rejected (4xx, no retry armed).
- retry backoff extraction renamed to relay-retry-backoff.ts::computeRetryDelayMs
with retryAfterMs folded in; RelayDrainRetrySchedule uses the same function.
- coordinator types move to relay-auth-coordinator-contract.ts to stay under
the file cap without a lint bypass.
b35500f to
897fa67
Compare
…e offline cause - RelayRetrySchedule (was RelayDrainRetrySchedule) owns the single armed retry for both the coordinator and the origin pool; `settled` resolves when the retry fires or is cancelled so a waiter can sit through it. - waitForLiveBrokerResult keeps waiting while a retry is armed and returns the observed offline cause only when the wait gives up. Terminal causes (signed out, unentitled, rejected) arm nothing, so they return immediately. - The wait is budgeted (30s default, matching the phone's RPC budget) so a sustained outage fails the caller instead of holding a demand ref open. Co-authored-by: Neil Parker <nwparker@users.noreply.github.com>
897fa67 to
f0295a3
Compare
|
Maintainer note: I force-pushed your branch (maintainer-can-modify was on) so it now stacks on #19659 — the two PRs guard the same consumer against two independent overloads of one
Your three tests are carried over verbatim (the cancel test keeps your flush comment). Body updated. Push back on anything here. |
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 18948934-e76a-4a2d-b74c-85d95cdf0675
📥 Commits
Reviewing files that changed from the base of the PR and between b35500fa34faa2452709dd429ffa9b1eab177913 and f0295a3.
📒 Files selected for processing (19)
src/main/runtime/relay/desktop-relay-service-failure-cause.test.tssrc/main/runtime/relay/desktop-relay-service.tssrc/main/runtime/relay/relay-auth-coordinator-contract.tssrc/main/runtime/relay/relay-auth-coordinator-offline-reason.test.tssrc/main/runtime/relay/relay-auth-coordinator-recovery.test.tssrc/main/runtime/relay/relay-auth-coordinator.tssrc/main/runtime/relay/relay-drain-retry-schedule.tssrc/main/runtime/relay/relay-offline-reason.test.tssrc/main/runtime/relay/relay-offline-reason.tssrc/main/runtime/relay/relay-origin-pool.tssrc/main/runtime/relay/relay-pairing-authorization.tssrc/main/runtime/relay/relay-retry-backoff.test.tssrc/main/runtime/relay/relay-retry-schedule.test.tssrc/main/runtime/relay/relay-retry-schedule.tssrc/renderer/src/components/mobile/MobilePage.tsxsrc/renderer/src/components/mobile/mobile-relay-diagnostics-payload.test.tssrc/renderer/src/components/mobile/mobile-relay-diagnostics-payload.tssrc/renderer/src/components/settings/MobilePane.tsxsrc/shared/mobile-relay-mint-failure.test.ts
💤 Files with no reviewable changes (1)
- src/main/runtime/relay/relay-drain-retry-schedule.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| // an open already in flight. It spans the first few rungs of the backoff | ||
| // ladder and stays inside the phone's 30s request budget, so a sustained | ||
| // outage fails the caller with its cause instead of parking the demand ref. | ||
| private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 20_000 |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use the required 10-minute default wait budget.
Line 51 sets the default to 20 seconds. The PR objective specifies a 10-minute default. Default callers can therefore stop waiting 580 seconds earlier than the stated contract.
Update the constant and its adjacent rationale.
Proposed fix
- private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 20_000
+ private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 10 * 60_000📝 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.
| private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 20_000 | |
| private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 10 * 60_000 |
| retry() | ||
| armed.resolve() |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Resolve settled when the retry callback throws.
If retry() throws, armed.resolve() does not run. A caller that awaits this signal remains blocked until an independent timeout expires.
Use finally to preserve the required callback-before-settlement ordering.
Proposed fix
- retry()
- armed.resolve()
+ try {
+ retry()
+ } finally {
+ armed.resolve()
+ }📝 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.
| retry() | |
| armed.resolve() | |
| try { | |
| retry() | |
| } finally { | |
| armed.resolve() | |
| } |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Named the offline cause instead of the generic
relay_control_not_active— a newRelayOfflineReasontype plusrelayOfflineReasonMintFailureCodemapssigned-out/not_entitled/broker_unavailable/broker_rejected/auth_unavailableto distinctrelay_*codes, carried out of the wait bywaitForLiveBrokerResult()and thrown byrequireActiveBroker(). - Generalized the retry schedule — deleted
relay-drain-retry-schedule.tsin favor of a sharedRelayRetrySchedule(exposing asettledsignal the waiter sits on) and the purecomputeRetryDelayMs, now used by both the auth coordinator andRelayOriginPool. - Tightened the wait budget from 10 min to 20 s —
LIVE_BROKER_WAIT_BUDGET_MSnow fits inside the phone's 30 s request budget while still spanning the first few backoff rungs. - Extracted the coordinator contract types into
relay-auth-coordinator-contract.ts— keepsrelay-auth-coordinator.tsunder the 300-line cap. - Shared the diagnostics payload between
MobilePageandMobilePane—collectMobileRelayDiagnosticsPayloadaddsrelayStatusandappVersion, and drops theselectedAddressfield that previously leaked a LAN/Tailscale IP. - Added regression tests covering the offline-reason mapping, the retry schedule, and the diagnostics payload.
ℹ️ Nitpicks
- The PR description still describes the original 3-file wait-through-retry scope and references the removed
retryScheduledsignal name; it doesn't mention the offline-cause naming or the diagnostics-payload sharing now in the diff.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Carried forward in #22122, which rebases this onto current main and adds one behaviour change: the endpoint probe ( Leaving this PR open — #22122 carries your commits (and #19659's, since GitHub cannot base a PR on a fork branch), with authorship and credit preserved. Conflict resolutions against #21562 are described in that PR's Testing section. Nothing here was force-pushed or rewritten. |
|
Thanks for this. The same fix landed in #27141 (the relay coordinator now records why it is not ready and callers wait through a scheduled retry within a bounded budget), which covers this PR's scenario, so this can be closed as superseded. |

ELI5
When your phone tries to pair and the desktop's relay connection was idle, the very first reconnect sometimes hits a brief hiccup. The desktop already retries that on its own a second later — but the phone's pairing request gave up and showed an error before that retry ran. Now it waits for the retry, for a bounded time, and if it still has to give up it says why.
What Changed
RelayAuthCoordinator.waitForLiveBrokerResult()previously awaited only the in-flight reconcile and returned as soon aspending === this.latestReconcile— which is exactly true while a retry timer is armed. The waiter read "not yet, a retry is coming" as "nothing more is coming".RelayRetrySchedule(the formerRelayDrainRetrySchedule, now shared by the coordinator and the origin pool) exposessettled: a promise that resolves when the armed retry fires or is cancelled. After a reconcile settles without a live broker, the waiter checks for an armed retry and, if one exists, sits through it and re-checks. A terminal outcome (signed out, unentitled, relay rejected us) arms nothing, so its cause returns immediately — no one waits out the budget to be told to sign in. A test pins that.offlineReasonfix(relay): name the cause when relay pairing cannot mint #19659 introduced, sorequireActiveBrokernames the cause the wait actually observed. Nothing about "a retry is pending" is encoded in the return type; the two callers of the wait keep their existing tolerance and the demand ref held bywithTransientDemandis unaffected.budgetMsparameter) bounds only the retry chain, never a reconcile already in flight — opens carry their own HTTP deadlines, and cutting a slow-but-succeeding open short would fail a pairing that was about to work (test: an 8s first open past a 1s budget still returns the broker). It stays inside the phone's 30s request budget so the cause reaches the phone instead of a timeout. Timers are cleared on the fast path via the existingwithTimeout.cancel()wakes a parked waiter (externalreconcile(),fenceAndCloseNow()), and keeps the attempt count so a superseded retry does not restart the backoff ladder.ensureLive()still defers to an armed retry.Why
Root-caused from two occurrences of the same diagnostic payload (
relay_control_not_activeatcreate_pairing_relay) in #19345. In both, a full app restart "fixed" it — a race masked by state reset, not an outage.waitForLiveBroker()gave up after exactly one cold-start attempt instead of waiting for the coordinator's own recovery.Fixes #19345
Testing
relay-auth-coordinator-recovery.test.ts: waits through a scheduled retry and resolves to the broker; a cancelled retry resolves the waiter (with a flush so it is really parked on the signal first); gives up once the budget elapses during a sustained outage; never cuts an in-flight open short; a signed-out waiter returns at once with its cause.relay-retry-schedule.test.ts: no signal while idle; settles after the retry ran; settles on cancel without running the retry; attempt count survives cancel;Retry-Afterfloor.Retry-Afterignored;ensureLiveignores an armed retry; budget cuts an in-flight open. One mutation survived — swappingretry()andarmed.resolve()order — and is inert:resolve()only queues a microtask, so a synchronousretry()in the same tick always runs first.pnpm tc, repo-wideoxlint,check:code-quality:changed(0 new),check:max-lines-ratchet(no new bypasses). Relay suite 22 files / 188 tests.AI Disclosure
Diagnosis, code and tests produced by an AI coding agent (Claude) under @intiamaru's direction and review; consolidation with #19659 by a maintainer with Claude Code.
Agent skill upstream boundary
Checklist
🤖 Generated with Claude Code