Skip to content

The agent that grows with you

fix: retain disconnected Ink input and canonical control receipts

Teknium1a5bae9bd1ab
diff --git a/ui-tui/src/__tests__/busyQueueAdmission.test.tsx b/ui-tui/src/__tests__/busyQueueAdmission.test.tsx
index 238fc1de90d..b5f2e4ee921 100644
--- a/ui-tui/src/__tests__/busyQueueAdmission.test.tsx
+++ b/ui-tui/src/__tests__/busyQueueAdmission.test.tsx
@@ -14,6 +14,8 @@ import { $uiState, patchUiState, resetUiState } from '../app/uiStore.js'
import { useSubmission } from '../app/useSubmission.js'
import { canonicalEvent, canonicalResult } from '../canonicalGateway.js'
import { useQueue } from '../hooks/useQueue.js'
+import { loadPendingInputs } from '../lib/pendingInputs.js'
+import { captureDestination } from '../app/submissionDestination.js'
// Canonical authority rows: `pending` carries the server-issued admission_id,
// the client's input_id and the public text under `ref` destination fields.
@@ -22,7 +24,7 @@ const row = (admission_id: string, input_id: string, text: string, status = 'que
ref: { profile_id: '/tmp/profile', session_id: 'stored-owner' }
})
-function mount(busyInputMode: 'queue' | 'interrupt' = 'queue') {
+function mount(busyInputMode: 'queue' | 'interrupt' | 'steer' = 'queue') {
const home = mkdtempSync(join(tmpdir(), 'ink-busy-admit-'))
vi.stubEnv('HERMES_HOME', home)
resetUiState()
@@ -140,6 +142,50 @@ it('deletes a server-queued row through prompt.cancel rather than local removal'
} finally { h.cleanup() }
})
+it('retains disconnected input durably on its old destination without dispatching or draining', async () => {
+ const h = mount()
+ try {
+ patchUiState({ gatewayConnected: false, busy: false } as any)
+ const destination = captureDestination()
+ h.submission.dispatchSubmission('DISCONNECTED_LOSS_SENTINEL')
+ await new Promise(resolve => setImmediate(resolve))
+ expect(h.calls).toEqual([])
+ expect(loadPendingInputs(destination)).toEqual([expect.objectContaining({ text: 'DISCONNECTED_LOSS_SENTINEL', destination })])
+ expect(h.queue.dequeue()).toBeUndefined()
+ } finally { h.cleanup() }
+})
+
+it('discards unknown execution with its generation, retaining the row on refusal', async () => {
+ const h = mount()
+ try {
+ h.request.mockImplementation(async (method, params) => { h.calls.push({method, params}); throw new Error('stale_generation') })
+ h.fanout([{ ...row('unknown-admission', 'unknown-input', 'interrupted input', 'unknown'), execution_generation: 7 }])
+ await expect.poll(() => h.queue.queuedDisplay).toEqual(['[unknown] interrupted input'])
+ h.queue.removeQ(0)
+ await expect.poll(() => h.calls.length).toBe(1)
+ expect(h.calls[0]).toEqual({ method: 'prompt.resolve_unknown', params: { session_id: 'owner', admission_id: 'unknown-admission', execution_generation: 7 } })
+ await expect.poll(() => $uiState.get().status).toContain('stale_generation')
+ expect(h.queue.queuedDisplay).toEqual(['[unknown] interrupted input'])
+ } finally { h.cleanup() }
+})
+
+it('preserves requested busy correction and generation through ambiguous retry without queue fallback', async () => {
+ const h = mount('steer')
+ try {
+ h.request.mockImplementation(async (method, params) => { h.calls.push({ method, params }); throw new Error('invalid_params') })
+ h.submission.dispatchSubmission('correction')
+ await expect.poll(() => h.calls.length).toBe(1)
+ expect(h.calls[0]).toMatchObject({ method: 'session.steer', params: { session_id: 'owner', text: 'correction', execution_generation: 1 } })
+ const first = h.calls[0]!.params
+ await expect.poll(() => h.queue.queueRef.current[0]?.failed).toBe(true)
+ patchUiState({ busyInputMode: 'interrupt', info: { ...$uiState.get().info!, execution_generation: 2 } })
+ h.submission.sendQueued(h.queue.dequeue(true)!)
+ await expect.poll(() => h.calls.length).toBe(2)
+ expect(h.calls[1]).toEqual({ method: 'session.steer', params: first })
+ expect(loadPendingInputs(captureDestination())[0]).toMatchObject({ controlMethod: 'session.steer', executionGeneration: 1 })
+ } finally { h.cleanup() }
+})
+
it('projects canonical pending rows onto the legacy pending_submissions shape for resume snapshots and fanout', () => {
const pending = [row('adm-3', 'in-3', 'hello')]
diff --git a/ui-tui/src/__tests__/gatewayClient.test.ts b/ui-tui/src/__tests__/gatewayClient.test.ts
index 967ee82a3a0..d162a647c16 100644
--- a/ui-tui/src/__tests__/gatewayClient.test.ts
+++ b/ui-tui/src/__tests__/gatewayClient.test.ts
@@ -166,6 +166,32 @@ describe('GatewayClient websocket attach mode', () => {
}
})
+ it('keeps discovery-only retries alive and delivers readiness to the mounted subscriber', async () => {
+ vi.useFakeTimers()
+ delete process.env.HERMES_TUI_GATEWAY_URL
+ const grant = { url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }
+ const bootstrap = vi.fn().mockResolvedValueOnce(grant).mockRejectedValueOnce(new Error('owner stopped')).mockRejectedValueOnce(new Error('owner stopped')).mockResolvedValue(grant)
+ const gw = new GatewayClient(bootstrap)
+ const events: any[] = []
+ gw.on('event', event => events.push(event))
+ try {
+ gw.start(); gw.drain()
+ await vi.advanceTimersByTimeAsync(0)
+ FakeWebSocket.instances[0]!.open()
+ await vi.advanceTimersByTimeAsync(0)
+ FakeWebSocket.instances[0]!.close()
+ await vi.advanceTimersByTimeAsync(RECONNECT_MAX_MS * 4)
+ expect(bootstrap.mock.calls.map(args => args[0])).toEqual([true, false, false, false])
+ const socket = FakeWebSocket.instances.at(-1)!
+ socket.open()
+ await vi.advanceTimersByTimeAsync(0)
+ const request = JSON.parse(socket.sent[0]!)
+ socket.message(JSON.stringify({ id: request.id, result: { session_create: { sources: ['tui'], parameters: [] } } }))
+ await vi.advanceTimersByTimeAsync(0)
+ expect(events.some(event => event.type === 'gateway.ready')).toBe(true)
+ } finally { gw.kill(); vi.useRealTimers() }
+ })
+
it('waits for websocket open and resolves RPC requests', async () => {
process.env.HERMES_TUI_GATEWAY_URL = 'ws://gateway.test/api/ws?token=abc'
const gw = new GatewayClient()
diff --git a/ui-tui/src/__tests__/useSubmission.test.ts b/ui-tui/src/__tests__/useSubmission.test.ts
index 6d7f1fdf25d..3bfa0580755 100644
--- a/ui-tui/src/__tests__/useSubmission.test.ts
+++ b/ui-tui/src/__tests__/useSubmission.test.ts
@@ -9,6 +9,7 @@ describe('prepareSubmission', () => {
const tokens: ComposerToken[] = [{ kind: 'paste', label, text: 'first\nmiddle\nlast' }]
expect(prepareSubmission(`review this: ${label}`, tokens)).toEqual({
+ attachments: [],
display: `review this: ${label}`,
text: 'review this: first\nmiddle\nlast'
})
diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.ts
index e96b010cd23..5cae26f3b43 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -15,6 +15,7 @@ import type {
} from '../gatewayTypes.js'
import { billingDialogCopy } from '../lib/billingDialog.js'
import { relativeLuminance } from '../lib/color.js'
+import { stageImagePath, type ImageAttachment } from '../lib/imageAttachments.js'
import { isTodoDone } from '../lib/liveProgress.js'
import { openExternalUrl } from '../lib/openExternalUrl.js'
import { rpcErrorMessage } from '../lib/rpc.js'
@@ -420,7 +421,7 @@ const normalizeSubagentStatus = (status: unknown, fallback: SubagentStatus): Sub
export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev: GatewayEvent) => void {
syncThemeToTerminalBackground()
- const { rpc } = ctx.gateway
+ const { gw, rpc } = ctx.gateway
const { STARTUP_RESUME_ID, newSession, recoverSidRef, resumeById, setCatalog } = ctx.session
const { bellOnComplete, bellOnPrompt, stdout, sys } = ctx.system
@@ -638,18 +639,27 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:
return sys('startup query skipped: no active session')
}
+ const destination = captureDestination()
+ const attachments: ImageAttachment[] = []
+
if (STARTUP_IMAGE) {
try {
- await rpc('image.attach', { path: STARTUP_IMAGE, session_id: sid })
+ if (gw.isCanonical) {
+ const image = await stageImagePath(STARTUP_IMAGE, gw, destination)
+ attachments.push({ path: image.path, mime: image.mime })
+ } else {
+ await rpc('image.attach', { path: STARTUP_IMAGE, session_id: sid })
+ }
} catch (e) {
- sys(`startup image attach failed: ${rpcErrorMessage(e)}`)
+ return sys(`startup image attach failed: ${rpcErrorMessage(e)}`)
}
}
// Startup queries are arbitrary launcher/script text (Omarchy prompted
// launches, `hermes --tui -q "…"`) — submit LITERALLY, bypassing the
// slash/!/interpolation dispatcher, matching one-shot's semantics.
- submitLiteralRef.current(STARTUP_QUERY || 'What do you see in this image?')
+ if (!isCurrentDestination(destination)) { return sys('startup query skipped: active session changed') }
+ submitLiteralRef.current(STARTUP_QUERY || 'What do you see in this image?', attachments)
}, 0)
}
diff --git a/ui-tui/src/app/interfaces.ts b/ui-tui/src/app/interfaces.ts
index 83d971d69d2..f8dac1a81d9 100644
--- a/ui-tui/src/app/interfaces.ts
+++ b/ui-tui/src/app/interfaces.ts
@@ -318,6 +318,7 @@ export interface TranscriptRow {
}
export interface UiState {
+ gatewayConnected?: boolean
battery: boolean
batteryStatus: BatteryInfo | null
bgTasks: Set<string>
@@ -384,7 +385,7 @@ export interface ComposerActions {
clearIn: () => void
stage?: (text: string, display?: string, destination?: SubmissionDestination) => QueueItem
dequeue: (retry?: boolean) => QueueItem | undefined
- enqueue: (text: string, display?: string, destination?: SubmissionDestination) => void
+ enqueue: (text: string, display?: string, destination?: SubmissionDestination) => QueueItem | void
handleTextPaste: (event: PasteEvent) => MaybePromise<ComposerPasteResult | null>
openEditor: () => Promise<void>
prependQueue: (item: QueueItem, destination?: SubmissionDestination) => void
@@ -499,7 +500,7 @@ export interface GatewayEventHandlerContext {
/** Submit text literally as a prompt — no slash/!/interpolation dispatch.
* Used for `-q` startup queries, which are arbitrary launcher-provided
* text (parity with one-shot's literal prompt handling). */
- submitLiteralRef: MutableRefObject<(value: string) => void>
+ submitLiteralRef: MutableRefObject<(value: string, attachments?: Array<{ path: string; mime: string }>) => void>
submitRef: MutableRefObject<(value: string) => void>
}
system: {
diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.ts
index 82c18a8fedb..1600c195cf4 100644
--- a/ui-tui/src/app/submissionCore.ts
+++ b/ui-tui/src/app/submissionCore.ts
@@ -114,11 +114,12 @@ export function submitPrompt(
}
deps.gw
- .request<PromptSubmitResponse>('prompt.submit', {
+ .request<PromptSubmitResponse>(item?.controlMethod ?? 'prompt.submit', {
session_id: sid,
text: item?.preparedText ?? submitText,
...((item?.attachments ?? opts.attachments)?.length ? { attachments: item?.attachments ?? opts.attachments } : {}),
- ...(item ? { submission_id: item.submissionId, queued: item.queued !== false } : {})
+ ...(item?.controlMethod ? { execution_generation: item.executionGeneration } : {}),
+ ...(item ? { submission_id: item.submissionId, ...(item.controlMethod ? {} : { queued: item.queued !== false }) } : {})
})
.then(r => {
if (item) {
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index d3866fc3f09..a76bebd051c 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -239,7 +239,7 @@ export function useMainApp(gw: GatewayClient) {
const onEventRef = useRef<(ev: GatewayEvent) => void>(() => {})
const sysRef = useRef<(text: string) => void>(() => {})
const submitRef = useRef<(value: string) => void>(() => {})
- const submitLiteralRef = useRef<(value: string) => void>(() => {})
+ const submitLiteralRef = useRef<(value: string, attachments?: Array<{ path: string; mime: string }>) => void>(() => {})
const terminalHintsShownRef = useRef(new Set<string>())
const historyItemsRef = useRef(historyItems)
const lastUserMsgRef = useRef(lastUserMsg)
@@ -833,6 +833,7 @@ export function useMainApp(gw: GatewayClient) {
useEffect(() => {
if (
!ui.sid ||
+ ui.gatewayConnected === false ||
ui.busy ||
composerRefs.queueEditRef.current !== null ||
composerRefs.queueRef.current.length === 0
@@ -846,7 +847,7 @@ export function useMainApp(gw: GatewayClient) {
patchUiState({ busy: true, status: 'running…' })
sendQueued(next)
}
- }, [ui.sid, ui.busy, composerActions, composerRefs, sendQueued])
+ }, [ui.sid, ui.busy, ui.gatewayConnected, composerActions, composerRefs, sendQueued])
const { pagerPageSize } = useInputHandlers({
actions: {
@@ -927,28 +928,18 @@ export function useMainApp(gw: GatewayClient) {
const exitHandler = () => {
turnController.reset()
- // A still-owned child dying while the TUI is alive is an *unexpected*
- // death — a user /quit exits Node before this fires, and a replaced child
- // is identity-skipped in GatewayClient. Rather than stranding a long
- // session (the user's complaint), respawn the gateway and resume the
- // persisted session via the next gateway.ready, so a single crash / OOM /
- // signal doesn't lose their work. planGatewayRecovery bounds the attempts
- // so a gateway that crash-loops on startup can't spawn-storm, and falls
- // back to recoverSidRef when sid was already cleared by a prior exit.
+ // Keep the old destination for durable offline input; discovery retries
+ // must never silently create a replacement for an ended session.
const plan = planGatewayRecovery(getUiState().sid, recoverSidRef.current, recoveryAtRef.current, Date.now())
- // Clear sid immediately: while the gateway is down, sid-guarded effects
- // (session.active_list poll, queue drain) would otherwise fire RPCs at a
- // dead/respawning gateway. recoverSidRef carries the session forward, and
- // resumeById restores sid once the fresh gateway is ready.
recoveryAtRef.current = plan.attempts
- patchUiState({ busy: false, compacting: false, sid: null, status: 'gateway exited' })
+ patchUiState({ busy: false, compacting: false, gatewayConnected: false, status: 'gateway exited' })
- if (plan.recover && plan.sid) {
+ if (plan.sid) {
recoverSidRef.current = plan.sid
turnController.pushActivity('gateway exited · recovering session…', 'warn')
sys('gateway exited — recovering your session (any in-flight reply was lost)')
- gw.start()
+ // GatewayClient retries discovery without starting a stopped owner.
return
}
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 2f13963b9e3..d35baae05ec 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -396,6 +396,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
busy: running,
info,
sid: r.session_id,
+ gatewayConnected: true,
status: statusFromLiveSession(r.status, running),
usage: usageFrom(info)
})
diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.ts
index bb7913065dc..b0aa9a7cb84 100644
--- a/ui-tui/src/app/useSubmission.ts
+++ b/ui-tui/src/app/useSubmission.ts
@@ -1,12 +1,13 @@
import { type MutableRefObject, useCallback, useEffect, useRef } from 'react'
import { TYPING_IDLE_MS } from '../config/timing.js'
-import { expandTokens } from '../domain/attachments.js'
+import { expandTokens, imageAttachments } from '../domain/attachments.js'
import { completionToApplyOnSubmit, looksLikeSlashCommand, parseSlashCommand } from '../domain/slash.js'
import type { GatewayClient } from '../gatewayClient.js'
import type { ShellExecResponse } from '../gatewayTypes.js'
import { queueItem, type QueueItem } from '../hooks/useQueue.js'
import { asRpcResult } from '../lib/rpc.js'
+import { savePendingInput } from '../lib/pendingInputs.js'
import { hasInterpolation, INTERPOLATION_RE } from '../protocol/interpolation.js'
import type { Msg } from '../types.js'
@@ -38,7 +39,8 @@ export const queueItemFromSlash = (displayCommand: string, expandedCommand: stri
export const prepareSubmission = (display: string, tokens: ComposerToken[]) => ({
display,
- text: expandTokens(tokens)(display)
+ text: expandTokens(tokens)(display),
+ attachments: imageAttachments(display, tokens)
})
/**
@@ -103,7 +105,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
showUserMessage = true,
displayText?: string,
expandOverride?: (value: string) => string,
- submitOpts: { skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem; behindTurn?: boolean } = {}
+ submitOpts: { attachments?: Array<{ path: string; mime: string }>; skipDetectDrop?: boolean; destination?: SubmissionDestination; queueItem?: QueueItem; behindTurn?: boolean } = {}
) => {
// Read tokens off the ref, not render state: a paste immediately followed
// by Enter submits before React has re-rendered with the new token.
@@ -252,13 +254,23 @@ export function useSubmission(opts: UseSubmissionOptions) {
}
}
+ if (gw.isCanonical && mode !== 'queue') {
+ const staged = item.settle ? item : composerActions.stage?.(item.text, item.display, destination)
+ if (!staged) { return }
+ staged.controlMethod ??= mode === 'steer' ? 'session.steer' : 'session.redirect'
+ staged.executionGeneration ??= live.info?.execution_generation
+ staged.attachments ??= item.attachments
+ return send(item.text, true, item.display, value => value, {
+ destination, behindTurn: true, queueItem: staged, attachments: item.attachments })
+ }
+
if (mode === 'queue') {
// Canonical authority: admit now so the input is crash-durable and in
// every viewer's pending list; the server FIFO orders it behind the
// running turn. Legacy gateways keep the renderer-side queue.
if (gw.isCanonical) {
return send(item.text, true, item.display, value => value, {
- destination, behindTurn: true, queueItem: item.settle ? item : undefined })
+ destination, behindTurn: true, queueItem: item.settle ? item : undefined, attachments: item.attachments })
}
return enqueueText()
@@ -272,7 +284,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
// the agent is in model generation, tool execution, or an older runtime.
// Reuse the normal submit pipeline so the correction gets its user bubble
// and file-drop interpolation exactly once.
- send(item.text, true, item.display, value => value, { destination, queueItem: item.settle ? item : undefined })
+ send(item.text, true, item.display, value => value, { destination, queueItem: item.settle ? item : undefined, attachments: item.attachments })
},
[composerActions, gw, send]
)
@@ -314,7 +326,8 @@ export function useSubmission(opts: UseSubmissionOptions) {
composerActions.clearIn()
if (queued) {
- composerActions.enqueue(queued.text, queued.display)
+ const retained = composerActions.enqueue(queued.text, queued.display, destination)
+ if (retained) { retained.attachments = submission.attachments; savePendingInput(retained) }
sys(`queued: "${queued.display.slice(0, 50)}${queued.display.length > 50 ? '…' : ''}"`)
} else {
slashRef.current(slash.command)
@@ -331,9 +344,10 @@ export function useSubmission(opts: UseSubmissionOptions) {
const live = getUiState()
- if (!live.sid) {
+ if (!live.sid || live.gatewayConnected === false) {
composerActions.pushHistory(toHistory)
- composerActions.enqueue(submission.text, submission.display)
+ const retained = composerActions.enqueue(submission.text, submission.display, destination)
+ if (retained) { retained.attachments = submission.attachments; savePendingInput(retained) }
composerActions.clearIn()
return
@@ -367,7 +381,7 @@ export function useSubmission(opts: UseSubmissionOptions) {
composerActions.pushHistory(toHistory)
if (getUiState().busy) {
- return handleBusyInput(queueItem(submission.text, submission.display))
+ return handleBusyInput({ ...queueItem(submission.text, submission.display), attachments: submission.attachments })
}
if (shouldInterpolateSubmission(full)) {
@@ -380,13 +394,13 @@ export function useSubmission(opts: UseSubmissionOptions) {
text =>
send(prepareSubmission(text, submissionTokens).text, true, text, value => value, {
destination,
- queueItem: item
+ queueItem: item, attachments: submission.attachments
}),
destination
)
}
- send(submission.text, true, submission.display, value => value)
+ send(submission.text, true, submission.display, value => value, { attachments: submission.attachments })
},
[
appendMessage,
@@ -459,12 +473,12 @@ export function useSubmission(opts: UseSubmissionOptions) {
// $(...) interpolation. Startup `-q` queries use this — they're arbitrary
// launcher/script text, and one-shot mode already treats them literally.
const submitLiteral = useCallback(
- (value: string) => {
+ (value: string, attachments?: Array<{ path: string; mime: string }>) => {
if (!value.trim()) {
return
}
- send(value, true, value, v => v, { skipDetectDrop: true })
+ send(value, true, value, v => v, { skipDetectDrop: true, attachments })
},
[send]
)
diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.ts
index a74b22d551f..02d8f0d0217 100644
--- a/ui-tui/src/canonicalGateway.ts
+++ b/ui-tui/src/canonicalGateway.ts
@@ -19,7 +19,7 @@ export function canonicalRequest(method: string, original: Record<string, unknow
if (unsupported.length) { throw new Error(`gateway does not support TUI launch options: ${unsupported.join(', ')}`) }
}
- if (method === 'prompt.submit' && params.submission_id) {
+ if (['prompt.submit', 'session.steer', 'session.redirect'].includes(method) && params.submission_id) {
params.input_id = params.submission_id
delete params.submission_id
}
@@ -38,7 +38,7 @@ export function canonicalResult(method: string, value: any, request: Record<stri
// The JSON-RPC response correlates the prepared input; admission_id is a
// separate server-issued identity and must not be rewritten to that input ID.
- if (method === 'prompt.submit' && value.ref) {
+ if (['prompt.submit', 'session.steer', 'session.redirect'].includes(method) && value.ref) {
return { ...value, input_id: request.input_id, target_profile_home: value.ref.profile_id, target_session_id: value.ref.session_id }
}
diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.ts
index 6779619d713..2bb88a2c987 100644
--- a/ui-tui/src/gatewayClient.ts
+++ b/ui-tui/src/gatewayClient.ts
@@ -328,6 +328,7 @@ export class GatewayClient extends EventEmitter {
}
this.start()
+ this.drain()
}, delay)
this.reconnectTimer.unref?.()
}
@@ -506,6 +507,7 @@ export class GatewayClient extends EventEmitter {
python: 'gateway ensure', cwd: '', stderr_tail: this.bootstrapError.message
} })
this.rejectPending(this.bootstrapError)
+ this.scheduleReconnect()
})
}
@@ -685,9 +687,9 @@ export class GatewayClient extends EventEmitter {
}
private toError(raw: unknown): Error {
- const err = raw as { message?: unknown } | null | undefined
+ const err = raw as { message?: unknown; code?: unknown; data?: unknown } | null | undefined
- return new Error(typeof err?.message === 'string' ? err.message : 'request failed')
+ 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) {
diff --git a/ui-tui/src/hooks/useQueue.ts b/ui-tui/src/hooks/useQueue.ts
index 273caaa5998..491d8cd7b06 100644
--- a/ui-tui/src/hooks/useQueue.ts
+++ b/ui-tui/src/hooks/useQueue.ts
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { isServerQueued } from '../app/pendingBubbles.js'
import { captureDestination, type SubmissionDestination } from '../app/submissionDestination.js'
-import { $uiState, getUiState } from '../app/uiStore.js'
+import { $uiState, getUiState, patchUiState } from '../app/uiStore.js'
import {
loadPendingInputs,
pendingDestinationKey,
@@ -25,6 +25,9 @@ export interface QueueItem {
ownerDestination?: SubmissionDestination
inFlight?: boolean
failed?: boolean
+ attachments?: Array<{ path: string; mime: string }>
+ controlMethod?: 'session.steer' | 'session.redirect'
+ executionGeneration?: number
preparedText?: string
legacyAttempted?: boolean
settle?: (accepted: boolean) => void
@@ -203,8 +206,15 @@ export function useQueue(gw?: { request: (method: string, params: Record<string,
)
const cancelServerRow = useCallback(
- (row: { admission_id: string }) => {
- void gw?.request('prompt.cancel', { session_id: getUiState().sid, admission_id: row.admission_id }).catch(() => {})
+ (row: { admission_id: string; status?: string; execution_generation?: number | null }) => {
+ const session_id = getUiState().sid
+ const unknown = row.status === 'unknown'
+ void gw?.request(unknown ? 'prompt.resolve_unknown' : 'prompt.cancel', {
+ session_id, admission_id: row.admission_id,
+ ...(unknown ? { execution_generation: row.execution_generation } : {})
+ }).catch((error: Error) => {
+ if (getUiState().sid === session_id) { patchUiState({ status: `discard failed: ${error.message}` }) }
+ })
},
[gw]
)
@@ -338,6 +348,7 @@ export function useQueue(gw?: { request: (method: string, params: Record<string,
const dequeue = useCallback(
(retry = false) => {
+ if (getUiState().gatewayConnected === false) { return undefined }
const queue = getQueue()
const item = queue.items[0]
@@ -358,6 +369,10 @@ export function useQueue(gw?: { request: (method: string, params: Record<string,
// Editing a durable row re-admits the edited text as a new input; the
// authority retires the original.
if (server) {
+ if (server.status === 'unknown') {
+ patchUiState({ status: 'unknown execution — Ctrl+X to discard before retrying' })
+ return undefined
+ }
cancelServerRow(server)
const item = queueItem(editedDisplay ?? server.user)
queue.items.push(item)
diff --git a/ui-tui/src/lib/pendingInputs.ts b/ui-tui/src/lib/pendingInputs.ts
index c0bc3e8bb3e..212c9ab7e13 100644
--- a/ui-tui/src/lib/pendingInputs.ts
+++ b/ui-tui/src/lib/pendingInputs.ts
@@ -94,7 +94,7 @@ export function savePendingInput(item: QueueItem): void {
const path = join(dir, `${item.submissionId}.json`)
const temporary = `${path}.${process.pid}.tmp`
const ownerDestination = pendingInputOwner(item.ownerDestination ?? item.destination)
- const { submissionId, display, text, preparedText, attachments, inFlight, failed, createdAt, queued, legacyAttempted } = item
+ const { submissionId, display, text, preparedText, attachments, controlMethod, executionGeneration, inFlight, failed, createdAt, queued, legacyAttempted } = item
const destination = inFlight || failed ? item.destination : ownerDestination
writeFileSync(
temporary,
@@ -106,6 +106,8 @@ export function savePendingInput(item: QueueItem): void {
text,
preparedText,
attachments,
+ controlMethod,
+ executionGeneration,
legacyAttempted,
createdAt,
queued,