Skip to content

The agent that grows with you

fix(shared): JSON-RPC channel ignores non-object frames and keeps the TUI's pong-based liveness

teknium12435131573dc
diff --git a/apps/shared/src/json-rpc-channel.test.ts b/apps/shared/src/json-rpc-channel.test.ts
index 2e8e7594f7e..960f6d17408 100644
--- a/apps/shared/src/json-rpc-channel.test.ts
+++ b/apps/shared/src/json-rpc-channel.test.ts
@@ -45,6 +45,19 @@ describe('JsonRpcRequestChannel', () => {
expect(events).toEqual(['session.info'])
})
+ // A stdout line that parses to a non-object used to reach `frame.id` and
+ // throw out of the readline handler (uncaughtException in the Ink process).
+ it.each(['null', '42', '"str"', 'true'])('ignores the non-object JSON line %s without throwing', text => {
+ const events: string[] = []
+ const channel = new JsonRpcRequestChannel({ onEvent: ev => void events.push(ev.type) })
+
+ channel.attach(spyTransport().transport)
+
+ expect(() => channel.handleFrame(text)).not.toThrow()
+ expect(channel.handleFrame(text)).toBeNull()
+ expect(events).toEqual([])
+ })
+
it('detach fails every in-flight call and a per-call timeout names the method', async () => {
vi.useFakeTimers()
@@ -68,7 +81,7 @@ describe('JsonRpcRequestChannel', () => {
}
})
- it('heartbeat pings while frames keep arriving and reports a silent transport', async () => {
+ it("'any-inbound' liveness (desktop/web): pings while frames keep arriving and reports a silent transport", async () => {
vi.useFakeTimers()
try {
@@ -77,6 +90,7 @@ describe('JsonRpcRequestChannel', () => {
const channel = new JsonRpcRequestChannel({
heartbeatDeadlineMs: 300,
heartbeatIntervalMs: 100,
+ heartbeatLiveness: 'any-inbound',
onHeartbeatFailure: e => void failures.push(e.message)
})
@@ -103,4 +117,57 @@ describe('JsonRpcRequestChannel', () => {
vi.useRealTimers()
}
})
+
+ // TUI contract: a backend whose request loop is wedged may still stream
+ // deltas; only a pong (or a response to our own request) proves it can
+ // answer, so notifications alone must NOT keep the transport alive.
+ it("'response' liveness (default, TUI): unanswered pings fail the heartbeat even while deltas stream", async () => {
+ vi.useFakeTimers()
+
+ try {
+ const failures: string[] = []
+
+ const channel = new JsonRpcRequestChannel({
+ heartbeatDeadlineMs: 300,
+ heartbeatIntervalMs: 100,
+ onHeartbeatFailure: e => void failures.push(e.message)
+ })
+
+ const { sent, transport } = spyTransport()
+
+ channel.attach(transport)
+ channel.startHeartbeat()
+
+ const pingIds = () =>
+ sent.map(f => JSON.parse(f) as { id: string; method: string }).filter(f => f.method === 'gateway.ping').map(f => f.id)
+
+ // Pongs arrive: alive well past the deadline.
+ for (let i = 0; i < 6; i++) {
+ await vi.advanceTimersByTimeAsync(100)
+ channel.handleFrame(JSON.stringify({ id: pingIds().at(-1), jsonrpc: '2.0', result: { ok: true } }))
+ }
+
+ expect(failures).toEqual([])
+
+ // A response to one of our own requests also counts.
+ const call = channel.request('session.list')
+ const callId = (JSON.parse(sent.at(-1)!) as { id: string }).id
+
+ await vi.advanceTimersByTimeAsync(250)
+ channel.handleFrame(JSON.stringify({ id: callId, jsonrpc: '2.0', result: [] }))
+ await call
+ await vi.advanceTimersByTimeAsync(100)
+ expect(failures).toEqual([])
+
+ // Deltas keep streaming but no ping is answered → dead.
+ for (let i = 0; i < 4; i++) {
+ await vi.advanceTimersByTimeAsync(100)
+ channel.handleFrame(JSON.stringify({ jsonrpc: '2.0', method: 'event', params: { type: 'message.delta', payload: {} } }))
+ }
+
+ expect(failures).toEqual(['WebSocket heartbeat acknowledgement timed out'])
+ } finally {
+ vi.useRealTimers()
+ }
+ })
})
diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.ts
index 0dab532fc29..d261f0fff37 100644
--- a/apps/shared/src/json-rpc-channel.ts
+++ b/apps/shared/src/json-rpc-channel.ts
@@ -61,10 +61,21 @@ export interface JsonRpcRequestChannelOptions {
onEvent?: (event: GatewayEvent) => void
requestIdPrefix?: string
requestTimeoutMs?: number
+ /**
+ * What resets the heartbeat deadline. `'response'` (default): only a
+ * `gateway.ping` pong or a response to one of our requests — a backend
+ * whose request loop is wedged but still streams deltas is dead for the
+ * caller and must be dropped (the Ink TUI's original contract).
+ * `'any-inbound'`: every frame, notifications included (the desktop/web
+ * WebSocket client's original contract).
+ */
+ heartbeatLiveness?: HeartbeatLiveness
/** `setTimeout`/`setInterval` handles are `unref`'d when the runtime supports it (Node) so a pending call cannot pin the process. */
unrefTimers?: boolean
}
+export type HeartbeatLiveness = 'any-inbound' | 'response'
+
interface PendingCall {
reject: (error: Error) => void
resolve: (value: unknown) => void
@@ -79,6 +90,7 @@ const DEFAULT_REQUEST_TIMEOUT_MS = 120_000
// heartbeat that the TUI gateway explicitly answers.
export const DEFAULT_HEARTBEAT_INTERVAL_MS = 15_000
export const DEFAULT_HEARTBEAT_DEADLINE_MS = 45_000
+const MAX_OUTSTANDING_PINGS = 8
// Hoisted decoder: attach mode can drive high-frequency binary frames (tool
// deltas, reasoning streams) and a fresh TextDecoder per message is avoidable
@@ -116,7 +128,8 @@ export class JsonRpcRequestChannel {
private transport: JsonRpcTransport | null = null
private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private heartbeatSequence = 0
- private lastInboundAt = 0
+ private readonly outstandingPings = new Set<string>()
+ private lastLivenessAt = 0
private readonly options: Required<Omit<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure'>> &
Pick<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure'>
@@ -125,6 +138,7 @@ export class JsonRpcRequestChannel {
createRequestId: options.createRequestId ?? ((nextId: number) => `${options.requestIdPrefix ?? 'r'}${nextId}`),
heartbeatDeadlineMs: options.heartbeatDeadlineMs ?? DEFAULT_HEARTBEAT_DEADLINE_MS,
heartbeatIntervalMs: options.heartbeatIntervalMs ?? DEFAULT_HEARTBEAT_INTERVAL_MS,
+ heartbeatLiveness: options.heartbeatLiveness ?? 'response',
onEvent: options.onEvent,
onHeartbeatFailure: options.onHeartbeatFailure,
requestIdPrefix: options.requestIdPrefix ?? 'r',
@@ -145,7 +159,7 @@ export class JsonRpcRequestChannel {
attach(transport: JsonRpcTransport): void {
this.stopHeartbeat()
this.transport = transport
- this.lastInboundAt = Date.now()
+ this.lastLivenessAt = Date.now()
}
/** Drop the transport and fail every in-flight call with `error`. */
@@ -244,11 +258,9 @@ export class JsonRpcRequestChannel {
* Route one inbound frame: a response settles its pending call, an
* `event` notification reaches `onEvent`. Returns the decoded frame so the
* owner can act on it too (mirror it, record seq, …) or `null` when the
- * text was not JSON.
+ * text was not JSON or not a JSON object (`null`, a scalar).
*/
handleFrame(text: string): JsonRpcFrame | null {
- this.lastInboundAt = Date.now()
-
let frame: JsonRpcFrame
try {
@@ -257,10 +269,25 @@ export class JsonRpcRequestChannel {
return null
}
+ if (!frame || typeof frame !== 'object') {
+ return null
+ }
+
+ if (this.options.heartbeatLiveness === 'any-inbound') {
+ this.lastLivenessAt = Date.now()
+ }
+
if (frame.id !== undefined && frame.id !== null) {
+ if (typeof frame.id === 'string' && this.outstandingPings.delete(frame.id)) {
+ this.lastLivenessAt = Date.now()
+
+ return frame
+ }
+
const call = this.pending.get(frame.id)
if (call) {
+ this.lastLivenessAt = Date.now()
this.clearPending(frame.id)
if (frame.error) {
@@ -283,12 +310,12 @@ export class JsonRpcRequestChannel {
/**
* Begin the `gateway.ping` keepalive on the bound transport. Only call when
* `gateway.ready.heartbeat` advertised support — an older backend would
- * answer with -32601 and never count as alive. Any inbound frame counts as
- * liveness; only a full deadline of silence drops the transport.
+ * answer with -32601 and never count as alive. What counts as liveness is
+ * `heartbeatLiveness`; a full deadline without it drops the transport.
*/
startHeartbeat(): void {
this.stopHeartbeat()
- this.lastInboundAt = Date.now()
+ this.lastLivenessAt = Date.now()
const transport = this.transport
@@ -301,16 +328,24 @@ export class JsonRpcRequestChannel {
return
}
- if (Date.now() - this.lastInboundAt >= this.options.heartbeatDeadlineMs) {
+ if (Date.now() - this.lastLivenessAt >= this.options.heartbeatDeadlineMs) {
this.failHeartbeat(new Error('WebSocket heartbeat acknowledgement timed out'))
return
}
+ const id = `heartbeat-${++this.heartbeatSequence}`
+ this.outstandingPings.add(id)
+
+ // In 'any-inbound' mode a backend that streams but never pongs keeps
+ // the transport alive indefinitely; forget stale ping ids so the set
+ // cannot grow with it.
+ if (this.outstandingPings.size > MAX_OUTSTANDING_PINGS) {
+ this.outstandingPings.delete(this.outstandingPings.values().next().value as string)
+ }
+
try {
- transport.send(
- JSON.stringify({ jsonrpc: '2.0', id: `heartbeat-${++this.heartbeatSequence}`, method: 'gateway.ping', params: {} })
- )
+ transport.send(JSON.stringify({ jsonrpc: '2.0', id, method: 'gateway.ping', params: {} }))
} catch (error) {
this.failHeartbeat(error instanceof Error ? error : new Error(String(error)))
}
@@ -322,6 +357,8 @@ export class JsonRpcRequestChannel {
}
stopHeartbeat(): void {
+ this.outstandingPings.clear()
+
if (this.heartbeatTimer !== null) {
clearInterval(this.heartbeatTimer)
this.heartbeatTimer = null
diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.ts
index 65696c142f0..48bb2acf818 100644
--- a/apps/shared/src/json-rpc-gateway.ts
+++ b/apps/shared/src/json-rpc-gateway.ts
@@ -147,6 +147,9 @@ export class JsonRpcGatewayClient {
createRequestId: this.options.createRequestId,
heartbeatDeadlineMs: this.options.heartbeatDeadlineMs,
heartbeatIntervalMs: this.options.heartbeatIntervalMs,
+ // Desktop/web have always counted any inbound frame as liveness; the
+ // TUI (stdio/attach owner) keeps its stricter pong-based contract.
+ heartbeatLiveness: 'any-inbound',
onEvent: event => this.handleEvent(event),
onHeartbeatFailure: error => this.invalidate(error.message),
requestTimeoutMs: this.options.requestTimeoutMs
@@ -249,8 +252,10 @@ export class JsonRpcGatewayClient {
// A server that closes during the handshake (auth gate, 4401/4403)
// may never fire `error`; without this the caller waits out the
// connect timeout for a verdict the socket already delivered. The
- // permanent close listener above has already moved the generation to
- // 'closed' (unless onSocketClose intercepted), so only settle here.
+ // permanent close listener above normally already dropped the socket
+ // and moved the generation to 'closed'; the branch below only runs
+ // when `onSocketClose` intercepted that transition and left the
+ // half-open socket bound.
const onClose = () => {
if (settled) {
return