Repository navigation
Conversation
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.
The coordinator's own comment states the contract: readContext "throws on transient failures and returns null solely when the cloud session is gone (absent, or cleared by a 401)". The implementation did not honour it. readFreshOrcaCloudSession collapsed readOrcaCloudSession's `unreadable` status into `reconnect-required`, so readRelayAuthContext returned null and the coordinator published RELAY_HOST_CLOSE_REASON.SIGNED_OUT, closed the broker with that wire reason, and armed no retry because a terminal cause arms none. `unreadable` fires on EPERM/EACCES/EBUSY/EMFILE/ENFILE/EIO — descriptor exhaustion on a busy machine, a Windows AV file lock. The phone latches setHostSignedOut and shows "Desktop signed out — sign in to Orca on your desktop to reconnect" for a failure the next read would have cleared. The contrast is the argument: `unreadable` is the one status the session store's own doc says "licenses nothing", and clearCloudSessionIfUnchanged already refuses to delete a session because of it — "a session we were denied is not a session we may delete". The relay taxonomy was the single place treating it as evidence the user signed out. Give it its own arm on FreshCloudSessionResult and throw for it in readRelayAuthContext, which lands it on the retryable auth_unavailable path the coordinator already has. Every other caller tests `status !== 'found'`, so their behaviour is unchanged. Correct the coordinator comment to say what it actually depends on: null-means-gone is a contract readRelayAuthContext owes it, not something that branch can verify. Measured before the fix: offlineReason "signed-out", mint code relay_signed_out. After: auth_unavailable. Not fixed here, and worth a separate look: `decrypt-failed` when safeStorage.isEncryptionAvailable() is false (a Linux keyring still locked at login) takes the same route to SIGNED_OUT, but reclassifying it changes sign-in semantics well beyond the relay.
…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> (cherry picked from commit f0295a3)
The LAN-connected phone polls getEndpoints to ask whether relay is available; a null answer costs it nothing. Sitting through an armed retry would stall a poll the local connection is already serving, so that path passes a 0 budget and answers from whatever is in flight. Only createPairingRelay and provisionRelay, which cannot proceed without a relay, take the 20s default.
…hecks These test doubles predate the changed-code casting gate; each cast now carries the SAFETY: rationale it requires.
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (7)
💤 Files with no reviewable changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review. 📝 WalkthroughWalkthroughRelay authentication now distinguishes signed-out, entitlement, authentication, broker, and broker rejection causes. Broker waiters can follow scheduled retries within a bounded budget and return the associated offline reason. Retry backoff and scheduling are shared across relay components. Unreadable cloud sessions now raise an error instead of appearing absent. Pairing authorization moved to a dedicated module. Mobile diagnostic payload collection is centralized and includes relay status and app version without network identifiers. Priority: ➖ Normal Severity of issue fixed: Medium Merge Risk: 🟡 Moderate · up to Closing the relay pool may leave delayed retry work active after shutdown, creating stale relay activity. This should be resolved or explicitly accepted before merging. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Out of Scope Changes checkExplanation The renderer changes for mobile Relay diagnostics are unrelated to issue
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
🟠 Major · Cancel the drain retry when the pool closes. · relay-origin-pool.ts:104
src/main/runtime/relay/relay-origin-pool.ts:104
🩺 Stability & Availability | 🟠 Major | ⚡ Quick winCancel the drain retry when the pool closes.
RelayRetrySchedule.reset()only resets the attempt counter. It does not clear the timer. IfcloseNow()runs while a drain retry is armed, the timer survives for up to the configured backoff orRetry-Afterduration. The timer retains this pool and can delay process shutdown.Cancel the retry before resetting its attempt count.
Proposed fix
this.closed = true this.rotation.cancel() + this.drainRetry.cancel() this.drainRetry.reset() this.retirement.clear()
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 990cd90c-9d88-473c-a013-fce5cad91d31
📒 Files selected for processing (24)
src/main/orca-profiles/profile-cloud-session-refresh.tssrc/main/runtime/relay/desktop-relay-service-failure-cause.test.tssrc/main/runtime/relay/desktop-relay-service-wait-budget.test.tssrc/main/runtime/relay/desktop-relay-service.tssrc/main/runtime/relay/relay-auth-context-unreadable-session.test.tssrc/main/runtime/relay/relay-auth-context.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-backoff.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; 8 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — two minor suggestions inline.
Reviewed changes
- Wait through a scheduled retry —
waitForLiveBrokerResult()now parks onRelayRetrySchedule.settledafter a transient reconcile failure, bounded by a 20 s budget, and returns the cause the wait actually observed. - Per-caller budget —
getEndpointspasses0(awaits only an in-flight open, never a retry);requireActiveBroker(pairing, provisioning, and the desktop QR mint) takes the default and maps the cause to a mint-failure code. RelayRetrySchedule— the retry ladder is now shared withrelay-origin-pool; addssettled, andcancel()keeps the attempt count so a superseded retry does not restart the backoff.- Offline-reason and unreadable-session taxonomy — new
relay-offline-reason.tsvocabulary, plusreadFreshOrcaCloudSession'sunreadableresult thatreadRelayAuthContextturns into retryableauth_unavailableinstead of a sign-out. - Renderer diagnostics payload — shared builder used by
MobilePageandMobilePane, deliberately dropping the selected address and relay cell URL.
All 224 tests in src/main/runtime/relay/ and the touched renderer/shared/profile tests pass locally. The only substantive note beyond the inline comments: the 20 s default budget flows into the desktop-initiated QR mint path (runtime-rpc-mobile-pairing.ts), which is intended per the PR body but is a UX change worth confirming.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| if (pending !== this.latestReconcile) { | ||
| continue | ||
| } |
There was a problem hiding this comment.
The absolute deadline is only evaluated on the pending === latestReconcile exit below, so this continue skips it by construction. Any caller that reassigns latestReconcile while the waiter is inside await pending (repeated refreshDemand()/reconcile() churn, e.g. an endpoint poll or an auth mutation) can keep the loop going past budgetMs, defeating the bound the 20 s budget exists to provide. Checking the deadline before continuing makes the bound unconditional without cutting the open in flight.
Technical details
# Deadline is not enforced on the continue path
## Affected sites
- `src/main/runtime/relay/relay-auth-coordinator.ts:176-178` — `if (pending !== this.latestReconcile) { continue }` re-enters `while (!this.stopped)` without ever reaching the `Date.now() >= deadline` check at line 184.
## Required outcome
- The `budgetMs` bound must hold regardless of how often `latestReconcile` is replaced while the waiter is suspended.
## Suggested approach (optional)
- Move the deadline check to the top of the `while` loop, or check it before the `continue`.
## Open questions for the human (optional)
- Is there a caller that can drive `reconcile()` at a rate comparable to the awaited reconcile's settlement? If not, this is purely defensive.The coordinator case used the default wait budget, and a plain Error is retryable, so the waiter parked through the ladder for the full budget -- 20s of real time, the entire relay directory's wall clock. Budget 0 proves the same classification: reconcileEpoch publishes the reason before the waiter's first deadline check. stop() keeps the armed retry from firing inside whatever test runs next in the worker.
…ry point desktop-relay-service-failure-cause.test.ts asserted the reason-to-code table a second time -- relay-offline-reason.test.ts already covers all six pairs, and the Record makes an unmapped reason a compile error. The only extra fact was the throw at the service boundary, bought with Object.create, a double cast into a private method, and two cast suppressions. One case through createPairingRelay pins the same throw.
desktop-relay-service.ts re-exported pairingAuthorizationForContext so one test's import string would not have to change, and the coordinator re-exported four contract types of which three have no consumer anywhere. Both files keep their extraction and stay under the line cap; the surface now names only what someone imports. RelayAuthContext keeps its re-export: six files import it from the coordinator.
…econd result arm readFreshOrcaCloudSession already re-throws every non-auth failure, and that channel already lands in the coordinator's auth_unavailable. The carried fix added a parallel 'unreadable' arm and hand-joined it back into that channel two files away, which left the other reader of the arm -- runWithFreshOrcaCloudSession, and so the org-members path -- still reporting a locked file as a sign-out. Throwing at the producer fixes both readers, and forceRefreshOrcaCloudSession stops advertising a state it cannot produce. Audited all five runWithFreshOrcaCloudSession callers: capability refresh, profile create and org-member calls already wrap the call in try/catch and now return 'failed' with the message instead of a false reconnect prompt; artifact and skill operations propagate to a caller that already handles a rejection from this path for any network error.
There was a problem hiding this comment.
ℹ️ No critical issues — one minor comment-accuracy nit inline.
Reviewed changes
Four commits landed since the prior pullfrog review at 6beb02a:
- Unreadable session raised at the producer —
readFreshOrcaCloudSessionnow throwsorca_cloud_session_unreadablefor a session file it exists but cannot read, instead of returning a third result arm;readRelayAuthContextdrops its own translation andforceRefreshOrcaCloudSessionno longer advertises a state it cannot produce. - Compat re-exports dropped —
pairingAuthorizationForContextis imported directly fromrelay-pairing-authorization, and the coordinator re-exports onlyRelayAuthContext; the other three types had no external consumer. - Tests rebalanced — the
Object.create-based cause-code test is deleted (the table is covered exhaustively inrelay-offline-reason.test.ts), acreatePairingRelaycase pins the mapped throw through the public entry point, and the unreadable-session test now passes budget 0. - New coverage — the unreadable-session path and the five mint-failure codes are pinned through their real entry points.
All 229 tests in src/main/runtime/relay/ plus profile-cloud-session-refresh.test.ts pass locally in 4.9 s (down from ~24 s, which was the 20 s park the prior review flagged).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| // outcome must throw so it lands in auth_unavailable. That is a contract | ||
| // readRelayAuthContext owes this helper, not something it can verify — it held for a | ||
| // refresh failure but not for a session file the process could not read, which spent | ||
| // SIGNED_OUT on transient I/O until relay-auth-context.ts started throwing for it. A |
There was a problem hiding this comment.
The throw this sentence credits to relay-auth-context.ts moved to readFreshOrcaCloudSession in profile-cloud-session-refresh.ts in this delta, and relay-auth-context.ts no longer throws for an unreadable session. Naming profile-cloud-session-refresh.ts (or dropping the file reference) keeps the contract note pointing at the code that actually enforces it.
|
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 pairing waits for the retry, for a bounded time, and if it still has to give up it says why. The phone's routine "is relay available?" poll does not wait at all, exactly as it does today.
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.offlineReasonfix(relay): name the cause when relay pairing cannot mint #19659 introduces, sorequireActiveBrokernames the cause the wait actually observed.createPairingRelayandprovisionRelaytake that default.getEndpointspasses a budget of0and behaves exactly as main does today: it awaits the open in flight, then answers.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.Four further changes came out of a design review of the carried commits:
getEndpointspasses0, as described above. fix(relay): wait through a scheduled retry before surfacing relay_control_not_active #19436 gave both callers the same budget.unreadablearm toFreshCloudSessionResultand converted it back into a throw two files away, inside the relay layer.readFreshOrcaCloudSessionalready re-throws every other transient read failure onto the path that becomesauth_unavailable, so the arm was a second channel for a meaning the function already had — and its other reader,runWithFreshOrcaCloudSession, ignored the new word and still reported a locked file as a sign-out. That path feeds the organization-members view, so it kept showing "sign in again" for a file the next read would have opened. The throw now happens inreadFreshOrcaCloudSessionitself: both readers are fixed,forceRefreshOrcaCloudSessionstops advertising a state it cannot produce, and the relay layer loses its translation step. All five callers were audited; the three that already wrap the call now surface a plain failure instead of a false reconnect prompt, and the two that propagate already handle a rejection from this path for any network error.RelayAuthContextkeeps its re-export because six files import it from the coordinator.Object.createplus a double cast to re-assert a reason-to-code table another test already covers exhaustively; it is deleted, with the one fact it uniquely pinned moved to a case that goes throughcreatePairingRelay.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.Why the two callers differ, which is the change from #19436:
getEndpointsis the LAN-connected phone's periodic availability poll, and arelay: nullanswer costs it nothing — the phone is already connected locally. Making that poll sit through a backoff ladder would let a relay outage stall a request a working local connection is serving, and would hold a transient demand ref open for the duration. Pairing is the opposite: there is no fallback, the user is waiting on it, and a bounded wait is strictly better than an error the desktop was about to fix itself. Passing the budget per call site keeps that policy at the caller, where the tolerance is known, instead of encoding "a retry is pending" in the coordinator's return type.Linked Issue
Fixes #19345
Visual Proof
N/A — no UI change. The user-visible difference is timing, and the error text on a pairing failure that #19659 already introduced; there is no new surface to screenshot.
Testing
desktop-relay-service-wait-budget.test.ts(new here): with a retry armed by a failed first open,getEndpointsresolves to{ v: 1, relay: null }in the same tick without a second open attempt, whilecreatePairingRelaystays parked and resolves only once the retry's open succeeds. A third case pins that a signed-out session reaches the caller asrelay_signed_out, not the generic code. Each assertion was mutation-checked against the line it exists for.profile-cloud-session-refresh.test.ts: an unreadable session file rejects rather than reporting as gone, and nothing clears the stored session. Mutation-checked by restoring thereconnect-requiredreturn.relay-auth-coordinator-recovery.test.ts: waits through a scheduled retry and resolves to the broker; a cancelled retry resolves the waiter; 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.pnpm tcclean. The relay directory,src/main/orca-profiles,src/main/artifactsandsrc/main/skillsall pass: 136 files, 1,079 tests. The relay directory alone is 27 files and 219 tests, in 2.1s.oxlintclean on the changed files.pnpm run check:code-quality:changed— 0 new findings across 23 changed files.Conflicts resolved in the carry-forward, all in
relay-auth-coordinator.tsagainst fix(relay): carry the signed-out reason when the broker's own renewal notices the session loss #21562 (e49b3aa): the entitlement branch keeps main'sauthLossCloseReason(context)helper and gains this stack'spublish('offline', …)reason argument andthis.retry.reset(); the corrected null-case reasoning from fix(relay): name the cause when relay pairing cannot mint #19659's latest commit moved onto that helper, which now owns the rule;RelayAuthCoordinatorOptionsmoved to the contract file carrying main'sRelayAccessTokenRefreshreturn type rather than the oldstring | null. Alsorelay-origin-pool.tskept main's rotation constructor while switching to the renamed retry schedule, anddesktop-relay-service.tskept main's renamed region-preference module path.Platforms: desktop-local promise and timer logic with no platform-dependent paths; not separately exercised on Windows or Linux. No SSH surface — this is the desktop's own relay control socket.
I manually tested these changes locally — the transient open failure cannot be reproduced interactively; it is covered by fake-timer tests.
Automated tests added/updated
AI Disclosure
Diagnosis, code and tests produced by an AI coding agent (Claude) under @intiamaru's direction and review; consolidation with #19659 by @nwparker. Rebase onto current main, the per-caller budget change, and its test by Claude Code under @Jinwoo-H's direction.
Agent skill upstream boundary
Notes
Backwards compatibility: no wire or RPC contract change —
getEndpointsreturns the shapes it does today, and the phone sees the samerelay: nullit already handles. Performance: the endpoint poll's cost is unchanged; the only added wait is on pairing, bounded at 20s and cancelled by any fence or fresh reconcile.Checklist
pnpm tc, touched suites,oxlint, and the changed-code quality gate pass locally🤖 Generated with Claude Code