Skip to content

fix(mobile): redial when the app resumes mid-dial - #12344

Merged
Jinwoo-H merged 1 commit into
mainfrom
mobile-connection-issues
Aug 3, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
mobile-connection-issues

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Reported in Slack as a P0: "was using it with my linux host then after i navigated out of the app and back it doesn't work anymore… Now i went back again it's connected now" (iOS 0.0.39(2), Linux host over Tailscale). Both desktops sat on Connecting… for about a minute after returning to the app.

The clue is that the second trip out-and-back fixed it. notifyForeground() — the recovery hook fired on AppState active and on network changes — only handled two states:

State on resume Behaviour
connected probe the socket, reap it if half-open
reconnecting clear backoff, redial now
connecting nothing
handshaking nothing

A phone suspended mid-dial resumes in connecting/handshaking. React Native keeps readyState in JS and only advances it on a delivered event, so a socket iOS reclaimed during suspension still looks CONNECTING — the client waits on a socket that can never open. The user pays the rest of the 12s connect budget and then the armed backoff (up to 60s, or the 90s trickle past the give-up cap) against a desktop that is answering. By the next foreground the client had drifted into reconnecting, where the nudge works.

This also explains the neutral Connecting… in the screenshots rather than Can't connect: classifyConnection escalates on reconnectAttempts, and the client was parked, not retrying.

