Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
203 changes: 203 additions & 0 deletions src/renderer/src/web/web-runtime-client-heartbeat.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
import { describe, expect, it, vi, afterEach, beforeEach } from 'vitest'
import { WebRuntimeClient } from './web-runtime-client'

// Why: a half-open browser WebSocket stays readyState===OPEN with no
// onclose/onerror, so the client must actively detect server silence and force
// a reconnect. These tests drive the private heartbeat with controllable time +
// visibility (the real timers/visibility are faked away).

const fakeSockets: FakeWebSocket[] = []

class FakeWebSocket {
static readonly CONNECTING = 0
static readonly OPEN = 1
static readonly CLOSED = 3
readyState = FakeWebSocket.CONNECTING
binaryType = 'arraybuffer'
onopen: (() => void) | null = null
onmessage: ((event: { data: unknown }) => void) | null = null
onclose: (() => void) | null = null
onerror: (() => void) | null = null
close = vi.fn(() => {
this.readyState = FakeWebSocket.CLOSED
})
send = vi.fn()
constructor(readonly _url: string) {
fakeSockets.push(this)
}
}

type HeartbeatInternals = {
ws: FakeWebSocket | null
state: string
sharedKey: Uint8Array | null
lastInboundFrameAt: number
lastHeartbeatTickAt: number
heartbeatProbeSentAt: number | null
runHeartbeatTick: () => void
now: () => number
isDocumentVisible: () => boolean
}

function makeConnectedClient(): {
client: WebRuntimeClient
internals: HeartbeatInternals
socket: FakeWebSocket
setNow: (ms: number) => void
setVisible: (visible: boolean) => void
} {
let nowMs = 1_000
let visible = true
const client = new WebRuntimeClient({
v: 2,
endpoint: 'ws://127.0.0.1:6768',
deviceToken: 'token',
publicKeyB64: Buffer.alloc(32).toString('base64')
})
const internals = client as unknown as HeartbeatInternals
// Override the protected time/visibility seams deterministically.
internals.now = () => nowMs
internals.isDocumentVisible = () => visible
const socket = fakeSockets[0]!
socket.readyState = FakeWebSocket.OPEN
internals.ws = socket
internals.sharedKey = new Uint8Array(32)
internals.state = 'connected'
internals.lastInboundFrameAt = nowMs
internals.lastHeartbeatTickAt = nowMs
internals.heartbeatProbeSentAt = null
return {
client,
internals,
socket,
setNow: (ms) => {
nowMs = ms
},
setVisible: (next) => {
visible = next
}
}
}

