diff --git a/mobile/src/transport/rpc-client.test.ts b/mobile/src/transport/rpc-client.test.ts index 977b6660c..03d7515b6 100644 --- a/mobile/src/transport/rpc-client.test.ts +++ b/mobile/src/transport/rpc-client.test.ts @@ -11,7 +11,7 @@ vi.mock('./e2ee', () => ({ publicKeyFromBase64: () => new Uint8Array(32), publicKeyToBase64: () => 'client-public-key', encrypt: (plaintext: string) => `encrypted:${plaintext}`, - decrypt: (raw: string) => raw.replace(/^encrypted:/, ''), + decrypt: (raw: string) => (raw === 'undecryptable' ? null : raw.replace(/^encrypted:/, '')), decryptBytes: (bytes: Uint8Array) => bytes })) @@ -260,11 +260,14 @@ describe('mobile rpc-client connection timeout', () => { })}` ) + client.notifyForeground() socket.receive(encodeBrowserFrame()) await Promise.resolve() await Promise.resolve() + await vi.advanceTimersByTimeAsync(8_000) expect(frames).toHaveLength(1) + expect(socket.close).not.toHaveBeenCalled() expect(frames[0]).toMatchObject({ seq: 7, format: 'jpeg', @@ -608,6 +611,12 @@ describe('mobile rpc-client connection timeout', () => { socket.receive(JSON.stringify({ type: 'e2ee_ready' })) socket.receive('encrypted:{"type":"e2ee_authenticated"}') } + function connectAuthenticated() { + const client = connect('ws://desktop.invalid', 'token', 'server-key') + const socket = mockSockets[0]! + openAndAuthenticate(socket) + return { client, socket } + } it('repro: a parked reconnect loop never retries on its own', async () => { const client = connect('ws://desktop.invalid', 'token', 'server-key') @@ -685,9 +694,7 @@ describe('mobile rpc-client connection timeout', () => { }) it('keeps a healthy connection when the foreground probe is answered', async () => { - const client = connect('ws://desktop.invalid', 'token', 'server-key') - const socket = mockSockets[0]! - openAndAuthenticate(socket) + const { client, socket } = connectAuthenticated() client.notifyForeground() const probe = sentRequest(socket, 'status.get') @@ -700,9 +707,115 @@ describe('mobile rpc-client connection timeout', () => { client.close() }) + it('keeps a healthy connection when another response arrives while the probe is pending', async () => { + const { client, socket } = connectAuthenticated() + + client.notifyForeground() + expect(sentRequests(socket, 'status.get')).toHaveLength(1) + + const poll = client.sendRequest('speech.models.list') + await Promise.resolve() + const pollRequest = sentRequest(socket, 'speech.models.list') + socket.receive( + `encrypted:${JSON.stringify({ + id: pollRequest.id, + ok: true, + result: { enabled: false, selectedModelId: '', dictationMode: 'toggle', models: [] } + })}` + ) + await expect(poll).resolves.toMatchObject({ ok: true }) + + await vi.advanceTimersByTimeAsync(8_000) + expect(socket.close).not.toHaveBeenCalled() + expect(client.getState()).toBe('connected') + + await vi.advanceTimersByTimeAsync(12_000) + expect(sentRequests(socket, 'status.get')).toHaveLength(2) + await vi.advanceTimersByTimeAsync(7_999) + expect(socket.close).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(1) + expect(socket.close).toHaveBeenCalled() + expect(client.getState()).toBe('reconnecting') + + client.close() + }) + + it('keeps a healthy connection when a non-auth RPC failure arrives while the probe is pending', async () => { + const { client, socket } = connectAuthenticated() + + client.notifyForeground() + expect(sentRequests(socket, 'status.get')).toHaveLength(1) + + const poll = client.sendRequest('speech.models.list') + await Promise.resolve() + const pollRequest = sentRequest(socket, 'speech.models.list') + socket.receive( + `encrypted:${JSON.stringify({ + id: pollRequest.id, + ok: false, + error: { code: 'download_failed', message: 'model download failed' } + })}` + ) + await expect(poll).resolves.toMatchObject({ + ok: false, + error: { code: 'download_failed' } + }) + + await vi.advanceTimersByTimeAsync(8_000) + expect(socket.close).not.toHaveBeenCalled() + expect(client.getState()).toBe('connected') + + client.close() + }) + + it('keeps a healthy connection when a binary stream frame arrives while the probe is pending', async () => { + const { client, socket } = connectAuthenticated() + const events: unknown[] = [] + + client.subscribe('terminal.subscribe', { terminal: 'term-1' }, (event) => { + events.push(event) + }) + const subscribe = sentRequest(socket, 'terminal.subscribe') + socket.receive( + `encrypted:${JSON.stringify({ + id: subscribe.id, + ok: true, + streaming: true, + result: { type: 'subscribed', streamId: 42 } + })}` + ) + + client.notifyForeground() + socket.receive(encodeTerminalOutput(42, 'still alive')) + await Promise.resolve() + await Promise.resolve() + await vi.advanceTimersByTimeAsync(8_000) + + expect(events).toContainEqual({ type: 'data', streamId: 42, chunk: 'still alive' }) + expect(socket.close).not.toHaveBeenCalled() + expect(client.getState()).toBe('connected') + + client.close() + }) + + it('does not count malformed or undecryptable inbound payloads as probe activity', async () => { + const { client, socket } = connectAuthenticated() + + client.notifyForeground() + socket.receive('undecryptable') + socket.receive('encrypted:{"unexpected":true}') + socket.receive('encrypted:{"id":"rpc-incomplete","ok":true}') + socket.receive(new Uint8Array([0xff, 0x00, 0x01])) + + await vi.advanceTimersByTimeAsync(8_000) + expect(socket.close).toHaveBeenCalled() + expect(client.getState()).toBe('reconnecting') + + client.close() + }) + it('is a no-op after the client is closed', () => { - const client = connect('ws://desktop.invalid', 'token', 'server-key') - openAndAuthenticate(mockSockets[0]!) + const { client } = connectAuthenticated() client.close() const socketsBefore = mockSockets.length @@ -722,6 +835,9 @@ describe('mobile rpc-client connection timeout', () => { socket.receive(JSON.stringify({ type: 'e2ee_ready' })) socket.receive('encrypted:{"type":"e2ee_authenticated"}') } + function unauthorizedResponsePayload(id: string): string { + return `encrypted:${JSON.stringify({ id, ok: false, error: { code: 'unauthorized', message: 'Unauthorized' } })}` + } it('retries the handshake on a transient e2ee_error instead of latching auth-failed', async () => { const client = connect('ws://desktop.invalid', 'token', 'server-key') @@ -784,9 +900,7 @@ describe('mobile rpc-client connection timeout', () => { // sendRequest awaits waitForConnected before sending — let it flush. await Promise.resolve() const id = sentRequest(live, 'status.get').id - live.receive( - `encrypted:${JSON.stringify({ id, ok: false, error: { code: 'unauthorized' } })}` - ) + live.receive(unauthorizedResponsePayload(id)) await request expect(client.getState()).toBe('reconnecting') @@ -811,9 +925,7 @@ describe('mobile rpc-client connection timeout', () => { const request = client.sendRequest('status.get').catch(() => undefined) await Promise.resolve() const id = sentRequest(first, 'status.get').id - first.receive( - `encrypted:${JSON.stringify({ id, ok: false, error: { code: 'unauthorized' } })}` - ) + first.receive(unauthorizedResponsePayload(id)) await request expect(client.getState()).toBe('reconnecting') diff --git a/mobile/src/transport/rpc-client.ts b/mobile/src/transport/rpc-client.ts index 8816e95a4..037775886 100644 --- a/mobile/src/transport/rpc-client.ts +++ b/mobile/src/transport/rpc-client.ts @@ -29,6 +29,8 @@ import { updateTerminalSubscriptionViewport as updateCachedTerminalSubscriptionViewport } from './rpc-client-terminal-subscription' import { describeSocketEvent } from './socket-event-debug' +import { isRpcResponse } from './rpc-response-shape' +import { websocketPayloadToUint8 } from './websocket-payload-bytes' type PendingRequest = { resolve: (response: RpcResponse) => void @@ -135,17 +137,10 @@ const HANDSHAKE_TIMEOUT_MS = 5_000 // constants, but the protocol value for CONNECTING is stable across runtimes. const WEBSOCKET_CONNECTING_STATE = 0 -// Why: app-level liveness probe. The server runs its own ping/pong sweep -// at 15s, but RN's WebSocket runtime auto-pongs at the native layer -// without surfacing anything to JS — so the mobile side can't *see* that -// the server thinks the link is fine. To detect a half-open socket from -// the mobile direction (e.g. server crashed, phone moved between wifi -// and cellular without TCP RST) we periodically round-trip a tiny RPC. -// If two consecutive probes time out we force-close the WS, which fires -// the existing reconnect path. 20s cadence + the 30s request timeout = -// worst-case ~50s before mobile decides the link is dead and kicks -// reconnect, which is still inside the user's perceived "responsive" -// window and well below iOS's typical background-disconnect window. +// Why: RN auto-pongs WebSocket pings natively, so JS needs an app-level +// liveness probe to detect half-open sockets. Any inbound app traffic after +// a probe starts proves the link is alive; otherwise an unanswered probe +// force-closes the socket so the reconnect path can recover. const ACTIVITY_PROBE_INTERVAL_MS = 20_000 export type ConnectOptions = { @@ -197,15 +192,10 @@ export function connect( // every 'connected'. let authRejectionCount = 0 let lastConnectedAt: number | null = null - // Why: diagnostic — when the rpc-client gets stuck in a state where every - // openConnection fails with code 1006 and only a force-quit recovers, we - // need to see whether (a) the new attempts even differ from the old ones, - // (b) anything is happening at the OS / RN-bridge layer between attempts, - // and (c) what the timing pattern is (instant 1006 = port closed / route - // dead, slow 1006 = packet drop / timeout). These three timestamps + the - // ws-construction counter are the cheapest visibility into RN/OkHttp - // process-state poisoning hypotheses. + // Why: cheap diagnostics for RN/OkHttp process-state poisoning: do retry + // attempts differ, is anything inbound, and are closes instant or slow? let lastInboundAt: number | null = null + let inboundSequence = 0 let lastWsClosedAt: number | null = null let wsConstructionCounter = 0 let currentWsOpenedAt: number | null = null @@ -443,8 +433,6 @@ export function connect( } async function handleSocketMessage(rawData: unknown) { - // Why: track last-inbound for the openConnection diagnostic. Server - // pongs and stream events both bump this — anything from the wire. lastInboundAt = Date.now() const raw = typeof rawData === 'string' ? rawData : null @@ -552,12 +540,16 @@ export function connect( return } - let response: RpcResponse + let response: unknown try { response = JSON.parse(plaintext) } catch { return } + if (!isRpcResponse(response)) { + return + } + recordValidatedInboundTraffic() // Why: a mid-session unauthorized may be a transient glitch, not a dead // pairing (issue #5200). handleAuthRejection retries the handshake a few @@ -827,30 +819,21 @@ export function connect( // state, sends a tiny status.get, and force-closes the WS if the probe // fails (which the existing onclose path then turns into a reconnect). function runActivityProbe() { - // Why: only probe while the channel is actually in 'connected'. The - // sendRequest path itself waits for connected, but a probe scheduled - // during a reconnect would just stack up timeouts and confuse logs. if (state !== 'connected' || !ws) { return } const probeWs = ws - // Why: short timeout (8s) — server's heartbeat is 15s, so if we - // don't see *anything* back within 8s the link is almost certainly - // half-open. Using REQUEST_TIMEOUT_MS (30s) here would make the - // user wait nearly a minute before reconnect kicks in. const id = nextId() - const probeStart = Date.now() + const probeInboundSequence = inboundSequence let timedOut = false const timeout = setTimeout(() => { timedOut = true pending.delete(id) - console.log('[net] activity-probe TIMEOUT — forcing reconnect', { - waitedMs: Date.now() - probeStart, - state - }) - // Why: only force-close if this is still the same socket the - // probe was sent on; a normal close that already swapped `ws` - // shouldn't trigger a redundant terminate. + 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() } @@ -948,9 +931,14 @@ export function connect( } } - function handleBinaryFrame(bytes: Uint8Array) { + function recordValidatedInboundTraffic(): void { + inboundSequence++ + } + + function handleBinaryFrame(bytes: Uint8Array): void { const browserFrame = decodeBrowserScreencastFrame(bytes) if (browserFrame) { + recordValidatedInboundTraffic() handleBrowserBinaryFrame(browserFrame) return } @@ -968,16 +956,18 @@ export function connect( stream.onBinaryFrame?.(frame) } - function handleTerminalBinaryFrame(bytes: Uint8Array) { + function handleTerminalBinaryFrame(bytes: Uint8Array): void { const frame = decodeTerminalStreamFrame(bytes) if (!frame) { return } const listener = terminalStreamListeners.get(frame.streamId) if (!listener) { + recordValidatedInboundTraffic() return } if (frame.opcode === TerminalStreamOpcode.Output) { + recordValidatedInboundTraffic() listener({ type: 'data', streamId: frame.streamId, @@ -990,10 +980,12 @@ export function connect( if (!meta) { return } + recordValidatedInboundTraffic() terminalSnapshots.set(frame.streamId, { streamId: frame.streamId, meta, chunks: [] }) return } if (frame.opcode === TerminalStreamOpcode.SnapshotChunk) { + recordValidatedInboundTraffic() const snapshot = terminalSnapshots.get(frame.streamId) if (!snapshot) { return @@ -1002,6 +994,7 @@ export function connect( return } if (frame.opcode === TerminalStreamOpcode.SnapshotEnd) { + recordValidatedInboundTraffic() const snapshot = terminalSnapshots.get(frame.streamId) if (!snapshot) { return @@ -1021,6 +1014,7 @@ export function connect( if (!meta) { return } + recordValidatedInboundTraffic() listener({ ...meta, type: 'resized', @@ -1029,6 +1023,7 @@ export function connect( return } if (frame.opcode === TerminalStreamOpcode.Error) { + recordValidatedInboundTraffic() listener({ type: 'error', streamId: frame.streamId, @@ -1302,27 +1297,3 @@ function isBrowserScreencastReadyResult( typeof (value as { subscriptionId?: unknown }).subscriptionId === 'string' ) } - -async function websocketPayloadToUint8(value: unknown): Promise { - if (value instanceof Uint8Array) { - return value - } - if (value instanceof ArrayBuffer) { - return new Uint8Array(value) - } - if (value && typeof value === 'object' && 'arrayBuffer' in value) { - const blob = value as { arrayBuffer: () => Promise } - return new Uint8Array(await blob.arrayBuffer()) - } - if (typeof FileReader !== 'undefined' && value instanceof Blob) { - return new Promise((resolve) => { - const reader = new FileReader() - reader.onload = () => { - resolve(reader.result instanceof ArrayBuffer ? new Uint8Array(reader.result) : null) - } - reader.onerror = () => resolve(null) - reader.readAsArrayBuffer(value) - }) - } - return null -} diff --git a/mobile/src/transport/rpc-response-shape.test.ts b/mobile/src/transport/rpc-response-shape.test.ts new file mode 100644 index 000000000..52ae58e62 --- /dev/null +++ b/mobile/src/transport/rpc-response-shape.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import { isRpcResponse } from './rpc-response-shape' + +describe('isRpcResponse', () => { + it('requires success responses to include a result field', () => { + expect(isRpcResponse({ id: 'rpc-1', ok: true, result: null })).toBe(true) + expect(isRpcResponse({ id: 'rpc-1', ok: true })).toBe(false) + }) + + it('requires failure responses to include code and message', () => { + expect( + isRpcResponse({ + id: 'rpc-1', + ok: false, + error: { code: 'failed', message: 'Nope' } + }) + ).toBe(true) + expect(isRpcResponse({ id: 'rpc-1', ok: false, error: { code: 'failed' } })).toBe(false) + }) +}) diff --git a/mobile/src/transport/rpc-response-shape.ts b/mobile/src/transport/rpc-response-shape.ts new file mode 100644 index 000000000..54903f5f3 --- /dev/null +++ b/mobile/src/transport/rpc-response-shape.ts @@ -0,0 +1,24 @@ +import type { RpcResponse } from './types' + +export function isRpcResponse(value: unknown): value is RpcResponse { + if (!value || typeof value !== 'object') { + return false + } + const response = value as { + id?: unknown + ok?: unknown + error?: { code?: unknown; message?: unknown } + } + if (typeof response.id !== 'string') { + return false + } + if (response.ok === true) { + return Object.prototype.hasOwnProperty.call(response, 'result') + } + return ( + response.ok === false && + !!response.error && + typeof response.error.code === 'string' && + typeof response.error.message === 'string' + ) +} diff --git a/mobile/src/transport/websocket-payload-bytes.test.ts b/mobile/src/transport/websocket-payload-bytes.test.ts new file mode 100644 index 000000000..4b501957e --- /dev/null +++ b/mobile/src/transport/websocket-payload-bytes.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it } from 'vitest' +import { websocketPayloadToUint8 } from './websocket-payload-bytes' + +describe('websocketPayloadToUint8', () => { + it('returns null when a blob-like payload rejects arrayBuffer conversion', async () => { + await expect( + websocketPayloadToUint8({ + arrayBuffer: async () => { + throw new Error('conversion failed') + } + }) + ).resolves.toBeNull() + }) +}) diff --git a/mobile/src/transport/websocket-payload-bytes.ts b/mobile/src/transport/websocket-payload-bytes.ts new file mode 100644 index 000000000..1cd8ac5cd --- /dev/null +++ b/mobile/src/transport/websocket-payload-bytes.ts @@ -0,0 +1,27 @@ +export async function websocketPayloadToUint8(value: unknown): Promise { + if (value instanceof Uint8Array) { + return value + } + if (value instanceof ArrayBuffer) { + return new Uint8Array(value) + } + if (value && typeof value === 'object' && 'arrayBuffer' in value) { + const blob = value as { arrayBuffer: () => Promise } + try { + return new Uint8Array(await blob.arrayBuffer()) + } catch { + return null + } + } + if (typeof FileReader !== 'undefined' && value instanceof Blob) { + return new Promise((resolve) => { + const reader = new FileReader() + reader.onload = () => { + resolve(reader.result instanceof ArrayBuffer ? new Uint8Array(reader.result) : null) + } + reader.onerror = () => resolve(null) + reader.readAsArrayBuffer(value) + }) + } + return null +}