The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(shared): a crashed server-request handler reports through an owner hook, not console.error
kshitijk4poordc8fe4def821
diff --git a/apps/desktop/src/api/client.ts b/apps/desktop/src/api/client.tsindex db0d0e7e052..e0b1d761fa9 100644--- a/apps/desktop/src/api/client.ts+++ b/apps/desktop/src/api/client.ts@@ -32,6 +32,9 @@ export class HermesGateway extends JsonRpcGatewayClient {connectErrorMessage: 'Could not connect to Hermes gateway',createRequestId: nextId => nextId,notConnectedErrorMessage: 'Hermes gateway is not connected',+ // The channel already answered -32603; surface the crash in devtools like the dial-failure sink.+ onRequestHandlerError: (error, request) =>+ console.error(`[gateway] server request handler crashed for ${request.method} (${request.id}):`, error),requestTimeoutMs: DEFAULT_GATEWAY_REQUEST_TIMEOUT_MS})}diff --git a/apps/shared/src/json-rpc-channel.test.ts b/apps/shared/src/json-rpc-channel.test.tsindex a6d71bab81e..da8189d86e3 100644--- a/apps/shared/src/json-rpc-channel.test.ts+++ b/apps/shared/src/json-rpc-channel.test.ts@@ -221,7 +221,14 @@ describe('JsonRpcRequestChannel', () => {// deliverRequest inside the socket listener — no response frame at all, so// the backend (clarify_tool: 3600s deadline) waited out the whole block.it('answers -32603 when a handler throws, keeps later frames working, and still answers -32601 otherwise', () => {- const channel = new JsonRpcRequestChannel()+ const crashed: Array<{ id: string; method: string; message: string }> = []+ const unhandled: string[] = []++ const channel = new JsonRpcRequestChannel({+ onRequestHandlerError: (error, req) => void crashed.push({ id: req.id, method: req.method, message: error.message }),+ onUnhandledRequest: req => void unhandled.push(req.method)+ })+const { sent, transport } = spyTransport()channel.attach(transport)@@ -249,6 +256,9 @@ describe('JsonRpcRequestChannel', () => {expect(frames[0].error?.message).toContain('boom')expect(frames[1].id).toBe('srq-2')expect(frames[1].error?.code).toBe(-32601)+ // The crash reports through its own hook; it is not an "unhandled" request.+ expect(crashed).toEqual([{ id: 'srq-1', method: 'boom', message: 'handler exploded' }])+ expect(unhandled).toEqual(['nobody'])// The channel survives: a normal request after the crash still routes.channel.handleFrame(JSON.stringify({ id: 'srq-3', jsonrpc: '2.0', method: 'clarify', params: { session_id: 's1' } }))diff --git a/apps/shared/src/json-rpc-channel.ts b/apps/shared/src/json-rpc-channel.tsindex f6a6a1926c8..20de1e393e1 100644--- a/apps/shared/src/json-rpc-channel.ts+++ b/apps/shared/src/json-rpc-channel.ts@@ -72,11 +72,6 @@ export const JSON_RPC_METHOD_NOT_FOUND = -32601/** JSON-RPC "internal error" — used when a server→client request handler throws. */export const JSON_RPC_INTERNAL_ERROR = -32603-/** Console sink so handler crashes are visible in the renderer devtools/console log. */-const reportChannelError = (message: string, error: unknown): void => {- console.error(`[json-rpc-channel] ${message}`, error)-}-/** Map a raw `error` member of a response frame to the typed error every surface inspects. */export function jsonRpcErrorFromFrame(raw: unknown, fallbackMessage = 'Hermes RPC failed'): JsonRpcGatewayError {const err = (raw && typeof raw === 'object' ? raw : {}) as JsonRpcErrorPayload@@ -110,6 +105,12 @@ export interface JsonRpcRequestChannelOptions {* its deadline against a client with no handler.*/onUnhandledRequest?: (request: { id: string; method: string; params: ServerRequestParams }) => void+ /**+ * A server→client request handler threw: the owner logs it. The channel has+ * already answered `-32603` so the backend does not wait out its deadline+ * against a crashed client (clarify blocks 3600s).+ */+ onRequestHandlerError?: (error: Error, request: { id: string; method: string; params: ServerRequestParams }) => voidrequestIdPrefix?: stringrequestTimeoutMs?: number/**@@ -183,9 +184,9 @@ export class JsonRpcRequestChannel {private lastLivenessAt = 0private readonly requestHandlers: ServerRequestHandler[] = []private readonly options: Required<- Omit<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure' | 'onUnhandledRequest'>+ Omit<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure' | 'onRequestHandlerError' | 'onUnhandledRequest'>> &- Pick<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure' | 'onUnhandledRequest'>+ Pick<JsonRpcRequestChannelOptions, 'onEvent' | 'onHeartbeatFailure' | 'onRequestHandlerError' | 'onUnhandledRequest'>constructor(options: JsonRpcRequestChannelOptions = {}) {this.options = {@@ -195,6 +196,7 @@ export class JsonRpcRequestChannel {heartbeatLiveness: options.heartbeatLiveness ?? 'response',onEvent: options.onEvent,onHeartbeatFailure: options.onHeartbeatFailure,+ onRequestHandlerError: options.onRequestHandlerError,onUnhandledRequest: options.onUnhandledRequest,requestIdPrefix: options.requestIdPrefix ?? 'r',requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,@@ -359,8 +361,6 @@ export class JsonRpcRequestChannel {fail: (code, message) => send({ error: { code, message } })}- let handled = false-for (const handler of this.requestHandlers) {let accepted: boolean | void@@ -371,28 +371,20 @@ export class JsonRpcRequestChannel {// deadline (clarify blocks 3600s): answer -32603 and stop. The `send`// guard makes this a no-op if the handler already responded.request.fail(JSON_RPC_INTERNAL_ERROR, `server request handler crashed: ${method}`)- this.options.onUnhandledRequest?.({ id, method, params })-- if (error instanceof Error) {- reportChannelError(`server request handler threw for ${method} (${id})`, error)- } else {- reportChannelError(`server request handler threw for ${method} (${id})`, new Error(String(error)))- }+ this.options.onRequestHandlerError?.(error instanceof Error ? error : new Error(String(error)), {+ id,+ method,+ params+ })return false}if (accepted !== false) {- handled = true-- break+ return true}}- if (handled) {- return true- }-request.fail(JSON_RPC_METHOD_NOT_FOUND, `no handler for server request: ${method}`)this.options.onUnhandledRequest?.({ id, method, params })diff --git a/apps/shared/src/json-rpc-gateway.ts b/apps/shared/src/json-rpc-gateway.tsindex 338272b762c..f548c3595ac 100644--- a/apps/shared/src/json-rpc-gateway.ts+++ b/apps/shared/src/json-rpc-gateway.ts@@ -4,6 +4,7 @@ import {DEFAULT_HEARTBEAT_INTERVAL_MS,type GatewayRequestId,JsonRpcRequestChannel,+ type JsonRpcRequestChannelOptions,type JsonRpcTransport,type ServerRequestHandler,wireFrameText@@ -21,6 +22,8 @@ export interface GatewayClientOptions {createRequestId?: (nextId: number) => GatewayRequestIdheartbeatDeadlineMs?: numberheartbeatIntervalMs?: number+ /** A server→client request handler threw; the channel already answered `-32603`. */+ onRequestHandlerError?: JsonRpcRequestChannelOptions['onRequestHandlerError']/** Return true to intercept the default closed-state transition. */onSocketClose?: (event: { code: number }) => boolean | void/** Fetch `session.events.since` after a reconnect (default). Off for notification-only feeds whose peer never answers RPCs. */@@ -126,8 +129,8 @@ export class JsonRpcGatewayClient {*/private replayEpoch: string | null = nullprivate readonly stateHandlers = new Set<(state: ConnectionState) => void>()- private readonly options: Required<Omit<GatewayClientOptions, 'socketFactory'>> &- Pick<GatewayClientOptions, 'socketFactory'>+ private readonly options: Required<Omit<GatewayClientOptions, 'onRequestHandlerError' | 'socketFactory'>> &+ Pick<GatewayClientOptions, 'onRequestHandlerError' | 'socketFactory'>constructor(options: GatewayClientOptions = {}) {this.options = {@@ -141,6 +144,7 @@ export class JsonRpcGatewayClient {onSocketClose: options.onSocketClose ?? (() => false),replay: options.replay ?? true,requestIdPrefix: options.requestIdPrefix ?? 'r',+ onRequestHandlerError: options.onRequestHandlerError,requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,socketFactory: options.socketFactory}@@ -153,6 +157,7 @@ export class JsonRpcGatewayClient {heartbeatLiveness: 'any-inbound',onEvent: event => this.handleEvent(event),onHeartbeatFailure: error => this.invalidate(error.message),+ onRequestHandlerError: this.options.onRequestHandlerError,requestTimeoutMs: this.options.requestTimeoutMs})}diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex 2175def6bc1..99a4db43583 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -135,6 +135,8 @@ export class GatewayClient extends EventEmitter {private readonly channel = new JsonRpcRequestChannel({onEvent: ev => this.publish(ev as AnyGatewayEvent),onHeartbeatFailure: () => this.onHeartbeatFailure(),+ onRequestHandlerError: (error, req) =>+ this.pushLog(`[protocol] server request handler crashed: ${req.method} (${error.message})`),onUnhandledRequest: req => this.pushLog(`[protocol] unhandled server request: ${req.method}`),requestTimeoutMs: REQUEST_TIMEOUT_MS,unrefTimers: true