Skip to content

The agent that grows with you

fix(ink): finish the gatewayClient merge onto the shared JsonRpcRequestChannel

teknium198f83a16aa1b
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index 852bfc3157a..860ad3fec47 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -17,7 +17,6 @@ import type {
SessionMostRecentResponse
} from '../gatewayTypes.js'
import { billingDialogCopy } from '../lib/billingDialog.js'
-import { relativeLuminance } from '../lib/color.js'
import { type ImageAttachment, stageImagePath } from '../lib/imageAttachments.js'
import { isTodoDone } from '../lib/liveProgress.js'
import { openExternalUrl } from '../lib/openExternalUrl.js'
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index 68864b2043e..fe7a90c662f 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -3,7 +3,7 @@ import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import { TYPING_IDLE_MS } from '../config/timing.js'
import { expandTokens, imageAttachments } from '../domain/attachments.js'
-import { completionToApplyOnSubmit, looksLikeSlashCommand, parseSlashCommand } from '../domain/slash.js'
+import { completionToApplyOnSubmit } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type { ShellExecResponse } from '../gatewayTypes.js'
import { queueItem, type QueueItem } from '../hooks/useQueue.js'
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index 43c0f367478..208214f7baf 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -112,14 +112,6 @@ const redactUrl = (raw: string): string => {
}
}
-interface Pending {
- id: string
- method: string
- reject: (e: Error) => void
- resolve: (v: unknown) => void
- timeout: ReturnType<typeof setTimeout>
-}
-
export interface LocalGatewayGrant { url: string; protocols: string[]; profile_id: string; instance_id: string }
const bootstrapLocalGateway = async (start: boolean): Promise<LocalGatewayGrant> => {
@@ -144,7 +136,7 @@ export class GatewayClient extends EventEmitter {
// only owns the two transports (child stdio, attached socket) and the
// buffered-event replay that Ink's mount order needs.
private readonly channel = new JsonRpcRequestChannel({
- onEvent: ev => this.publish(ev as AnyGatewayEvent),
+ onEvent: ev => this.publishWire(ev as AnyGatewayEvent),
onHeartbeatFailure: () => this.onHeartbeatFailure(),
requestTimeoutMs: REQUEST_TIMEOUT_MS,
unrefTimers: true
@@ -155,7 +147,6 @@ export class GatewayClient extends EventEmitter {
private readyTimer: ReturnType<typeof setTimeout> | null = null
private subscribed = false
private drainGeneration = 0
- private heartbeatTimer: ReturnType<typeof setInterval> | null = null
private reconnectTimer: ReturnType<typeof setTimeout> | null = null
private reconnectAttempts = 0
// Set on kill() so we never auto-reconnect after an intentional shutdown.
@@ -175,6 +166,29 @@ export class GatewayClient extends EventEmitter {
this.setMaxListeners(0)
}
+ /** Frames off the socket. On a canonical gateway the owner's execution stamp rides on
+ * the params (`authority_epoch`/`execution_generation`); fold it into the payload the
+ * pre-cutover handlers read, and let this client own readiness (it publishes
+ * `gateway.ready` itself after `runtime.describe`, so the listener's ready would be a
+ * second one) while still negotiating the transport's heartbeat capability. */
+ private publishWire(ev: AnyGatewayEvent) {
+ if (this.isCanonical && ev.type === 'gateway.ready') {
+ if ((ev as GatewayEvent<'gateway.ready'>).payload?.heartbeat && this.ws?.readyState === WS_OPEN) {
+ this.channel.startHeartbeat()
+ }
+
+ return
+ }
+
+ if (this.isCanonical) {
+ const shared = ev as AnyGatewayEvent & { authority_epoch?: number; execution_generation?: number }
+ ev.payload = { ...canonicalEvent(ev).payload, execution_epoch: String(shared.authority_epoch),
+ execution_generation: shared.execution_generation } as never
+ }
+
+ this.publish(ev)
+ }
+
private publish(ev: AnyGatewayEvent) {
if (ev.type === 'gateway.ready') {
this.ready = true
@@ -290,7 +304,7 @@ export class GatewayClient extends EventEmitter {
// Reject any in-flight RPCs left over from the previous transport
// before we swap. Otherwise the old transport's stale exit/close
// handlers (now identity-gated to ignore unrelated transports)
- // never fire `rejectPending`, leaving callers hanging on promises
+ // never settle the channel's pending RPCs, leaving callers hanging on promises
// attached to a discarded child / socket.
this.channel.detach(new Error('gateway restarting'))
this.ready = false
@@ -453,7 +467,7 @@ export class GatewayClient extends EventEmitter {
this.publish({ type: 'gateway.start_timeout', payload: {
python: 'gateway ensure', cwd: '', stderr_tail: this.bootstrapError.message
} })
- this.rejectPending(this.bootstrapError)
+ this.channel.detach(this.bootstrapError)
this.scheduleReconnect()
})
}
@@ -598,67 +612,6 @@ export class GatewayClient extends EventEmitter {
this.startLocalGateway()
}
- private dispatch(msg: Record<string, unknown>) {
- const id = msg.id as string | undefined
-
- if (id && id === this.heartbeatPendingId) {
- this.heartbeatPendingId = null
- this.heartbeatSentAt = 0
-
- return
- }
-
- const p = id ? this.pending.get(id) : undefined
-
- if (p) {
- this.settle(p, msg.error ? this.toError(msg.error) : null, msg.result)
-
- return
- }
-
- if (msg.method === 'event') {
- const ev = asGatewayEvent(msg.params)
-
- if (ev) {
- // The canonical client owns readiness after runtime.describe. Forwarding
- // the listener's legacy ready as well creates two sessions/startup turns,
- // but its transport capabilities still have to be negotiated.
- if (this.isCanonical && ev.type === 'gateway.ready') {
- if (ev.payload?.heartbeat && this.ws?.readyState === WS_OPEN) {
- this.startHeartbeat(this.ws)
- }
-
- return
- }
-
- if (this.isCanonical) {
- const shared = ev as GatewayEvent & { authority_epoch?: number; execution_generation?: number }
- ev.payload = { ...canonicalEvent(ev).payload, execution_epoch: String(shared.authority_epoch),
- execution_generation: shared.execution_generation } as any
- }
-
- this.publish(ev)
- }
- }
- }
-
- private toError(raw: unknown): Error {
- const err = raw as { message?: unknown; code?: unknown; data?: unknown } | null | undefined
-
- return Object.assign(new Error(typeof err?.message === 'string' ? err.message : 'request failed'), { code: err?.code, data: err?.data })
- }
-
- private settle(p: Pending, err: Error | null, result: unknown) {
- clearTimeout(p.timeout)
- this.pending.delete(p.id)
-
- if (err) {
- p.reject(err)
- } else {
- p.resolve(result)
- }
- }
-
private pushLog(line: string) {
this.logs.push(truncateLine(line))
}
@@ -749,6 +702,11 @@ export class GatewayClient extends EventEmitter {
private notConnected = (method: string) => new Error(`gateway not connected: ${method}`)
+ private requestOverWebSocket<T = unknown>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number): Promise<T> {
+ return this.ensureAttachedWebSocket(method).then(() =>
+ this.channel.request<T>(method, params, timeoutMs, undefined, () => this.notConnected(method)))
+ }
+
request<T = unknown>(method: string, params: Record<string, unknown> = {}, timeoutMs?: number): Promise<T> {
const attachUrl = resolveGatewayAttachUrl()
@@ -762,9 +720,7 @@ export class GatewayClient extends EventEmitter {
this.start()
}
- return this.ensureAttachedWebSocket(method).then(() =>
- this.channel.request<T>(method, params, timeoutMs, undefined, () => this.notConnected(method))
- )
+ return this.requestOverWebSocket<T>(method, params, timeoutMs)
}
if (!this.bootstrapFlight) { this.start() }
@@ -773,7 +729,8 @@ export class GatewayClient extends EventEmitter {
if (this.bootstrapError) { throw this.bootstrapError }
const request = canonicalRequest(method, params, this.creationContract)
- return this.requestOverWebSocket<T>(request.method, request.params).then(value => canonicalResult(method, value, request.params))
+ return this.requestOverWebSocket<T>(request.method, request.params, timeoutMs)
+ .then(value => canonicalResult(method, value, request.params))
})
}
@@ -781,7 +738,7 @@ export class GatewayClient extends EventEmitter {
this.disposed = true
this.localGeneration++
this.clearReconnect()
- this.stopHeartbeat()
+ this.channel.stopHeartbeat()
this.lifecycle(`[lifecycle] GatewayClient.kill reason=${reason} (detach only)`)
this.closeGatewaySocket()
this.closeSidecarSocket()