Repository navigation
fix(mobile): redial when the app resumes mid-dial - #12344
Conversation
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.
📝 WalkthroughWalkthroughThe 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)
✅ Passed checks (4 passed)
✨ 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 |
There was a problem hiding this comment.
🧹 Nitpick comments (4)
mobile/src/transport/rpc-client-activity-probe.ts (1)
31-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider clearing in-flight probe state in
stop().
stop()clears the interval only. It leaves the 8s timeout armed and leavesinFlightset totrue. Today the timeout is cleared indirectly, becauserpc-client.tscallsrejectAllPendingafteractivityProbe.stop()and the pending entry'srejectisonSettled. That coupling is implicit. If a future change deletes the pending entry without invoking the callback,inFlightstaystrueand 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
cancelInFlightinsiderun()to clear the timeout, clear the pending id, and resetinFlight; clear it tonullon settle.mobile/src/transport/foreground-stale-dial-restart.test.ts (1)
269-275: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that the first nudge preserves the fresh dial.
Line 274 compares
latest()toafterFirstNudge, which is captured after the first nudge. If the first nudge replaced the fresh dial,afterFirstNudgewould hold the replacement and line 274 would still pass. The test name targets the first nudge, so the assertion should pinafterFirstNudgetofresh.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 valueBound 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 withseq 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 winResume the stopped processes on any exit.
The script sends
SIGSTOPto the desktop runtime at line 45 and to the app at line 57. It sendsSIGCONTonly on the normal path, at lines 62 and 75.set -eis 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
trapthat resumes both PIDs onEXIT.♻️ 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
📒 Files selected for processing (5)
mobile/scripts/repro-mobile-foreground-stall.shmobile/src/transport/foreground-stale-dial-restart.test.tsmobile/src/transport/rpc-client-activity-probe.tsmobile/src/transport/rpc-client.tsmobile/src/transport/rpc-stale-dial.ts
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]>
Co-authored-by: OrcaWin <[email protected]>
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]>
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 AppStateactiveand on network changes — only handled two states:connectedreconnectingconnectinghandshakingA phone suspended mid-dial resumes in
connecting/handshaking. React Native keepsreadyStatein JS and only advances it on a delivered event, so a socket iOS reclaimed during suspension still looksCONNECTING— 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 intoreconnecting, where the nudge works.This also explains the neutral
Connecting…in the screenshots rather thanCan't connect:classifyConnectionescalates onreconnectAttempts, 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
activeand 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 lintpnpm typecheckpnpm test— 44287 pass. 6 pre-existing failures incheck-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).mobile: 2891 tests pass,oxlintandtscclean, max-lines ratchet OK.Two independent reproductions
1.
mobile/src/transport/foreground-stale-dial-restart.test.ts(6 tests, realrpc-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.setSystemTimewithout draining the timer queue reproduces it. Against the unfixed client: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 (
SIGSTOPon the app process is real suspension — timers frozen, socket dangling); andSIGSTOPon 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 withxcrun simctl, becauseorca emulatorroutes through the desktop runtime the script freezes.Unfixed, captured live — note the absence of any
foreground —line:Fixed, same scenario:
Fresh socket 2ms after the user returns.
attempt: 12is past the give-up cap, so this user would otherwise have waited the 90s trickle.AI Review Report
Self-reviewed. Risks checked:
reconnectAttempton the new path, which would have masked a genuine outage behindConnecting…— 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.connection-revival-triggers.tsfires 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.closeAndSynthesize()call site previously establishedws === socketvia its own guard, so folding them is behaviour-preserving. A synchronousoncloseduringclose()still short-circuits the duplicate synthesize, as before.handleAuthRejection; the redial is gated onstate === 'reconnecting'so a latchedauth-failedis not dialled over.notifyForegroundis 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.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.shis a local dev tool that signals PIDs it discovers viapgrep; it is not shipped or invoked by the app.Notes
Two refactors ride along, both forced and both behaviour-preserving.
rpc-client.tscrossed itsmax-linescap twice while fixing this, and AGENTS.md forbids bumping or disabling it. Rather than shuffle code to dodge lint I extracted the activity probe torpc-client-activity-probe.ts(~55 lines, a genuinely separate concern, matching the existingrpc-client-*.tssplit) and folded four copies of the forced-close dance intocloseAndSynthesize(). Existing probe tests (half-open reaping, coalescing, stale timers, malformed payloads) pass untouched. Net effect:rpc-client.tsis 35 lines smaller than before. Reviewers who want the fix in isolation should readnotifyForeground,redialNow, andrpc-stale-dial.ts.Adjacent issues left alone — both real, both distinct from this bug, worth separate tickets:
RelayReconnectController.needsRecovery()treatsconnecting/handshakingas "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.app/index.tsxdefaults tohostStates[item.id] ?? 'connecting'withhostAttempts ?? 0, so a host with no live client entry renders a permanent, never-escalatingConnecting…— 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.