Skip to content

The agent that grows with you

feat(shared): heartbeat and socket-generation invalidation in JsonRpcGatewayClient

Eva9153be2a5126
diff --git a/apps/desktop/src/lib/json-rpc-gateway-heartbeat.test.ts b/apps/desktop/src/lib/json-rpc-gateway-heartbeat.test.ts
new file mode 100644
index 00000000000..5d9f8b18a5b
--- /dev/null
+++ b/apps/desktop/src/lib/json-rpc-gateway-heartbeat.test.ts
@@ -0,0 +1,131 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+interface ListenerEntry {
+ callback: (event: any) => void
+ once: boolean
+}
+
+class FakeSocket {
+ static readonly CLOSED = 3
+ static readonly OPEN = 1
+
+ readonly sent: string[] = []
+ readyState = FakeSocket.OPEN
+ private listeners = new Map<string, ListenerEntry[]>()
+
+ addEventListener(type: string, callback: (event: any) => void, options?: AddEventListenerOptions): void {
+ const entries = this.listeners.get(type) ?? []
+
+ entries.push({ callback, once: Boolean(options?.once) })
+ this.listeners.set(type, entries)
+ }
+
+ close(): void {
+ if (this.readyState === FakeSocket.CLOSED) {
+ return
+ }
+
+ this.readyState = FakeSocket.CLOSED
+ this.emit('close', { code: 1000 })
+ }
+
+ emit(type: string, event: any = {}): void {
+ const entries = [...(this.listeners.get(type) ?? [])]
+
+ for (const entry of entries) {
+ entry.callback(event)
+
+ if (entry.once) {
+ this.removeEventListener(type, entry.callback)
+ }
+ }
+ }
+
+ message(frame: unknown): void {
+ this.emit('message', { data: JSON.stringify(frame) })
+ }
+
+ removeEventListener(type: string, callback: (event: any) => void): void {
+ this.listeners.set(
+ type,
+ (this.listeners.get(type) ?? []).filter(entry => entry.callback !== callback)
+ )
+ }
+
+ send(payload: string): void {
+ this.sent.push(payload)
+ }
+}
+
+describe('JsonRpcGatewayClient heartbeat recovery', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it('invalidates a silently dead advertised socket and ignores its late frames', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', { OPEN: FakeSocket.OPEN })
+ const socket = new FakeSocket()
+ const states: string[] = []
+ const events: string[] = []
+
+ const client = new JsonRpcGatewayClient({
+ heartbeatDeadlineMs: 45,
+ heartbeatIntervalMs: 15,
+ socketFactory: () => socket as unknown as WebSocket
+ })
+
+ client.onState(state => states.push(state))
+ client.onAny(event => events.push(event.type))
+
+ const connected = client.connect('ws://gateway.test/api/ws')
+ socket.emit('open')
+ await connected
+ socket.message({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: { heartbeat: true } }
+ })
+
+ await vi.advanceTimersByTimeAsync(61)
+
+ expect(client.connectionState).toBe('closed')
+ expect(socket.readyState).toBe(FakeSocket.CLOSED)
+ expect(states.at(-1)).toBe('closed')
+
+ socket.message({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'message.complete', payload: { text: 'late duplicate' } }
+ })
+ expect(events).toEqual(['gateway.ready'])
+ })
+
+ it('keeps older backends open when gateway.ready does not advertise heartbeat', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', { OPEN: FakeSocket.OPEN })
+ const socket = new FakeSocket()
+
+ const client = new JsonRpcGatewayClient({
+ heartbeatDeadlineMs: 45,
+ heartbeatIntervalMs: 15,
+ socketFactory: () => socket as unknown as WebSocket
+ })
+
+ const connected = client.connect('ws://gateway.test/api/ws')
+ socket.emit('open')
+ await connected
+ socket.message({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: {} }
+ })
+
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(client.connectionState).toBe('open')
+ expect(socket.readyState).toBe(FakeSocket.OPEN)
+ expect(socket.sent).toEqual([])
+ })
+})
diff --git a/apps/desktop/src/lib/json-rpc-gateway-recovery.test.ts b/apps/desktop/src/lib/json-rpc-gateway-recovery.test.ts
new file mode 100644
index 00000000000..f6bcc4ac4e1
--- /dev/null
+++ b/apps/desktop/src/lib/json-rpc-gateway-recovery.test.ts
@@ -0,0 +1,196 @@
+import { JsonRpcGatewayClient } from '@hermes/shared'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+interface ListenerEntry {
+ callback: (event: any) => void
+ once: boolean
+}
+
+class LoopbackSocket {
+ static readonly CLOSED = 3
+ static readonly CONNECTING = 0
+ static readonly OPEN = 1
+
+ readyState = LoopbackSocket.CONNECTING
+ private listeners = new Map<string, ListenerEntry[]>()
+
+ constructor(
+ readonly generation: number,
+ private readonly backend: RecoveryBackend
+ ) {}
+
+ addEventListener(type: string, callback: (event: any) => void, options?: AddEventListenerOptions): void {
+ const entries = this.listeners.get(type) ?? []
+
+ entries.push({ callback, once: Boolean(options?.once) })
+ this.listeners.set(type, entries)
+ }
+
+ close(): void {
+ if (this.readyState === LoopbackSocket.CLOSED) {
+ return
+ }
+
+ this.readyState = LoopbackSocket.CLOSED
+ this.emit('close', { code: 1000 })
+ }
+
+ message(frame: unknown): void {
+ this.emit('message', { data: JSON.stringify(frame) })
+ }
+
+ open(): void {
+ this.readyState = LoopbackSocket.OPEN
+ this.emit('open', {})
+ this.message({
+ jsonrpc: '2.0',
+ method: 'event',
+ params: { type: 'gateway.ready', payload: { heartbeat: true } }
+ })
+ }
+
+ removeEventListener(type: string, callback: (event: any) => void): void {
+ this.listeners.set(
+ type,
+ (this.listeners.get(type) ?? []).filter(entry => entry.callback !== callback)
+ )
+ }
+
+ send(payload: string): void {
+ this.backend.receive(this, JSON.parse(payload) as Record<string, any>)
+ }
+
+ private emit(type: string, event: any): void {
+ const entries = [...(this.listeners.get(type) ?? [])]
+
+ for (const entry of entries) {
+ entry.callback(event)
+
+ if (entry.once) {
+ this.removeEventListener(type, entry.callback)
+ }
+ }
+ }
+}
+
+class RecoveryBackend {
+ readonly sockets: LoopbackSocket[] = []
+ readonly messages: Array<{ role: 'assistant' | 'user'; content: string }> = []
+ promptSubmits = 0
+
+ createSocket(): LoopbackSocket {
+ const socket = new LoopbackSocket(this.sockets.length + 1, this)
+
+ this.sockets.push(socket)
+ queueMicrotask(() => socket.open())
+
+ return socket
+ }
+
+ receive(socket: LoopbackSocket, frame: Record<string, any>): void {
+ if (socket.generation === 1 && frame.method === 'prompt.submit') {
+ this.promptSubmits += 1
+ this.messages.push(
+ { role: 'user', content: String(frame.params?.text ?? '') },
+ { role: 'assistant', content: 'persisted while transport was blackholed' }
+ )
+
+ // Accepted and persisted, but every outbound packet (including the RPC
+ // response, heartbeat acknowledgement, and message.complete) is dropped.
+ return
+ }
+
+ if (socket.generation === 1) {
+ return
+ }
+
+ if (frame.method === 'gateway.ping') {
+ socket.message({ jsonrpc: '2.0', id: frame.id, result: { ok: true } })
+
+ return
+ }
+
+ if (frame.method === 'session.activate') {
+ socket.message({
+ jsonrpc: '2.0',
+ id: frame.id,
+ result: {
+ session_id: 'runtime-1',
+ session_key: 'stored-1',
+ messages: this.messages,
+ running: false,
+ status: 'idle'
+ }
+ })
+ }
+ }
+}
+
+describe('hermes-ws-recovery-v1 silent blackhole', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.useRealTimers()
+ })
+
+ it('recovers the persisted final on a replacement socket without duplicating the prompt', async () => {
+ vi.useFakeTimers()
+ vi.stubGlobal('WebSocket', { OPEN: LoopbackSocket.OPEN })
+ const backend = new RecoveryBackend()
+
+ const client = new JsonRpcGatewayClient({
+ heartbeatDeadlineMs: 45,
+ heartbeatIntervalMs: 15,
+ socketFactory: () => backend.createSocket() as unknown as WebSocket
+ })
+
+ let epoch = 0
+ let intentionalShutdown = false
+ let recovered: Promise<any> | null = null
+
+ client.onState(state => {
+ if (state === 'open') {
+ epoch += 1
+
+ if (epoch > 1) {
+ recovered = client.request('session.activate', { session_id: 'runtime-1' })
+ }
+ }
+
+ if (state === 'closed' && !intentionalShutdown) {
+ void client.connect('ws://gateway.test/api/ws')
+ }
+ })
+
+ await client.connect('ws://gateway.test/api/ws')
+ await Promise.resolve()
+
+ const ambiguousSubmit = client
+ .request('prompt.submit', { session_id: 'runtime-1', text: 'one prompt' })
+ .then(
+ () => null,
+ error => error as Error
+ )
+
+ await vi.advanceTimersByTimeAsync(61)
+ await vi.waitFor(() => expect(backend.sockets).toHaveLength(2))
+ await vi.waitFor(() => expect(recovered).not.toBeNull())
+
+ await expect(ambiguousSubmit).resolves.toMatchObject({
+ message: 'WebSocket heartbeat acknowledgement timed out'
+ })
+ await expect(recovered).resolves.toMatchObject({
+ messages: [
+ { role: 'user', content: 'one prompt' },
+ { role: 'assistant', content: 'persisted while transport was blackholed' }
+ ],
+ running: false,
+ status: 'idle'
+ })
+ expect(backend.promptSubmits).toBe(1)
+
+ intentionalShutdown = true
+ client.close()
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(backend.sockets).toHaveLength(2)
+ })
+})
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index 8a2713a3eed..ee30995cbc5 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -77,6 +77,8 @@ export interface GatewayClientOptions {
connectErrorMessage?: string
connectTimeoutMs?: number
createRequestId?: (nextId: number) => GatewayRequestId
+ heartbeatDeadlineMs?: number
+ heartbeatIntervalMs?: number
/** Return true to intercept the default closed-state transition. */
onSocketClose?: (event: CloseEvent) => boolean | void
requestIdPrefix?: string
@@ -87,6 +89,8 @@ export interface GatewayClientOptions {
const ANY = '*'
const DEFAULT_REQUEST_TIMEOUT_MS = 120_000
+const DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000
+const DEFAULT_HEARTBEAT_DEADLINE_MS = 45_000
// A reconnect after sleep/wake must not hang forever in 'connecting' (which
// keeps the composer disabled and stuck on "Starting Hermes..."). If the open
// handshake doesn't land in this window, fail to 'error' so callers can retry.
@@ -97,6 +101,9 @@ export class JsonRpcGatewayClient {
private pending = new Map<GatewayRequestId, PendingCall>()
private socket: WebSocketLike | null = null
private state: ConnectionState = 'idle'
+ private heartbeatTimer: ReturnType<typeof setInterval> | null = null
+ private heartbeatSequence = 0
+ private lastInboundAt = 0
private readonly eventHandlers = new Map<string, Set<(event: GatewayEvent) => void>>()
private readonly stateHandlers = new Set<(state: ConnectionState) => void>()
private readonly options: Required<Omit<GatewayClientOptions, 'socketFactory'>> &
@@ -108,6 +115,8 @@ export class JsonRpcGatewayClient {
connectErrorMessage: options.connectErrorMessage ?? 'WebSocket connection failed',
connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,
createRequestId: options.createRequestId ?? ((nextId: number) => `${options.requestIdPrefix ?? 'r'}${nextId}`),
+ heartbeatDeadlineMs: options.heartbeatDeadlineMs ?? DEFAULT_HEARTBEAT_DEADLINE_MS,
+ heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
notConnectedErrorMessage: options.notConnectedErrorMessage ?? 'gateway not connected',
onSocketClose: options.onSocketClose ?? (() => false),
requestIdPrefix: options.requestIdPrefix ?? 'r',
@@ -153,12 +162,14 @@ export class JsonRpcGatewayClient {
const socket = this.options.socketFactory?.(wsUrl) ?? new WebSocket(wsUrl)
this.socket = socket
+ this.stopHeartbeat()
socket.addEventListener('message', message => {
if (this.socket !== socket) {
return
}
+ this.lastInboundAt = Date.now()
this.handleMessage(message.data)
})
@@ -172,6 +183,7 @@ export class JsonRpcGatewayClient {
}
this.socket = null
+ this.stopHeartbeat()
this.setState('closed')
this.rejectAllPending(new Error(this.options.closedErrorMessage))
})
@@ -253,11 +265,26 @@ export class JsonRpcGatewayClient {
socket.close()
} finally {
this.socket = null
+ this.stopHeartbeat()
this.setState('closed')
this.rejectAllPending(new Error(this.options.closedErrorMessage))
}
}
+ /**
+ * Invalidate the current socket generation after an ambiguous transport
+ * outcome. The outer connection owner decides whether/when to reconnect.
+ */
+ invalidate(message = this.options.closedErrorMessage): void {
+ const socket = this.socket
+
+ if (!socket) {
+ return
+ }
+
+ this.invalidateSocket(socket, new Error(message))
+ }
+
on<P = unknown>(type: GatewayEventName, handler: (event: GatewayEvent<P>) => void): () => void {
let handlers = this.eventHandlers.get(type)
@@ -408,10 +435,81 @@ export class JsonRpcGatewayClient {
}
if (frame.method === 'event' && frame.params?.type) {
+ if (frame.params.type === 'gateway.ready' && this.gatewayReadyAdvertisesHeartbeat(frame.params.payload)) {
+ const socket = this.socket
+
+ if (socket) {
+ this.startHeartbeat(socket)
+ }
+ }
+
this.dispatchEvent(frame.params)
}
}
+ private gatewayReadyAdvertisesHeartbeat(payload: unknown): boolean {
+ return Boolean(payload && typeof payload === 'object' && (payload as { heartbeat?: unknown }).heartbeat === true)
+ }
+
+ private startHeartbeat(socket: WebSocketLike): void {
+ this.stopHeartbeat()
+ this.lastInboundAt = Date.now()
+
+ if (this.options.heartbeatIntervalMs <= 0 || this.options.heartbeatDeadlineMs <= 0) {
+ return
+ }
+
+ this.heartbeatTimer = setInterval(() => {
+ if (this.socket !== socket || socket.readyState !== WebSocket.OPEN) {
+ return
+ }
+
+ if (Date.now() - this.lastInboundAt >= this.options.heartbeatDeadlineMs) {
+ this.invalidateSocket(socket, new Error('WebSocket heartbeat acknowledgement timed out'))
+
+ return
+ }
+
+ try {
+ socket.send(
+ JSON.stringify({
+ jsonrpc: '2.0',
+ id: `heartbeat-${++this.heartbeatSequence}`,
+ method: 'gateway.ping',
+ params: {}
+ })
+ )
+ } catch (error) {
+ this.invalidateSocket(socket, error instanceof Error ? error : new Error(String(error)))
+ }
+ }, this.options.heartbeatIntervalMs)
+ }
+
+ private stopHeartbeat(): void {
+ if (this.heartbeatTimer !== null) {
+ clearInterval(this.heartbeatTimer)
+ this.heartbeatTimer = null
+ }
+ }
+
+ private invalidateSocket(socket: WebSocketLike, error: Error): void {
+ if (this.socket !== socket) {
+ return
+ }
+
+ this.socket = null
+ this.stopHeartbeat()
+
+ try {
+ socket.close()
+ } catch {
+ // The generation was already invalidated; the reconnect owner can redial.
+ }
+
+ this.setState('closed')
+ this.rejectAllPending(error)
+ }
+
private clearPending(id: GatewayRequestId): void {
const call = this.pending.get(id)