Skip to content

fix(relay): wait through a scheduled retry before surfacing relay_control_not_active - #22122

Closed
Jinwoo-H wants to merge 11 commits into
mainfrom
jinwoo/relay-wait-through-retry
Closed

Jinwoo-H wants to merge 11 commits into
mainfrom
jinwoo/relay-wait-through-retry

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​748 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​748
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​353 $\color{#cf222e}{\Huge{\mathbf{−}}}$​167 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​186

Supersedes #19659, #19436 and #20055, rebased onto current main. Fixes #19345.

Original work by @intiamaru's agent, consolidated by @nwparker. Carried forward here because neither source branch could be rebased without rewriting its author's branch: #19436 and #19659 live on forks, so GitHub cannot take fix/relay-pairing-failure-cause as a base.

The base is main and the first four commits are the ones #19659 and #20055 already carry. The last seven are this PR's: the wait-through-retry mechanism from #19436, plus the design changes below.

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 as pending === 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".

  • The temporal case stays in the loop. RelayRetrySchedule (the former RelayDrainRetrySchedule, now shared by the coordinator and the origin pool) exposes settled: 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.
  • The causal case stays in the return value. When the loop gives up it returns the offlineReason fix(relay): name the cause when relay pairing cannot mint #19659 introduces, so requireActiveBroker names the cause the wait actually observed.
  • Bounded, and only where waiting buys something. The 20s budget bounds 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. createPairingRelay and provisionRelay take that default. getEndpoints passes a budget of 0 and behaves exactly as main does today: it awaits the open in flight, then answers.
  • cancel() wakes a parked waiter (external reconcile(), 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:

  • The endpoint probe does not wait. getEndpoints passes 0, as described above. fix(relay): wait through a scheduled retry before surfacing relay_control_not_active #19436 gave both callers the same budget.
  • An unreadable session file is raised where it is detected. fix(relay): stop an unreadable session file reporting as a sign-out #20055 added a third unreadable arm to FreshCloudSessionResult and converted it back into a throw two files away, inside the relay layer. readFreshOrcaCloudSession already re-throws every other transient read failure onto the path that becomes auth_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 in readFreshOrcaCloudSession itself: both readers are fixed, forceRefreshOrcaCloudSession stops 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.
  • No compat re-exports. Two files were split to stay under the line cap and then re-exported the moved symbols, so nothing about either module's surface actually narrowed. Both re-exports are gone; three of the four re-exported coordinator types had no consumer anywhere. RelayAuthContext keeps its re-export because six files import it from the coordinator.
  • Two tests traded for better ones. The unreadable-session case used the default wait budget against a retryable failure, so it parked through the backoff ladder for 20 seconds of real time — by itself the entire relay directory's runtime, now 2.1s for the directory. And one file reached a private method through Object.create plus 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 through createPairingRelay.

Why

Root-caused from two occurrences of the same diagnostic payload (relay_control_not_active at create_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: getEndpoints is the LAN-connected phone's periodic availability poll, and a relay: null answer 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, getEndpoints resolves to { v: 1, relay: null } in the same tick without a second open attempt, while createPairingRelay stays parked and resolves only once the retry's open succeeds. A third case pins that a signed-out session reaches the caller as relay_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 the reconnect-required return.

  • 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-After floor.

  • pnpm tc clean. The relay directory, src/main/orca-profiles, src/main/artifacts and src/main/skills all pass: 136 files, 1,079 tests. The relay directory alone is 27 files and 219 tests, in 2.1s. oxlint clean 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.ts against fix(relay): carry the signed-out reason when the broker's own renewal notices the session loss #21562 (e49b3aa): the entitlement branch keeps main's authLossCloseReason(context) helper and gains this stack's publish('offline', …) reason argument and this.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; RelayAuthCoordinatorOptions moved to the contract file carrying main's RelayAccessTokenRefresh return type rather than the old string | null. Also relay-origin-pool.ts kept main's rotation constructor while switching to the renamed retry schedule, and desktop-relay-service.ts kept 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

  • Not applicable.

Notes

Backwards compatibility: no wire or RPC contract change — getEndpoints returns the shapes it does today, and the phone sees the same relay: null it 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

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • N/A — no UI change
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (pure timing and promise logic; desktop-local)
  • pnpm tc, touched suites, oxlint, and the changed-code quality gate pass locally

🤖 Generated with Claude Code

tan7vir and others added 7 commits September 21, 2026 21:28
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.
@coderabbitai

coderabbitai Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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 configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 7f218130-4862-4536-9089-71af8100e18e

📥 Commits

Reviewing files that changed from the base of the PR and between 6beb02a and e0124c3.

📒 Files selected for processing (7)
  • src/main/orca-profiles/profile-cloud-session-refresh.test.ts
  • src/main/orca-profiles/profile-cloud-session-refresh.ts
  • src/main/runtime/relay/desktop-relay-service-wait-budget.test.ts
  • src/main/runtime/relay/desktop-relay-service.test.ts
  • src/main/runtime/relay/desktop-relay-service.ts
  • src/main/runtime/relay/relay-auth-context-unreadable-session.test.ts
  • src/main/runtime/relay/relay-auth-coordinator.ts
💤 Files with no reviewable changes (1)
  • src/main/runtime/relay/desktop-relay-service.ts

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


📝 Walkthrough

Walkthrough

Relay 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 e0124

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)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The renderer changes for mobile Relay diagnostics are unrelated to issue #19345. MobilePage, MobilePane, and the new diagnostics helper and tests collect relay status and app version and remove ne… Move the mobile Relay diagnostics changes and their tests to a linked diagnostics issue or a separate pull request. Keep this pull request focused on the retry-aware relay wait and required terminal-reason handling.
Docstring Coverage ⚠️ Warning Docstring coverage is 46.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 15 functions across 25 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Issue #19345 requires pairing to wait through an already scheduled retry, use a bounded wait, and return terminal causes without the retry delay. RelayAuthCoordinator.waitForLiveBrokerResult() obser…
Title check ✅ Passed The title clearly and concisely describes the primary change: waiting through a scheduled relay retry before reporting relay_control_not_active.
Description check ✅ Passed The description is complete and focused. It includes the required explanation, changes, rationale, linked issue, visual-proof justification, testing details, AI disclosure, compatibility notes, and ch…
Full details: Out of Scope Changes check

Explanation

The renderer changes for mobile Relay diagnostics are unrelated to issue #19345. MobilePage, MobilePane, and the new diagnostics helper and tests collect relay status and app version and remove network identifiers from copied diagnostics. These changes do not implement or test the retry-aware pairing wait.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new 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.

❤️ 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: 1

Caution

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

⚠️ Outside diff range comments (1)

🟠 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 win

Cancel the drain retry when the pool closes.

RelayRetrySchedule.reset() only resets the attempt counter. It does not clear the timer. If closeNow() runs while a drain retry is armed, the timer survives for up to the configured backoff or Retry-After duration. 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

📥 Commits

Reviewing files that changed from the base of the PR and between 197550c and 6beb02a.

📒 Files selected for processing (24)
  • src/main/orca-profiles/profile-cloud-session-refresh.ts
  • src/main/runtime/relay/desktop-relay-service-failure-cause.test.ts
  • src/main/runtime/relay/desktop-relay-service-wait-budget.test.ts
  • src/main/runtime/relay/desktop-relay-service.ts
  • src/main/runtime/relay/relay-auth-context-unreadable-session.test.ts
  • src/main/runtime/relay/relay-auth-context.ts
  • src/main/runtime/relay/relay-auth-coordinator-contract.ts
  • src/main/runtime/relay/relay-auth-coordinator-offline-reason.test.ts
  • src/main/runtime/relay/relay-auth-coordinator-recovery.test.ts
  • src/main/runtime/relay/relay-auth-coordinator.ts
  • src/main/runtime/relay/relay-drain-retry-schedule.ts
  • src/main/runtime/relay/relay-offline-reason.test.ts
  • src/main/runtime/relay/relay-offline-reason.ts
  • src/main/runtime/relay/relay-origin-pool.ts
  • src/main/runtime/relay/relay-pairing-authorization.ts
  • src/main/runtime/relay/relay-retry-backoff.test.ts
  • src/main/runtime/relay/relay-retry-backoff.ts
  • src/main/runtime/relay/relay-retry-schedule.test.ts
  • src/main/runtime/relay/relay-retry-schedule.ts
  • src/renderer/src/components/mobile/MobilePage.tsx
  • src/renderer/src/components/mobile/mobile-relay-diagnostics-payload.test.ts
  • src/renderer/src/components/mobile/mobile-relay-diagnostics-payload.ts
  • src/renderer/src/components/settings/MobilePane.tsx
  • src/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.

@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 critical issues — two minor suggestions inline.

Reviewed changes

  • Wait through a scheduled retry — waitForLiveBrokerResult() now parks on RelayRetrySchedule.settled after a transient reconcile failure, bounded by a 20 s budget, and returns the cause the wait actually observed.
  • Per-caller budget — getEndpoints passes 0 (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 with relay-origin-pool; adds settled, and cancel() keeps the attempt count so a superseded retry does not restart the backoff.
  • Offline-reason and unreadable-session taxonomy — new relay-offline-reason.ts vocabulary, plus readFreshOrcaCloudSession's unreadable result that readRelayAuthContext turns into retryable auth_unavailable instead of a sign-out.
  • Renderer diagnostics payload — shared builder used by MobilePage and MobilePane, 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.

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

Comment on lines +176 to +178
if (pending !== this.latestReconcile) {
continue
}

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.

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.

@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 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 — readFreshOrcaCloudSession now throws orca_cloud_session_unreadable for a session file it exists but cannot read, instead of returning a third result arm; readRelayAuthContext drops its own translation and forceRefreshOrcaCloudSession no longer advertises a state it cannot produce.
  • Compat re-exports dropped — pairingAuthorizationForContext is imported directly from relay-pairing-authorization, and the coordinator re-exports only RelayAuthContext; the other three types had no external consumer.
  • Tests rebalanced — the Object.create-based cause-code test is deleted (the table is covered exhaustively in relay-offline-reason.test.ts), a createPairingRelay case 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).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using 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

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.

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.

@OrcaWin

OrcaWin commented Oct 10, 2026

Copy link
Copy Markdown
Collaborator

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.

@nwparker

nwparker commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded — the linked issue (#19345) has been resolved on main by #27139 (3822ad8b3a), #27141 (1f5e8df421). Thanks for the contribution!

@nwparker nwparker closed this Nov 5, 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.

Mobile pairing fails with relay_control_not_active on first cold-start reconnect attempt

5 participants