Repository navigation
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This PR replaces the fixed 2.5s direct head start with a first-authenticated-wins race between the direct and relay dials on every mobile reconnect. I read the full 12-file diff end-to-end, traced the cutover against migrateTo, verified the test and typecheck suites, and found the design sound.
- Race-from-t=0 recovery —
relayDialAllowedyields only to a live session, andrecoverRelaykicksdirectProbe.probeNow()when nothing is connected, so an unfinished direct dial no longer blocks relay recovery. - Outright direct adoption —
DirectReturnProbe.adoptsOutrightlets a reconnecting direct socket win without hysteresis or the operation mutex, while hysteresis still arbitrates promotions against a live relay. - Lost-race damper — new
RelayLostRaceDamperpaces relay dials that lose to direct (2s doubling to a 30s cap) with a 250ms floor that collapses the window when direct is genuinely gone, so a dead LAN never waits out the window. - Pre-handshake withdraw —
withdrawWhenDirectWinscloses the cell socket the moment direct wins, so the desktop never finishes an E2EE handshake for a doomed dial. - Credential refresh split — rotation extracted to
MobileRelayCredentialRefresh, behavior-preserving;mobile-relay-direct-grace-timer.tsdeleted with no dead references.
I confirmed single-winner atomicity holds in migrateTo (the post-auth shouldAbort re-check and the synchronous cutover block run without an intervening await), close() is idempotent so the withdraw + abort double-close is safe, and the operation mutex is always released via finally. Ran the four changed test files (58 tests) and tsc --noEmit — all green.
ℹ️ noteDirectRestored fires on relay wins too
The onStateChange handler calls lostRace.noteDirectRestored() on every connected transition, including a relay win, but the damper's contract for that method is "direct came back inside the floor." It is correct today only because every relay connected transition flows through recordMigration → lostRace.reset(), which clears the transiently-restored window; a relay that fails resume-confirm after cutover never reaches recordMigration, but in that case the restored window is re-clamped by the following non-connected state change. Flagging for awareness rather than change — a future edit that skips or reorders recordMigration against the state listener would silently keep a stale damper window alive.
Note the PR is stacked on mobile/relay-connect-critical-path (#19236) and needs retargeting to main, and is gated on owner sign-off as stated in the description.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
88551ac to
7817d86
Compare
📝 WalkthroughWalkthroughThe mobile transport now races direct and relay connections from reconnect start. Direct winners can adopt immediately, while losing relay sessions are withdrawn without extra backoff. A damping component controls repeated lost races and adapts when direct connectivity returns. Credential rotation uses a dedicated collaborator. Foreground and background transitions invoke immediate direct probes. Relay-session withdrawal and E2EE close behavior receive additional coverage. Merge Risk: 🟡 Moderate · up to A failed relay-host save after credential rotation can leave recovery dialing an outdated relay endpoint. Resolve this partial-success path before merge. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides strong technical context and verification details, but it omits most required template sections, including ELI5, Linked Issue with a Fixes reference, Visual Proof or N/A, Testing checkboxes, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist confirmations. Resolution Update the description to include every required template section. Add an explicit Linked Issue entry using
✨ 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 |
7817d86 to
e708717
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The delta since the prior review is a rebase onto the reopened phase-1 head (mobile/relay-connect-critical-path, which carries #19280's review fixes) plus one new commit that reconciles the direct-probe test fixture with the race-era hooks. The transport code is otherwise unchanged from the previously reviewed version.
- Rebased onto the phase-1 head — the base moved from
mainback tomobile/relay-connect-critical-path;DirectReturnProbe's production code is byte-identical apart from theclear()change below. - Direct-probe fixture reconciled —
e7087173d9supplies thecanDialandadoptsOutrighthooks the race introduces, withadoptsOutright: () => falsekeeping these tests on the hysteresis (live-relay) path, so the fixture no longer throws at the first dial. clear()also resets the deferred re-arm —DirectReturnProbe.clear()now nullsdeferredDelayMsalongside the timer, so a cleared probe cannot resurrect a stale deferred schedule. In every current call path this is defensive:probeNow()only reachesclear()when no probe is in flight (the deferral is already consumed), and the external callers (background(),stop()) run withcanSchedule()already false.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
@coderabbitai review |
✅ Action performedReview finished.
|
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: a47e8eb4-9d00-410d-8d34-61a61b9b9179
📒 Files selected for processing (13)
mobile/src/transport/mobile-direct-return-probe.test.tsmobile/src/transport/mobile-direct-return-probe.tsmobile/src/transport/mobile-endpoint-reconnect-race.test.tsmobile/src/transport/mobile-endpoint-supervisor-direct-probe.test.tsmobile/src/transport/mobile-endpoint-supervisor-test-fakes.tsmobile/src/transport/mobile-endpoint-supervisor.test.tsmobile/src/transport/mobile-endpoint-supervisor.tsmobile/src/transport/mobile-relay-background-grace.tsmobile/src/transport/mobile-relay-credential-refresh.tsmobile/src/transport/mobile-relay-direct-grace-timer.tsmobile/src/transport/mobile-relay-e2ee-link.test.tsmobile/src/transport/mobile-relay-lost-race-damper.tsmobile/src/transport/mobile-relay-session-establisher.ts
💤 Files with no reviewable changes (1)
- mobile/src/transport/mobile-relay-direct-grace-timer.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.
| refreshed = true | ||
| await args.persistResolvedRelay(result.relay) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
Keep relay-host persistence in the refresh success path.
run adopts the new bundle and sets refreshed before persistResolvedRelay() completes. If saveHost rejects, finally still clears the fresh-credential gate. The durable bundle is fresh, but this.host.relay remains stale. A later run(false) can skip rotation, so recovery can dial the stale endpoint. Set success only after host persistence succeeds, and retain and retry the resolved relay before releasing the gate.
There was a problem hiding this comment.
The read of the code is correct, but this is pre-existing behaviour that this PR moved rather than introduced, so I am not changing it here.
mobile-relay-credential-refresh.ts is a verbatim extraction of rotateCredentialIfNeeded from the supervisor. The same ordering is on main today at mobile/src/transport/mobile-endpoint-supervisor.ts:325-328:
this.bundle = result.bundle
// Why: a scheduled rotation can finish after the old credential enters the rejection gate.
credentialRefreshed = true
this.host = await persistRelayHost(this.host, result.relay, this.dependencies.saveHost)Same catch, same finally, same gate lift. The extraction changes where the code lives, not when refreshed is set relative to the persist. A git show origin/main:mobile/src/transport/mobile-endpoint-supervisor.ts diffed against the new class shows the body unchanged apart from the dependency injection.
On the substance: the flagged window needs saveHost to reject after a successful rotation, which leaves host.relay stale while the bundle is durable, and mobileRelayCredentialNeedsRotation then short-circuits later unforced runs. That is worth fixing, and it is worth fixing on its own so the change is reviewable against the rotation and rehome tests rather than buried in a reconnect-latency PR. This branch is a stacked, held perf change, so widening it to alter credential-persistence semantics is the wrong place.
Flagging it for the owner's mobile pass as a separate item rather than silently folding it in.
There was a problem hiding this comment.
@Jinwoo-H, thanks for the detailed verification.
The ordering is pre-existing behavior, and this PR only extracts it into MobileRelayCredentialRefresh. The persistence failure case remains valid, but it is out of scope for this reconnect-latency change.
Would you like me to open a GitHub follow-up issue for the mobile owner? The issue can cover retrying persistResolvedRelay() before completeRefresh() releases the fresh-credential gate.
🐇
✏️ Learnings added
Learnt from: Jinwoo-H
Repo: stablyai/orca PR: 19256
File: mobile/src/transport/mobile-relay-credential-refresh.ts:56-57
Timestamp: 2026-09-07T10:50:30.213Z
Learning: In `mobile/src/transport/mobile-relay-credential-refresh.ts`, `MobileRelayCredentialRefresh.run()` preserves the pre-existing ordering from `rotateCredentialIfNeeded` in `mobile/src/transport/mobile-endpoint-supervisor.ts`: it adopts the rotated credential bundle and marks the refresh successful before `persistResolvedRelay()` completes. A failure to persist the resolved relay can leave the stored relay endpoint stale while the new bundle is durable. This behavior should be fixed in a separate credential-persistence change, not in PR `#19256`.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
You are interacting with an AI system.
There was a problem hiding this comment.
No, please do not open an issue. This whole stack is held for the owner's mobile review pass, and the follow-up is theirs to schedule. It is recorded in the handoff notes on this thread, which is enough to pick it up.
There was a problem hiding this comment.
@Jinwoo-H, understood. I will not open a follow-up issue.
The handoff notes on this thread identify the credential-persistence follow-up for the mobile owner’s review pass. The finding remains deferred outside PR #19256.
🧠 Learnings used
Learnt from: Jinwoo-H
Repo: stablyai/orca PR: 19256
File: mobile/src/transport/mobile-relay-credential-refresh.ts:56-57
Timestamp: 2026-09-07T10:50:32.287Z
Learning: In `mobile/src/transport/mobile-relay-credential-refresh.ts`, `MobileRelayCredentialRefresh.run()` preserves the pre-existing ordering from `rotateCredentialIfNeeded` in `mobile/src/transport/mobile-endpoint-supervisor.ts`: it adopts the rotated credential bundle and marks the refresh successful before `persistResolvedRelay()` completes. A failure to persist the resolved relay can leave the stored relay endpoint stale while the new bundle is durable. This behavior should be fixed in a separate credential-persistence change, not in PR `#19256`.
You are interacting with an AI system.
…nect A foreground reconnect gave the direct dial a fixed 2.5s head start, and while that dial sat in 'connecting'/'handshaking' the supervisor refused to open a relay socket at all. A phone that is off the LAN paid the full head start on every reconnect and got nothing for it, and a phone whose relay dropped could only return to the LAN through three hysteresis probes. Both dials now start together and the first authenticated socket is adopted through the existing migrateTo cutover. Nothing about the migration machinery changes: only who is allowed to start a dial. - The relay dial now yields to a live session and to nothing else. An unfinished direct dial is progress on the other runner, not a reason to stand still. - The direct return probe grows a second adoption policy. Against a live relay hysteresis still has to prove direct stable; during a reconnect there is no session to protect, so an authenticated direct socket wins outright. probeNow pre-empts a pending 15s tick so that dial starts with the relay dial, not after it, and the dial itself no longer waits for the operation mutex — a relay dial holding it is exactly the case the race exists for. - A loser closes and books nothing. The relay dial withdraws inside migrateTo and returns 'aborted', so no backoff is booked against it; a direct socket that loses leaves the promotion streak untouched. Only a reconnect that both paths lose books a failure, once, on the relay cadence. Kept: the 30s background grace and the foreground gate, because a backgrounded phone must not open a billed relay splice; the shared failure cooldown, because a genuine relay failure still has to be paced; the hysteresis dwell after a migration, because it is what stops a marginal LAN flapping a healthy session. The accepted cost is one relay socket per reconnect for a phone that is on its LAN. It closes as soon as the direct path authenticates, before the resume confirm, because migrateTo only checks the abort predicate after E2EE auth. Tests that encoded the removed rules: - 'fails over when the direct retry loop publishes reconnecting' asserted no relay dial while direct was handshaking. The failover now precedes the direct client giving up, so it asserts the dial instead of its absence. - 'does not spend a queued relay retry while direct authentication is progressing' encoded the block outright; it now asserts the retry runs on the failure cadence while a handshake drags on. - The four grace-race cases move to mobile-endpoint-reconnect-race.test.ts as t=0, direct-wins, background/resume and both-lose cases. - Five relay-bookkeeping cases now state their premise with unreachableDirect. They describe a phone with no LAN, which used to be implicit and is now load-bearing: with a reachable LAN the direct socket wins those reconnects.
…aces Review follow-up to 4e31130471. Racing both paths from t=0 was correct but charged the LAN case twice: once per reconnect in cell work, and again whenever the LAN flapped. Withdraw before the handshake. migrateTo only consults its abort predicate after E2EE authentication, so a dial that had already lost still made the cell reserve a splice and the desktop finish a key exchange. The establisher now watches the logical client across the dial and closes the cell socket the moment direct authenticates. In the common window, after relay-auth is on the wire and before the hello lands, nothing of the key exchange has started, so the withdrawal costs the desktop nothing. The dial still reports itself aborted and still books nothing. The watch is dropped once migrateTo returns, because past the cutover this session is the active path and a later direct promotion must not read as a reason to close the client's own socket. Damp races that a blip started. relayDialAllowed yields only to a live session and a lost race books nothing, so a flapping LAN drove one cell socket per blip with only the relay's per-host rate limiter as a backstop, and reaching that limiter would have converted a benign race into a booked relay failure. After a race is lost to direct, the next unforced race is suppressed for 2s, doubling per consecutive loss to a 30s cap. This is not backoff and is kept separate from it: a forced replacement is never damped, a relay dial that wins clears the streak, and a foreground resume clears it too, so the path the user is watching never waits. The window arms its own lapse timer, so a LAN that dies inside the window still reaches relay without a new trigger. A superseded cutover no longer escapes probe() as an unhandled rejection. Only the probe timer calls it, and it discards the promise, so the routine end of a lost race would have surfaced as one. Credential rotation moves to MobileRelayCredentialRefresh. The supervisor crossed the 300-line cap; rotation is a self-contained responsibility that only runs over a live direct connection, so it splits cleanly instead of taking a max-lines bump.
… gone Round-2 review follow-up to 9a21da4326. The damper armed its window when direct won the race, and nothing shortened it. A LAN that died inside that window left the phone waiting out the whole thing, up to 30s at the cap, with only a log line to show for it. My previous commit body claimed the path the user watches never waits; that was true only of a foreground resume, and it is corrected here. Losing the direct path now collapses the wait to a 250ms floor, so the next recovery races almost at once. The floor is not zero because the reason the damper exists is a LAN that drops and comes straight back, and a disconnect is how such a blip begins. So the rest of the window is kept aside rather than spent: if direct returns inside the floor it was a blip and the window resumes, and if the floor lapses with direct still gone it was an outage and the held window is void. Without the second half, one blip would have bought a flapping LAN a free pass on every race that followed, which is the case the damper was added for. The streak itself is untouched by the clamp. A LAN that flaps all afternoon still escalates toward the cap; only the current wait is cut short. record() now takes the same forceReplacement guard as suppresses(), so a forced replacement that stands down cannot grow the streak or be read as a loss to direct. A lease rotation or a reconsidered network change is not a LAN that flapped. Also documents that a genuine relay failure deliberately does not reset the streak, and that the damper and the failure backoff serialize rather than stack: a damped attempt never reaches the dial that would book a cooldown.
The phase-1 probe test predates canDial and adoptsOutright, so its hooks literal threw at the first dial. These cases model a live relay session.
e708717 to
310915d
Compare

Stacked on #19280
Base is
mobile/relay-connect-critical-path. Retarget tomainafter #19280 merges.#19236 was merged and then reverted on
mainby #19265, so phase 1 was re-opened as #19280 for the separate mobile review pass. This branch was rebased onto that new phase-1 head, which carries phase 1's review fixes. One extra commit here (e7087173d9) gives phase 1's direct-probe test fixture thecanDialandadoptsOutrighthooks this branch introduces; without it the fixture threw at the first dial. The earlier diff againstmainwas taken over amainthat still contained phase 1 and no longer applies.Held: do not merge without the owner's mobile-pass go.
Why
On every reconnect the phone gave the direct (LAN) path a fixed 2.5 s head start and blocked relay recovery while direct was connecting or handshaking. Off-LAN users paid that head start on every reconnect for nothing.
What
migrateTo; the loser closes cleanly and books nothing. The grace timer module is deleted; relay yields only to a live session (relayDialAllowed). When relay owns the client, the direct-return probe adopts an authenticated direct socket outright when no live session exists and no longer waits on the operation mutex.mobile-relay-lost-race-damper.ts): after a relay dial loses to direct, the next unforced race is suppressed for 2 s, doubling per consecutive loss to a 30 s cap. Separate from the failure backoff. A relay win or a foreground resume clears it. If the direct path is then lost, the wait collapses to a 250 ms floor with the remaining window set aside and restored only if direct returns within the floor, so a flapping LAN cannot drive unbounded relay dials and a dead LAN never leaves the user waiting out the window.mobile-relay-credential-refresh.ts(behaviour-preserving split).Wire
No change.
Verification
mobile:tsc --noEmit,vitest run(517 files, 4222 tests),oxlint,oxfmt --check;check:code-quality:changed0 across 20 files.Not for merge until the owner gives the go.