Skip to content

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

Closed
intiamaru wants to merge 4 commits into
stablyai:mainfrom
intiamaru:fix/relay-auth-coordinator-wait-through-scheduled-retry
Closed

intiamaru wants to merge 4 commits into
stablyai:mainfrom
intiamaru:fix/relay-auth-coordinator-wait-through-scheduled-retry

Conversation

@intiamaru

@intiamaru intiamaru commented Sep 8, 2026 •

Copy link
Copy Markdown

Stacked on #19659. Base is main because the parent lives on another fork, so this diff shows #19659's commits until it merges. This PR's own change is the top commit (f0295a30e27).

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 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. A test pins that.
  • The causal case stays in the return value. When the loop finally gives up it returns the offlineReason fix(relay): name the cause when relay pairing cannot mint #19659 introduced, so requireActiveBroker names 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 by withTransientDemand is unaffected.
  • Bounded. The budget (20s default; budgetMs parameter) 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 existing withTimeout.
  • 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.

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.

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-After floor.
  • Mutation-tested (each killed by the assertion written for it): never wait through a retry; cancel does not wake the waiter; budget removed; budget applied only to the reconcile wait; terminal cause parks for the budget; cancel restarts the ladder; Retry-After ignored; ensureLive ignores an armed retry; budget cuts an in-flight open. One mutation survived — swapping retry() and armed.resolve() order — and is inert: resolve() only queues a microtask, so a synchronous retry() in the same tick always runs first.
  • pnpm tc, repo-wide oxlint, check:code-quality:changed (0 new), check:max-lines-ratchet (no new bypasses). Relay suite 22 files / 188 tests.
  • Automated tests added/updated
  • Manually tested (the transient failure cannot be reproduced interactively; covered by fake-timer 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

  • Not applicable.

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/promise logic; desktop-local)
  • lint / typecheck / touched suites pass locally

🤖 Generated with Claude Code

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

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

  • waitForLiveBroker waits through a scheduled retry — a retryScheduled resolvable signal, set by scheduleRetry and resolved by both the retry firing and cancelRetry, lets the waiter sit through the coordinator's own recovery instead of returning null on the first cold-start failure.
  • Backoff math extracted to relay-retry-backoff.ts — pure computeRetryDelayMs mirrors the existing relay-drain-retry-schedule.ts pattern and keeps the coordinator under the 300-line cap.
  • Two regression tests added — one asserts waitForLiveBroker resolves to the broker after the scheduled retry succeeds; the other guards the cancelRetry wake-up path against a hung waiter.

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

@coderabbitai

coderabbitai Bot commented Sep 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change centralizes relay retry scheduling with capped exponential backoff and Retry-After handling. waitForLiveBroker() now supports a bounded wait and returns offline reasons through waitForLiveBrokerResult(). DesktopRelayService maps those reasons to specific failure codes. Mobile diagnostics collection now omits network identifiers. Tests cover retry recovery, cancellation, timeout, failure classification, and sanitized payloads.

Severity of issue fixed: Medium

Merge Risk: 🟠 High · up to f0295

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)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes changes beyond the retry-wait objective in [#19345], including mobile diagnostics payload refactoring, offline-reason failure-code mapping, and pairing-authorization extraction. These … 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 i…
Docstring Coverage ⚠️ Warning Docstring coverage is 45.45% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 19 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 The changes satisfy issue [#19345]. waitForLiveBroker now waits through scheduled retries, wakes when retries are canceled, applies a bounded wait budget, and includes regression tests for recovery an…
Title check ✅ Passed The title clearly and concisely describes the main change: waiting through a scheduled relay retry before reporting relay_control_not_active.
Description check ✅ Passed The description is complete and directly explains the problem, implementation, rationale, linked issue, tests, AI disclosure, and checklist status. It includes Fixes #19345 and marks the UI proof as n…
Full details: Out of Scope Changes check

Explanation

The PR includes changes beyond the retry-wait objective in [#19345], including mobile diagnostics payload refactoring, offline-reason failure-code mapping, and pairing-authorization extraction. These changes are not required to fix the reported cold-start retry race.

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.

  • Fix all pre-merge checks with AI

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


ℹ️ 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.ts
  • src/main/runtime/relay/relay-auth-coordinator.ts
  • src/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.

@intiamaru

Copy link
Copy Markdown
Author

Added a follow-up commit on top of the retryScheduled mechanism: waitForLiveBroker() now takes a budgetMs (default 10 minutes — deliberately long, tightenable later) and gives up once the deadline passes, whether it's waiting on the current reconcile attempt or on a scheduled retry.

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 computeRetryDelayMs in relay-retry-backoff.ts to keep the coordinator file under the 300-line cap. Added a regression test (gives up once its wait budget elapses during a sustained outage) confirming it resolves to null rather than hanging.

pnpm lint, pnpm typecheck, and the full relay-auth-coordinator*/relay suite (159 tests) pass locally.

@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 — 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 new raceDeadline helper, so a sustained outage returns null after LIVE_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 outage drives waitForLiveBroker(5_000) with fake timers and asserts it resolves null while the retry ladder keeps firing.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | 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: 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.ts
  • src/main/runtime/relay/relay-auth-coordinator.ts
  • src/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())))

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