Fix: abandon a dial older than the revival signal and redial immediately. The abandoned dial keeps the failure it represents instead of zeroing the attempt counter — it never authenticated, so it is the same failure the connect timeout would have booked had we waited it out. Zeroing there would let a resume (or a flapping network) reset the counter faster than it climbs, pinning the card at Connecting… through a real outage (regression against #10119).

The 2s staleness floor is what keeps this safe: AppState active and a Wi-Fi→cellular change both reach this nudge back to back, and a dial younger than 2s belongs to the current foreground session.

Screenshots

No visual change. The user-visible change is timing — Connecting… clears on the first return instead of the second.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — 44287 pass. 6 pre-existing failures in check-root-directory-entries, updater, agent-exec-handler; verified identical with this branch stashed, none touch mobile.
  • pnpm build — not run; no build-affecting change (mobile RN sources only, no desktop/native code, no deps).
  • Added tests that fail without the fix.

mobile: 2891 tests pass, oxlint and tsc clean, max-lines ratchet OK.

Two independent reproductions

1. mobile/src/transport/foreground-stale-dial-restart.test.ts (6 tests, real rpc-client, fake timers).

The harness detail that matters: a suspended app is not a slow app. Wall-clock passes but not one JS timer runs, so the backoff loop does not keep cycling in the background. Advancing fake timers re-simulates it as though the phone were awake and the bug vanishes; advancing vi.setSystemTime without draining the timer queue reproduces it. Against the unfixed client:

AssertionError: expected 61000 to be +0

61 seconds after the user returns before the client opens its next socket.

The escalation guard was verified to fail on the counter-resetting variant with expected 0 to be greater than or equal to 12.

2. mobile/scripts/repro-mobile-foreground-stall.sh — the real app on the iOS Simulator.

Two things the Simulator will not do on its own: it never suspends an app, so the bug hides (SIGSTOP on the app process is real suspension — timers frozen, socket dangling); and SIGSTOP on the desktop runtime makes its port blackhole, since the kernel still completes the TCP handshake from the listen backlog but no WebSocket upgrade returns — what a wedged Tailscale tunnel looks like to the phone. Driven entirely with xcrun simctl, because orca emulator routes through the desktop runtime the script freezes.

Unfixed, captured live — note the absence of any foreground — line:

[net] state { attempt: 8, dweltMs: 5385, from: "connecting", to: "reconnecting" }
[net] scheduleReconnect { attempt: 9, delayMs: 60000, trickle: false }

Fixed, same scenario:

[net] foreground — abandoning stale dial { dialAgeMs: 7170, state: "connecting" }
[net] state { attempt: 11, from: "connecting", to: "reconnecting" }
[net] foreground — restarting reconnect loop { attempt: 12, hadTimer: true }
[net] openConnection { attempt: 0, msSinceLastClose: 2, ... }

Fresh socket 2ms after the user returns. attempt: 12 is past the give-up cap, so this user would otherwise have waited the 90s trickle.

AI Review Report

Self-reviewed. Risks checked:

  • Escalation semantics. First version reset reconnectAttempt on the new path, which would have masked a genuine outage behind Connecting… — a regression against [Bug]: The mobile client fails to connect over cellular network and remains stuck at "connecting". #10119. Caught in review, fixed, and locked down by a test verified to fail on the resetting variant.
  • Dial churn. A revival nudge also fires on network-type change. Abandoning an in-flight dial there is correct rather than costly: connection-revival-triggers.ts fires precisely because a Wi-Fi→cellular handoff leaves the old socket bound to a gone interface. The 2s floor stops back-to-back nudges churning a healthy dial.
  • Close-path equivalence. Each closeAndSynthesize() call site previously established ws === socket via its own guard, so folding them is behaviour-preserving. A synchronous onclose during close() still short-circuits the duplicate synthesize, as before.
  • auth-failed. A close carrying 4001 routes to handleAuthRejection; the redial is gated on state === 'reconnecting' so a latched auth-failed is not dialled over.
  • Cross-platform. No platform-conditional code. notifyForeground is shared by iOS and Android; the bug is generic to any OS that suspends the JS runtime. No paths, shortcuts, labels, shell behaviour, or Electron surface touched. The repro script is macOS-only by nature (iOS Simulator) and is a dev tool, not shipped code.
  • Scope. Nothing outside mobile/ imports the changed files.

Security Audit

No new input handling, command execution, path handling, auth, secrets, dependency, or IPC surface. The change is control flow inside an existing WebSocket client. E2EE handshake, device-token auth, and the 4001 unauthorized path are untouched; abandoning a dial closes an unauthenticated socket and opens a fresh one with a new ephemeral keypair, preserving forward secrecy. The one new log line records a connection state and a duration — no endpoints, tokens, or PII. mobile/scripts/repro-mobile-foreground-stall.sh is a local dev tool that signals PIDs it discovers via pgrep; it is not shipped or invoked by the app.

Notes

Two refactors ride along, both forced and both behaviour-preserving. rpc-client.ts crossed its max-lines cap twice while fixing this, and AGENTS.md forbids bumping or disabling it. Rather than shuffle code to dodge lint I extracted the activity probe to rpc-client-activity-probe.ts (~55 lines, a genuinely separate concern, matching the existing rpc-client-*.ts split) and folded four copies of the forced-close dance into closeAndSynthesize(). Existing probe tests (half-open reaping, coalescing, stale timers, malformed payloads) pass untouched. Net effect: rpc-client.ts is 35 lines smaller than before. Reviewers who want the fix in isolation should read notifyForeground, redialNow, and rpc-stale-dial.ts.

Adjacent issues left alone — both real, both distinct from this bug, worth separate tickets:

  1. RelayReconnectController.needsRecovery() treats connecting/handshaking as "live direct progress" and refuses to start relay recovery during them. A blackholed direct endpoint holds that state for 12s per dial, so the relay fallback is blocked for most of each cycle. This PR mitigates the foreground case but not the automatic one.
  2. app/index.tsx defaults to hostStates[item.id] ?? 'connecting' with hostAttempts ?? 0, so a host with no live client entry renders a permanent, never-escalating Connecting… — same misleading label, different cause.

Verification gap: exercised over LAN and Orca Relay in the Simulator. The reporter's Tailscale-to-Linux path I could not drive directly — the blackhole models what a wedged tunnel looks like to the phone, but not the tunnel's own resume behaviour.

A phone suspended while dialling resumes still holding that socket, and React
Native keeps its readyState at CONNECTING because no close event was ever
delivered. notifyForeground only acted on 'connected' and 'reconnecting', so a
resume into 'connecting'/'handshaking' did nothing: the user waited out the rest
of the dead socket's 12s connect budget and then the armed backoff — up to a
further 60s, or the 90s trickle past the give-up cap — against a desktop that was
answering the whole time. Leaving and re-entering the app a second time landed in
'reconnecting', where the nudge works, which is why it appeared to fix itself.

Abandon a dial older than the revival signal and redial at once. The abandoned
dial keeps the failure it represents rather than zeroing the attempt counter:
that counter is the only input to the escalated "Can't reach desktop" verdict, so
resetting it on every resume would pin the card at "Connecting…" through a real
outage (issue #10119).

Extracts the activity probe to its own module and folds four copies of the
forced-close dance into closeAndSynthesize(), which keeps rpc-client.ts under its
max-lines cap without touching .oxlintrc.json. Both are behaviour-preserving and
leave the file 35 lines smaller.

Adds a fake-timer harness that models suspension as wall-clock passing while no
timer runs, plus an emulator driver that reproduces it against a real desktop.
@coderabbitai

coderabbitai Bot commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds a mobile foreground-stall reproduction script and tests for recovery after suspension during dialing or handshaking. It introduces a shared RPC activity probe for detecting half-open sockets. The RPC client now tracks dial age, centralizes timer and probe cleanup, synthesizes close handling for timeout paths, and replaces stale foreground dials. Recovery tests cover retry escalation, state reset, duplicate notifications, and stalled handshakes.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% 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 clearly summarizes the main change: redialing when the mobile app resumes during an active dial.
Description check ✅ Passed The description includes all required sections and provides detailed change, testing, review, security, and platform information.
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.

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

🧹 Nitpick comments (4)
mobile/src/transport/rpc-client-activity-probe.ts (1)

31-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider clearing in-flight probe state in stop().

stop() clears the interval only. It leaves the 8s timeout armed and leaves inFlight set to true. Today the timeout is cleared indirectly, because rpc-client.ts calls rejectAllPending after activityProbe.stop() and the pending entry's reject is onSettled. That coupling is implicit. If a future change deletes the pending entry without invoking the callback, inFlight stays true and the probe never runs again for that client.

Making the probe own its own cleanup removes that dependency.

♻️ Proposed self-contained cleanup
   let timer: ReturnType<typeof setInterval> | null = null
   let inFlight = false
+  let cancelInFlight: (() => void) | null = null
 
   function stop(): void {
     if (timer) {
       clearInterval(timer)
       timer = null
     }
+    cancelInFlight?.()
   }

Set cancelInFlight inside run() to clear the timeout, clear the pending id, and reset inFlight; clear it to null on settle.

mobile/src/transport/foreground-stale-dial-restart.test.ts (1)

269-275: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the first nudge preserves the fresh dial.

Line 274 compares latest() to afterFirstNudge, which is captured after the first nudge. If the first nudge replaced the fresh dial, afterFirstNudge would hold the replacement and line 274 would still pass. The test name targets the first nudge, so the assertion should pin afterFirstNudge to fresh.

Line 275 checks the mock's own constructor argument, so it does not verify client behavior.

♻️ Proposed tightening
     client.notifyForeground()
     const afterFirstNudge = latest()
+    expect(afterFirstNudge).toBe(fresh)
     client.notifyForeground()
     client.notifyForeground()
 
     expect(latest()).toBe(afterFirstNudge)
-    expect(fresh.endpoint).toBe(TAILSCALE_ENDPOINT)
+    expect(sockets.length).toBe(2)
mobile/scripts/repro-mobile-foreground-stall.sh (2)

50-53: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

Bound the wait for the connect window.

This loop has no timeout. If the log never shows "to": "connecting" for the given port, the script spins forever. The later wait at lines 77-83 is bounded with seq 1 45. Apply the same convention here.

♻️ Proposed bounded wait
-while true; do
-  since "$MARK" | grep "$PORT" | grep -q '"to": "connecting"' && break
-  sleep 0.3
-done
+for _ in $(seq 1 200); do
+  since "$MARK" | grep "$PORT" | grep -q '"to": "connecting"' && break
+  sleep 0.3
+done
+if ! since "$MARK" | grep "$PORT" | grep -q '"to": "connecting"'; then
+  step "!!! no connect window observed for port $PORT — aborting"
+  exit 1
+fi

44-46: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Resume the stopped processes on any exit.

The script sends SIGSTOP to the desktop runtime at line 45 and to the app at line 57. It sends SIGCONT only on the normal path, at lines 62 and 75. set -e is active, and the operator can interrupt the run with Ctrl-C. In those cases the desktop runtime and the mobile app stay frozen, and the developer must find and resume them by hand.

Add a trap that resumes both PIDs on EXIT.

♻️ Proposed cleanup trap
 echo "### app=$APP desktop=$DESK port=$PORT"
 
+# Never leave the runtime or the app frozen if the run aborts.
+trap 'kill -CONT "$APP" "$DESK" 2>/dev/null || true' EXIT
+
 step "[1] desktop goes unreachable"
 kill -STOP "$DESK"

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d81c071a-dd3f-4367-b268-1e4c2a51c629

📥 Commits

Reviewing files that changed from the base of the PR and between e25381c and 3f6d0c4.

📒 Files selected for processing (5)
  • mobile/scripts/repro-mobile-foreground-stall.sh
  • mobile/src/transport/foreground-stale-dial-restart.test.ts
  • mobile/src/transport/rpc-client-activity-probe.ts
  • mobile/src/transport/rpc-client.ts
  • mobile/src/transport/rpc-stale-dial.ts

@Jinwoo-H
Jinwoo-H merged commit d3c34c7 into main Aug 3, 2026
44 checks passed
@Jinwoo-H
Jinwoo-H deleted the mobile-connection-issues branch August 3, 2026 20:54
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
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.

2 participants