The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): retry a create whose launch pin failed under its committed request_id
Teknium19f3f71259f9
diff --git a/ui-tui/src/__tests__/gatewayClient.test.ts b/ui-tui/src/__tests__/gatewayClient.test.tsindex d1ef6f76c68..6aa528bd8d1 100644--- a/ui-tui/src/__tests__/gatewayClient.test.ts+++ b/ui-tui/src/__tests__/gatewayClient.test.ts@@ -279,6 +279,54 @@ describe('GatewayClient websocket attach mode', () => {} finally { gw.kill(); vi.unstubAllEnvs(); vi.useRealTimers() }})+ it('retries a create whose launch pin failed after the ACK under the same request_id (one session, pin reapplied)', async () => {+ vi.useFakeTimers()+ delete process.env.HERMES_TUI_GATEWAY_URL+ vi.stubEnv('HERMES_TUI_TOOL_PROGRESS', 'verbose')+ const gw = new GatewayClient(async () => ({ url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }))+ gw.on('event', () => undefined)++ try {+ gw.start(); gw.drain()+ await vi.advanceTimersByTimeAsync(0)+ const socket = FakeWebSocket.instances[0]!+ socket.open()+ await vi.advanceTimersByTimeAsync(0)+ const frames = () => socket.sent.map(text => JSON.parse(text) as { id: number; method: string; params: any })+ const last = (method: string) => frames().filter(f => f.method === method).at(-1)!+ const answer = (method: string, body: object) => socket.message(JSON.stringify({ jsonrpc: '2.0', id: last(method).id, ...body }))+ // The owner keys a local session by request_id, exactly like create_local_session.+ const minted = new Map<string, string>()++ const ack = () => {+ const requestId = last('session.create').params.request_id as string+ minted.set(requestId, minted.get(requestId) ?? `orphan-${minted.size + 1}`)+ answer('session.create', { result: { session_id: minted.get(requestId), info: {} } })+ }++ answer('runtime.describe', { result: { session_create: { sources: ['tui'], parameters: ['source', 'request_id', 'model'] } } })+ await vi.advanceTimersByTimeAsync(0)++ // The caller (useSessionLifecycle) mints a fresh request_id on every attempt.+ const first = gw.request('session.create', { request_id: 'attempt-1', model: 'm' })+ const firstOutcome = first.catch((error: Error) => error)+ await vi.advanceTimersByTimeAsync(0)+ ack()+ await vi.advanceTimersByTimeAsync(0)+ answer('config.set', { error: { code: -32000, message: 'config refused' } })+ expect(await firstOutcome).toMatchObject({ message: 'config refused' })++ const retry = gw.request<{ session_id: string }>('session.create', { request_id: 'attempt-2', model: 'm' })+ await vi.advanceTimersByTimeAsync(0)+ ack()+ await vi.advanceTimersByTimeAsync(0)+ expect(last('config.set').params).toMatchObject({ key: 'verbose', session_id: 'orphan-1', value: 'verbose' })+ answer('config.set', { result: { key: 'verbose', value: 'verbose', scope: 'session' } })+ await expect(retry).resolves.toMatchObject({ session_id: 'orphan-1' })+ expect([...minted.values()]).toEqual(['orphan-1'])+ } finally { gw.kill(); vi.unstubAllEnvs(); vi.useRealTimers() }+ })+it('re-ensures a crashed owner on a bounded number of reconnects, then stays discovery-only', async () => {vi.useFakeTimers()delete process.env.HERMES_TUI_GATEWAY_URLdiff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex dfb1a54205a..9541ce6f4b6 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -7,6 +7,7 @@ import type { GatewayEvent } from '@hermes/shared/gateway-events'import {DEFAULT_HEARTBEAT_DEADLINE_MS,DEFAULT_HEARTBEAT_INTERVAL_MS,+ JsonRpcGatewayError,JsonRpcRequestChannel,type ServerRequest,wireFrameText@@ -184,6 +185,8 @@ export class GatewayClient extends EventEmitter {isCanonical = falseprivate creationContract?: CreationContractprivate describeFlight?: Promise<void>+ // The last session.create whose outcome is in doubt (see createCanonical).+ private unsettledCreate?: { key: string; requestId: unknown }constructor(private bootstrap: (start: boolean, recover?: boolean) => Promise<LocalGatewayGrant> = bootstrapLocalGateway@@ -880,9 +883,32 @@ export class GatewayClient extends EventEmitter {return (async () => {if (method === 'session.create' && !this.creationContract) { await this.describeRuntime() }const request = canonicalRequest(method, params, this.creationContract)- const toolProgress = method === 'session.create' ? launchToolProgress() : undefined++ if (request.method === 'session.create') { return this.createCanonical<T>(request.params, timeoutMs) }const value = await this.requestOverWebSocket<T>(request.method, request.params, timeoutMs)+ return canonicalResult(method, value, request.params)+ })()+ }++ /** session.create plus the launch tool-progress pin, as one outcome for the caller. The owner keys a+ * local session by request_id, so a create that failed after it may have committed (lost ACK, or the+ * pin refused after the ACK) is retried with the SAME request_id when the options match: the owner+ * answers with the session it already minted and the pin is reapplied, never a second session. */+ private async createCanonical<T>(prepared: Record<string, unknown>, timeoutMs?: number): Promise<T> {+ const toolProgress = launchToolProgress()+ const { request_id: _fresh, ...options } = prepared+ const key = JSON.stringify(Object.keys(options).sort().map(name => [name, options[name]]))+ const retry = this.unsettledCreate?.key === key ? this.unsettledCreate : undefined+ // Taken, not peeked: a concurrent create never shares an identity still in flight.+ this.unsettledCreate = undefined+ const params = retry ? { ...prepared, request_id: retry.requestId } : prepared+ let acknowledged = false++ try {+ const value = await this.requestOverWebSocket<T>('session.create', params, timeoutMs)+ acknowledged = true+if (toolProgress) {// Launch pin, before the caller can submit: a refusal fails this create visibly.const sid = (value as { session_id?: string } | null)?.session_id@@ -890,8 +916,16 @@ export class GatewayClient extends EventEmitter {await this.requestOverWebSocket('config.set', { key: 'verbose', session_id: sid, value: toolProgress })}- return canonicalResult(method, value, request.params)- })()+ return canonicalResult('session.create', value, params)+ } catch (error) {+ // An owner's error reply to the create itself is a definitive refusal (nothing to recover);+ // an ACKed create, a timeout or a dropped socket may have committed the session.+ if (acknowledged || !(error instanceof JsonRpcGatewayError)) {+ this.unsettledCreate = { key, requestId: params.request_id }+ }++ throw error+ }}kill(reason = 'requested') {