The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): close a canonical live row through the verb the gateway has
686f6c61c994e6b5c7a8
diff --git a/locales/_keys.tui.json b/locales/_keys.tui.jsonindex 78c3258ab11..8b78b97e20a 100644--- a/locales/_keys.tui.json+++ b/locales/_keys.tui.json@@ -675,6 +675,7 @@"pickers.session.draftModel","pickers.session.errors.alreadyClosed","pickers.session.errors.couldNotLoadResumable",+ "pickers.session.errors.notAttached","pickers.session.hint.close","pickers.session.hint.delete","pickers.session.hint.model",diff --git a/ui-tui/src/__tests__/canonicalSwitcherClose.test.tsx b/ui-tui/src/__tests__/canonicalSwitcherClose.test.tsxnew file mode 100644index 00000000000..9502b53b08a--- /dev/null+++ b/ui-tui/src/__tests__/canonicalSwitcherClose.test.tsx@@ -0,0 +1,183 @@+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 { getUiState, resetUiState } from '../app/uiStore.js'+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'+import { canonicalRequest, canonicalResult } from '../canonicalGateway.js'+import { ActiveSessionSwitcher } from '../components/activeSessionSwitcher.js'+import { DEFAULT_THEME } from '../theme.js'++// #139536: on a canonical gateway the switcher's `^d` close sent no request at all (`session.close`+// is not in the canonical contract) and then reported "session was already closed". The view closes+// the row it holds with main's `tui_close` stamp; a row it holds nothing for is not claimed as closed.++const liveRow = { id: 'live', session_id: 'live', title: 'Current conversation', started_at: 2, message_count: 1, running: false }++function detachFixture() {+ const home = mkdtempSync(join(tmpdir(), 'ink-switcher-close-'))+ vi.stubEnv('HERMES_HOME', home)+ resetUiState()+ const subscriptions = new Map<string, string>()+ const pending: Array<{ resolve: () => void }> = []++ const request = vi.fn((method: string, original: Record<string, unknown>) => {+ const wire = canonicalRequest(method, original)+ const sid = String(wire.params.session_id)++ if (wire.method === 'session.resume') {+ const token = subscriptions.get(sid) ?? `sub-${subscriptions.size + 1}`+ subscriptions.set(sid, token)++ const result = canonicalResult(method, { session_id: sid, stored_session_id: sid, subscription_id: token,+ authority_epoch: 1, execution_generation: 0, messages: [], pending: [], running: false,+ info: { model: 'test', tools: {}, skills: {} } })++ return new Promise(resolve => pending.push({ resolve: () => resolve(result) }))+ }++ if (wire.method === 'session.detach') {+ const detached = subscriptions.get(sid) === wire.params.subscription_id++ if (detached) {subscriptions.delete(sid)}++ return Promise.resolve({ ...wire.params, detached })+ }++ throw new Error(`unexpected viewer operation: ${wire.method}`)+ })++ let lifecycle!: ReturnType<typeof useSessionLifecycle>++ function Harness() {+ lifecycle = useSessionLifecycle({ colsRef: { current: 80 }, composerActions: { setComposerTokens: vi.fn() },+ gw: { isCanonical: true, request }, rpc: request, 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>switcher close</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 })++ return { request, lifecycle: () => lifecycle,+ async attach(sid: string) {+ lifecycle.resumeById(sid)+ await vi.waitFor(() => expect(pending.length).toBeGreaterThan(0))+ pending.shift()!.resolve()+ await vi.waitFor(() => expect(getUiState().sid).toBe(sid))+ },+ cleanup() {+ instance.unmount()+ resetUiState()+ vi.unstubAllEnvs()+ rmSync(home, { recursive: true, force: true })+ } }+}++const detaches = (request: ReturnType<typeof vi.fn>) =>+ request.mock.calls.filter(([method]) => method === 'session.detach').map(([, params]) => params)++it('closeLiveView detaches the canonical row this view holds with the tui_close stamp', async () => {+ const f = detachFixture()++ try {+ await f.attach('x')+ await expect(f.lifecycle().closeLiveView('x')).resolves.toEqual({ closed: true })+ expect(detaches(f.request)).toEqual([{ session_id: 'x', subscription_id: 'sub-1', end_reason: 'tui_close' }])+ } finally {+ f.cleanup()+ }+})++it('closeLiveView sends nothing for a canonical row this view holds no subscription for', async () => {+ const f = detachFixture()++ try {+ await f.attach('x')+ await expect(f.lifecycle().closeLiveView('other')).resolves.toBeNull()+ expect(detaches(f.request)).toEqual([])+ } finally {+ f.cleanup()+ }+})++function mountSwitcher(onClose: (id: string) => Promise<null | { closed?: boolean; ok?: boolean }>) {+ const request = vi.fn(async (method: string, params: Record<string, unknown>) => {+ if (method === 'session.list') {+ return { scope: params.scope ?? 'live', sessions: params.scope === 'stored' ? [] : [liveRow] }+ }++ throw Object.assign(new Error(`unknown method: ${method}`), { code: -32601 })+ })++ const stdin = Object.assign(new PassThrough(), { isTTY: true, setRawMode: vi.fn(), ref: vi.fn(), unref: vi.fn() })+ const stdout = Object.assign(new PassThrough(), { columns: 100, rows: 30, isTTY: false })+ const out = { text: '' }++ stdout.on('data', chunk => {+ out.text += chunk.toString()+ })++ const element = (+ <ActiveSessionSwitcher+ currentSessionId="live"+ gw={{ isCanonical: true, request } as any}+ onCancel={vi.fn()}+ onClose={onClose as any}+ onNew={vi.fn()}+ onNewPrompt={vi.fn()}+ onResume={vi.fn()}+ onSelect={vi.fn()}+ t={DEFAULT_THEME}+ />+ )++ const instance = renderSync(element, { stdin: stdin as any, stdout: stdout as any,+ stderr: new PassThrough() as any, patchConsole: false })++ const closeLive = async () => {+ await vi.waitFor(() => expect(out.text).toContain('Current conversation'))+ // `^d` on the live row the view is on (the initial selection lands there).+ stdin.write('\u0004')+ await vi.waitFor(() => expect(onClose).toHaveBeenCalledWith('live'))+ await vi.waitFor(() => {+ instance.rerender(React.cloneElement(element))+ expect(out.text).toMatch(/error: /)+ })+ }++ return { closeLive, instance, out }+}++it('reports no close instead of blaming main when the canonical row is not held', async () => {+ const onClose = vi.fn(async () => null)+ const m = mountSwitcher(onClose)++ try {+ await m.closeLive()+ expect(m.out.text).toContain('error: this view is not attached to that session')+ expect(m.out.text).not.toContain('already closed')+ } finally {+ m.instance.unmount()+ }+})++it('keeps main\'s "already closed" for a receipt that refuses the close', async () => {+ const onClose = vi.fn(async () => ({ closed: false }))+ const m = mountSwitcher(onClose)++ try {+ await m.closeLive()+ expect(m.out.text).toContain('error: session was already closed')+ } finally {+ m.instance.unmount()+ }+})diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.tsindex 09aa3d92c73..d287657e62a 100644--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@ -1412,7 +1412,7 @@ export function useMainApp(gw: GatewayClient) {patchUiState({ status: t('session.status.closingSession') })try {- const result = (await session.closeSession(id)) as null | SessionCloseResponse+ const result = (await session.closeLiveView(id)) as null | SessionCloseResponsepatchUiState({ status: 'ready' })return resultdiff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex 68e730f722f..f577192b7a0 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -236,6 +236,51 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {await Promise.all(open.map(([sessionId, subscriptionId]) => detachCanonical(sessionId, subscriptionId, 'tui_shutdown')))}, [detachCanonical])+ // The Ink session switcher's `^d` close of a live row. On the legacy transport it is main's+ // `session.close`; on a canonical gateway that method is not in the contract (-32601), so the view+ // can only drop its own hold with main's `tui_close` stamp: the owner ends the idle local session+ // once the last viewer leaves, which is what takes the row out of the live feed.+ const closeLiveView = useCallback(+ async (targetSid: string): Promise<null | SessionCloseResponse> => {+ if (!gw.isCanonical) {+ const closed = await rpc<SessionCloseResponse>('session.close', { session_id: targetSid })++ closed?.messages?.forEach(message => sys(message))++ return closed+ }++ // An in-flight detach for this row (a resume switch, /new) wins: this view no longer holds it.+ await canonicalDetachFlights.current.get(targetSid)++ const subscriptionId = canonicalSubscriptions.current.get(targetSid)++ if (!subscriptionId) {+ // A live row this view holds nothing for is not ours to end (another viewer's session, or an+ // ownerless row the gateway kept): nothing is sent, and the caller reports no close at all.+ return null+ }++ const result = asRpcResult<SessionDetachResponse>(+ await rpc<SessionDetachResponse>('session.detach', {+ end_reason: 'tui_close',+ session_id: targetSid,+ subscription_id: subscriptionId+ })+ )++ if (!result?.detached) {+ // The subscription was already stale: main had dropped this view's hold, so nothing was closed.+ return null+ }++ canonicalSubscriptions.current.delete(targetSid)++ return { closed: true }+ },+ [gw.isCanonical, rpc, sys]+ )+const disposeStaleAttachments = useCallback(() => {// In-flight attaches can share a token before either result is adopted.// Decide disposal only after their handlers have adopted (or refused) it.@@ -729,6 +774,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {() => ({activateLiveSession,closeForExit,+ closeLiveView,closeSession,guardBusySessionSwitch,newLiveSession,@@ -741,6 +787,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {[activateLiveSession,closeForExit,+ closeLiveView,closeSession,guardBusySessionSwitch,newLiveSession,diff --git a/ui-tui/src/components/activeSessionSwitcher.tsx b/ui-tui/src/components/activeSessionSwitcher.tsxindex 25895ababe6..41690fa008f 100644--- a/ui-tui/src/components/activeSessionSwitcher.tsx+++ b/ui-tui/src/components/activeSessionSwitcher.tsx@@ -519,7 +519,13 @@ export function ActiveSessionSwitcher({const closed = Boolean(result?.closed ?? result?.ok)if (!closed) {- setActionErr(messages().pickers.session.errors.alreadyClosed)+ // A canonical view closes only what it holds: a null answer means no close was attempted, not+ // that main refused one. Only a receipt can say the session was already closed.+ setActionErr(+ gw.isCanonical && result === null+ ? messages().pickers.session.errors.notAttached+ : messages().pickers.session.errors.alreadyClosed+ )return}@@ -539,7 +545,7 @@ export function ActiveSessionSwitcher({} finally {setClosingId('')}- }, [closingId, currentSessionId, history.length, items, load, onClose, onNew, onSelect, rowKind, sel])+ }, [closingId, currentSessionId, gw.isCanonical, history.length, items, load, onClose, onNew, onSelect, rowKind, sel])const performDelete = useCallback((id: string) => {diff --git a/ui-tui/src/i18n/en/pickers.ts b/ui-tui/src/i18n/en/pickers.tsindex 8c4147418ea..45a23ad6a48 100644--- a/ui-tui/src/i18n/en/pickers.ts+++ b/ui-tui/src/i18n/en/pickers.ts@@ -110,7 +110,8 @@ export const pickersEn = {},errors: {couldNotLoadResumable: 'could not load resumable sessions',- alreadyClosed: 'session was already closed'+ alreadyClosed: 'session was already closed',+ notAttached: 'this view is not attached to that session — nothing was closed'},row: {new: 'new',