The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): fence a resume/activate snapshot against fanout frames that beat the reply
Tekniuma8cf0f7174a4
diff --git a/ui-tui/src/__tests__/inkResumeSnapshotFence.test.tsx b/ui-tui/src/__tests__/inkResumeSnapshotFence.test.tsxnew file mode 100644index 00000000000..ca5e9eb06b5--- /dev/null+++ b/ui-tui/src/__tests__/inkResumeSnapshotFence.test.tsx@@ -0,0 +1,99 @@+import { PassThrough } from 'node:stream'++import { renderSync, Text } from '@hermes/ink'+import React from 'react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++const { FakeWebSocket } = vi.hoisted(() => {+ class FakeWebSocket {+ static OPEN = 1+ static CLOSED = 3+ static instances: FakeWebSocket[] = []+ readyState = 0+ sent: string[] = []+ private listeners = new Map<string, Array<(event: any) => void>>()++ constructor(readonly url: string) { FakeWebSocket.instances.push(this) }++ addEventListener(type: string, callback: (event: any) => void) { this.listeners.set(type, [...(this.listeners.get(type) ?? []), callback]) }++ removeEventListener() {}++ send(payload: string) { this.sent.push(payload) }++ close(code = 1000) { this.readyState = FakeWebSocket.CLOSED; this.emit('close', { code }) }++ open() { this.readyState = FakeWebSocket.OPEN; this.emit('open', {}) }++ message(data: string) { this.emit('message', { data }) }++ private emit(type: string, event: any) { for (const callback of this.listeners.get(type) ?? []) { callback(event) } }+ }++ return { FakeWebSocket }+})++vi.mock('undici', () => ({ WebSocket: FakeWebSocket }))++import { getUiState, resetUiState } from '../app/uiStore.js'+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'+import { GatewayClient } from '../gatewayClient.js'++const originalWebSocket = globalThis.WebSocket+beforeEach(() => { (globalThis as { WebSocket?: unknown }).WebSocket = FakeWebSocket as unknown as typeof WebSocket })+afterEach(() => { FakeWebSocket.instances = []; vi.useRealTimers(); resetUiState(); (globalThis as { WebSocket?: unknown }).WebSocket = originalWebSocket })++// B2-19: fanout frames published after the owner's resume snapshot can reach the socket before the+// resume reply. Ink holds the session's frames during the attach and, after applying the snapshot,+// replays only those after it (same replay_epoch, seq > last_sequence): the turn's completion is not+// lost to the snapshot's running:true, and frames the snapshot already contains are not applied twice.+it('a completion that beats the resume reply is replayed after the snapshot, covered frames are dropped', async () => {+ vi.useFakeTimers()+ delete process.env.HERMES_TUI_GATEWAY_URL+ delete process.env.HERMES_TUI_SIDECAR_URL+ const gw = new GatewayClient(async () => ({ url: 'ws://gateway.test/api/ws', protocols: [], instance_id: 'owner', profile_id: 'fixture' }))+ const events: any[] = []+ gw.on('event', event => events.push(event))+ let lifecycle!: ReturnType<typeof useSessionLifecycle>+ const history: unknown[][] = []++ function Harness() {+ lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() }, gw, rpc: vi.fn(),+ scrollRef: { current: null }, panel: vi.fn(), sys: vi.fn(), setHistoryItems: (items: unknown[]) => history.push(items),+ setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(), setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)++ return <Text>session</Text>+ }++ const instance = renderSync(<Harness />, { stdin: new PassThrough() as any,+ stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any, stderr: new PassThrough() as any, patchConsole: false })++ 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 })+ const reply = (method: string, result: unknown) => socket.message(JSON.stringify({ jsonrpc: '2.0', id: frames().find(f => f.method === method)!.id, result }))+ reply('runtime.describe', { session_create: { sources: ['tui'], parameters: [] } })+ await vi.advanceTimersByTimeAsync(0)++ lifecycle.resumeById('s')+ await vi.advanceTimersByTimeAsync(0)++ const fanout = (type: string, seq: number, payload: Record<string, unknown>) => socket.message(JSON.stringify({ jsonrpc: '2.0', method: 'event',+ params: { type, session_id: 's', replay_epoch: 'r1', seq, authority_epoch: 1, execution_generation: 2, payload } }))++ fanout('message.delta', 5, { text: 'already in the snapshot' })+ fanout('message.complete', 6, { text: 'final answer' })+ await vi.advanceTimersByTimeAsync(0)+ expect(events.filter(event => event.session_id === 's')).toEqual([])++ reply('session.resume', { session_id: 's', stored_session_id: 's', running: true, authority_epoch: 1, execution_generation: 2,+ replay_epoch: 'r1', last_sequence: 5, messages: [], prompts: [], info: {} })+ await vi.advanceTimersByTimeAsync(0)+ expect(getUiState().sid).toBe('s')+ expect(events.filter(event => event.session_id === 's').map(event => [event.type, event.seq])).toEqual([['message.complete', 6]])+ } finally { instance.unmount(); gw.kill() }+})diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex a6ec80f3246..4554424c590 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -482,6 +482,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {clearConnectionOperation()const pendingDetach = canonicalDetachFlights.current.get(id)+ const hold = gw.holdAttach?.(id) ?? nullconst request = pendingDetach? pendingDetach.then(() =>@@ -532,6 +533,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {// still-pending approval/clarify prompts are the only way they come back.gw.hydrateSharedPrompts?.(r)hydrateLiveSessionInflight(r.inflight)+ gw.settleAttach?.(hold, r)if (r.pending_connection) {applyConnectionRequest(r.pending_connection)@@ -549,7 +551,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {sys(`error: ${e.message}`)patchUiState({ status: 'ready' })})- .finally(() => finishAttachment(flight))+ .finally(() => {+ // A failed or superseded attach releases what it held (no-op after a settled snapshot).+ gw.settleAttach?.(hold)+ finishAttachment(flight)+ })},[adoptAttachment,@@ -592,6 +598,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {}const pendingDetach = canonicalDetachFlights.current.get(id)+ const hold = gw.holdAttach?.(id) ?? nullconst request = pendingDetach? pendingDetach.then(() =>@@ -643,6 +650,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {})gw.hydrateSharedPrompts?.(r)hydrateLiveSessionInflight(r.inflight)+ gw.settleAttach?.(hold, r)if (r.pending_connection) {applyConnectionRequest(r.pending_connection)@@ -667,6 +675,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {sys(`error: ${e.message}`)patchUiState({ status: 'ready' })})+ .finally(() => gw.settleAttach?.(hold))}).finally(() => finishAttachment(flight))},diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex 7dcfa92b8bf..e18fc82a0e6 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -137,6 +137,8 @@ const bootstrapLocalGateway = async (start: boolean, recover = false): Promise<Lreturn JSON.parse(stdout) as LocalGatewayGrant}++export interface AttachHold { sid: string; frames: AnyGatewayEvent[] }export class GatewayClient extends EventEmitter {private ws: WebSocket | null = nullprivate wsConnectPromise: Promise<void> | null = null@@ -185,6 +187,7 @@ export class GatewayClient extends EventEmitter {isCanonical = falseprivate creationContract?: CreationContractprivate describeFlight?: Promise<void>+ private attachHold: AttachHold | null = null// The last session.create whose outcome is in doubt (see createCanonical).private unsettledCreate?: { key: string; requestId: unknown }@@ -233,11 +236,17 @@ export class GatewayClient extends EventEmitter {// An idle frame (session.info from _publish_pending) carries its stamp in the payload only// (B2-18): fall back to it, and never stamp an absent value over it.const shared = ev as AnyGatewayEvent & { authority_epoch?: number; execution_generation?: number }- const payload = canonicalEvent(ev).payload ?? {}+ const payload = (canonicalEvent(ev).payload ?? {}) as { authority_epoch?: number; execution_generation?: number }const epoch = shared.authority_epoch ?? payload.authority_epochconst generation = shared.execution_generation ?? payload.execution_generationev.payload = { ...payload, ...(epoch !== undefined ? { execution_epoch: String(epoch) } : {}),...(generation !== undefined ? { execution_generation: generation } : {}) } as never++ if (this.attachHold && (ev as { session_id?: unknown }).session_id === this.attachHold.sid) {+ this.attachHold.frames.push(ev)++ return+ }}this.publish(ev)@@ -497,6 +506,32 @@ export class GatewayClient extends EventEmitter {}}+ /** B2-19: hold this session's canonical frames while its resume/activate is in flight. Fanout+ * frames can beat the reply; the caller applies the snapshot, then settleAttach replays only the+ * held frames after the snapshot (same replay_epoch, seq > last_sequence). */+ holdAttach(sessionId: string): AttachHold | null {+ if (!this.isCanonical) { return null }++ return (this.attachHold = { sid: sessionId, frames: [] })+ }++ /** End a hold: with the applied snapshot, replay only frames it does not contain; without one+ * (failed or superseded attach), deliver what was held. A replaced hold is a no-op. */+ settleAttach(hold: AttachHold | null, snapshot?: object | null) {+ if (!hold || this.attachHold !== hold) { return }+ this.attachHold = null++ const fence = snapshot as { last_sequence?: unknown; replay_epoch?: unknown } | null | undefined++ for (const ev of hold.frames) {+ const { replay_epoch: epoch, seq } = ev as { replay_epoch?: unknown; seq?: unknown }++ if (!fence || (epoch === fence.replay_epoch && typeof seq === 'number' && seq > Number(fence.last_sequence ?? -1))) {+ this.publish(ev)+ }+ }+ }+hydrateSharedPrompts(snapshot: unknown) {if (!this.isCanonical) { return }const result = snapshot as { session_id: string; authority_epoch: number; prompts?: Array<Record<string, unknown>> }