Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(mobile): detect dead direct links in seconds (#36112)

Kelvin Amoaba0a75796a0380
diff --git a/config/flaky-test-pattern-baseline.txt b/config/flaky-test-pattern-baseline.txt
index 1a3ae98caf1..4506c581638 100644
--- a/config/flaky-test-pattern-baseline.txt
+++ b/config/flaky-test-pattern-baseline.txt
@@ -1228,7 +1228,6 @@
1 test-timeout-needs-reason:mobile/src/test-support/rpc-recording/recorded-request-params.test.ts
1 test-timeout-needs-reason:mobile/src/test-support/rpc-recording/rpc-recording-through-bridge.test.ts
1 test-timeout-needs-reason:mobile/src/transport/mobile-web-bundle-host-slow-link.test.ts
-1 test-timeout-needs-reason:mobile/src/transport/rpc-client-live-recovery.test.ts
3 test-timeout-needs-reason:mobile/src/transport/rpc-client-reconnect-wait.test.ts
1 test-timeout-needs-reason:src/cli/agent-launch-process.test.ts
1 test-timeout-needs-reason:src/cli/runtime/launch-serve-replaced-app-restart.test.ts
diff --git a/mobile/src/transport/connection-revival-triggers.test.ts b/mobile/src/transport/connection-revival-triggers.test.ts
index 3711aafd02f..d5167076cc2 100644
--- a/mobile/src/transport/connection-revival-triggers.test.ts
+++ b/mobile/src/transport/connection-revival-triggers.test.ts
@@ -11,8 +11,6 @@ type NetworkListener = (state: NetworkSnapshot) => void
const appStateListeners = new Map<string, Set<AppStateListener>>()
const networkListeners = new Set<NetworkListener>()
const subscriptions = new Set<() => void>()
-let seededNetworkState: NetworkSnapshot = { isConnected: true, type: 'WIFI' }
-let readNetworkState = () => Promise.resolve(seededNetworkState)
const appStateRemove = vi.fn()
const networkRemove = vi.fn()
@@ -34,7 +32,6 @@ vi.mock('react-native', () => ({
}))
vi.mock('expo-network', () => ({
- getNetworkStateAsync: () => readNetworkState(),
addNetworkStateListener: (listener: NetworkListener) => {
networkListeners.add(listener)
return {
@@ -46,12 +43,6 @@ vi.mock('expo-network', () => ({
}
}))
-async function subscribeAndSeed(nudge: RevivalNudge): Promise<() => void> {
- const unsubscribe = subscribe(nudge)
- await Promise.resolve()
- return unsubscribe
-}
-
function subscribe(nudge: RevivalNudge): () => void {
const unsubscribe = subscribeConnectionRevivalTriggers(nudge)
subscriptions.add(unsubscribe)
@@ -82,8 +73,6 @@ describe('subscribeConnectionRevivalTriggers', () => {
vi.clearAllMocks()
appStateListeners.clear()
networkListeners.clear()
- readNetworkState = () => Promise.resolve(seededNetworkState)
- seededNetworkState = { isConnected: true, type: 'WIFI' }
nudge = vi.fn<RevivalNudge>()
})
@@ -98,8 +87,8 @@ describe('subscribeConnectionRevivalTriggers', () => {
vi.restoreAllMocks()
})
- it('nudges when the app returns to the foreground, not on background', async () => {
- await subscribeAndSeed(nudge)
+ it('nudges when the app returns to the foreground, not on background', () => {
+ subscribe(nudge)
emitAppState('background')
expect(nudge).not.toHaveBeenCalled()
emitAppState('active')
@@ -107,12 +96,26 @@ describe('subscribeConnectionRevivalTriggers', () => {
expect(nudge).toHaveBeenLastCalledWith('app-resume')
})
- it('keeps elapsed background time when a device sleep pauses the monotonic clock', async () => {
+ it('does not treat focus or an inactive interruption as a background return', () => {
+ subscribe(nudge)
+ emitAppState('active')
+ emitAppState('inactive')
+ emitAppState('active')
+ expect(nudge).not.toHaveBeenCalled()
+
+ emitAppState('background')
+ emitAppState('inactive')
+ emitAppState('active')
+ emitAppState('active')
+ expect(nudge).toHaveBeenCalledExactlyOnceWith('app-resume')
+ })
+
+ it('keeps elapsed background time when a device sleep pauses the monotonic clock', () => {
let wall = 1_000
let monotonic = 50
const wallClock = vi.spyOn(Date, 'now').mockImplementation(() => wall)
const monotonicClock = vi.spyOn(performance, 'now').mockImplementation(() => monotonic)
- const unsubscribe = await subscribeAndSeed(nudge)
+ const unsubscribe = subscribe(nudge)
const elapsed = startSocketDeadlineClock()
try {
emitAppState('background')
@@ -129,8 +132,8 @@ describe('subscribeConnectionRevivalTriggers', () => {
}
})
- it('nudges when the network comes back online', async () => {
- await subscribeAndSeed(nudge)
+ it('nudges when the network comes back online', () => {
+ subscribe(nudge)
emitNetwork({ isConnected: false, type: 'NONE' })
expect(nudge).not.toHaveBeenCalled()
emitNetwork({ isConnected: true, type: 'WIFI' })
@@ -138,43 +141,31 @@ describe('subscribeConnectionRevivalTriggers', () => {
expect(nudge).toHaveBeenLastCalledWith('network-change')
})
- it('nudges when the app started offline and the first event is the recovery', async () => {
- seededNetworkState = { isConnected: false, type: 'NONE' }
- await subscribeAndSeed(nudge)
+ it('nudges on the first connected network event', () => {
+ subscribe(nudge)
emitNetwork({ isConnected: true, type: 'WIFI' })
expect(nudge).toHaveBeenCalledTimes(1)
expect(nudge).toHaveBeenLastCalledWith('network-change')
})
- it('nudges on a Wi-Fi to cellular handoff that never reports offline', async () => {
- await subscribeAndSeed(nudge)
+ it('nudges on a Wi-Fi to cellular handoff that never reports offline', () => {
+ subscribe(nudge)
+ emitNetwork({ isConnected: true, type: 'WIFI' })
+ nudge.mockClear()
emitNetwork({ isConnected: true, type: 'CELLULAR' })
expect(nudge).toHaveBeenCalledTimes(1)
expect(nudge).toHaveBeenLastCalledWith('network-change')
})
- it('stays quiet when the network state matches the seeded baseline', async () => {
- await subscribeAndSeed(nudge)
+ it('nudges on same-type Wi-Fi events because the path may have changed', () => {
+ subscribe(nudge)
emitNetwork({ isConnected: true, type: 'WIFI' })
emitNetwork({ isConnected: true, type: 'WIFI' })
- expect(nudge).not.toHaveBeenCalled()
+ expect(nudge.mock.calls).toEqual([['network-change'], ['network-change']])
})
- it('keeps a newer network event when a stale seed resolves later', async () => {
- let finishSeed: (state: NetworkSnapshot) => void = () => {}
- const pendingSeed = new Promise<NetworkSnapshot>((resolve) => {
- finishSeed = resolve
- })
- readNetworkState = () => pendingSeed
+ it('removes both OS listeners when disposed', () => {
const unsubscribe = subscribe(nudge)
- emitNetwork({ isConnected: true, type: 'CELLULAR' })
- finishSeed({ isConnected: true, type: 'WIFI' })
- await Promise.resolve()
- emitNetwork({ isConnected: true, type: 'CELLULAR' })
- expect(nudge).not.toHaveBeenCalled()
- emitNetwork({ isConnected: true, type: 'WIFI' })
- expect(nudge).toHaveBeenCalledTimes(1)
- expect(nudge).toHaveBeenLastCalledWith('network-change')
unsubscribe()
expect(appStateRemove).toHaveBeenCalledTimes(1)
expect(networkRemove).toHaveBeenCalledTimes(1)
diff --git a/mobile/src/transport/connection-revival-triggers.ts b/mobile/src/transport/connection-revival-triggers.ts
index 2fc1437dfcd..96b0ae371a9 100644
--- a/mobile/src/transport/connection-revival-triggers.ts
+++ b/mobile/src/transport/connection-revival-triggers.ts
@@ -1,5 +1,5 @@
import { AppState } from 'react-native'
-import { addNetworkStateListener, getNetworkStateAsync, type NetworkState } from 'expo-network'
+import { addNetworkStateListener } from 'expo-network'
import { recordSocketDeadlineAppState } from './socket-deadline-clock'
// Resume/network handoff can kill sockets without close events and suspend retry timers; nudge recovery from OS signals (#5049).
@@ -7,41 +7,25 @@ export function subscribeConnectionRevivalTriggers(
nudge: (reason: 'app-resume' | 'network-change') => void
): () => void {
recordSocketDeadlineAppState(AppState.currentState)
+ let wasBackgrounded = AppState.currentState === 'background'
const appStateSub = AppState.addEventListener('change', (next) => {
recordSocketDeadlineAppState(next)
- if (next === 'active') {
+ if (next === 'background') {
+ wasBackgrounded = true
+ } else if (next === 'active' && wasBackgrounded) {
+ wasBackgrounded = false
nudge('app-resume')
}
})
- let lastNetwork: Pick<NetworkState, 'isConnected' | 'type'> | null = null
- let disposed = false
- // Seed the baseline so the first offline-to-online change is not swallowed.
- void getNetworkStateAsync()
- .then((state) => {
- if (!disposed && lastNetwork == null) {
- lastNetwork = { isConnected: state.isConnected, type: state.type }
- }
- })
- .catch(() => {})
const networkSub = addNetworkStateListener((state) => {
- const previous = lastNetwork
- lastNetwork = { isConnected: state.isConnected, type: state.type }
if (state.isConnected !== true) {
return
}
- const cameOnline = previous != null && previous.isConnected !== true
- // A Wi-Fi/cellular handoff can kill TCP while connectivity stays true.
- const switchedNetworks = previous?.type != null && state.type !== previous.type
- if (cameOnline || switchedNetworks) {
- console.log('[net] network changed — nudging clients', {
- type: state.type,
- cameOnline
- })
- nudge('network-change')
- }
+ // Wi-Fi roaming can replace the TCP path without changing the reported network type.
+ console.log('[net] network changed — nudging clients', { type: state.type })
+ nudge('network-change')
})
return () => {
- disposed = true
appStateSub.remove()
networkSub.remove()
}
diff --git a/mobile/src/transport/direct-rpc-client.ts b/mobile/src/transport/direct-rpc-client.ts
index 8241d8f9ebf..af96c02259e 100644
--- a/mobile/src/transport/direct-rpc-client.ts
+++ b/mobile/src/transport/direct-rpc-client.ts
@@ -16,12 +16,16 @@ import {
type RpcStreamingListener,
type RpcStreamSubscribeOptions
} from './rpc-client-stream-registry'
-import { RpcSessionLivenessWatchdog } from './rpc-session-liveness-watchdog'
+import {
+ DECISIVE_PROBE_TIMEOUT_MS,
+ RpcSessionLivenessWatchdog
+} from './rpc-session-liveness-watchdog'
import { isStaleForegroundDial } from './rpc-stale-dial'
import type { ConnectionState, ForegroundNudgeReason, RpcResponse } from './types'
import { negotiateMobileRuntimeCapabilities } from './mobile-runtime-capability-negotiation'
const LIVENESS_REQUEST_ID_PREFIX = 'mobile-liveness-'
+const DIRECT_FOREGROUND_PROBE_MIN_INTERVAL_MS = 10_000
export class DirectRpcClient implements RpcClient {
private socketSession: RpcClientSocketSession | null = null
@@ -71,6 +75,7 @@ export class DirectRpcClient implements RpcClient {
})
this.liveness = new RpcSessionLivenessWatchdog({
transport: 'direct',
+ voluntaryProbeMinIntervalMs: DIRECT_FOREGROUND_PROBE_MIN_INTERVAL_MS,
sendProbe: (identity) => identity === this.livenessSession && this.sendLivenessProbe(),
terminate: (identity) => {
if (identity === this.livenessSession && this.socketSession === this.livenessSession) {
@@ -152,36 +157,36 @@ export class DirectRpcClient implements RpcClient {
this.streams.updateTerminalViewport(terminal, viewport)
}
- getState(): ConnectionState {
- return this.connectionState.get()
- }
+ getState = (): ConnectionState => this.connectionState.get()
- getReconnectAttempt(): number {
- return this.reconnect.getAttempt()
- }
+ getReconnectAttempt = (): number => this.reconnect.getAttempt()
- getLastConnectedAt(): number | null {
- return this.connectionState.getLastConnectedAt()
- }
+ getLastConnectedAt = (): number | null => this.connectionState.getLastConnectedAt()
getLastInboundAt = (): number | null => this.liveness.getLastInboundAt() || null
- onStateChange(listener: (state: ConnectionState) => void): () => void {
- return this.connectionState.addListener(listener)
- }
+ onStateChange = (listener: (state: ConnectionState) => void): (() => void) =>
+ this.connectionState.addListener(listener)
// The watchdog starts before capability negotiation, when a probe cannot be written yet.
readonly probeLivenessNow = (): void =>
void (this.getState() === 'connected' && this.liveness.probeCurrentDecisively())
- notifyForeground(_reason?: ForegroundNudgeReason): void {
+ notifyForeground(reason: ForegroundNudgeReason = 'focus'): void {
if (this.intentionallyClosed) {
return
}
if (this.getState() === 'connected') {
console.log('[net] foreground — probing live connection')
if (this.livenessSession) {
- this.liveness.probeNow(this.livenessSession)
+ if (reason === 'app-resume') {
+ this.liveness.probeAfterBackground(this.livenessSession)
+ } else {
+ this.liveness.probeNow(
+ this.livenessSession,
+ reason === 'network-change' ? DECISIVE_PROBE_TIMEOUT_MS : null
+ )
+ }
}
return
}
@@ -302,13 +307,10 @@ export class DirectRpcClient implements RpcClient {
}
private sendLivenessProbe(): boolean {
- if (this.getState() !== 'connected') {
- return false
- }
- return this.sendFrame({
- id: `${LIVENESS_REQUEST_ID_PREFIX}${this.nextId()}`,
- method: 'status.get'
- })
+ return (
+ this.getState() === 'connected' &&
+ this.sendFrame({ id: `${LIVENESS_REQUEST_ID_PREFIX}${this.nextId()}`, method: 'status.get' })
+ )
}
private waitForConnected(timeoutMs?: number): Promise<void> {
@@ -321,7 +323,5 @@ export class DirectRpcClient implements RpcClient {
return this.connectionState.waitForConnected(timeoutMs)
}
- private nextId(): string {
- return `rpc-${++this.requestCounter}-${Date.now()}`
- }
+ private nextId = (): string => `rpc-${++this.requestCounter}-${Date.now()}`
}
diff --git a/mobile/src/transport/mobile-endpoint-nudge-router.test.ts b/mobile/src/transport/mobile-endpoint-nudge-router.test.ts
index 808ad53f6c8..824ad323592 100644
--- a/mobile/src/transport/mobile-endpoint-nudge-router.test.ts
+++ b/mobile/src/transport/mobile-endpoint-nudge-router.test.ts
@@ -11,7 +11,7 @@ function routerFixture() {
getGeneration: vi.fn(() => 1),
sendRequest: vi.fn(async () => ({}))
} as unknown as StableLogicalRpcClient
- const handleActiveNudge = vi.fn(() => 'probe' as const)
+ const handleActiveNudge = vi.fn()
const setForeground = vi.fn((next: boolean) => {
foreground = next
})
@@ -22,7 +22,6 @@ function routerFixture() {
isStopped: () => false,
isForeground: () => foreground,
setForeground,
- replaceRelay: vi.fn(),
scheduleDirectProbe
})
return { handleActiveNudge, logical, router, scheduleDirectProbe, setForeground }
diff --git a/mobile/src/transport/mobile-endpoint-nudge-router.ts b/mobile/src/transport/mobile-endpoint-nudge-router.ts
index 392bac0589d..2a8c329ffde 100644
--- a/mobile/src/transport/mobile-endpoint-nudge-router.ts
+++ b/mobile/src/transport/mobile-endpoint-nudge-router.ts
@@ -10,7 +10,6 @@ export class MobileEndpointNudgeRouter {
isStopped: () => boolean
isForeground: () => boolean
setForeground: (foreground: boolean) => void
- replaceRelay: () => void
scheduleDirectProbe: () => void
}
) {}
@@ -27,10 +26,7 @@ export class MobileEndpointNudgeRouter {
}
args.setForeground(true)
}
- const verdict = args.controller.handleActiveNudge(args.logical, reason)
- if (verdict === 'replace') {
- args.replaceRelay()
- }
+ args.controller.handleActiveNudge(args.logical, reason)
args.scheduleDirectProbe()
}
}
diff --git a/mobile/src/transport/mobile-endpoint-supervisor-nudge.test.ts b/mobile/src/transport/mobile-endpoint-supervisor-nudge.test.ts
index a11d057c02a..c7b9c6a245e 100644
--- a/mobile/src/transport/mobile-endpoint-supervisor-nudge.test.ts
+++ b/mobile/src/transport/mobile-endpoint-supervisor-nudge.test.ts
@@ -28,80 +28,30 @@ describe('mobile endpoint supervisor nudges', () => {
vi.useRealTimers()
})
- it('replaces a relay make-before-break on a network nudge without going grey', async () => {
+ it('keeps a healthy relay bound across repeated network hints', async () => {
const logical = createStableLogicalRpcClient(new FakeSession('disconnected'), 'lan')
const activeRelay = new FakeRelaySession('connected')
- const replacement = new FakeRelaySession('connecting')
const deps = dependencies({
- openRelay: vi.fn().mockReturnValueOnce(activeRelay).mockReturnValue(replacement),
+ openRelay: vi.fn(() => activeRelay),
openDirect: vi.fn(() => new FakeSession('disconnected'))
})
const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
-
- await supervisor.start()
- expect(deps.openRelay).toHaveBeenCalledOnce()
- expect(logical.getActivePath()).toBe('relay')
-
- const states: string[] = []
- const unsubscribe = logical.onStateChange((state) => states.push(state))
- supervisor.nudge('network-change')
- await vi.advanceTimersByTimeAsync(0)
- expect(deps.openRelay).toHaveBeenCalledTimes(2)
- expect(logical.getState()).toBe('connected')
- expect(logical.getGeneration()).toBe(2)
- expect(activeRelay.close).not.toHaveBeenCalled()
- expect(replacement.close).not.toHaveBeenCalled()
- replacement.publishState('connected')
- await vi.advanceTimersByTimeAsync(0)
- expect(logical.getGeneration()).toBe(3)
- expect(activeRelay.close).toHaveBeenCalledOnce()
- expect(replacement.close).not.toHaveBeenCalled()
- expect(states).not.toContain('disconnected')
- await logical.sendRequest('status.get')
- expect(replacement.sendRequest).toHaveBeenCalledWith('status.get', undefined, undefined)
- expect(activeRelay.sendRequest).not.toHaveBeenCalled()
- expect(logical.getState()).toBe('connected')
- unsubscribe()
- supervisor.stop()
- expect(vi.getTimerCount()).toBe(0)
- logical.close()
- })
-
- it('suspends only after a failed replacement dial, then backs off further nudges', async () => {
- const logical = new FakeLogicalClient('disconnected', 'lan')
- const openRelay = vi
- .fn()
- .mockReturnValueOnce(new FakeRelaySession('connected'))
- .mockImplementation(() => new FakeRelaySession('disconnected', new RelayOuterError(4408)))
- const deps = dependencies({
- openRelay,
- // Keep direct unavailable so relay recovery stays the only path under test.
- openDirect: vi.fn(() => new FakeSession('disconnected')),
- // Deterministic full jitter: fraction 0.5 → half the backoff window.
- randomBytes: () => new Uint8Array([128, 0])
- })
- const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
-
await supervisor.start()
- expect(openRelay).toHaveBeenCalledOnce()
-
- // A failed replacement must retire the suspect session and book shared cooldown so the armed retry can recover.
- supervisor.nudge('network-change')
- await vi.advanceTimersByTimeAsync(0)
- expect(logical.suspendActiveSession).toHaveBeenCalledOnce()
- expect(openRelay).toHaveBeenCalledTimes(2)
+ const generation = logical.getGeneration()
- for (let i = 0; i < 5; i++) {
+ for (let index = 0; index < 3; index++) {
supervisor.nudge('network-change')
- await vi.advanceTimersByTimeAsync(0)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(logical.getState()).toBe('connected')
+ expect(logical.getGeneration()).toBe(generation)
+ expect(deps.openRelay).toHaveBeenCalledOnce()
+ expect(activeRelay.close).not.toHaveBeenCalled()
}
- expect(openRelay).toHaveBeenCalledTimes(2)
-
- await vi.advanceTimersByTimeAsync(249)
- expect(openRelay).toHaveBeenCalledTimes(2)
- await vi.advanceTimersByTimeAsync(1)
- expect(openRelay).toHaveBeenCalledTimes(3)
+ await logical.sendRequest('status.get')
+ expect(activeRelay.sendRequest).toHaveBeenCalledWith('status.get', undefined, undefined)
supervisor.stop()
+ logical.close()
+ expect(vi.getTimerCount()).toBe(0)
})
it('restarts a disconnected Relay immediately on an app-resume retry', async () => {
@@ -148,61 +98,6 @@ describe('mobile endpoint supervisor nudges', () => {
supervisor.stop()
})
- it('queues a network replacement that lands while another dial owns the mutex', async () => {
- const logical = new FakeLogicalClient('disconnected', 'lan')
- let resolveWrite: (() => void) | undefined
- const deps = dependencies({
- openDirect: vi.fn(() => new FakeSession('disconnected')),
- writeBundle: vi
- .fn()
- .mockResolvedValueOnce(undefined)
- .mockImplementation(
- () =>
- new Promise<void>((resolve) => {
- resolveWrite = resolve
- })
- )
- })
- const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
- await supervisor.start()
- expect(deps.openRelay).toHaveBeenCalledOnce()
-
- // Queue a second handoff while slow persistence holds the recovery mutex.
- supervisor.nudge('network-change')
- await vi.advanceTimersByTimeAsync(0)
- expect(deps.openRelay).toHaveBeenCalledTimes(2)
- supervisor.nudge('network-change')
- expect(logical.suspendActiveSession).not.toHaveBeenCalled()
-
- resolveWrite?.()
- await vi.advanceTimersByTimeAsync(0)
- expect(deps.openRelay).toHaveBeenCalledTimes(2)
- expect(logical.getState()).toBe('connected')
- supervisor.stop()
- })
-
- it('keeps a healthy relay bound when a nudge finds no dialable credential', async () => {
- const logical = new FakeLogicalClient('connected', 'relay')
- const expired = {
- ...bundle,
- current: { ...bundle.current, expiresAt: 1 }
- }
- const deps = dependencies({
- readBundle: vi.fn(async () => expired),
- randomBytes: () => new Uint8Array([128, 0])
- })
- const supervisor = new MobileEndpointSupervisor(logical, host.id, relay, deps)
- await supervisor.start()
-
- supervisor.nudge('network-change')
- await vi.advanceTimersByTimeAsync(0)
- // Why: no dial happened, so nothing has disproven the live session.
- expect(logical.suspendActiveSession).not.toHaveBeenCalled()
- expect(deps.openRelay).not.toHaveBeenCalled()
- expect(logical.getState()).toBe('connected')
- supervisor.stop()
- })
-
it('withdraws the racing relay dial when direct authenticated while it was in flight', async () => {
// Withdraw if direct wins before relay authentication; never close the winning session.
const directSession = new FakeSession('connecting')
diff --git a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
index ab57b7c7d79..671fa93cb75 100644
--- a/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
+++ b/mobile/src/transport/mobile-endpoint-supervisor-test-fakes.ts
@@ -72,7 +72,6 @@ export class FakeRelaySession extends FakeSession implements MobileRelayRpcSessi
resumeExpiresAt: this.resumeExpiry
})
getFailure = () => this.failure
- readonly probeAfterBackground = vi.fn()
}
export class FakeLogicalClient extends FakeSession implements StableLogicalRpcClient {
diff --git a/mobile/src/transport/mobile-endpoint-supervisor.test.ts b/mobile/src/transport/mobile-endpoint-supervisor.test.ts
index a903f0ed17f..12e864d0703 100644
--- a/mobile/src/transport/mobile-endpoint-supervisor.test.ts
+++ b/mobile/src/transport/mobile-endpoint-supervisor.test.ts
@@ -780,13 +780,15 @@ describe('mobile endpoint supervisor', () => {
await vi.advanceTimersByTimeAsync(60_000)
expect(openRelay).toHaveBeenCalledTimes(2)
- // A network nudge inside the cooldown must not dial early and must not tear
- // down the healthy session; the queued intent runs at the 250 ms boundary.
+ // Ambiguous network hints leave the healthy session and the lease retry cadence intact.
supervisor.nudge('network-change')
expect(logical.suspendActiveSession).not.toHaveBeenCalled()
await vi.advanceTimersByTimeAsync(249)
expect(openRelay).toHaveBeenCalledTimes(2)
await vi.advanceTimersByTimeAsync(1)
+ expect(openRelay).toHaveBeenCalledTimes(2)
+ expect(logical.suspendActiveSession).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(4_750)
expect(openRelay).toHaveBeenCalledTimes(3)
supervisor.stop()
})
diff --git a/mobile/src/transport/mobile-endpoint-supervisor.ts b/mobile/src/transport/mobile-endpoint-supervisor.ts
index 28d2e1b162e..d7ccb8e0a9b 100644
--- a/mobile/src/transport/mobile-endpoint-supervisor.ts
+++ b/mobile/src/transport/mobile-endpoint-supervisor.ts
@@ -73,7 +73,6 @@ export class MobileEndpointSupervisor {
isStopped: () => this.stopped,
isForeground: () => this.backgroundGrace.isForeground(),
setForeground: (foreground) => this.setForeground(foreground),
- replaceRelay: () => void this.recoverRelay(true, true),
scheduleDirectProbe: () => this.directProbe.schedule(0)
})
this.leaseRotation = new RelayLeaseRotationTimer(dependencies, () => {
diff --git a/mobile/src/transport/mobile-relay-background-lifecycle.test.ts b/mobile/src/transport/mobile-relay-background-lifecycle.test.ts
index 80c6c5be3f1..fcc2bfbe53d 100644
--- a/mobile/src/transport/mobile-relay-background-lifecycle.test.ts
+++ b/mobile/src/transport/mobile-relay-background-lifecycle.test.ts
@@ -41,7 +41,7 @@ describe('mobile Relay background lifecycle', () => {
supervisor.stop()
})
- it('probes a retained relay once when the app really returns from the background', async () => {
+ it('nudges retained relay availability with the tolerant focus policy', async () => {
const logical = new FakeLogicalClient('disconnected', 'lan')
const session = new FakeRelaySession('connected')
const deps = dependencies({
@@ -52,20 +52,19 @@ describe('mobile Relay background lifecycle', () => {
await supervisor.start()
expect(logical.getActivePath()).toBe('relay')
- // A foreground nudge (iOS inactive→active, manual reconnect) is not a background return.
- supervisor.nudge('app-resume')
- expect(session.probeAfterBackground).not.toHaveBeenCalled()
+ supervisor.nudge('focus')
+ expect(session.notifyForeground).not.toHaveBeenCalled()
supervisor.setForeground(false)
await vi.advanceTimersByTimeAsync(5_000)
supervisor.setForeground(true)
- expect(session.probeAfterBackground).toHaveBeenCalledOnce()
+ expect(session.notifyForeground).toHaveBeenCalledExactlyOnceWith('focus')
// Past the grace the relay is already released, so there is nothing to probe.
supervisor.setForeground(false)
await vi.advanceTimersByTimeAsync(30_000)
supervisor.setForeground(true)
- expect(session.probeAfterBackground).toHaveBeenCalledOnce()
+ expect(session.notifyForeground).toHaveBeenCalledExactlyOnceWith('focus')
supervisor.stop()
})
diff --git a/mobile/src/transport/mobile-relay-reconnect-controller.test.ts b/mobile/src/transport/mobile-relay-reconnect-controller.test.ts
index 02e40b60fed..4f28713240c 100644
--- a/mobile/src/transport/mobile-relay-reconnect-controller.test.ts
+++ b/mobile/src/transport/mobile-relay-reconnect-controller.test.ts
@@ -302,9 +302,9 @@ describe('relay reconnect controller', () => {
it('resets backoff after an authenticated relay remains stable', () => {
const onRetry = vi.fn()
const reconnect = createController(onRetry)
- const session: Pick<MobileRelayRpcSession, 'getFailure' | 'probeAfterBackground'> = {
+ const session: Pick<MobileRelayRpcSession, 'getFailure' | 'notifyForeground'> = {
getFailure: () => new RelayOuterError(4408),
- probeAfterBackground: () => {}
+ notifyForeground: () => {}
}
const logical = {
getActivePath: () => 'relay'
@@ -364,20 +364,20 @@ describe('relay reconnect controller', () => {
expect(relayFailureAllowsGraceRetry(new RelayOuterError(4429))).toBe(false)
})
- it('probes a retained relay once on a real background return, not on a foreground nudge', () => {
+ it('nudges a retained relay tolerantly when availability returns', () => {
const reconnect = createController(vi.fn())
- const session = { getFailure: () => null, probeAfterBackground: vi.fn() }
+ const session = { getFailure: () => null, notifyForeground: vi.fn() }
const logical = new FakeLogicalClient('connected', 'relay')
reconnect.setActiveSession(session)
reconnect.handleForeground(logical, true)
- expect(session.probeAfterBackground).not.toHaveBeenCalled()
+ expect(session.notifyForeground).not.toHaveBeenCalled()
reconnect.handleForeground(logical, false)
- expect(session.probeAfterBackground).toHaveBeenCalledOnce()
+ expect(session.notifyForeground).toHaveBeenCalledExactlyOnceWith('focus')
reconnect.clear()
reconnect.handleForeground(logical, false)
- expect(session.probeAfterBackground).toHaveBeenCalledOnce()
+ expect(session.notifyForeground).toHaveBeenCalledExactlyOnceWith('focus')
})
it('redials an attach timeout once quickly per failure streak', () => {
@@ -398,7 +398,7 @@ describe('relay reconnect controller', () => {
vi.advanceTimersByTime(1)
expect(onRetry).toHaveBeenCalledTimes(2)
- reconnect.setActiveSession({ getFailure: () => null, probeAfterBackground: () => {} })
+ reconnect.setActiveSession({ getFailure: () => null, notifyForeground: () => {} })
vi.advanceTimersByTime(30_000)
reconnect.registerFailure(attachTimeout())
vi.advanceTimersByTime(1_500)
diff --git a/mobile/src/transport/mobile-relay-reconnect-controller.ts b/mobile/src/transport/mobile-relay-reconnect-controller.ts
index 9464214fff9..1b69ea5bd5a 100644
--- a/mobile/src/transport/mobile-relay-reconnect-controller.ts
+++ b/mobile/src/transport/mobile-relay-reconnect-controller.ts
@@ -25,7 +25,7 @@ export type RelayReconnectDependencies = {
}
type RecoveryGate = 'external-signal' | 'fresh-credential'
-type RetainableRelaySession = Pick<MobileRelayRpcSession, 'getFailure' | 'probeAfterBackground'>
+type RetainableRelaySession = Pick<MobileRelayRpcSession, 'getFailure' | 'notifyForeground'>
export class RelayReconnectController {
private readonly failureCount = new RelayRecoveryFailureCount(RELAY_STABLE_CONNECTION_MS)
@@ -61,8 +61,8 @@ export class RelayReconnectController {
handleForeground(logical: StableLogicalRpcClient, wasForeground: boolean): void {
if (!wasForeground) {
- // Only a relay the background grace retained is still set here.
- this.activeSession?.probeAfterBackground()
+ // Availability also returns after iOS inactive interruptions; only app-resume proves background.
+ this.activeSession?.notifyForeground('focus')
// Resume resets gated cadence even without clearing the credential gate; reopening must not wait a whole escalated tick.
this.gateReprobeStreak = 0
if (this.recoveryGate !== 'fresh-credential') {
@@ -75,11 +75,8 @@ export class RelayReconnectController {
this.onRetry()
}
- // Probe healthy relays on focus/resume and replace on handoff without first suspending the active session.
- handleActiveNudge(
- logical: StableLogicalRpcClient,
- reason: ForegroundNudgeReason
- ): 'probe' | 'replace' | 'recover' {
+ // A network callback may describe a healthy unchanged path; the session watchdog owns probing it.
+ handleActiveNudge(logical: StableLogicalRpcClient, reason: ForegroundNudgeReason): void {
if (this.recoveryGate === 'external-signal') {
this.liftGate()
}
@@ -93,10 +90,9 @@ export class RelayReconnectController {
logical.getActivePath() === 'relay' &&
logical.getState() === 'connected'
) {
- return reason === 'network-change' ? 'replace' : 'probe'
+ return
}
this.onRetry()
- return 'recover'
}
handleStateFailure(logical: StableLogicalRpcClient, state: ConnectionState): Error | null {
diff --git a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts
index f99d064b92f..cfa2cda6168 100644
--- a/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts
+++ b/mobile/src/transport/mobile-relay-rpc-session-liveness.test.ts
@@ -21,6 +21,8 @@ vi.mock('./mobile-relay-e2ee-link', () => ({
}))
import { connectMobileRelayRpcSession } from './mobile-relay-rpc-session'
+import { RelayReconnectController } from './mobile-relay-reconnect-controller'
+import { createStableLogicalRpcClient } from './stable-logical-rpc-client'
import type { ConnectionLogSink } from './types'
const relay = {
@@ -192,7 +194,7 @@ describe('mobile relay RPC session liveness', () => {
session.notifyForeground('focus')
await vi.advanceTimersByTimeAsync(9_999)
- session.notifyForeground('app-resume')
+ session.notifyForeground('focus')
expect(fakes.sendText).toHaveBeenCalledOnce()
await vi.advanceTimersByTimeAsync(1)
session.notifyForeground('focus')
@@ -201,12 +203,16 @@ describe('mobile relay RPC session liveness', () => {
session.close()
})
- it('does not probe the old relay on a network change', async () => {
+ it('checks a relay on network hints and ends a silent session after one 4s miss', async () => {
const session = await authenticateSession()
session.notifyForeground('network-change')
- expect(fakes.sendText).not.toHaveBeenCalled()
+ expect(sentRequests().map(({ method }) => method)).toEqual(['status.get'])
+ await vi.advanceTimersByTimeAsync(3_000)
+ session.notifyForeground('network-change')
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(session.getState()).toBe('disconnected')
session.close()
})
@@ -260,7 +266,7 @@ describe('mobile relay RPC session liveness', () => {
const onLog = vi.fn<ConnectionLogSink>()
const session = await authenticateSession(onLog)
- session.probeAfterBackground()
+ session.notifyForeground('app-resume')
expect(sentRequests().map(({ method }) => method)).toEqual(['status.get'])
await vi.advanceTimersByTimeAsync(3_999)
expect(session.getState()).toBe('connected')
@@ -276,21 +282,63 @@ describe('mobile relay RPC session liveness', () => {
)
})
- it('keeps two 4s misses for an app-resume nudge without a background stay', async () => {
+ it('checks a distinct background return after a recently answered network probe', async () => {
const session = await authenticateSession()
+ session.notifyForeground('network-change')
+ const probe = sentRequests()[0]
+ if (!probe || !fakes.linkOptions) {
+ throw new Error('Expected an active relay probe')
+ }
+ fakes.linkOptions.onText(
+ JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
+ )
+ await vi.advanceTimersByTimeAsync(1_000)
session.notifyForeground('app-resume')
- await vi.advanceTimersByTimeAsync(4_000)
+ await vi.advanceTimersByTimeAsync(3_999)
expect(session.getState()).toBe('connected')
+ await vi.advanceTimersByTimeAsync(1)
+ expect(session.getState()).toBe('disconnected')
+ })
+
+ it('keeps availability returns tolerant while a proven resume bypasses recent probes', async () => {
+ const session = await authenticateSession()
+ const logical = createStableLogicalRpcClient(session, 'relay')
+ const controller = new RelayReconnectController(
+ {
+ now: Date.now,
+ randomBytes: (length) => new Uint8Array(length),
+ setTimer: (callback, delay) => setTimeout(callback, delay),
+ clearTimer: clearTimeout
+ },
+ vi.fn()
+ )
+ controller.setActiveSession(session)
+ session.notifyForeground('focus')
+ const probe = sentRequests()[0]
+ if (!probe || !fakes.linkOptions) {
+ throw new Error('Expected the focus probe')
+ }
+ fakes.linkOptions.onText(JSON.stringify({ id: probe.id, ok: true, result: {} }))
+ await vi.advanceTimersByTimeAsync(1_000)
+
+ // The lifecycle boolean also becomes false during an inactive-only iOS interruption.
+ controller.handleForeground(logical, false)
await vi.advanceTimersByTimeAsync(4_000)
+ expect(session.getState()).toBe('connected')
+ expect(fakes.sendText).toHaveBeenCalledOnce()
+ logical.notifyForeground('app-resume')
+ await vi.advanceTimersByTimeAsync(4_000)
expect(session.getState()).toBe('disconnected')
+ controller.clear()
+ logical.close()
})
it('keeps a relay that answers the background-return probe', async () => {
const session = await authenticateSession()
- session.probeAfterBackground()
+ session.notifyForeground('app-resume')
const probe = sentRequests()[0]!
fakes.linkOptions!.onText(
JSON.stringify({ id: probe.id, ok: true, result: {}, _meta: { runtimeId: 'r1' } })
diff --git a/mobile/src/transport/mobile-relay-rpc-session.ts b/mobile/src/transport/mobile-relay-rpc-session.ts
index 8a58ba66c38..c7fd8baa521 100644
--- a/mobile/src/transport/mobile-relay-rpc-session.ts
+++ b/mobile/src/transport/mobile-relay-rpc-session.ts
@@ -38,8 +38,6 @@ export type MobileRelayRpcSession = RpcClient &
getResumeExpiresAt(): number | null
getResumeConfirmation(): DeviceResumeConfirmed | null
getFailure(): Error | null
- // One decisive probe for a relay retained through a real background stay.
- probeAfterBackground(): void
}
export function connectMobileRelayRpcSession(args: {
@@ -134,9 +132,16 @@ export function connectMobileRelayRpcSession(args: {
stateListeners.add(listener)
return () => stateListeners.delete(listener)
},
- notifyForeground: (reason) => {
- if (state === 'connected' && reason !== 'network-change') {
- livenessWatchdog.probeNow(livenessIdentity)
+ notifyForeground: (reason = 'focus') => {
+ if (state === 'connected') {
+ if (reason === 'app-resume') {
+ livenessWatchdog.probeAfterBackground(livenessIdentity)
+ } else {
+ livenessWatchdog.probeNow(
+ livenessIdentity,
+ reason === 'network-change' ? DECISIVE_PROBE_TIMEOUT_MS : null
+ )
+ }
}
},
close() {
@@ -157,9 +162,6 @@ export function connectMobileRelayRpcSession(args: {
getResumeExpiresAt: () => resumeExpiresAt,
getResumeConfirmation: () => resumeConfirmation,
getFailure: () => failure,
- probeAfterBackground: () =>
- state === 'connected' &&
- livenessWatchdog.probeNow(livenessIdentity, DECISIVE_PROBE_TIMEOUT_MS),
probeLivenessNow: () => state === 'connected' && livenessWatchdog.probeCurrentDecisively()
}
const connectWaiters = new MobileRelayConnectWaiters(client)
diff --git a/mobile/src/transport/mobile-relay-runtime-failover.test.ts b/mobile/src/transport/mobile-relay-runtime-failover.test.ts
index b62cccf8432..87a86a32ecb 100644
--- a/mobile/src/transport/mobile-relay-runtime-failover.test.ts
+++ b/mobile/src/transport/mobile-relay-runtime-failover.test.ts
@@ -87,7 +87,6 @@ class FakeRelaySession extends FakeSession implements MobileRelayRpcSession {
getResumeExpiresAt = () => Date.now() + 30 * 24 * 3_600_000
getResumeConfirmation = () => null
getFailure = () => this.failure
- readonly probeAfterBackground = vi.fn()
}
class FakeLogicalClient extends FakeSession implements StableLogicalRpcClient {
diff --git a/mobile/src/transport/relay-host-reachability-verdict.test.ts b/mobile/src/transport/relay-host-reachability-verdict.test.ts
index 5a174a433d4..ccdc33cacfd 100644
--- a/mobile/src/transport/relay-host-reachability-verdict.test.ts
+++ b/mobile/src/transport/relay-host-reachability-verdict.test.ts
@@ -111,7 +111,7 @@ describe('RelayReconnectController relay host reachability', () => {
const reported: RelayHostReachability[] = []
const controller = controllerReportingTo(changesReportedTo(reported))
controller.registerFailure(hostOffline(), false)
- controller.setActiveSession({ getFailure: () => null, probeAfterBackground: () => {} })
+ controller.setActiveSession({ getFailure: () => null, notifyForeground: () => {} })
controller.registerFailure(hostOffline(), false)
controller.registerFailure(hostOffline(), false)
expect(reported).toEqual(['connecting'])
@@ -122,7 +122,7 @@ describe('RelayReconnectController relay host reachability', () => {
const controller = controllerReportingTo(changesReportedTo(reported))
controller.registerFailure(hostOffline(), false)
controller.registerFailure(hostOffline(), false)
- controller.setActiveSession({ getFailure: () => null, probeAfterBackground: () => {} })
+ controller.setActiveSession({ getFailure: () => null, notifyForeground: () => {} })
expect(reported).toEqual(['connecting', 'host-offline', 'connecting'])
})
diff --git a/mobile/src/transport/relay-host-signed-out-verdict.test.ts b/mobile/src/transport/relay-host-signed-out-verdict.test.ts
index b3d9005b706..a3791f008ec 100644
--- a/mobile/src/transport/relay-host-signed-out-verdict.test.ts
+++ b/mobile/src/transport/relay-host-signed-out-verdict.test.ts
@@ -173,7 +173,7 @@ describe('the sign-out the cell reported outranks a later plain 4404', () => {
const controller = controllerReporting(reported)
controller.assertHostReachability('signed-out')
- controller.setActiveSession({ getFailure: () => null, probeAfterBackground: () => {} })
+ controller.setActiveSession({ getFailure: () => null, notifyForeground: () => {} })
expect(reported).toEqual(['connecting', 'signed-out', 'connecting'])
})
diff --git a/mobile/src/transport/rpc-client-live-recovery.test.ts b/mobile/src/transport/rpc-client-live-recovery.test.ts
index 66a207cc0bb..151e193fe7c 100644
--- a/mobile/src/transport/rpc-client-live-recovery.test.ts
+++ b/mobile/src/transport/rpc-client-live-recovery.test.ts
@@ -151,10 +151,10 @@ describe.runIf(RUN_LIVE)('live foreground recovery (issue #5049)', () => {
}
})
- it(
- 'reaps a half-open link via the foreground probe and recovers',
+ it.each(['focus', 'app-resume', 'network-change'] as const)(
+ 'reaps a half-open link via %s and recovers',
{ timeout: 60_000 },
- async () => {
+ async (reason) => {
wss = await startServer()
client = connect(`ws://127.0.0.1:${serverPort(wss)}`, AUTH_TOKEN, serverPublicKeyB64)
const c = client
@@ -164,14 +164,14 @@ describe.runIf(RUN_LIVE)('live foreground recovery (issue #5049)', () => {
// Half-open: server keeps TCP up but stops answering, then the app
// comes back to the foreground.
blackhole = true
- c.notifyForeground()
- // Three fair probe windows tolerate transient mobile/Tailscale stalls.
+ c.notifyForeground(reason)
const detectMs = await waitFor(
'half-open detected',
32_000,
() => c.getState() !== 'connected'
)
- expect(detectMs).toBeLessThan(30_000)
+ console.log('[direct-revival-capture]', { reason, detectMs })
+ expect(detectMs).toBeLessThan(reason === 'focus' ? 30_000 : 6_000)
blackhole = false
await waitFor('recovered after link healed', 15_000, () => c.getState() === 'connected')
diff --git a/mobile/src/transport/rpc-session-liveness-integration.test.ts b/mobile/src/transport/rpc-session-liveness-integration.test.ts
index 4c58a358252..4926f64caed 100644
--- a/mobile/src/transport/rpc-session-liveness-integration.test.ts
+++ b/mobile/src/transport/rpc-session-liveness-integration.test.ts
@@ -113,6 +113,79 @@ describe('physical session liveness', () => {
}
})
+ it.each(['app-resume', 'network-change'] as const)(
+ 'ends a silent direct socket after one 4s miss on %s',
+ async (reason) => {
+ const client = connect('ws://desktop.invalid', 'token', 'server-key')
+ const socket = sockets[0]
+ if (!socket) {
+ throw new Error('Expected a direct socket')
+ }
+ socket.authenticate()
+
+ try {
+ client.notifyForeground(reason)
+ await vi.advanceTimersByTimeAsync(3_999)
+ expect(client.getState()).toBe('connected')
+ await vi.advanceTimersByTimeAsync(1)
+ expect(socket.close).toHaveBeenCalledOnce()
+ expect(client.getState()).toBe('reconnecting')
+ } finally {
+ client.close()
+ }
+ }
+ )
+
+ it('upgrades a focus probe on resume without letting repeated nudges extend the deadline', async () => {
+ const client = connect('ws://desktop.invalid', 'token', 'server-key')
+ const socket = sockets[0]
+ if (!socket) {
+ throw new Error('Expected a direct socket')
+ }
+ socket.authenticate()
+
+ try {
+ client.notifyForeground('focus')
+ await vi.advanceTimersByTimeAsync(1_000)
+ client.notifyForeground('app-resume')
+ await vi.advanceTimersByTimeAsync(3_000)
+ client.notifyForeground('network-change')
+ expect(client.getState()).toBe('connected')
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(socket.close).toHaveBeenCalledOnce()
+ expect(client.getState()).toBe('reconnecting')
+ } finally {
+ client.close()
+ }
+ })
+
+ it('checks a distinct background return after a recently answered network probe', async () => {
+ const client = connect('ws://desktop.invalid', 'token', 'server-key')
+ const socket = sockets[0]
+ if (!socket) {
+ throw new Error('Expected a direct socket')
+ }
+ socket.authenticate()
+
+ try {
+ client.notifyForeground('network-change')
+ const probe: unknown = JSON.parse(socket.sent.at(-1)?.replace(/^encrypted:/, '') ?? 'null')
+ if (!probe || typeof probe !== 'object' || !('id' in probe)) {
+ throw new Error('Expected the network probe')
+ }
+ socket.onmessage?.({
+ data: `encrypted:${JSON.stringify({ id: probe.id, ok: true, result: {} })}`
+ })
+ await vi.advanceTimersByTimeAsync(1_000)
+ client.notifyForeground('app-resume')
+ await vi.advanceTimersByTimeAsync(4_000)
+ expect(socket.close).toHaveBeenCalledOnce()
+ expect(client.getState()).toBe('reconnecting')
+ } finally {
+ client.close()
+ }
+ })
+
it('ends a silent socket after one 4s miss when a caller stopped hearing back', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
const socket = sockets[0]!
@@ -144,8 +217,7 @@ describe('physical session liveness', () => {
socket.authenticate()
try {
- // A network switch starts the three-miss probe first.
- client.notifyForeground('network-change')
+ client.notifyForeground('focus')
await vi.advanceTimersByTimeAsync(4_000)
client.probeLivenessNow?.()
await vi.advanceTimersByTimeAsync(4_000)
@@ -214,7 +286,7 @@ describe('physical session liveness', () => {
client.close()
})
- it('does not let probe replies consume the authentication retry budget', () => {
+ it('does not let probe replies consume the authentication retry budget', async () => {
const client = connect('ws://desktop.invalid', 'token', 'server-key')
const socket = sockets[0]!
socket.authenticate()
@@ -248,6 +320,7 @@ describe('physical session liveness', () => {
error: { code: 'unauthorized', message: 'Unauthorized' }
})}`
})
+ await vi.advanceTimersByTimeAsync(10_000)
}
expect(client.getState()).toBe('connected')
diff --git a/mobile/src/transport/rpc-session-liveness-watchdog.test.ts b/mobile/src/transport/rpc-session-liveness-watchdog.test.ts
index cddc394ae43..f414c7bb673 100644
--- a/mobile/src/transport/rpc-session-liveness-watchdog.test.ts
+++ b/mobile/src/transport/rpc-session-liveness-watchdog.test.ts
@@ -46,6 +46,38 @@ describe('RpcSessionLivenessWatchdog', () => {
expect(terminate).toHaveBeenCalledWith(identity)
})
+ it('coalesces recent network hints without losing or postponing a decisive probe', async () => {
+ const identity = {}
+ const sendProbe = vi.fn(() => true)
+ const terminate = vi.fn()
+ const watchdog = new RpcSessionLivenessWatchdog({
+ transport: 'direct',
+ sendProbe,
+ terminate,
+ voluntaryProbeMinIntervalMs: 10_000
+ })
+ watchdog.start(identity)
+ watchdog.probeNow(identity)
+ watchdog.noteAuthenticatedInbound(identity)
+ await vi.advanceTimersByTimeAsync(1_000)
+ watchdog.probeNow(identity, 4_000)
+ expect(sendProbe).toHaveBeenCalledTimes(2)
+ watchdog.noteAuthenticatedInbound(identity)
+
+ for (let index = 0; index < 3; index++) {
+ await vi.advanceTimersByTimeAsync(1_000)
+ watchdog.probeNow(identity, 4_000)
+ watchdog.noteAuthenticatedInbound(identity)
+ expect(sendProbe).toHaveBeenCalledTimes(2)
+ }
+ await vi.advanceTimersByTimeAsync(999)
+ expect(sendProbe).toHaveBeenCalledTimes(2)
+ await vi.advanceTimersByTimeAsync(1)
+ expect(sendProbe).toHaveBeenCalledTimes(3)
+ await vi.advanceTimersByTimeAsync(4_000)
+ expect(terminate).toHaveBeenCalledExactlyOnceWith(identity)
+ })
+
it('reports causal evidence before terminating a stale session', async () => {
const onTimeout = vi.fn()
const terminate = vi.fn()
diff --git a/mobile/src/transport/rpc-session-liveness-watchdog.ts b/mobile/src/transport/rpc-session-liveness-watchdog.ts
index f8c2b4f2913..07d739235db 100644
--- a/mobile/src/transport/rpc-session-liveness-watchdog.ts
+++ b/mobile/src/transport/rpc-session-liveness-watchdog.ts
@@ -41,6 +41,7 @@ export class RpcSessionLivenessWatchdog {
private missedProbes = 0
private lastInboundAt = 0
private lastVoluntaryProbeAt: number | null = null
+ private lastDecisiveProbeAt: number | null = null
private readonly idleProbeMs: number | null
private readonly probeTimeoutMs: number
private readonly missedProbeLimit: number
@@ -66,6 +67,7 @@ export class RpcSessionLivenessWatchdog {
this.missedProbes = 0
this.lastInboundAt = this.now()
this.lastVoluntaryProbeAt = null
+ this.lastDecisiveProbeAt = null
this.armIdle(identity)
}
@@ -95,17 +97,50 @@ export class RpcSessionLivenessWatchdog {
// A decisive probe ends the session on its first miss when suspension may have killed the link.
probeNow(identity: RpcSessionIdentity, decisiveTimeoutMs: number | null = null): void {
- if (this.identity !== identity || this.probing) {
+ this.requestProbe(identity, decisiveTimeoutMs)
+ }
+
+ // A distinct background stay invalidates recent health evidence, but not an already running deadline.
+ probeAfterBackground(identity: RpcSessionIdentity): void {
+ this.requestProbe(identity, DECISIVE_PROBE_TIMEOUT_MS, true)
+ }
+
+ private requestProbe(
+ identity: RpcSessionIdentity,
+ decisiveTimeoutMs: number | null,
+ afterBackground = false
+ ): void {
+ const decisive = decisiveTimeoutMs !== null
+ if (this.identity !== identity || (this.probing && (!decisive || this.probingDecisively))) {
return
}
const now = this.now()
+ const lastProbeAt = decisive ? this.lastDecisiveProbeAt : this.lastVoluntaryProbeAt
+ const minIntervalMs = decisive
+ ? Math.min(this.voluntaryProbeMinIntervalMs, decisiveTimeoutMs)
+ : this.voluntaryProbeMinIntervalMs
if (
- this.lastVoluntaryProbeAt !== null &&
- now - this.lastVoluntaryProbeAt < this.voluntaryProbeMinIntervalMs
+ !afterBackground &&
+ !this.probing &&
+ lastProbeAt !== null &&
+ now - lastProbeAt < minIntervalMs
) {
+ if (decisive) {
+ this.clearActiveTimer()
+ this.timer = this.setTimer(
+ () => {
+ this.timer = null
+ this.requestProbe(identity, decisiveTimeoutMs)
+ },
+ minIntervalMs - (now - lastProbeAt)
+ )
+ }
return
}
this.lastVoluntaryProbeAt = now
+ if (decisive) {
+ this.lastDecisiveProbeAt = now
+ }
this.startProbe(identity, decisiveTimeoutMs)
}
@@ -132,6 +167,7 @@ export class RpcSessionLivenessWatchdog {
this.missedProbes = 0
this.lastInboundAt = 0
this.lastVoluntaryProbeAt = null
+ this.lastDecisiveProbeAt = null
}
private armIdle(identity: RpcSessionIdentity, delayMs = this.idleProbeMs): void {