🔎 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 || true

Repository: 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 -240

Repository: 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)
+    }
+  })
 }

@intiamaru

Copy link
Copy Markdown
Author

Addressed both review findings in b35500f:

  • Timer leak (pullfrog + coderabbit): swapped the bespoke `raceDeadline` for the existing `withTimeout` from `shared/promise-timeout-fallback.ts`, which already clears its timer in `.finally()`. Its "rejection resolves the fallback" behavior is a no-op here since neither `latestReconcile` nor `retryScheduled.promise` ever reject. Dropped the now-unused `raceDeadline` from `relay-retry-backoff.ts`.
  • Test race (coderabbit, on the "resolves a wait for a canceled retry" test): `fenceAndCloseNow()` could run before the waiter reached `await retry.promise`, so the test passed via the early-return branch without actually exercising `cancelRetry`'s wake-up call. Added a timer flush so it parks on the retry signal first.

159/159 relay tests, lint, ratchet, and full typecheck pass locally.

@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 — the prior timer-leak nit is cleanly addressed.

Reviewed changes

  • Replaced raceDeadline with the shared withTimeout — the timer-leak finding from the prior review is resolved by reusing src/shared/promise-timeout-fallback.ts, whose .finally clears its deadline timer; waitForLiveBroker now awaits each step via withTimeout(pending, remainingMs(), undefined), and the now-unused raceDeadline helper was dropped from relay-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 before fenceAndCloseNow() runs, so the cancelRetry wake-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.

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

tan7vir and others added 2 commits September 9, 2026 07:27
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.
@nwparker
nwparker force-pushed the fix/relay-auth-coordinator-wait-through-scheduled-retry branch from b35500f to 897fa67 Compare September 10, 2026 11:33
…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>
@nwparker
nwparker force-pushed the fix/relay-auth-coordinator-wait-through-scheduled-retry branch from 897fa67 to f0295a3 Compare September 10, 2026 11:34
@nwparker

Copy link
Copy Markdown
Contributor

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 null, and they meet at exactly one point: what the loop carries out when it finally gives up. Your commit is preserved as the top commit with you as author (f0295a30e27); the base is still main, so the diff shows #19659's commits until that merges. Changes relative to b35500fa34f:

  • The retryScheduled signal moved into RelayRetrySchedule (the former RelayDrainRetrySchedule, now shared with the origin pool) as settled, and the coordinator's retryTimer/retryAttempt fields with it. Same semantics as yours: resolves on fire or cancel.
  • The budget now bounds only the retry chain, not 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. There is a test for it (8s first open past a 1s budget still returns the broker).
  • Default budget 20s rather than 10 minutes: the phone's request budget is 30s, so nothing is still listening past that, and the point of the budget is that the cause reaches the phone instead of a timeout.
  • A terminal outcome (signed out, unentitled, relay rejected) arms no retry, so it returns immediately with its cause — pinned by a test so the budget can never turn into "wait 20s to be told to sign in".

Your three tests are carried over verbatim (the cancel test keeps your flush comment). Body updated. Push back on anything here.

@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: 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.ts
  • src/main/runtime/relay/desktop-relay-service.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-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; 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

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

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.

Suggested change
private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 20_000
private static readonly LIVE_BROKER_WAIT_BUDGET_MS = 10 * 60_000

Comment on lines +31 to +32
retry()
armed.resolve()

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

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.

Suggested change
retry()
armed.resolve()
try {
retry()
} finally {
armed.resolve()
}

@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

  • Named the offline cause instead of the generic relay_control_not_active — a new RelayOfflineReason type plus relayOfflineReasonMintFailureCode maps signed-out / not_entitled / broker_unavailable / broker_rejected / auth_unavailable to distinct relay_* codes, carried out of the wait by waitForLiveBrokerResult() and thrown by requireActiveBroker().
  • Generalized the retry schedule — deleted relay-drain-retry-schedule.ts in favor of a shared RelayRetrySchedule (exposing a settled signal the waiter sits on) and the pure computeRetryDelayMs, now used by both the auth coordinator and RelayOriginPool.
  • Tightened the wait budget from 10 min to 20 s — LIVE_BROKER_WAIT_BUDGET_MS now 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 — keeps relay-auth-coordinator.ts under the 300-line cap.
  • Shared the diagnostics payload between MobilePage and MobilePane — collectMobileRelayDiagnosticsPayload adds relayStatus and appVersion, and drops the selectedAddress field 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 retryScheduled signal name; it doesn't mention the offline-cause naming or the diagnostics-payload sharing now in the diff.

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

@Jinwoo-H

Copy link
Copy Markdown
Contributor

Carried forward in #22122, which rebases this onto current main and adds one behaviour change: the endpoint probe (getEndpoints) now passes a wait budget of 0, so only createPairingRelay and provisionRelay sit through an armed retry. The LAN-connected phone's availability poll keeps main's current no-wait behaviour.

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.

@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