fix(mobile): redial when the app resumes mid-dial (#12344)
Co-authored-by: OrcaWin <293788423+OrcaWin@users.noreply.github.com>
This commit is contained in:
+85
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env bash
|
||||
# Repro driver for "mobile sits on Connecting… after leaving and re-entering the
|
||||
# app" (Slack P0, iOS 0.0.39(2)).
|
||||
#
|
||||
# Two things the iOS Simulator will not do on its own, and how this works around
|
||||
# them:
|
||||
#
|
||||
# * It never suspends an app the way a device does, so the JS runtime keeps
|
||||
# servicing timers while backgrounded and the bug hides. SIGSTOP on the app
|
||||
# process reproduces real suspension: timers frozen, socket left dangling.
|
||||
# * SIGSTOP on the desktop runtime makes its port blackhole — the kernel still
|
||||
# completes the TCP handshake from the listen backlog, but no WebSocket
|
||||
# upgrade ever comes back, which is what a wedged Tailscale tunnel or a relay
|
||||
# with nothing behind it looks like to the phone.
|
||||
#
|
||||
# Everything is driven with xcrun simctl rather than `orca emulator`, because the
|
||||
# emulator CLI routes through the desktop runtime that this script freezes.
|
||||
#
|
||||
# Setup:
|
||||
# node scripts/start-emulator.mjs --device "iPhone 17 Pro" --wait-for-ready \
|
||||
# > /tmp/orca-emulator-boot.log 2>&1 &
|
||||
#
|
||||
# Usage: repro-mobile-foreground-stall.sh <udid> <paired-host-port> [log]
|
||||
set -euo pipefail
|
||||
|
||||
UDID="${1:?simulator udid}"
|
||||
PORT="${2:?port of the paired host, from the [net] logs}"
|
||||
LOG="${3:-/tmp/orca-emulator-boot.log}"
|
||||
BUNDLE_ID=com.stably.orca.mobile
|
||||
# Long enough for the tiered backoff to reach its 30s/60s tail.
|
||||
ESCALATE_SECONDS=200
|
||||
|
||||
APP=$(pgrep -f "CoreSimulator.*Orca.app/Orca" | head -1)
|
||||
DESK=$(pgrep -f "serve-mobile-pairing" | head -1)
|
||||
: "${APP:?mobile app is not running in the simulator}"
|
||||
: "${DESK:?headless desktop runtime is not running}"
|
||||
|
||||
strip() { sed 's/\x1b\[[0-9;]*m//g'; }
|
||||
since() { sed -n "$(( $1 + 1 )),\$p" "$LOG" | strip; }
|
||||
step() { echo "$(date +%T) $*"; }
|
||||
|
||||
echo "### app=$APP desktop=$DESK port=$PORT"
|
||||
|
||||
step "[1] desktop goes unreachable"
|
||||
kill -STOP "$DESK"
|
||||
sleep "$ESCALATE_SECONDS"
|
||||
step "[2] backoff at $(since 0 | grep "$PORT" | grep -o '"attempt": [0-9]*' | tail -1)"
|
||||
|
||||
MARK=$(wc -l < "$LOG")
|
||||
while true; do
|
||||
since "$MARK" | grep "$PORT" | grep -q '"to": "connecting"' && break
|
||||
sleep 0.3
|
||||
done
|
||||
step "[3] connect window open — user switches away"
|
||||
xcrun simctl launch "$UDID" com.apple.mobilesafari >/dev/null 2>&1
|
||||
sleep 1
|
||||
kill -STOP "$APP"
|
||||
step "[4] phone suspended mid-dial"
|
||||
sleep 5
|
||||
|
||||
MARK=$(wc -l < "$LOG")
|
||||
kill -CONT "$APP"
|
||||
sleep 0.3
|
||||
xcrun simctl launch "$UDID" "$BUNDLE_ID" >/dev/null 2>&1
|
||||
T0=$(date +%s)
|
||||
step "[5] user returns to Orca <-- t0, desktop still down"
|
||||
|
||||
# The desktop is deliberately still unreachable here: the only question is
|
||||
# whether returning to the app abandons the dead dial or waits it out.
|
||||
sleep 6
|
||||
echo "--- first 6s after t0 ---"
|
||||
since "$MARK" | grep -E "$PORT|foreground" \
|
||||
| grep -E 'state |foreground|scheduleReconnect|openConnection' | head -8
|
||||
|
||||
kill -CONT "$DESK"
|
||||
step "[6] desktop healthy again"
|
||||
for _ in $(seq 1 45); do
|
||||
if since "$MARK" | grep "$PORT" | grep -q '"to": "connected"'; then
|
||||
step ">>> connected $(( $(date +%s) - T0 ))s after t0"
|
||||
exit 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
step ">>> STILL STUCK 90s after t0"
|
||||
exit 1
|
||||
@@ -0,0 +1,301 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { connect } from './rpc-client'
|
||||
import { classifyConnection, verdictDisplayLabel } from './connection-health'
|
||||
|
||||
// Slack P0 — "mobile connection issue. 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."
|
||||
//
|
||||
// The tell is that the SECOND foreground fixed it. notifyForeground only ever
|
||||
// acted on 'connected' (probe the socket) and 'reconnecting' (redial now). A
|
||||
// phone that is suspended mid-dial resumes in 'connecting'/'handshaking', where
|
||||
// the nudge did nothing: the user waited out the remainder of the 12s connect
|
||||
// budget on a socket opened over a network path that no longer existed, and
|
||||
// then the *preserved* backoff delay — up to 60s of "Connecting…" against a
|
||||
// desktop that was answering the whole time. By the next foreground the client
|
||||
// had landed in 'reconnecting', where the nudge works, so it connected at once.
|
||||
|
||||
vi.mock('./e2ee', () => ({
|
||||
generateKeyPair: () => ({ publicKey: new Uint8Array(32), secretKey: new Uint8Array(32) }),
|
||||
deriveSharedKey: () => new Uint8Array(32),
|
||||
publicKeyFromBase64: () => new Uint8Array(32),
|
||||
publicKeyToBase64: () => 'client-public-key',
|
||||
encrypt: (plaintext: string) => `encrypted:${plaintext}`,
|
||||
decrypt: (raw: string) => raw.replace(/^encrypted:/, ''),
|
||||
decryptBytes: (bytes: Uint8Array) => bytes
|
||||
}))
|
||||
|
||||
// Mirrors React Native's WebSocket: readyState lives in JS and only advances on
|
||||
// a delivered event, so a socket the OS killed while the app was suspended stays
|
||||
// CONNECTING forever from the client's point of view.
|
||||
class MockWebSocket {
|
||||
static CONNECTING = 0
|
||||
static OPEN = 1
|
||||
static CLOSING = 2
|
||||
static CLOSED = 3
|
||||
readonly CONNECTING = 0
|
||||
readonly OPEN = 1
|
||||
|
||||
readyState = MockWebSocket.CONNECTING
|
||||
onopen: (() => void) | null = null
|
||||
onclose: ((event?: unknown) => void) | null = null
|
||||
onmessage: ((event: { data: unknown }) => void) | null = null
|
||||
onerror: ((event?: unknown) => void) | null = null
|
||||
// A socket the OS tore down while suspended never reports its own close.
|
||||
deliversCloseEvent = true
|
||||
sent: string[] = []
|
||||
|
||||
constructor(readonly endpoint: string) {
|
||||
sockets.push(this)
|
||||
}
|
||||
|
||||
send(payload: string): void {
|
||||
this.sent.push(payload)
|
||||
}
|
||||
|
||||
close(): void {
|
||||
if (this.readyState === MockWebSocket.CLOSED) {
|
||||
return
|
||||
}
|
||||
this.readyState = MockWebSocket.CLOSED
|
||||
if (this.deliversCloseEvent) {
|
||||
this.onclose?.({ code: 1006, wasClean: false })
|
||||
}
|
||||
}
|
||||
|
||||
open(): void {
|
||||
this.readyState = MockWebSocket.OPEN
|
||||
this.onopen?.()
|
||||
}
|
||||
|
||||
authenticate(): void {
|
||||
this.open()
|
||||
this.onmessage?.({ data: JSON.stringify({ type: 'e2ee_ready' }) })
|
||||
this.onmessage?.({ data: 'encrypted:{"type":"e2ee_authenticated"}' })
|
||||
}
|
||||
}
|
||||
|
||||
const sockets: MockWebSocket[] = []
|
||||
const originalWebSocket = globalThis.WebSocket
|
||||
|
||||
function latest(): MockWebSocket {
|
||||
const socket = sockets[sockets.length - 1]
|
||||
if (!socket) {
|
||||
throw new Error('no socket opened')
|
||||
}
|
||||
return socket
|
||||
}
|
||||
|
||||
function label(client: ReturnType<typeof connect>, endpoint: string): string {
|
||||
return verdictDisplayLabel(
|
||||
classifyConnection({
|
||||
state: client.getState(),
|
||||
reconnectAttempts: client.getReconnectAttempt(),
|
||||
lastConnectedAt: client.getLastConnectedAt(),
|
||||
endpoint,
|
||||
nowMs: Date.now()
|
||||
})
|
||||
)
|
||||
}
|
||||
|
||||
// A suspended app is not a slow app: wall-clock time passes but not one JS timer
|
||||
// runs, so the backoff loop does NOT keep cycling in the background. Advancing
|
||||
// the system clock without draining the timer queue is what reproduces that —
|
||||
// the connect timer armed before the suspension is still pending on resume, and
|
||||
// the client is still sitting in the state it was suspended in.
|
||||
function suspend(backgroundMs: number): void {
|
||||
for (const socket of sockets) {
|
||||
// iOS reclaims a suspended app's sockets without telling JS.
|
||||
socket.deliversCloseEvent = false
|
||||
}
|
||||
vi.setSystemTime(Date.now() + backgroundMs)
|
||||
}
|
||||
|
||||
// Steps the clock one second at a time and reports how long the user has to sit
|
||||
// on "Connecting…" before the client opens its next socket.
|
||||
async function millisecondsUntilNextDial(dialsBefore: number): Promise<number> {
|
||||
const limitMs = 180_000
|
||||
for (let elapsedMs = 0; elapsedMs <= limitMs; elapsedMs += 1_000) {
|
||||
if (sockets.length > dialsBefore) {
|
||||
return elapsedMs
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(1_000)
|
||||
}
|
||||
return limitMs
|
||||
}
|
||||
|
||||
// Waits out the current backoff so the phone is suspended mid-dial — the state
|
||||
// the reporter's phone resumed into — rather than between dials.
|
||||
async function advanceUntilDialing(client: ReturnType<typeof connect>): Promise<void> {
|
||||
for (let elapsedMs = 0; elapsedMs <= 120_000; elapsedMs += 250) {
|
||||
if (client.getState() === 'connecting') {
|
||||
return
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(250)
|
||||
}
|
||||
throw new Error(`client never re-entered connecting (state=${client.getState()})`)
|
||||
}
|
||||
|
||||
const TAILSCALE_ENDPOINT = 'ws://100.84.12.9:6769'
|
||||
|
||||
describe('foregrounding a phone that was suspended mid-dial', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
sockets.length = 0
|
||||
globalThis.WebSocket = MockWebSocket as unknown as typeof WebSocket
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
vi.restoreAllMocks()
|
||||
globalThis.WebSocket = originalWebSocket
|
||||
})
|
||||
|
||||
it('abandons a dial that predates the foreground edge instead of waiting it out', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
expect(client.getState()).toBe('connected')
|
||||
|
||||
// The user leaves the app. The link dies while the phone is suspended, so
|
||||
// the client is left holding a socket that will never open.
|
||||
latest().close()
|
||||
expect(client.getState()).toBe('reconnecting')
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
expect(client.getState()).toBe('connecting')
|
||||
const doomed = latest()
|
||||
|
||||
suspend(120_000)
|
||||
|
||||
// Back in the app. The desktop is healthy and answering.
|
||||
const socketsBeforeForeground = sockets.length
|
||||
client.notifyForeground()
|
||||
|
||||
expect(sockets.length).toBe(socketsBeforeForeground + 1)
|
||||
expect(latest()).not.toBe(doomed)
|
||||
latest().authenticate()
|
||||
expect(client.getState()).toBe('connected')
|
||||
})
|
||||
|
||||
it('does not strand the user on "Connecting…" for a minute after returning', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
latest().close()
|
||||
|
||||
// The desktop drops off the network while the user is still in the app, so
|
||||
// the tiered backoff climbs into its slow tail (15s, 30s, 60s) before they
|
||||
// ever leave. This is what makes the post-resume wait a full minute.
|
||||
for (let dial = 0; dial < 6; dial++) {
|
||||
await vi.advanceTimersByTimeAsync(12_000 + 60_000)
|
||||
}
|
||||
expect(client.getReconnectAttempt()).toBeGreaterThanOrEqual(6)
|
||||
await advanceUntilDialing(client)
|
||||
|
||||
suspend(90_000)
|
||||
const dialsBefore = sockets.length
|
||||
client.notifyForeground()
|
||||
|
||||
// The desktop is reachable again and the user is looking at the screen, so
|
||||
// the redial has to be in flight now — not after the abandoned socket's
|
||||
// connect budget expires and another tail-length backoff is waited out.
|
||||
expect(await millisecondsUntilNextDial(dialsBefore)).toBe(0)
|
||||
|
||||
latest().authenticate()
|
||||
expect(client.getState()).toBe('connected')
|
||||
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('clears the escalated label once the foreground redial lands', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
latest().close()
|
||||
for (let dial = 0; dial < 4; dial++) {
|
||||
await vi.advanceTimersByTimeAsync(12_000 + 60_000)
|
||||
}
|
||||
// Four failed dials is past WARNING_ATTEMPTS, so the card reads "Can't
|
||||
// connect — check Tailscale" rather than a neutral "Connecting…".
|
||||
expect(label(client, TAILSCALE_ENDPOINT)).toBe("Can't connect — check Tailscale")
|
||||
await advanceUntilDialing(client)
|
||||
const doomed = latest()
|
||||
|
||||
suspend(120_000)
|
||||
client.notifyForeground()
|
||||
|
||||
expect(latest()).not.toBe(doomed)
|
||||
latest().authenticate()
|
||||
expect(client.getState()).toBe('connected')
|
||||
expect(client.getReconnectAttempt()).toBe(0)
|
||||
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('keeps escalating when the user checks back repeatedly during a real outage', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
latest().close()
|
||||
|
||||
// The desktop really is gone. Abandoning the stale dial must book the failure
|
||||
// it represents, or each visit resets the counter faster than it can climb and
|
||||
// the card reassures the user with "Connecting…" indefinitely (issue #10119).
|
||||
for (let visit = 0; visit < 14; visit++) {
|
||||
await advanceUntilDialing(client)
|
||||
suspend(30_000)
|
||||
client.notifyForeground()
|
||||
}
|
||||
|
||||
expect(client.getReconnectAttempt()).toBeGreaterThanOrEqual(12)
|
||||
expect(label(client, TAILSCALE_ENDPOINT)).toBe("Can't reach desktop — check Tailscale")
|
||||
|
||||
// And the escalation is not sticky: the desktop comes back, the card clears.
|
||||
latest().authenticate()
|
||||
expect(label(client, TAILSCALE_ENDPOINT)).toBe('Connected')
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('leaves a dial opened after the foreground edge alone', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
latest().close()
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
const fresh = latest()
|
||||
expect(client.getState()).toBe('connecting')
|
||||
|
||||
// A Wi-Fi→cellular handoff fires a second revival nudge right behind the
|
||||
// AppState one. It must not churn the dial that the first nudge just opened.
|
||||
client.notifyForeground()
|
||||
const afterFirstNudge = latest()
|
||||
client.notifyForeground()
|
||||
client.notifyForeground()
|
||||
|
||||
expect(latest()).toBe(afterFirstNudge)
|
||||
expect(fresh.endpoint).toBe(TAILSCALE_ENDPOINT)
|
||||
|
||||
client.close()
|
||||
})
|
||||
|
||||
it('abandons a handshake stalled across the suspension', async () => {
|
||||
const client = connect(TAILSCALE_ENDPOINT, 'token', 'server-key')
|
||||
latest().authenticate()
|
||||
latest().close()
|
||||
await vi.advanceTimersByTimeAsync(500)
|
||||
|
||||
// The upgrade completed but the desktop never sent e2ee_ready before the
|
||||
// phone was suspended — the classic wedged relay/Tailscale half-open.
|
||||
latest().open()
|
||||
expect(client.getState()).toBe('handshaking')
|
||||
const wedged = latest()
|
||||
|
||||
suspend(120_000)
|
||||
client.notifyForeground()
|
||||
|
||||
expect(latest()).not.toBe(wedged)
|
||||
latest().authenticate()
|
||||
expect(client.getState()).toBe('connected')
|
||||
|
||||
client.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { ConnectionState } from './types'
|
||||
|
||||
// Why: RN auto-pongs pings natively, so JS needs an app-level probe to detect half-open sockets.
|
||||
const ACTIVITY_PROBE_INTERVAL_MS = 20_000
|
||||
const ACTIVITY_PROBE_TIMEOUT_MS = 8_000
|
||||
|
||||
export type RpcActivityProbeDependencies = {
|
||||
getState: () => ConnectionState
|
||||
getSocket: () => WebSocket | null
|
||||
// Counts only validated inbound traffic, so a malformed frame cannot pass for liveness.
|
||||
getInboundSequence: () => number
|
||||
nextId: () => string
|
||||
registerPending: (id: string, onSettled: () => void) => void
|
||||
clearPending: (id: string) => void
|
||||
sendProbe: (id: string) => boolean
|
||||
forceReconnect: (socket: WebSocket) => void
|
||||
}
|
||||
|
||||
export type RpcActivityProbe = {
|
||||
start: () => void
|
||||
stop: () => void
|
||||
run: () => void
|
||||
}
|
||||
|
||||
export function createRpcActivityProbe(
|
||||
dependencies: RpcActivityProbeDependencies
|
||||
): RpcActivityProbe {
|
||||
let timer: ReturnType<typeof setInterval> | null = null
|
||||
let inFlight = false
|
||||
|
||||
function stop(): void {
|
||||
if (timer) {
|
||||
clearInterval(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
function run(): void {
|
||||
const probeWs = dependencies.getSocket()
|
||||
if (dependencies.getState() !== 'connected' || !probeWs || inFlight) {
|
||||
return
|
||||
}
|
||||
inFlight = true
|
||||
const id = dependencies.nextId()
|
||||
const probeInboundSequence = dependencies.getInboundSequence()
|
||||
let timedOut = false
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true
|
||||
inFlight = false
|
||||
dependencies.clearPending(id)
|
||||
// Why: any validated frame answered for the socket, even if this probe did not.
|
||||
if (dependencies.getInboundSequence() > probeInboundSequence) {
|
||||
return
|
||||
}
|
||||
console.log('[net] activity-probe TIMEOUT — forcing reconnect', {
|
||||
state: dependencies.getState()
|
||||
})
|
||||
// Why: stale probe timers must not close a replacement socket.
|
||||
if (probeWs === dependencies.getSocket() && probeWs.readyState === WebSocket.OPEN) {
|
||||
dependencies.forceReconnect(probeWs)
|
||||
}
|
||||
}, ACTIVITY_PROBE_TIMEOUT_MS)
|
||||
|
||||
dependencies.registerPending(id, () => {
|
||||
if (timedOut) {
|
||||
return
|
||||
}
|
||||
inFlight = false
|
||||
clearTimeout(timeout)
|
||||
})
|
||||
|
||||
if (!dependencies.sendProbe(id)) {
|
||||
inFlight = false
|
||||
clearTimeout(timeout)
|
||||
dependencies.clearPending(id)
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
run,
|
||||
stop,
|
||||
start(): void {
|
||||
stop()
|
||||
timer = setInterval(run, ACTIVITY_PROBE_INTERVAL_MS)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,8 @@ import {
|
||||
import { markRpcDeliveryUnknown } from './rpc-delivery-ambiguity'
|
||||
import { openRpcRequestBudget, resolvePostConnectRequestTimeout } from './rpc-request-budget'
|
||||
import { isRpcResponse } from './rpc-response-shape'
|
||||
import { createRpcActivityProbe } from './rpc-client-activity-probe'
|
||||
import { isStaleForegroundDial } from './rpc-stale-dial'
|
||||
import { websocketPayloadToUint8 } from './websocket-payload-bytes'
|
||||
|
||||
type PendingRequest = {
|
||||
@@ -126,9 +128,6 @@ const HANDSHAKE_TIMEOUT_MS = 5_000
|
||||
// Why: RN may not expose WebSocket.readyState constants, but the CONNECTING protocol value (0) is stable across runtimes.
|
||||
const WEBSOCKET_CONNECTING_STATE = 0
|
||||
|
||||
// Why: RN auto-pongs pings natively, so JS needs an app-level probe to detect half-open sockets.
|
||||
const ACTIVITY_PROBE_INTERVAL_MS = 20_000
|
||||
|
||||
export type ConnectOptions = {
|
||||
onStateChange?: (state: ConnectionState) => void
|
||||
// Fires for every lifecycle event so the UI can show where 'Connecting…' is stuck (e.g. broken Tailscale route).
|
||||
@@ -169,8 +168,6 @@ export function connect(
|
||||
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let connectTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let handshakeTimer: ReturnType<typeof setTimeout> | null = null
|
||||
let activityProbeTimer: ReturnType<typeof setInterval> | null = null
|
||||
let activityProbeInFlight = false
|
||||
let intentionallyClosed = false
|
||||
// Consecutive auth rejections; tolerate up to AUTH_RETRY_BUDGET (issue #5200) before latching to avoid a needless re-pair.
|
||||
let authRejectionCount = 0
|
||||
@@ -181,6 +178,7 @@ export function connect(
|
||||
let inboundSequence = 0
|
||||
let lastWsClosedAt: number | null = null
|
||||
let wsConstructionCounter = 0
|
||||
let dialStartedAt = 0
|
||||
|
||||
// Why: fresh ephemeral keypair per connection provides forward secrecy.
|
||||
let sharedKey: Uint8Array | null = null
|
||||
@@ -302,6 +300,7 @@ export function connect(
|
||||
msSinceLastInbound: lastInboundAt != null ? now - lastInboundAt : null
|
||||
})
|
||||
setState('connecting')
|
||||
dialStartedAt = now
|
||||
sharedKey = null
|
||||
|
||||
emitLog(
|
||||
@@ -328,11 +327,7 @@ export function connect(
|
||||
'WebSocket connect timeout',
|
||||
`No TCP/WS handshake within ${CONNECT_TIMEOUT_MS / 1000}s — endpoint unreachable?`
|
||||
)
|
||||
openingWs.close()
|
||||
if (ws === openingWs) {
|
||||
synthesizedCloses.remember(openingWs, authenticationGeneration)
|
||||
handleSocketClosed(openingWs, { timedOut: true })
|
||||
}
|
||||
closeAndSynthesize(openingWs)
|
||||
}
|
||||
}, CONNECT_TIMEOUT_MS)
|
||||
|
||||
@@ -372,12 +367,7 @@ export function connect(
|
||||
'Handshake timeout',
|
||||
`No e2ee_ready/e2ee_authenticated within ${HANDSHAKE_TIMEOUT_MS / 1000}s`
|
||||
)
|
||||
openingWs.close()
|
||||
// Why: React Native can omit onclose for a wedged iOS transport.
|
||||
if (ws === openingWs) {
|
||||
synthesizedCloses.remember(openingWs, authenticationGeneration)
|
||||
handleSocketClosed(openingWs, { timedOut: true })
|
||||
}
|
||||
closeAndSynthesize(openingWs)
|
||||
}, HANDSHAKE_TIMEOUT_MS)
|
||||
}
|
||||
|
||||
@@ -422,17 +412,14 @@ export function connect(
|
||||
try {
|
||||
const msg = JSON.parse(plaintext)
|
||||
if (msg.type === 'e2ee_authenticated') {
|
||||
if (handshakeTimer) {
|
||||
clearTimeout(handshakeTimer)
|
||||
handshakeTimer = null
|
||||
}
|
||||
clearHandshakeTimer()
|
||||
console.log('[net] e2ee_authenticated — connected', {
|
||||
streamCount: streamListeners.size
|
||||
})
|
||||
openingWsAuthenticated = true
|
||||
setState('connected')
|
||||
emitLog('success', 'Authenticated', 'Channel ready for RPC')
|
||||
startActivityProbe()
|
||||
activityProbe.start()
|
||||
for (const [id, stream] of streamListeners) {
|
||||
if (stream.cancelled) {
|
||||
removeStreamListener(id)
|
||||
@@ -458,10 +445,7 @@ export function connect(
|
||||
}
|
||||
} else if (msg.type === 'e2ee_error' || (!msg.ok && msg.error?.code === 'unauthorized')) {
|
||||
console.log('[net] e2ee auth FAILED', { msgType: msg.type, error: msg.error })
|
||||
if (handshakeTimer) {
|
||||
clearTimeout(handshakeTimer)
|
||||
handshakeTimer = null
|
||||
}
|
||||
clearHandshakeTimer()
|
||||
handleAuthRejection('Unauthorized — pairing may be revoked')
|
||||
}
|
||||
} catch {
|
||||
@@ -654,11 +638,8 @@ export function connect(
|
||||
activeBrowserScreencastRequestId = null
|
||||
pendingBrowserScreencastRequestId = null
|
||||
markStreamsForReplay()
|
||||
if (handshakeTimer) {
|
||||
clearTimeout(handshakeTimer)
|
||||
handshakeTimer = null
|
||||
}
|
||||
stopActivityProbe()
|
||||
clearHandshakeTimer()
|
||||
activityProbe.stop()
|
||||
if (intentionallyClosed) {
|
||||
console.log('[net] handleSocketClosed — intentional close')
|
||||
setState('disconnected')
|
||||
@@ -768,66 +749,33 @@ export function connect(
|
||||
}
|
||||
}
|
||||
|
||||
// Why: app-level liveness probe (see ACTIVITY_PROBE_INTERVAL_MS) — force-closes the WS on failure so onclose reconnects.
|
||||
function runActivityProbe() {
|
||||
if (state !== 'connected' || !ws || activityProbeInFlight) {
|
||||
return
|
||||
}
|
||||
activityProbeInFlight = true
|
||||
const probeWs = ws
|
||||
const id = nextId()
|
||||
const probeInboundSequence = inboundSequence
|
||||
let timedOut = false
|
||||
const timeout = setTimeout(() => {
|
||||
timedOut = true
|
||||
activityProbeInFlight = false
|
||||
pending.delete(id)
|
||||
if (inboundSequence > probeInboundSequence) {
|
||||
return
|
||||
}
|
||||
console.log('[net] activity-probe TIMEOUT — forcing reconnect', { state })
|
||||
// Why: stale probe timers must not close a replacement socket.
|
||||
if (probeWs === ws && probeWs.readyState === WebSocket.OPEN) {
|
||||
probeWs.close()
|
||||
// Why: React Native can omit onclose for a wedged iOS transport.
|
||||
if (probeWs === ws) {
|
||||
synthesizedCloses.remember(probeWs, authenticationGeneration)
|
||||
handleSocketClosed(probeWs, { timedOut: true })
|
||||
}
|
||||
}
|
||||
}, 8_000)
|
||||
pending.set(id, {
|
||||
resolve: () => {
|
||||
if (timedOut) {
|
||||
return
|
||||
}
|
||||
activityProbeInFlight = false
|
||||
clearTimeout(timeout)
|
||||
},
|
||||
reject: () => {
|
||||
if (timedOut) {
|
||||
return
|
||||
}
|
||||
activityProbeInFlight = false
|
||||
clearTimeout(timeout)
|
||||
}
|
||||
})
|
||||
if (!sendEncrypted({ id, deviceToken, method: 'status.get' })) {
|
||||
activityProbeInFlight = false
|
||||
clearTimeout(timeout)
|
||||
pending.delete(id)
|
||||
function clearHandshakeTimer() {
|
||||
if (handshakeTimer) {
|
||||
clearTimeout(handshakeTimer)
|
||||
handshakeTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function startActivityProbe() {
|
||||
stopActivityProbe()
|
||||
activityProbeTimer = setInterval(runActivityProbe, ACTIVITY_PROBE_INTERVAL_MS)
|
||||
// Why: a revival signal dials at once rather than waiting out the armed backoff.
|
||||
// Only the caller knows whether the attempt that led here should be forgiven.
|
||||
function redialNow(resetAttempts: boolean) {
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer)
|
||||
reconnectTimer = null
|
||||
}
|
||||
if (resetAttempts) {
|
||||
reconnectAttempt = 0
|
||||
}
|
||||
openConnection()
|
||||
}
|
||||
|
||||
function stopActivityProbe() {
|
||||
if (activityProbeTimer) {
|
||||
clearInterval(activityProbeTimer)
|
||||
activityProbeTimer = null
|
||||
// Why: React Native can omit onclose for a wedged iOS transport, so every forced
|
||||
// close has to synthesize the close event it may never deliver.
|
||||
function closeAndSynthesize(socket: WebSocket) {
|
||||
socket.close()
|
||||
if (ws === socket) {
|
||||
synthesizedCloses.remember(socket, authenticationGeneration)
|
||||
handleSocketClosed(socket, { timedOut: true })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1005,6 +953,17 @@ export function connect(
|
||||
}
|
||||
}
|
||||
|
||||
const activityProbe = createRpcActivityProbe({
|
||||
getState: () => state,
|
||||
getSocket: () => ws,
|
||||
getInboundSequence: () => inboundSequence,
|
||||
nextId,
|
||||
registerPending: (id, onSettled) => pending.set(id, { resolve: onSettled, reject: onSettled }),
|
||||
clearPending: (id) => pending.delete(id),
|
||||
sendProbe: (id) => sendEncrypted({ id, deviceToken, method: 'status.get' }),
|
||||
forceReconnect: closeAndSynthesize
|
||||
})
|
||||
|
||||
openConnection()
|
||||
|
||||
return {
|
||||
@@ -1160,22 +1119,31 @@ export function connect(
|
||||
if (state === 'connected') {
|
||||
// Why: OS can kill the TCP path while backgrounded without onclose; probe now to detect the half-open socket in ≤8s (issue #5049).
|
||||
console.log('[net] foreground — probing live connection')
|
||||
startActivityProbe()
|
||||
runActivityProbe()
|
||||
activityProbe.start()
|
||||
activityProbe.run()
|
||||
return
|
||||
}
|
||||
const dialing = ws
|
||||
const dialAgeMs = Date.now() - dialStartedAt
|
||||
let abandoned = false
|
||||
if (dialing && isStaleForegroundDial(state, dialAgeMs)) {
|
||||
console.log('[net] foreground — abandoning stale dial', { state, dialAgeMs })
|
||||
closeAndSynthesize(dialing)
|
||||
abandoned = true
|
||||
}
|
||||
if (state === 'reconnecting') {
|
||||
// Why: foreground is a strong user signal — restart immediately instead of waiting out a 60s/90s backoff timer.
|
||||
console.log('[net] foreground — restarting reconnect loop', {
|
||||
attempt: reconnectAttempt,
|
||||
hadTimer: !!reconnectTimer
|
||||
})
|
||||
if (reconnectTimer) {
|
||||
clearTimeout(reconnectTimer)
|
||||
reconnectTimer = null
|
||||
}
|
||||
reconnectAttempt = 0
|
||||
openConnection()
|
||||
// Why: an abandoned dial keeps the failure it already represents. It never
|
||||
// authenticated, so it is the same failure the connect timeout would have
|
||||
// booked had we waited it out — we skip the wait, we don't pardon it. 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
|
||||
// (issue #10119). A redial with no dial to abandon is a genuinely fresh start.
|
||||
redialNow(!abandoned)
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1186,11 +1154,8 @@ export function connect(
|
||||
reconnectTimer = null
|
||||
}
|
||||
clearConnectTimer()
|
||||
if (handshakeTimer) {
|
||||
clearTimeout(handshakeTimer)
|
||||
handshakeTimer = null
|
||||
}
|
||||
stopActivityProbe()
|
||||
clearHandshakeTimer()
|
||||
activityProbe.stop()
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { ConnectionState } from './types'
|
||||
|
||||
// Why: a dial older than this predates the revival signal, so it was opened over a
|
||||
// network path that may no longer exist. Younger dials belong to the current
|
||||
// foreground session — AppState 'active' and a Wi-Fi→cellular change fire back to
|
||||
// back, and both reach the same nudge, so this also keeps them from churning it.
|
||||
const STALE_DIAL_AGE_MS = 2_000
|
||||
|
||||
// A phone suspended mid-dial resumes still holding that socket, and React Native
|
||||
// keeps its readyState at CONNECTING because no close event was ever delivered.
|
||||
// Treating 'connecting'/'handshaking' as progress worth waiting out left the user
|
||||
// on the rest of the 12s connect budget over a dead path, then a preserved backoff
|
||||
// delay — up to a further 60s of "Connecting…" against an answering desktop.
|
||||
export function isStaleForegroundDial(state: ConnectionState, dialAgeMs: number): boolean {
|
||||
return (state === 'connecting' || state === 'handshaking') && dialAgeMs >= STALE_DIAL_AGE_MS
|
||||
}
|
||||
Reference in New Issue
Block a user