describe('WebRuntimeClient liveness heartbeat', () => {
beforeEach(() => {
fakeSockets.length = 0
vi.stubGlobal('window', {
setTimeout,
clearTimeout,
setInterval,
clearInterval,
atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
btoa: (value: string) => Buffer.from(value, 'binary').toString('base64')
})
vi.stubGlobal('WebSocket', FakeWebSocket)
})

afterEach(() => {
vi.unstubAllGlobals()
})

// Advance time AND record a tick boundary so the suspended-loop detector
// (sinceLastTick) sees a normal cadence, mirroring back-to-back real ticks.
function advanceOneTick(internals: HeartbeatInternals, setNow: (ms: number) => void): void {
const next = internals.now() + 10_000
setNow(next)
}

it('does nothing while the socket keeps receiving frames', () => {
const { internals, socket } = makeConnectedClient()
// Just under the idle threshold → no probe, no close.
internals.lastInboundFrameAt = internals.now() - 24_000
internals.lastHeartbeatTickAt = internals.now() - 10_000
internals.runHeartbeatTick()
expect(socket.send).not.toHaveBeenCalled()
expect(socket.close).not.toHaveBeenCalled()
})

it('sends a status.get probe after the idle threshold of silence', () => {
const { internals, socket, setNow } = makeConnectedClient()
// 30s since last inbound frame, but the tick loop ran on normal cadence
// (last tick ~10s ago), so this is real silence > HEARTBEAT_IDLE_MS (25s).
internals.lastInboundFrameAt = 1_000
setNow(31_000)
internals.lastHeartbeatTickAt = 31_000 - 10_000
internals.runHeartbeatTick()
expect(socket.send).toHaveBeenCalledTimes(1)
expect(socket.close).not.toHaveBeenCalled()
expect(internals.heartbeatProbeSentAt).toBe(31_000)
})

it('closes the socket only after a SENT probe goes unanswered (not raw silence)', () => {
const { internals, socket, setNow } = makeConnectedClient()
// Tick 1: 30s silence on normal cadence → probe sent.
internals.lastInboundFrameAt = 1_000
setNow(31_000)
internals.lastHeartbeatTickAt = 31_000 - 10_000
internals.runHeartbeatTick()
expect(socket.send).toHaveBeenCalledTimes(1)
expect(socket.close).not.toHaveBeenCalled()
// Tick 2 (normal cadence later): probe still unanswered past the grace
// window (20s) → close + reconnect.
setNow(31_000 + 21_000)
internals.lastHeartbeatTickAt = 31_000 + 21_000 - 10_000
internals.runHeartbeatTick()
expect(socket.close).toHaveBeenCalledTimes(1)
expect(internals.ws).toBeNull()
})

it('does NOT close on resume after a long hidden gap — re-probes instead (regression)', () => {
const { internals, socket, setNow, setVisible } = makeConnectedClient()
// Tab goes hidden for 10 minutes; the tick loop is suspended meanwhile.
setVisible(false)
internals.lastInboundFrameAt = 1_000
internals.lastHeartbeatTickAt = 1_000
setNow(1_000 + 600_000)
// First tick after resume: huge sinceLastTick re-baselines, no false close.
setVisible(true)
internals.runHeartbeatTick()
expect(socket.close).not.toHaveBeenCalled()
// It re-baselined liveness, so it does not immediately probe either.
expect(socket.send).not.toHaveBeenCalled()
expect(internals.heartbeatProbeSentAt).toBeNull()
expect(internals.lastInboundFrameAt).toBe(1_000 + 600_000)
})

it('skips probing while the tab is hidden (battery)', () => {
const { internals, socket, setNow, setVisible } = makeConnectedClient()
setVisible(false)
internals.lastInboundFrameAt = 1_000
internals.lastHeartbeatTickAt = 1_000
setNow(1_000 + 30_000)
internals.runHeartbeatTick()
expect(socket.send).not.toHaveBeenCalled()
expect(socket.close).not.toHaveBeenCalled()
})

it('does not probe when not in the connected state', () => {
const { internals, socket, setNow } = makeConnectedClient()
internals.state = 'handshaking'
internals.lastInboundFrameAt = 1_000
setNow(1_000 + 30_000)
internals.lastHeartbeatTickAt = 1_000 + 30_000 - 10_000
internals.runHeartbeatTick()
expect(socket.send).not.toHaveBeenCalled()
expect(socket.close).not.toHaveBeenCalled()
})

it('resets liveness when an inbound frame arrives between ticks', () => {
const { internals, socket, setNow } = makeConnectedClient()
internals.lastInboundFrameAt = 1_000
setNow(31_000)
internals.lastHeartbeatTickAt = 31_000 - 10_000
internals.runHeartbeatTick()
expect(socket.send).toHaveBeenCalledTimes(1)
// A reply lands: onmessage stamps lastInboundFrameAt and clears the probe.
internals.lastInboundFrameAt = internals.now()
internals.heartbeatProbeSentAt = null
Comment on lines +194 to +196

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Exercise the real onmessage path here.

These lines manually reset heartbeat state, so the test never verifies the upstream contract in src/renderer/src/web/web-runtime-client.ts:393-405 that inbound frames clear heartbeatProbeSentAt and refresh lastInboundFrameAt. If that wiring regresses, this test still passes. Stub handleSocketMessage and invoke socket.onmessage?.(...) instead.

advanceOneTick(internals, setNow) // 10s later → quiet again, well under idle
internals.lastHeartbeatTickAt = internals.now() - 10_000
internals.runHeartbeatTick()
expect(socket.send).toHaveBeenCalledTimes(1)
expect(socket.close).not.toHaveBeenCalled()
})
})
4 changes: 4 additions & 0 deletions src/renderer/src/web/web-runtime-client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ describe('WebRuntimeClient', () => {
vi.stubGlobal('window', {
setTimeout,
clearTimeout,
// Why: the connected-state liveness heartbeat arms a window.setInterval, so
// the stub must provide interval timers once a client reaches 'connected'.
setInterval,
clearInterval,
atob: (value: string) => Buffer.from(value, 'base64').toString('binary'),
btoa: (value: string) => Buffer.from(value, 'binary').toString('base64')
})
Expand Down
105 changes: 105 additions & 0 deletions src/renderer/src/web/web-runtime-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ const HANDSHAKE_TIMEOUT_MS = 10_000
const FILE_WATCH_READY_CLEANUP_TIMEOUT_MS = 5_000
const RECONNECT_DELAYS_MS = [500, 1000, 2000, 4000, 8000, 15_000]
const SHARED_CONNECTION_SUBSCRIPTION_METHODS = new Set(['files.watch'])
// Why: the browser WebSocket API hides protocol pings/pongs, so a half-open
// connection (mobile NAT idle timeout, server crash, wifi→cellular handoff)
// leaves readyState===OPEN with no onclose/onerror — the UI silently freezes on
// stale data and never reconnects. Poll connection liveness while the tab is
// visible: after HEARTBEAT_IDLE_MS of silence send a cheap status.get probe
// (any inbound frame proves liveness), and only if that probe stays unanswered
// for HEARTBEAT_PROBE_GRACE_MS close the socket to drive the reconnect path.
// Closing is gated on an unanswered PROBE, never on raw accumulated silence, so
// a backgrounded/frozen tab can never be mistaken for a dead socket on resume.
const HEARTBEAT_INTERVAL_MS = 10_000
const HEARTBEAT_IDLE_MS = 25_000
const HEARTBEAT_PROBE_GRACE_MS = 20_000

export class WebRuntimeClient {
private ws: WebSocket | null = null
Expand All @@ -74,6 +86,16 @@ export class WebRuntimeClient {
private connectTimer: number | null = null
private handshakeTimer: number | null = null
private reconnectTimer: number | null = null
private heartbeatTimer: number | null = null
private lastInboundFrameAt = 0
// Why: timestamp of an outstanding liveness probe (null = none in flight).
// The dead-close fires only when a SENT probe goes unanswered, never on raw
// silence, so a hidden/frozen tab resuming after a long gap re-probes first.
private heartbeatProbeSentAt: number | null = null
// Why: detect a suspended tick loop (backgrounded/frozen tab). If a tick lands
// far later than scheduled, treat the gap as "no evidence", reset the clocks,
// and re-probe instead of closing.
private lastHeartbeatTickAt = 0
private readonly pending = new Map<string, PendingRequest>()
private readonly subscriptions = new Map<string, RuntimeSubscription>()
private readonly childClients = new Set<WebRuntimeClient>()
Expand Down Expand Up @@ -374,6 +396,11 @@ export class WebRuntimeClient {
if (this.ws !== ws) {
return
}
// Why: any inbound frame (RPC reply, subscription push, keepalive, probe
// echo) proves the socket is alive — reset the liveness watchdog and clear
// any outstanding probe.
this.lastInboundFrameAt = this.now()
this.heartbeatProbeSentAt = null
void this.handleSocketMessage(event.data, ws)
}

Expand Down Expand Up @@ -551,6 +578,7 @@ export class WebRuntimeClient {
this.sharedKey = null
this.clearConnectTimer()
this.clearHandshakeTimer()
this.clearHeartbeatTimer()
this.rejectAllPending('Remote Orca runtime connection interrupted.')
this.notifySubscriptionsClosed()
if (this.intentionallyClosed || this.state === 'auth-failed') {
Expand All @@ -577,6 +605,7 @@ export class WebRuntimeClient {
private setState(next: WebRuntimeConnectionState): void {
this.state = next
if (next === 'connected') {
this.startHeartbeat()
for (const waiter of this.waiters.splice(0)) {
waiter.resolve()
}
Expand Down Expand Up @@ -624,6 +653,7 @@ export class WebRuntimeClient {
private clearTimers(): void {
this.clearConnectTimer()
this.clearHandshakeTimer()
this.clearHeartbeatTimer()
if (this.reconnectTimer) {
window.clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
Expand All @@ -643,6 +673,81 @@ export class WebRuntimeClient {
this.handshakeTimer = null
}
}

// Why: overridable seams so a test can drive deterministic time + visibility
// without faking globals across the whole crypto/transport fixture.
protected now(): number {
return Date.now()
}

protected isDocumentVisible(): boolean {
return typeof document === 'undefined' || document.visibilityState !== 'hidden'
}

private startHeartbeat(): void {
this.clearHeartbeatTimer()
const now = this.now()
this.lastInboundFrameAt = now
this.lastHeartbeatTickAt = now
this.heartbeatProbeSentAt = null
this.heartbeatTimer = window.setInterval(() => this.runHeartbeatTick(), HEARTBEAT_INTERVAL_MS)
}

private clearHeartbeatTimer(): void {
if (this.heartbeatTimer) {
window.clearInterval(this.heartbeatTimer)
this.heartbeatTimer = null
}
this.heartbeatProbeSentAt = null
}

private runHeartbeatTick(): void {
const now = this.now()
// Why: if this tick lands far later than scheduled, the loop was suspended
// (backgrounded/frozen tab) — that gap is NOT evidence the socket died, so
// re-baseline the liveness clocks and drop any stale probe before judging.
const sinceLastTick = now - this.lastHeartbeatTickAt
this.lastHeartbeatTickAt = now
if (sinceLastTick >= HEARTBEAT_INTERVAL_MS * 2) {
this.lastInboundFrameAt = now
this.heartbeatProbeSentAt = null
}
// Why: a backgrounded tab shows no live data and the user can't see
// staleness, so don't spend battery probing; the next visible tick re-checks.
if (!this.isDocumentVisible()) {
return
}
const ws = this.ws
if (!ws || ws.readyState !== WebSocket.OPEN || this.state !== 'connected') {
return
}
// Why: close ONLY when a probe we actually sent has gone unanswered past the
// grace window — never on raw accumulated silence. This guarantees at least
// one real round-trip attempt before declaring the socket half-open.
if (
this.heartbeatProbeSentAt !== null &&
now - this.heartbeatProbeSentAt >= HEARTBEAT_PROBE_GRACE_MS
) {
ws.close()
this.handleSocketClosed(ws)
return
}
if (this.heartbeatProbeSentAt === null && now - this.lastInboundFrameAt >= HEARTBEAT_IDLE_MS) {
// Why: a fire-and-forget liveness probe. The reply (or any other frame)
// resets lastInboundFrameAt and clears heartbeatProbeSentAt; the id is
// intentionally unmatched in handleSocketMessage so it adds no pending
// request or timeout. If sending fails the socket isn't OPEN — skip.
if (
this.sendEncrypted({
id: `web-heartbeat-${this.nextId()}`,
deviceToken: this.pairing.deviceToken,
method: 'status.get'
})
) {
this.heartbeatProbeSentAt = now
}
}
}
}

function isSubscriptionResponse(
Expand Down
Loading