The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: rewind receipt uses the public message shape; record display columns in schema history; TUI lint
Teknium2a5a2c7b0204
diff --git a/hermes_cli/session_schema_history.py b/hermes_cli/session_schema_history.pyindex f899ffbafd5..e2f3d2216b5 100644--- a/hermes_cli/session_schema_history.py+++ b/hermes_cli/session_schema_history.py@@ -236,6 +236,10 @@ SCHEMA_HISTORY: dict[str, _TableHistory] = {('+', 'display_metadata', 'display_kind'),)),('14 2026-08-25T10:55Z 1104ffe0b9', (('+', '_compressed_summary', 'observed'),)),+ ('15 2026-09-09T17:05Z 1c6683e8e0', (+ ('+', 'display_identity', 'display_metadata'),+ ('+', 'display_order', 'display_identity'),+ )),),),"session_model_usage": _TableHistory(diff --git a/hermes_state_mutations.py b/hermes_state_mutations.pyindex ba4dcecb566..b5f50cb43ec 100644--- a/hermes_state_mutations.py+++ b/hermes_state_mutations.py@@ -74,7 +74,9 @@ def _rewind(db, conn, session_id, payload):require_idle(db, conn, [session_id])target, ids, head, replacement = rewind_in_transaction(db, conn, session_id,payload['target_message_id'], preserve_compaction_handoff=payload.get('preserve_compaction_handoff', False))- target['content'] = db._decode_content(target.get('content'))+ # Receipts are JSON: publish the same public message shape get_messages() returns (decoded+ # content/tool_calls, no internal display_identity BLOB / display_order).+ target = db._row_to_message_dict(target, warn_context='rewind receipt', summary_flag=True)conn.execute('UPDATE sessions SET runtime_generation=runtime_generation+1 WHERE id=?', (session_id,))return {session_id}, {'rewound_count': len(ids), 'target_message': target,'new_head_id': head, 'replacement_message_id': replacement}diff --git a/tests/gateway/test_status.py b/tests/gateway/test_status.pyindex 7b8a69e2ab1..410f4d70747 100644--- a/tests/gateway/test_status.py+++ b/tests/gateway/test_status.py@@ -214,7 +214,10 @@ class TestScopedGatewayPidQuery:monkeypatch.setattr(status, "_pid_exists", lambda pid: False)assert status.get_running_pid(pid_path) is Noneassert not pid_path.exists()- assert not (profile_dir / "gateway.lock").exists()+ # gateway.lock is an ownership inode (gateway/runtime_ownership.py): a stale record+ # is cleared through the PID file only; unlinking the lock would let a contender that+ # already opened it become a second owner.+ assert (profile_dir / "gateway.lock").exists()class TestGatewayRuntimeStatus:diff --git a/ui-tui/src/__tests__/busyQueueAdmission.test.tsx b/ui-tui/src/__tests__/busyQueueAdmission.test.tsxindex 701b38cfecb..238fc1de90d 100644--- a/ui-tui/src/__tests__/busyQueueAdmission.test.tsx+++ b/ui-tui/src/__tests__/busyQueueAdmission.test.tsx@@ -26,24 +26,33 @@ function mount(busyInputMode: 'queue' | 'interrupt' = 'queue') {const home = mkdtempSync(join(tmpdir(), 'ink-busy-admit-'))vi.stubEnv('HERMES_HOME', home)resetUiState()+const info = { model: 'test', skills: {}, tools: {}, profile_name: 'default',stored_session_id: 'stored-owner', execution_epoch: '1', execution_generation: 1, running: true }+patchUiState({ sid: 'owner', info, busy: true, status: 'running…', busyInputMode })const calls: Array<{ method: string; params: any }> = []+const request = vi.fn((method: string, params: any) => {calls.push({ method, params })+if (method === 'input.detect_drop') { return Promise.resolve({ matched: false }) }+if (method === 'prompt.submit') {return Promise.resolve({ admission_id: `adm-${params.submission_id}`, input_id: params.submission_id,target_session_id: 'stored-owner', target_profile_home: home, status: 'queued' })}+if (method === 'prompt.cancel') { return Promise.resolve({ admission_id: params.admission_id, status: 'terminal', outcome: 'cancelled' }) }throw new Error(`unexpected RPC: ${method}`)})+const gw = { request, isCanonical: true } as anylet queue!: ReturnType<typeof useQueue>let submission!: ReturnType<typeof useSubmission>+const noop = () => {}+const onEvent = createGatewayEventHandler({composer: { dequeue: () => undefined, queueEditRef: { current: null }, sendQueued: noop, setInput: noop },gateway: { gw, rpc: async () => null },@@ -52,6 +61,7 @@ function mount(busyInputMode: 'queue' | 'interrupt' = 'queue') {transcript: { appendMessage: noop, panel: noop, setHistoryItems: noop },voice: { setProcessing: noop, setRecording: noop, setVoiceEnabled: noop }} as any)+// The wire shape the gateway fans out; the client translates it exactly once.const fanout = (pending: any[]) => onEvent(canonicalEvent({ type: 'session.info', session_id: 'owner',payload: { stored_session_id: 'stored-owner', pending, running: true, execution_generation: 1, revision: 3,@@ -72,6 +82,7 @@ function mount(busyInputMode: 'queue' | 'interrupt' = 'queue') {return <Text>{ui.status} {queue.queuedDisplay.join('|')}</Text>}+const instance = renderSync(<Harness />, {stdin: new PassThrough() as any,stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,@@ -87,6 +98,7 @@ function mount(busyInputMode: 'queue' | 'interrupt' = 'queue') {it('admits busy queue-mode input to the authority immediately with a stable input_id instead of holding it locally', async () => {const h = mount('queue')+try {h.submission.dispatchSubmission('follower while busy')await expect.poll(() => h.calls.filter(c => c.method === 'prompt.submit').length).toBe(1)@@ -103,6 +115,7 @@ it('admits busy queue-mode input to the authority immediately with a stable inpuit('renders the queue from the session.info pending fanout, excluding the started row, and clears it when the fanout empties', async () => {const h = mount('queue')+try {h.fanout([row('adm-1', 'in-1', 'currently running', 'started'), row('adm-2', 'in-2', 'second in line')])await expect.poll(() => h.queue.queuedDisplay).toEqual(['[queued] second in line'])@@ -113,6 +126,7 @@ it('renders the queue from the session.info pending fanout, excluding the starteit('deletes a server-queued row through prompt.cancel rather than local removal', async () => {const h = mount('queue')+try {h.fanout([row('adm-9', 'in-9', 'cancel me')])await expect.poll(() => h.queue.queuedDisplay).toEqual(['[queued] cancel me'])@@ -128,8 +142,10 @@ it('deletes a server-queued row through prompt.cancel rather than local removal'it('projects canonical pending rows onto the legacy pending_submissions shape for resume snapshots and fanout', () => {const pending = [row('adm-3', 'in-3', 'hello')]+const snapshot = canonicalResult('session.resume', { session_id: 'sid', stored_session_id: 'sid', authority_epoch: 1,execution_generation: 2, running: true, messages: [], pending }, {})+expect(snapshot.info.pending_submissions).toEqual([expect.objectContaining({ admission_id: 'adm-3', input_id: 'in-3', user: 'hello',status: 'queued', target_session_id: 'stored-owner', target_profile_home: '/tmp/profile' })])const ev = canonicalEvent({ type: 'session.info', session_id: 'sid', payload: { pending } } as any)diff --git a/ui-tui/src/__tests__/canonicalGateway.test.ts b/ui-tui/src/__tests__/canonicalGateway.test.tsindex 996f94250c1..42a4f248563 100644--- a/ui-tui/src/__tests__/canonicalGateway.test.ts+++ b/ui-tui/src/__tests__/canonicalGateway.test.ts@@ -1,4 +1,5 @@import { expect, it } from 'vitest'+import { canonicalRequest, canonicalResult, sharedControlParams } from '../canonicalGateway.js'it('retains prepared identity and rejects unsupported TUI launch policy instead of impersonating CLI', () => {diff --git a/ui-tui/src/__tests__/canonicalHistory.test.ts b/ui-tui/src/__tests__/canonicalHistory.test.tsindex 1fe8b525e21..29a3d0cbeee 100644--- a/ui-tui/src/__tests__/canonicalHistory.test.ts+++ b/ui-tui/src/__tests__/canonicalHistory.test.ts@@ -1,4 +1,5 @@import { expect, it } from 'vitest'+import { canonicalResult } from '../canonicalGateway.js'import { toTranscriptMessages } from '../domain/messages.js'@@ -10,6 +11,7 @@ it('hydrates canonical persisted replies through the same transcript path as res{ role: 'assistant', content: 'CLARIFY_FINISHED', timestamp: 123 },{ role: 'session_meta', content: null },]+for (const method of ['session.create', 'session.resume', 'session.activate']) {const snapshot = canonicalResult(method, { messages, authority_epoch: 1, execution_generation: 2 })const rendered = toTranscriptMessages(snapshot.messages)diff --git a/ui-tui/src/__tests__/coldPendingRenderer.test.tsx b/ui-tui/src/__tests__/coldPendingRenderer.test.tsxindex 46f24d7a092..2c3bf4b2402 100644--- a/ui-tui/src/__tests__/coldPendingRenderer.test.tsx+++ b/ui-tui/src/__tests__/coldPendingRenderer.test.tsx@@ -3,14 +3,16 @@ import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { PassThrough } from 'node:stream'+import { renderSync, Text } from '@hermes/ink'import React from 'react'import { expect, it, vi } from 'vitest'++import { submitPrompt } from '../app/submissionCore.js'+import { captureDestination } from '../app/submissionDestination.js'import { getUiState, resetUiState } from '../app/uiStore.js'import { useSessionLifecycle } from '../app/useSessionLifecycle.js'-import { submitPrompt } from '../app/submissionCore.js'import { useQueue } from '../hooks/useQueue.js'-import { captureDestination } from '../app/submissionDestination.js'import { loadPendingInputs } from '../lib/pendingInputs.js'async function coldResume(legacy: boolean) {@@ -32,20 +34,25 @@ async function coldResume(legacy: boolean) {`], { cwd: process.cwd(), env: { ...process.env, HERMES_HOME: home }, stdio: 'pipe' })let queue!: ReturnType<typeof useQueue>let lifecycle!: ReturnType<typeof useSessionLifecycle>+const request = vi.fn(async (method: string, params: any) => method === 'session.resume'? { session_id: 'R2', session_key: 'S', messages: [], running: false, info: { model: 'test', tools: {}, skills: {}, stored_session_id: 'S', profile_name: 'default', running: false } }: { admission_id: params.submission_id, target_session_id: 'S', target_profile_home: home, status: 'queued' })+function Harness() {queue = useQueue()lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },gw: { request }, rpc: async () => ({}), scrollRef: { current: null }, panel: vi.fn(), sys: vi.fn(),setHistoryItems: vi.fn(), setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)+return <Text>{queue.queuedDisplay.join('|')}</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 {lifecycle.resumeById('S')await vi.waitFor(() => expect(getUiState().sid).toBe('R2'))@@ -60,6 +67,7 @@ async function coldResume(legacy: boolean) {{ destination: item.destination, queueItem: item, skipDetectDrop: true })await new Promise(resolve => setImmediate(resolve))const submissions = request.mock.calls.filter(([method]) => method === 'prompt.submit')+if (legacy) {expect(submissions).toEqual([])expect(queue.queueRef.current[0]).toMatchObject({ failed: true, legacyAttempted: true })diff --git a/ui-tui/src/__tests__/createSlashHandler.test.ts b/ui-tui/src/__tests__/createSlashHandler.test.tsindex bab7180e39b..ba1d932daba 100644--- a/ui-tui/src/__tests__/createSlashHandler.test.ts+++ b/ui-tui/src/__tests__/createSlashHandler.test.ts@@ -568,6 +568,7 @@ describe('createSlashHandler', () => {model: 'test', tools: {}, skills: {}, execution_epoch: 'owner', execution_generation: 2,execution_state: 'idle', running: false, stored_session_id: 'stored-source'}+const flush = () => new Promise(resolve => setImmediate(resolve))for (const change of [diff --git a/ui-tui/src/__tests__/gatewayClient.test.ts b/ui-tui/src/__tests__/gatewayClient.test.tsindex a9131f34a9d..967ee82a3a0 100644--- a/ui-tui/src/__tests__/gatewayClient.test.ts+++ b/ui-tui/src/__tests__/gatewayClient.test.ts@@ -145,6 +145,7 @@ describe('GatewayClient websocket attach mode', () => {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))+try {gw.start()gw.drain()diff --git a/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts b/ui-tui/src/__tests__/gatewayLocalLaunch.test.tsindex 8a04727eb66..91039d0bba6 100644--- a/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts+++ b/ui-tui/src/__tests__/gatewayLocalLaunch.test.ts@@ -1,8 +1,9 @@-import { afterEach, expect, it, vi } from 'vitest'import { mkdtempSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'+import { afterEach, expect, it, vi } from 'vitest'+vi.mock('node:child_process', () => ({ execFile: vi.fn(), spawn: vi.fn(() => { throw new Error('independent owner forbidden') }) }))import { GatewayClient } from '../gatewayClient.js'diff --git a/ui-tui/src/__tests__/legacyAdmissionRecovery.test.ts b/ui-tui/src/__tests__/legacyAdmissionRecovery.test.tsindex b4cc98825e0..febe3b9342e 100644--- a/ui-tui/src/__tests__/legacyAdmissionRecovery.test.ts+++ b/ui-tui/src/__tests__/legacyAdmissionRecovery.test.ts@@ -17,18 +17,22 @@ it('never redispatches an ambiguous legacy attempt after native journal reload',resetUiState()patchUiState({ sid: 'runtime', info: { model: 'test', tools: {}, skills: {}, stored_session_id: 'stored' } })const destination = captureDestination()+const item: QueueItem = {submissionId: randomUUID(), text: 'exact Ω', display: 'exact Ω', destination, inFlight: true}+item.settle = accepted => {item.inFlight = falseitem.failed = !acceptedsavePendingInput(item)}+const request = vi.fn(async (_method: string, params: Record<string, unknown>) => {if (params.submission_id) { throw Object.assign(new Error('unsupported'), { code: 4094 }) }throw new Error('lost legacy ACK')})+const deps = {gw: { request }, appendMessage: vi.fn(), enqueue: vi.fn(), expand: (value: string) => value,setLastUserMsg: vi.fn(), sys: vi.fn()diff --git a/ui-tui/src/__tests__/receiptBusyRenderer.test.tsx b/ui-tui/src/__tests__/receiptBusyRenderer.test.tsxindex e6a53edfdb4..888b6285822 100644--- a/ui-tui/src/__tests__/receiptBusyRenderer.test.tsx+++ b/ui-tui/src/__tests__/receiptBusyRenderer.test.tsx@@ -26,23 +26,30 @@ function mount() {const home = mkdtempSync(join(tmpdir(), 'ink-receipt-busy-'))vi.stubEnv('HERMES_HOME', home)resetUiState()+const info = { model: 'test', skills: {}, tools: {}, profile_name: 'default',stored_session_id: 'stored-owner', execution_epoch: 'owner-epoch', execution_generation: 1, running: false }+patchUiState({ sid: 'owner', info, busy: false, status: 'ready' })const submits: ReturnType<typeof deferred>[] = []const snapshots: ReturnType<typeof deferred>[] = []+const request = vi.fn((method: string) => {if (method === 'input.detect_drop') { return Promise.resolve({ matched: false }) }const pending = deferred()+if (method === 'prompt.submit') { submits.push(pending) }else if (method === 'session.activate') { snapshots.push(pending) }else { throw new Error(`unexpected RPC: ${method}`) }return pending.promise})+let queue!: ReturnType<typeof useQueue>let submission!: ReturnType<typeof useSubmission>+const noop = () => {}+const onEvent = createGatewayEventHandler({composer: { dequeue: () => undefined, queueEditRef: { current: null }, sendQueued: noop, setInput: noop },gateway: { gw: { request }, rpc: async () => null },@@ -51,6 +58,7 @@ function mount() {transcript: { appendMessage: noop, panel: noop, setHistoryItems: noop },voice: { setProcessing: noop, setRecording: noop, setVoiceEnabled: noop }} as any)+const emit = (type: string, generation: number) => onEvent({ type, session_id: 'owner',payload: { execution_epoch: info.execution_epoch, execution_generation: generation, text: 'completed' } } as any)@@ -68,11 +76,13 @@ function mount() {useEffect(() => {if (!ui.sid || ui.busy || queue.queueEditRef.current !== null || !queue.queueRef.current.length) { return }const next = queue.dequeue()+if (next) { submission.sendQueued(next) }}, [ui.sid, ui.busy, queue, submission])return <Text>{ui.status} {queue.queuedDisplay.join('|')}</Text>}+const instance = renderSync(<Harness />, {stdin: new PassThrough() as any,stdout: Object.assign(new PassThrough(), { columns: 80, rows: 20, isTTY: false }) as any,@@ -93,6 +103,7 @@ function mount() {it('reconciles terminal and unknown retries to idle so queued follow-ups can drain without another terminal event', async () => {for (const status of ['terminal', 'unknown']) {const h = mount()+try {const item = h.queue.stage('original')h.submission.sendQueued(item)@@ -119,14 +130,17 @@ it('reconciles terminal and unknown retries to idle so queued follow-ups can drait('preserves a newer running generation across old receipts and delayed idle snapshots', async () => {for (const delayed of [false, true]) {const h = mount()+try {const item = h.queue.stage('retry old identity')h.submission.sendQueued(item)await expect.poll(() => h.submits.length).toBe(1)+if (!delayed) { h.emit('message.start', 2) }h.submits[0]!.resolve(h.receipt(item.submissionId!, 'terminal'))await expect.poll(() => h.queue.queueRef.current.length).toBe(0)await expect.poll(() => h.snapshots.length).toBe(1)+if (delayed) { h.emit('message.start', 2) }h.snapshots[0]!.resolve(h.snapshot(!delayed, delayed ? 1 : 2))await new Promise(resolve => setTimeout(resolve, 20))diff --git a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsxindex ad47051f15f..586e0c898c9 100644--- a/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx+++ b/ui-tui/src/__tests__/slashAttachmentRenderer.test.tsx@@ -21,6 +21,7 @@ function mount() {patchUiState({ sid: 'owner' })const images = new Map<string, string[]>()const pending: Array<{ sid: string; finish: (path: string) => void }> = []+const request = vi.fn((method: string, params: any) => {if (method === 'image.attach' || method === 'clipboard.paste') {return new Promise(resolve => {@@ -30,6 +31,7 @@ function mount() {} })})}+if (method === 'image.detach') {images.set(params.session_id, (images.get(params.session_id) ?? []).filter(path => path !== params.path))} else if (!method.startsWith('complete.')) {@@ -38,6 +40,7 @@ function mount() {return Promise.resolve({})})+const gw = { request } as anyconst submitRef = { current: (_value: string) => {} }const slashRef = { current: (_value: string) => false }@@ -85,6 +88,7 @@ function mount() {it('slash attachment submission leaves a visible removable image in the cleared composer', async () => {for (const command of ['/image /owned.png', '/paste']) {const h = mount()+try {await h.submit(command)expect(h.pending).toHaveLength(1)@@ -111,17 +115,21 @@ it('stale attachment cleanup uses its captured owner and preserves a concurrentfor (const samePath of [false, true]) {for (const staleFirst of [false, true]) {const h = mount()+try {if (command === 'drop') {void h.composer.actions.handleTextPaste({ text: '/owned.png', value: '', cursor: 0 })} else {await h.submit(command)}+h.composer.actions.setInput('user edit')+if (navigation) {patchUiState({ sid: 'other' })h.composer.actions.clearIn()}+await h.submit('/image /valid.png')expect(h.pending).toHaveLength(2)const validPath = samePath ? '/owned.png' : '/valid.png'@@ -137,6 +145,7 @@ it('stale attachment cleanup uses its captured owner and preserves a concurrent])expect(h.images.get(sid)).toContain(validPath)const detach = h.request.mock.calls.filter(([method]) => method === 'image.detach')+if (samePath && !navigation) {expect(detach).toEqual([])} else {diff --git a/ui-tui/src/__tests__/slashSessionAuthority.test.tsx b/ui-tui/src/__tests__/slashSessionAuthority.test.tsxindex 60f348bc0a9..d4c646e929f 100644--- a/ui-tui/src/__tests__/slashSessionAuthority.test.tsx+++ b/ui-tui/src/__tests__/slashSessionAuthority.test.tsx@@ -16,12 +16,16 @@ it('branch hydration replaces source authority only after a successful destinativi.stubEnv('HERMES_HOME', home)vi.stubEnv('HERMES_TUI_ACTIVE_SESSION_FILE', join(home, 'active'))resetUiState()+const source = { model: 'test', skills: {}, tools: {}, stored_session_id: 'stored-source',execution_epoch: 'source-owner', execution_generation: 9, running: true }+patchUiState({ sid: 'source', info: source, busy: true })const pending: Array<{ method: string; resolve: (value: any) => void }> = []+const request = vi.fn((method: string) => method === 'session.close'? Promise.resolve({}) : new Promise(resolve => pending.push({ method, resolve })))+const setHistoryItems = vi.fn()const sys = vi.fn()let slash!: (command: string) => boolean@@ -31,14 +35,17 @@ it('branch hydration replaces source authority only after a successful destinatigw: { request }, rpc: request, scrollRef: { current: null }, panel: vi.fn(), sys,setHistoryItems, setLastUserMsg: vi.fn(), setSessionStartedAt: vi.fn(), setStickyPrompt: vi.fn(),setVoiceProcessing: vi.fn(), setVoiceRecording: vi.fn() } as any)+slash = createSlashHandler({ slashFlightRef: { current: 0 }, gateway: { gw: { request }, rpc: request },local: {}, session: { ...lifecycle, setSessionStartedAt: vi.fn() }, transcript: { sys, setHistoryItems } } as any)+return <Text>branch</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 })+const flush = () => new Promise(resolve => setImmediate(resolve))try {diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex d77fa0ce2a9..e96b010cd23 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -775,8 +775,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:// snapshots replace that epoch; delayed push events cannot reset it.const current = getUiState().infoconst execution = (ev.payload ?? {}) as { execution_epoch?: string; execution_generation?: number }+const genericError = ev.type === 'error' &&execution.execution_epoch === undefined && execution.execution_generation === undefined+const lifecycle = !genericError && ['session.info', 'message.start', 'message.complete', 'error'].includes(ev.type)if (lifecycle && current?.execution_generation !== undefined) {@@ -797,10 +799,12 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:}const settled = ev as unknown as { type: string; payload?: { prompt_id?: string } }+if (settled.type === 'approval.settled' || settled.type === 'clarify.settled') {const kind = settled.type === 'approval.settled' ? 'approval' : 'clarify'patchOverlayState(previous => previous[kind]?.sharedControl?.prompt_id === settled.payload?.prompt_id? { ...previous, [kind]: null } : previous)+return}@@ -1309,8 +1313,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:case 'clarify.request': {const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }+const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined+const batch = (ev.payload.questions ?? []).filter(q => typeof q?.qid === 'string' && q.qid && typeof q?.question === 'string' && q.question.trim()).map(q => ({@@ -1343,8 +1349,10 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:case 'approval.request': {const shared = ev.payload as typeof ev.payload & { prompt_id?: string; execution_generation?: number }+const sharedControl = shared.prompt_id && ev.session_id && typeof shared.execution_generation === 'number'? { session_id: ev.session_id, execution_generation: shared.execution_generation, prompt_id: shared.prompt_id } : undefined+const description = String(ev.payload.description ?? 'dangerous command')// Only an explicit false (tirith warning) drops the permanent-allow option.const allowPermanent = ev.payload.allow_permanent !== falsediff --git a/ui-tui/src/app/pendingBubbles.ts b/ui-tui/src/app/pendingBubbles.tsindex 25948a9b061..10355ff1c91 100644--- a/ui-tui/src/app/pendingBubbles.ts+++ b/ui-tui/src/app/pendingBubbles.ts@@ -16,6 +16,7 @@ export const resetBubbleLedger = () => shown.clear()export function newlyStartedRows(previous: PendingRow[] | undefined, incoming: PendingRow[] | undefined): PendingRow[] {if (!previous || !incoming) { return [] }const wasQueued = new Set(previous.filter(row => row.status === 'queued').map(row => row.admission_id))+return incoming.filter(row => row.status === 'started' && wasQueued.has(row.admission_id) && !(row.input_id && shown.has(row.input_id)))}diff --git a/ui-tui/src/app/submissionCore.ts b/ui-tui/src/app/submissionCore.tsindex a0017971fa0..74354f4eade 100644--- a/ui-tui/src/app/submissionCore.ts+++ b/ui-tui/src/app/submissionCore.ts@@ -104,7 +104,9 @@ export function submitPrompt(if (item) {item.preparedText ??= submitText+if (opts.behindTurn) { item.queued = true }+if (ownsTurn() && show) { markBubbleShown(item.submissionId) }savePendingInput(item)}@@ -181,6 +183,7 @@ export function submitPrompt(try {item.legacyAttempted = truesavePendingInput(item)+const r = await deps.gw.request<PromptSubmitResponse>('prompt.submit', {session_id: sid,text: item.preparedText ?? submitText,diff --git a/ui-tui/src/app/useComposerState.ts b/ui-tui/src/app/useComposerState.tsindex 16c520f05e6..c4d23db7fdb 100644--- a/ui-tui/src/app/useComposerState.ts+++ b/ui-tui/src/app/useComposerState.ts@@ -110,10 +110,12 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptionsconst [input, setInputState] = useState('')const [inputBuf, setInputBufState] = useState<string[]>([])const composerRevision = useRef(0)+const setInputBuf = useCallback<StateSetter<string[]>>(next => {composerRevision.current++setInputBufState(next)}, [])+const [tokens, setTokens] = useState<ComposerToken[]>([])// Tokens and the input line are read from keystroke handlers that run several// times before React re-renders, so the refs — not the state — are the source@@ -209,6 +211,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptionsconst attachmentFlights = useRef(0)const staleAttachments = useRef<Array<{ destination: SubmissionDestination; path: string }>>([])+const resolveAttachment = useCallback(async <T extends { path?: string }>(destination: SubmissionDestination,@@ -217,12 +220,14 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptionsaccept: (attached: T | null) => ComposerPasteResult | null): Promise<ComposerPasteResult | null> => {attachmentFlights.current+++try {const attached = await requestif (isCurrentDestination(destination) && revision === composerRevision.current) {return accept(attached)}+if (attached?.path) {staleAttachments.current.push({ destination, path: attached.path })}@@ -230,6 +235,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptionsreturn null} finally {attachmentFlights.current--+// Detach is path-based: wait for concurrent replies before deciding// whether that path belongs to a surviving visible attachment.if (!attachmentFlights.current) {@@ -240,6 +246,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptions) {continue}+void gw.request('image.detach', { session_id: stale.destination.sid, path: stale.path }).catch(() => {})}}@@ -274,6 +281,7 @@ export function useComposerState({ gw, submitRef, sys }: UseComposerStateOptionsif (r?.attached) {return attachImageToken(r, value, cursor)}+if (!quiet) {sys(r?.message || 'No image found in clipboard')}diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.tsindex 48c9459cf6f..b8698770c77 100644--- a/ui-tui/src/app/useInputHandlers.ts+++ b/ui-tui/src/app/useInputHandlers.ts@@ -1,8 +1,8 @@-import { sharedControlParams } from '../canonicalGateway.js'import { forceRedraw, useInput } from '@hermes/ink'import { useStore } from '@nanostores/react'import { useEffect, useRef } from 'react'+import { sharedControlParams } from '../canonicalGateway.js'import { DASHBOARD_TUI_MODE } from '../config/env.js'import { DOUBLE_ESC_MS, TYPING_IDLE_MS } from '../config/timing.js'import { applyCompletion } from '../domain/slash.js'@@ -221,9 +221,11 @@ export function useInputHandlers(ctx: InputHandlerContext): InputHandlerResult {if (overlay.approval) {const fresh = capturePromptResponseGuard('approval', overlay.approval)+if (!fresh()) {return}+return gateway.rpc<ApprovalRespondResponse>('approval.respond', { choice: 'deny', session_id: getUiState().sid, ...sharedControlParams(overlay.approval) }).then(r => r && fresh() && (patchOverlayState({ approval: null }), patchTurnState({ outcome: 'denied' })))diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.tsindex 1caaf198132..d3866fc3f09 100644--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@ -706,9 +706,11 @@ export function useMainApp(gw: GatewayClient) {}const fresh = capturePromptResponseGuard('clarify', clarify)+if (!fresh()) {return}+const label = toolTrailLabel('clarify')turnController.turnTools = turnController.turnTools.filter(line => !sameToolTrailGroup(label, line))@@ -759,9 +761,11 @@ export function useMainApp(gw: GatewayClient) {}const fresh = capturePromptResponseGuard('clarify', clarify)+if (!fresh()) {return}+rpc<ClarifyRespondResponse & { remaining?: string[] }>('clarify.respond', {answer,question_id: qid,@@ -1032,13 +1036,16 @@ export function useMainApp(gw: GatewayClient) {const answerApproval = useCallback((choice: string) => {const fresh = capturePromptResponseGuard('approval', overlay.approval)+if (!fresh()) {return}+return respondWith('approval.respond', { choice, session_id: ui.sid, ...sharedControlParams(overlay.approval) }, () => {if (!fresh()) {return}+patchOverlayState({ approval: null })patchTurnState({ outcome: choice === 'deny' ? 'denied' : `approved (${choice})` })patchUiState({ status: 'running…' })@@ -1054,9 +1061,11 @@ export function useMainApp(gw: GatewayClient) {}const fresh = capturePromptResponseGuard('sudo', overlay.sudo)+if (!fresh()) {return}+const requestId = overlay.sudo.requestIdif (!pw) {@@ -1067,6 +1076,7 @@ export function useMainApp(gw: GatewayClient) {if (!fresh()) {return}+patchOverlayState({ sudo: null })patchUiState({ status: 'running…' })})@@ -1081,9 +1091,11 @@ export function useMainApp(gw: GatewayClient) {}const fresh = capturePromptResponseGuard('secret', overlay.secret)+if (!fresh()) {return}+const requestId = overlay.secret.requestIdif (!value) {@@ -1094,6 +1106,7 @@ export function useMainApp(gw: GatewayClient) {if (!fresh()) {return}+patchOverlayState({ secret: null })patchUiState({ status: 'running…' })})diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex b7912df4830..2f13963b9e3 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -1,11 +1,11 @@import { randomUUID } from 'node:crypto'-import { localCreationOptions } from '../canonicalGateway.js'import { writeFileSync } from 'node:fs'import type { ScrollBoxHandle } from '@hermes/ink'import { evictInkCaches } from '@hermes/ink'import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'+import { localCreationOptions } from '../canonicalGateway.js'import { buildSetupRequiredSections, SETUP_REQUIRED_TITLE } from '../content/setup.js'import { introMsg, toTranscriptMessages } from '../domain/messages.js'import { ZERO } from '../domain/usage.js'diff --git a/ui-tui/src/app/useSubmission.ts b/ui-tui/src/app/useSubmission.tsindex 73c7d4ae1d6..bb7913065dc 100644--- a/ui-tui/src/app/useSubmission.ts+++ b/ui-tui/src/app/useSubmission.ts@@ -282,6 +282,7 @@ export function useSubmission(opts: UseSubmissionOptions) {if (typeof input !== 'string') {return sendQueued(input)}+const full = inputif (!full.trim()) {diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.tsindex 19377b64e2e..a74b22d551f 100644--- a/ui-tui/src/canonicalGateway.ts+++ b/ui-tui/src/canonicalGateway.ts@@ -7,33 +7,41 @@ export interface CreationContract { sources: string[]; parameters: string[] }export function canonicalRequest(method: string, original: Record<string, unknown>, contract?: CreationContract) {const params = { ...original }+if (method === 'session.create') {delete params.colsparams.source = 'tui'params.request_id ??= randomUUID()+if (!contract?.sources.includes('tui')) { throw new Error('gateway does not support tui session policy; update/restart the gateway') }const unsupported = Object.keys(params).filter(key => !contract.parameters.includes(key))+if (unsupported.length) { throw new Error(`gateway does not support TUI launch options: ${unsupported.join(', ')}`) }}+if (method === 'prompt.submit' && params.submission_id) {params.input_id = params.submission_iddelete params.submission_id}+if (method === 'session.resume' || method === 'session.activate') {method = 'session.resume'delete params.colsdelete params.omit_messages}+return { method, params }}export function canonicalResult(method: string, value: any, request: Record<string, unknown> = {}): any {if (!value || typeof value !== 'object') { return value }+// 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) {return { ...value, input_id: request.input_id, target_profile_home: value.ref.profile_id, target_session_id: value.ref.session_id }}+if (['session.create', 'session.resume', 'session.activate'].includes(method)) {// Canonical snapshots contain stored conversation rows (`content`), not// the legacy TUI's display rows (`text`). Without this translation only@@ -42,10 +50,12 @@ export function canonicalResult(method: string, value: any, request: Record<strirow && typeof row === 'object'? { ...row, text: row.content, name: row.tool_name }: row) : value.messages+return { ...value, messages, info: { ...value.info, stored_session_id: value.stored_session_id,execution_epoch: String(value.authority_epoch), execution_generation: value.execution_generation,running: value.running, pending_submissions: pendingSubmissions(value.pending) } }}+return value}@@ -54,12 +64,14 @@ export function canonicalResult(method: string, value: any, request: Record<stri// queue panel, the receipt matcher and Desktop all read the same list.export function pendingSubmissions(pending: unknown) {if (!Array.isArray(pending)) { return undefined }+return pending.filter(row => row && typeof row === 'object').map(row => ({...row, user: row.text, target_profile_home: row.ref?.profile_id, target_session_id: row.ref?.session_id }))}export function canonicalEvent<T extends { type: string; payload?: any }>(event: T): T {const pending = pendingSubmissions(event.payload?.pending)+return pending ? { ...event, payload: { ...event.payload, pending_submissions: pending } } : event}@@ -69,7 +81,10 @@ export function localCreationOptions(env = process.env): Record<string, unknown>skills: env.HERMES_TUI_SKILLS, checkpoints: env.HERMES_TUI_CHECKPOINTS,max_turns: env.HERMES_TUI_MAX_TURNS, accept_hooks: env.HERMES_ACCEPT_HOOKS}+const options: Record<string, unknown> = Object.fromEntries(Object.entries(fields).filter(([, value]) => value))+if (env.HERMES_TUI_TOOLSETS) { options.toolsets = env.HERMES_TUI_TOOLSETS.split(',') }+return options}diff --git a/ui-tui/src/gatewayClient.ts b/ui-tui/src/gatewayClient.tsindex 90579ac5406..6779619d713 100644--- a/ui-tui/src/gatewayClient.ts+++ b/ui-tui/src/gatewayClient.ts@@ -7,7 +7,6 @@ import { promisify } from 'node:util'import { WebSocket as UndiciWebSocket } from 'undici'import { canonicalEvent, canonicalRequest, canonicalResult, type CreationContract } from './canonicalGateway.js'-import type { GatewayEvent } from './gatewayTypes.js'import { CircularBuffer } from './lib/circularBuffer.js'import { recordParentLifecycle } from './lib/parentLog.js'@@ -141,9 +140,11 @@ export interface LocalGatewayGrant { url: string; protocols: string[]; profile_iconst bootstrapLocalGateway = async (start: boolean): Promise<LocalGatewayGrant> => {const root = process.env.HERMES_PYTHON_SRC_ROOT ?? resolve(import.meta.dirname, '../../')+const { stdout } = await promisify(execFile)(resolvePython(root),[resolve(root, 'ui-tui/scripts/gateway_bootstrap.py'), ...(start ? ['--start'] : [])],{ cwd: root, env: { ...process.env, PYTHONPATH: root }, timeout: 40_000, maxBuffer: 1024 * 1024 })+return JSON.parse(stdout) as LocalGatewayGrant}@@ -449,6 +450,7 @@ export class GatewayClient extends EventEmitter {hydrateSharedPrompts(snapshot: unknown) {if (!this.isCanonical) { return }const result = snapshot as { session_id: string; authority_epoch: number; prompts?: Array<Record<string, unknown>> }+for (const prompt of result.prompts ?? []) {this.publishLocalEvent({ type: `${prompt.kind}.request`, session_id: result.session_id,payload: { ...prompt, execution_epoch: String(result.authority_epoch) } } as unknown as GatewayEvent)@@ -541,9 +543,11 @@ export class GatewayClient extends EventEmitter {this.lastActivityAt = Date.now()this.clearReconnect()this.connectSidecarMirror()+if (this.isCanonical) {void this.requestOverWebSocket<{session_create: CreationContract}>('runtime.describe').then(description => {this.creationContract = description.session_create+if (this.ws === ws) { this.publish({ type: 'gateway.ready', payload: {} }) }}).catch(error => {this.publish({ type: 'gateway.start_timeout', payload: {@@ -668,11 +672,13 @@ export class GatewayClient extends EventEmitter {// The canonical client owns readiness after runtime.describe. Forwarding// the listener's legacy ready as well creates two sessions/startup turns.if (this.isCanonical && ev.type === 'gateway.ready') { 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)}}@@ -784,6 +790,7 @@ export class GatewayClient extends EventEmitter {if (!this.ws || this.ws.readyState === WS_CLOSED || this.ws.readyState === WS_CLOSING) {this.start()+if (!resolveGatewayAttachUrl()) { await this.bootstrapFlight }}@@ -851,9 +858,11 @@ export class GatewayClient extends EventEmitter {}if (!this.bootstrapFlight) { this.start() }+return this.bootstrapFlight!.then(() => {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))})}diff --git a/ui-tui/src/types.ts b/ui-tui/src/types.tsindex e7860d16c6f..e9d9d1732fd 100644--- a/ui-tui/src/types.ts+++ b/ui-tui/src/types.ts@@ -1,3 +1,5 @@+import type { SharedControl } from './canonicalGateway.js'+export interface ActiveTool {context?: stringid: string@@ -95,7 +97,7 @@ export interface DelegationStatus {}export interface ApprovalReq {- sharedControl?: import('./canonicalGateway.js').SharedControl+ sharedControl?: SharedControl// false when the backend won't honor a permanent allow (tirith warning) → hide "Always allow".allowPermanent?: booleanchoices?: string[]@@ -121,7 +123,7 @@ export interface ClarifyBatchQuestion {}export interface ClarifyReq {- sharedControl?: import('./canonicalGateway.js').SharedControl+ sharedControl?: SharedControlchoices: string[] | nullquestion: stringrequestId: string