Skip to content

fix(mobile): reset reconnect attempts only after the E2EE handshake completes - #11465

Merged
brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-10119-cellular-stuck-connecting
Jul 30, 2026
Merged

brennanb2025 merged 1 commit into
mainfrom
brennanb2025/fix-10119-cellular-stuck-connecting

Conversation

@brennanb2025

Copy link
Copy Markdown
Contributor

Summary

Fixes #10119 — mobile client stuck at "Connecting…" over cellular.

ws.onopen reset reconnectAttempt to 0 before the E2EE handshake completed. A WebSocket upgrade succeeding is not a healthy session — that requires e2ee_authenticated, two round trips later under a 5s budget. So for any endpoint that accepts the socket but never finishes the handshake (high-RTT/lossy cellular link, relay with no desktop attached), the counter oscillated 0↔1 forever:

  • neither escalation gate in connection-health.ts (>= 3 → "Can't connect", >= 12 → "Can't reach desktop" + re-pair affordance) could ever fire, and
  • the backoff index stayed pinned at 500ms, burning a fresh socket every ~5.6s indefinitely (battery + data on cellular).

Verified live on an iOS 26.5 simulator against a stalling fake desktop: attempt was 0 on every connecting → handshaking transition and msSinceLastClose never left 502–512ms.

Two changes:

  1. rpc-client.ts — reset reconnectAttempt on the 'connected' transition (e2ee_authenticated), not in ws.onopen. Failed handshakes now count, so gates fire and backoff grows to the 90s trickle.
  2. connection-health.ts — apply the same warning/unreachable gates while connecting/handshaking. Every redial re-enters connecting, which previously flipped an escalated verdict back to "Connecting…" for the whole dial window (12s of every blackhole cycle), so the failure never latched — the reported symptom.

Existing-test timing updates: consecutive failed handshakes now grow the backoff, so the auth-retry tests (#5200 scenarios) advance 1000ms instead of 500ms between rejection cycles. The auth-retry budget semantics themselves are unchanged (all existing assertions pass).

Relationship to #10385 (coordination note — an agent is working that issue separately)

This PR does NOT cover #10385 (iOS shows falsely connected after RPC stalls; Force Reconnect can't recover). That defect lives in the post-handshake 'connected' state (half-open socket liveness / force-reconnect path). This PR only changes pre-handshake failure accounting and label gating; it does not touch notifyForeground's connected-path, the activity probe, or any close/reconnect plumbing. Lines touched in rpc-client.ts: the ws.onopen handler (removed the reset), the setState('connected') branch (added the reset), and one interface comment — no expected overlap with a #10385 fix.

Screenshots

No visual change — no new UI, copy, or components. The fix changes when the existing connection labels/verdicts ("Can't connect", "Can't reach desktop", re-pair affordance) are shown: they now actually appear during a failure loop and latch instead of reverting to "Connecting…" on every redial.

Testing

  • pnpm lint (mobile oxlint clean; pre-commit also ran the react-doctor oxlint config)
  • pnpm typecheck (mobile tsc --noEmit clean)
  • pnpm test (full mobile suite: 357 files, 2618 passed / 3 skipped)
  • pnpm build — N/A for mobile/ (no build script; Mobile Checks runs typecheck/test/lint/format, all clean locally including oxfmt --check)
  • Added or updated high-quality tests that would catch regressions, or explained why tests were not needed

Non-vacuity proof (measured against parent 24a2accc3c): with the two source files reverted to parent, 8/8 new assertions fail — cellular-connecting-label-stall.test.ts (5 failures: max attempts pinned at 1, no escalated label ever, label reverts each dial, counter not reset semantics) and the new classifyConnection dialing cases (3 failures). The opt-in real-socket test (ORCA_MOBILE_LIVE_REPRO=1, real ws server answering e2ee_hello 1s past the budget, real timers) also fails on parent with expected 1 to be greater than or equal to 3. With the fix restored, everything is green.

New coverage:

  • cellular-connecting-label-stall.test.ts — deterministic fake-timer walk of four carrier behaviors (handshake 1s too slow, accept-then-silent, blackholed LAN address, RST contrast), sampling what every screen would render every 250ms for up to 15 simulated minutes. Asserts gates fire, labels latch, backoff grows (socket count bounded), and the counter resets only on a completed handshake.
  • cellular-handshake-stall-real-socket.test.ts — real-socket/real-timer guard against mock drift, opt-in via ORCA_MOBILE_LIVE_REPRO=1 (same pattern as rpc-client-live-recovery.test.ts) since it needs ~22s wall clock.
  • connection-health.test.ts — unit cases for the gates during connecting/handshaking, including the stale heuristic and the below-gate "Connecting…" behavior.

AI Review Report

Reviewed the full state machine for regressions before writing the fix:

  • Auth-retry budget ([Bug]: Android 0.0.12: Terminal tabs randomly freeze and become unresponsive over Tailscale, requiring app restart #5200): rejection retries still schedule reconnects and still latch auth-failed after 3; only their spacing grows (500ms → 1000ms for cycle 2). Existing tests updated for timing only, assertions unchanged.
  • Foreground recovery ([Bug]: Android remote session sometimes becomes unresponsive and requires reopening the app #5049/[Bug] Lose connection mid typing to host on tailscale #7824): notifyForeground keeps its own explicit reconnectAttempt = 0 (deliberate user signal) — untouched, covered by existing tests.
  • Trickle-after-cap: with attempts now growing during handshake-stall loops, the loop correctly reaches GIVE_UP_AFTER_ATTEMPTS and slows to the 90s trickle instead of dialing every ~5.6s forever; waitForConnected's fail-fast at the cap becomes reachable for these loops (intended escalation).
  • Relay path: mobile-relay-rpc-session.ts hardcodes getReconnectAttempt: () => 0 (its retry counter lives in the reconnect controller) — unchanged here, see Notes.
  • Cross-platform: pure TypeScript in the React Native transport layer, identical on iOS and Android; no keyboard shortcuts, labels, file paths, shell commands, or Electron-touching code. Desktop/SSH/WSL unaffected — no desktop module changes (connection-health.ts only imports the pre-existing shared Tailscale-hint helper). macOS/Linux/Windows desktop builds are not in the blast radius.

Security Audit

No new input handling, command execution, path handling, or IPC. The E2EE handshake protocol, token handling, and 4001 close-code mapping are unchanged — the fix only moves when a failure counter resets and which pre-existing label is chosen. Endpoint redaction in logs is untouched. No dependency changes. The auth-failure latch cannot be reached later or bypassed earlier than before (verified by the unchanged #5200 test assertions).

Notes

  • Backoff growth is itself a cellular win: the broken loop burned a socket every ~5.6s indefinitely; it now backs off to the existing 90s trickle (~160 → ~17 sockets per 15 minutes in the deterministic repro).
  • Blackholed-endpoint first escalation remains ~37.5s (three 12s connect timeouts; WARNING_ATTEMPTS = 3 calibration deliberately unchanged) — but it now latches instead of reverting to "Connecting…" for 12s of every later cycle.
  • Follow-up candidate (not this PR): the relay session facade reports a constant getReconnectAttempt() === 0, so relay-path failure loops still can't escalate the label; its retry counter lives in mobile-relay-reconnect-controller.ts and would need threading through.
  • Not covered here: [Bug]: iOS 0.0.33 remains falsely connected after session RPC stalls and Force Reconnect cannot recover #10385 (falsely-connected state) — see the coordination note in the Summary.

…ompletes

ws.onopen zeroed reconnectAttempt before the handshake, so any endpoint
that accepted the socket but never authenticated pinned the counter at
0-1: no escalation gate could fire, backoff never grew, and every screen
showed "Connecting…" forever (issue #10119). Reset the counter on
e2ee_authenticated instead, and make classifyConnection apply the
warning/unreachable gates during connecting/handshaking so an escalated
verdict latches through redials.
@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Connection health classification now preserves warning and unreachable labels while dialing, including connecting and handshaking states. The RPC client keeps reconnect attempts through WebSocket opens and resets them only after completed E2EE authentication. New mocked and real-socket tests cover stalled cellular connections, delayed handshakes, label persistence, recovery, and retry progression. Existing authorization retry tests now use 1-second timer advances to match handshake backoff timing.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main behavior change in reconnect handling.
Description check ✅ Passed The description includes all required sections and sufficiently covers summary, testing, review, security, and notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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.

@greptile-apps

greptile-apps Bot commented Jul 30, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a mobile client stuck-at-"Connecting…" regression on cellular (#10119) by moving reconnectAttempt = 0 from ws.onopen to setState('connected'), and by applying the connection-health.ts escalation gates to the connecting and handshaking states in addition to reconnecting.

  • rpc-client.ts: Removes the premature counter reset in ws.onopen; the reset now only fires when e2ee_authenticated completes. Failed handshakes now accumulate in the counter, allowing the >= 3 / >= 12 escalation gates to fire.
  • connection-health.ts: Drops the early-return that always returned "Connecting…" for connecting/handshaking, and instead routes those states through the same warning/unreachable gates as reconnecting. The final fallback distinguishes reconnecting from the others to return the correct label string.
  • Tests: Three new test files cover the fix end-to-end (fake timers across four carrier behaviors, real-socket opt-in guard, and unit cases for the gate logic); two existing test files update timer advances from 500ms to 1000ms to reflect that failed handshakes now grow the backoff.

Confidence Score: 5/5

The two source changes are minimal and surgically scoped: one line moved in rpc-client.ts and a handful of lines restructured in connection-health.ts. All existing assertions pass; the only test changes are timer advances that now match the new backoff growth.

Both changes are correctly reasoned and well-bounded. The counter reset moving from ws.onopen to setState('connected') closes the 0↔1 oscillation exactly as described. The connection-health restructuring correctly applies the escalation gates to all dialing states while preserving the 'Connecting…' vs 'Reconnecting…' label distinction. The notifyForeground deliberate reset, the auth-retry budget, and the trickle cap are all untouched and confirmed by the existing test suite. New coverage is thorough: fake-timer behavioral assertions, a real-socket guard, and unit cases for the gate logic. No regressions were found.

Files Needing Attention: No files require special attention. The core logic changes in rpc-client.ts and connection-health.ts are each fewer than 10 lines and are fully covered by the new and updated tests.

Important Files Changed

Filename Overview
mobile/src/transport/rpc-client.ts Core fix: removes reconnectAttempt reset from ws.onopen and moves it to the setState('connected') branch; comment clarifies the rationale. No regressions to notifyForeground or auth-retry budget paths.
mobile/src/transport/connection-health.ts Drops the early-return for connecting/handshaking states; applies warning/unreachable gates uniformly; final fallback correctly returns 'Reconnecting…' vs 'Connecting…' by inspecting the state value.
mobile/src/transport/cellular-connecting-label-stall.test.ts New deterministic fake-timer suite covering four carrier behaviors (blackhole, refused, open-then-silent, slow-handshake). Asserts label latching, backoff growth, socket count bounding, and counter reset semantics.
mobile/src/transport/cellular-handshake-stall-real-socket.test.ts Opt-in real-socket/real-timer guard (ORCA_MOBILE_LIVE_REPRO=1) against mock drift. Correctly skips in default runs with a sentinel test to avoid vitest file-with-zero-tests failure.
mobile/src/transport/connection-health.test.ts Adds five unit cases covering gate behavior during connecting/handshaking: warning verdict, unreachable verdict, stale heuristic, and below-gate 'Connecting…' preservation.
mobile/src/transport/rpc-client.test.ts Timer advances between auth-retry cycles updated from 500ms to 1000ms to reflect that failed handshakes now grow the backoff index; assertions are unchanged.
mobile/src/transport/rpc-client-unauthorized-close.test.ts Same 500ms→1000ms timing fix as rpc-client.test.ts for both the pure 4001-close path and the mixed e2ee_error/4001 budget test.

Sequence Diagram

sequenceDiagram
    participant App
    participant rpc as rpc-client.ts
    participant ws as WebSocket
    participant health as connection-health.ts

    App->>rpc: connect(endpoint, token, serverKey)
    rpc->>ws: new WebSocket(endpoint)
    rpc->>rpc: setState('connecting')
    note over rpc: reconnectAttempt unchanged (was reset here before fix)

    ws-->>rpc: onopen
    rpc->>rpc: setState('handshaking')
    rpc->>ws: send(e2ee_hello)

    alt Handshake succeeds
        ws-->>rpc: e2ee_ready
        rpc->>ws: sendEncrypted(e2ee_auth)
        ws-->>rpc: e2ee_authenticated
        rpc->>rpc: setState('connected')
        note over rpc: reconnectAttempt = 0 (moved here from onopen)
        rpc->>rpc: "authRejectionCount = 0"
    else Handshake stalls / timeout (5s)
        rpc->>ws: close()
        ws-->>rpc: onclose
        rpc->>rpc: setState('reconnecting')
        rpc->>rpc: scheduleReconnect — reconnectAttempt++
        note over rpc: counter NOT reset (was reset pre-fix)
    end

    App->>health: classifyConnection(state, reconnectAttempts, lastConnectedAt)
    alt "state = connected"
        health-->>App: normal / Connected
    else "state = connecting or handshaking or reconnecting"
        alt "reconnectAttempts >= 12"
            health-->>App: unreachable / Can't reach desktop
        else "reconnectAttempts >= 3"
            health-->>App: warning / Can't connect
        else
            health-->>App: normal / Connecting… or Reconnecting…
        end
    end
Loading

Reviews (1): Last reviewed commit: "fix(mobile): reset reconnect attempts on..." | Re-trigger Greptile

@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: Pro Plus

Run ID: 6a50109d-fb79-4a48-814a-8d9b219a6823

📥 Commits

Reviewing files that changed from the base of the PR and between 64aa726 and b831cbd.

📒 Files selected for processing (7)
  • mobile/src/transport/cellular-connecting-label-stall.test.ts
  • mobile/src/transport/cellular-handshake-stall-real-socket.test.ts
  • mobile/src/transport/connection-health.test.ts
  • mobile/src/transport/connection-health.ts
  • mobile/src/transport/rpc-client-unauthorized-close.test.ts
  • mobile/src/transport/rpc-client.test.ts
  • mobile/src/transport/rpc-client.ts

@brennanb2025
brennanb2025 merged commit d413dfb into main Jul 30, 2026
43 checks passed
Jinwoo-H pushed a commit that referenced this pull request Aug 4, 2026
Completes the 0.0.37 release attempted on 2026-08-03 (run 30791649691
failed on the version assertion). Ships the post-0.0.36 transport fixes:
relay session recovery when the LAN endpoint is unreachable (#12344,
#11368, #11465, #11690) and honest worktree-catalog failure states
(#12235) — the released-app defect class verified live tonight.

Co-authored-by: OrcaWin <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ompletes (stablyai#11465)

ws.onopen zeroed reconnectAttempt before the handshake, so any endpoint
that accepted the socket but never authenticated pinned the counter at
0-1: no escalation gate could fire, backoff never grew, and every screen
showed "Connecting…" forever (issue stablyai#10119). Reset the counter on
e2ee_authenticated instead, and make classifyConnection apply the
warning/unreachable gates during connecting/handshaking so an escalated
verdict latches through redials.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Completes the 0.0.37 release attempted on 2026-08-03 (run 30791649691
failed on the version assertion). Ships the post-0.0.36 transport fixes:
relay session recovery when the LAN endpoint is unreachable (stablyai#12344,
stablyai#11368, stablyai#11465, stablyai#11690) and honest worktree-catalog failure states
(stablyai#12235) — the released-app defect class verified live tonight.

Co-authored-by: OrcaWin <[email protected]>
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.

[Bug]: The mobile client fails to connect over cellular network and remains stuck at "connecting".

1 participant