The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): a /new, /resume or live-session pick during reconnect wins over recovery
Teknium7e863e6ea8bb
diff --git a/ui-tui/src/__tests__/reconnectUserAttachWins.test.ts b/ui-tui/src/__tests__/reconnectUserAttachWins.test.tsnew file mode 100644index 00000000000..61bebb32855--- /dev/null+++ b/ui-tui/src/__tests__/reconnectUserAttachWins.test.ts@@ -0,0 +1,153 @@+import { PassThrough } from 'stream'++import { renderSync } from '@hermes/ink'+import React, { useEffect } from 'react'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'+import { turnController } from '../app/turnController.js'+import { resetTurnState } from '../app/turnStore.js'+import { getUiState, patchUiState, resetUiState } from '../app/uiStore.js'+import { useSessionLifecycle } from '../app/useSessionLifecycle.js'++const info = { cwd: '/w', model: 'test', skills: {}, tools: {} }++const deferred = <T>() => {+ let resolve!: (value: T) => void+ let reject!: (error: Error) => void+ const promise = new Promise<T>((res, rej) => ((resolve = res), (reject = rej)))++ return { promise, reject, resolve }+}++/** The real lifecycle hook and the real gateway.ready handler sharing one recovery ref,+ * as useMainApp wires them, over an owner whose answers the test controls. */+function mount(answer: (method: string, params: any) => Promise<unknown>) {+ let api: null | ReturnType<typeof useSessionLifecycle> = null+ const recoverSidRef = { current: null as null | string }+ const request = vi.fn(answer)+ const gw = { isCanonical: true, request }++ const rpc = (async (method: string, params: any) => {+ try {+ return await request(method, params)+ } catch {+ return null+ }+ }) as any++ function Probe() {+ const lifecycle = useSessionLifecycle({+ colsRef: { current: 80 },+ composerActions: { setComposerTokens: vi.fn() } as any,+ gw: gw as any,+ panel: vi.fn(),+ recoverSidRef,+ rpc,+ scrollRef: { current: null },+ setHistoryItems: vi.fn(),+ setLastUserMsg: vi.fn(),+ setSessionStartedAt: vi.fn(),+ setStickyPrompt: vi.fn(),+ setVoiceProcessing: vi.fn(),+ setVoiceRecording: vi.fn(),+ sys: vi.fn()+ })++ useEffect(() => {+ api = lifecycle+ })++ return null+ }++ const stream = () => Object.assign(new PassThrough(), { columns: 80, isTTY: false, rows: 24 })++ renderSync(React.createElement(Probe), {+ patchConsole: false,+ stderr: stream() as unknown as NodeJS.WriteStream,+ stdin: stream() as unknown as NodeJS.ReadStream,+ stdout: stream() as unknown as NodeJS.WriteStream+ })++ const ready = () =>+ createGatewayEventHandler({+ composer: { setInput: vi.fn() },+ gateway: { gw, rpc },+ session: {+ STARTUP_RESUME_ID: '',+ colsRef: { current: 80 },+ newSession: (...args: any[]) => api!.newSession(...args),+ recoverSidRef,+ resetSession: vi.fn(),+ resumeById: (id: string) => api!.resumeById(id),+ setCatalog: vi.fn()+ },+ submission: { submitLiteralRef: { current: vi.fn() }, submitRef: { current: vi.fn() } },+ system: { bellOnComplete: false, sys: vi.fn() },+ transcript: { appendMessage: vi.fn(), panel: vi.fn(), setHistoryItems: vi.fn() },+ voice: { setProcessing: vi.fn(), setRecording: vi.fn(), setVoiceEnabled: vi.fn() }+ } as any)({ payload: {}, type: 'gateway.ready' } as any)++ return { api: () => api!, ready, recoverSidRef, request }+}++const resumed = (session_id: string) => ({ info, messages: [], session_id, session_key: session_id, status: 'idle' })++// Socket closed on session "old": the exit handler armed recovery and marked the view+// disconnected. The user types /new during "reconnecting…"; its frame forces the+// reconnect, and gateway.ready is published after runtime.describe.+describe('a user attach during reconnect supersedes the recovery resume', () => {+ beforeEach(() => {+ resetUiState()+ resetTurnState()+ turnController.fullReset()+ patchUiState({ gatewayConnected: false, sid: 'old', storedSid: 'old' })+ })++ it('/new answered after gateway.ready keeps the new session', async () => {+ const create = deferred<unknown>()++ const h = mount(async method =>+ method === 'session.create' ? create.promise : method === 'session.resume' ? resumed('old') : null+ )++ h.recoverSidRef.current = 'old'+ await vi.waitFor(() => expect(h.api()).toBeTruthy())++ const minted = h.api().newSession()+ h.ready()+ create.resolve({ info, session_id: 'new', stored_session_id: 'new' })++ expect(await minted).toBe('new')+ await new Promise(resolve => setTimeout(resolve, 10))+ expect(getUiState().sid).toBe('new')+ expect(h.request.mock.calls.filter(([method]) => method === 'session.resume')).toEqual([])+ expect(h.request.mock.calls.filter(([method]) => method === 'session.create')).toHaveLength(1)+ expect(h.request).not.toHaveBeenCalledWith('session.detach', expect.objectContaining({ session_id: 'new' }))+ expect(h.recoverSidRef.current).toBeNull()+ })++ it('a refused /new hands the target back and recovers the old session', async () => {+ const create = deferred<unknown>()++ const h = mount(async method =>+ method === 'session.create' ? create.promise : method === 'session.resume' ? resumed('old') : null+ )++ h.recoverSidRef.current = 'old'+ await vi.waitFor(() => expect(h.api()).toBeTruthy())++ const minted = h.api().newSession()+ h.ready()+ create.reject(new Error('runtime_draining'))++ expect(await minted).toBeNull()+ await vi.waitFor(() =>+ expect(h.request).toHaveBeenCalledWith('session.resume', expect.objectContaining({ session_id: 'old' }))+ )+ await vi.waitFor(() => expect(getUiState().gatewayConnected).toBe(true))+ expect(getUiState().sid).toBe('old')+ expect(h.recoverSidRef.current).toBeNull()+ })+})diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 91cfac825e7..7f8500cc757 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -959,6 +959,13 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:return}+ // The view already holds a session (a user attach took over the recovery target, or+ // bound before the first ready): never forge or auto-resume a replacement behind it.+ // The one-shot startup prompt still goes to that session.+ if (getUiState().sid) {+ return scheduleStartupPrompt()+ }+if (STARTUP_RESUME_ID) {patchUiState({ status: t('session.status.resuming') })resumeById(STARTUP_RESUME_ID)diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.tsindex 4df40528a62..be47fa6b097 100644--- a/ui-tui/src/app/useMainApp.ts+++ b/ui-tui/src/app/useMainApp.ts@@ -627,6 +627,7 @@ export function useMainApp(gw: GatewayClient) {gw,onFreshSessionStarted: DASHBOARD_TUI_MODE ? setDashboardFreshSessionId : undefined,panel,+ recoverSidRef,rpc,scrollRef,setHistoryItems,diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex a6ec80f3246..9d99a040f42 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -4,7 +4,7 @@ import { writeFileSync } from 'node:fs'import type { ScrollBoxHandle } from '@hermes/ink'import { evictInkCaches } from '@hermes/ink'import type { InflightTurn, SessionResumeResult, Usage } from '@hermes/shared/gateway-events'-import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'+import { type MutableRefObject, type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'import { localCreationOptions } from '../canonicalGateway.js'import { STARTUP_WORKSPACE_CWD } from '../config/env.js'@@ -138,6 +138,8 @@ export interface UseSessionLifecycleOptions {gw: GatewayClientonFreshSessionStarted?: (sessionId: string) => voidpanel: (title: string, sections: PanelSection[]) => void+ /** The session gateway.ready resumes after a transport loss (owned by useMainApp). */+ recoverSidRef?: MutableRefObject<null | string>rpc: GatewayRpcscrollRef: RefObject<null | ScrollBoxHandle>setHistoryItems: StateSetter<Msg[]>@@ -156,6 +158,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {gw,onFreshSessionStarted,panel,+ recoverSidRef,rpc,scrollRef,setHistoryItems,@@ -173,7 +176,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {const closeSession = useCallback(async (targetSid?: null | string, deferMessages = false) => {const closed =- targetSid && !gw.isCanonical ? await rpc<SessionCloseResponse>('session.close', { session_id: targetSid }) : null+ targetSid && !gw.isCanonical+ ? await rpc<SessionCloseResponse>('session.close', { session_id: targetSid })+ : nullif (!deferMessages) {closed?.messages?.forEach(message => sys(message))@@ -191,6 +196,48 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {const canonicalDetachFlights = useRef(new Map<string, Promise<void>>())const staleAttachments = useRef(new Map<string, { session_id: string; subscription_id: string }>())+ // A user attach (/new, /resume <other>, picking a live session) supersedes the pending+ // recovery resume: it holds the target so gateway.ready cannot snap the view back.+ // If the newest attach ends unbound, the target is handed back and recovered now+ // (gateway.ready has usually passed already); any bind settles it.+ const heldRecovery = useRef<null | string>(null)+ const resumeRef = useRef<(id: string) => Promise<void>>(async () => undefined)++ const holdRecovery = useCallback(+ (id?: string) => {+ const target = recoverSidRef?.current++ if (recoverSidRef && target && target !== id) {+ heldRecovery.current ??= target+ recoverSidRef.current = null+ }++ return Boolean(heldRecovery.current) && recoverSidRef?.current !== id+ },+ [recoverSidRef]+ )++ const settleRecovery = useCallback(+ (flight: number, bound: boolean, holding: boolean) => {+ const target = heldRecovery.current++ if (flight !== attachmentFlight.current || !target || (!bound && !holding)) {+ return+ }++ heldRecovery.current = null++ if (bound && recoverSidRef?.current === target) {+ // A second disconnect before this bind re-armed the old session; the bind supersedes it.+ recoverSidRef.current = null+ } else if (!bound && recoverSidRef) {+ recoverSidRef.current = target+ void resumeRef.current(target)+ }+ },+ [recoverSidRef]+ )+const detachCanonical = useCallback((sessionId?: null | string, subscriptionId?: null | string) => {if (!gw.isCanonical || !sessionId || !subscriptionId) {@@ -331,6 +378,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {const flight = ++attachmentFlight.currentconst previousSid = getUiState().sidconst previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined+ const holding = holdRecovery()+ let bound = falsependingAttachments.current.add(flight)try {@@ -433,9 +482,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)adoptAttachment(r, previousSid, previousSubscription)+ bound = truereturn r.session_id} finally {+ settleRecovery(flight, bound, holding)finishAttachment(flight)}},@@ -446,12 +497,14 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {discardStaleAttachment,finishAttachment,gw,+ holdRecovery,onFreshSessionStarted,panel,resetSession,rpc,setHistoryItems,setSessionStartedAt,+ settleRecovery,sys])@@ -476,6 +529,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {pendingAttachments.current.add(flight)const previousSid = getUiState().sidconst previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined+ const holding = holdRecovery(id)+ let bound = falsepatchOverlayState({ sessions: false })patchUiState({ status: t('session.status.switchingSession') })// The card belongs to the session being left; the activated one answers with its own.@@ -540,6 +595,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {cancelResumeScrollRef.current?.()cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)adoptAttachment(r, previousSid, previousSubscription)+ bound = true}).catch((e: Error) => {if (flight !== attachmentFlight.current) {@@ -549,17 +605,22 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {sys(`error: ${e.message}`)patchUiState({ status: 'ready' })})- .finally(() => finishAttachment(flight))+ .finally(() => {+ settleRecovery(flight, bound, holding)+ finishAttachment(flight)+ })},[adoptAttachment,discardStaleAttachment,finishAttachment,gw,+ holdRecovery,resetSession,scrollRef,setHistoryItems,setSessionStartedAt,+ settleRecovery,sys])@@ -571,6 +632,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {const current = captureDestination()const previousSid = current.sidconst previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined+ const holding = holdRecovery(id)+ let bound = falseconst destination =current.sid === id || current.storedSid === id ? current : { ...current, sid: id, storedSid: id }@@ -658,6 +721,11 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {}adoptAttachment(r, previousSid, previousSubscription)+ bound = true++ if (recoverSidRef?.current === id) {+ recoverSidRef.current = null+ }}).catch((e: Error) => {if (flight !== attachmentFlight.current) {@@ -668,7 +736,10 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {patchUiState({ status: 'ready' })})})- .finally(() => finishAttachment(flight))+ .finally(() => {+ settleRecovery(flight, bound, holding)+ finishAttachment(flight)+ })},[adoptAttachment,@@ -677,16 +748,21 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {discardStaleAttachment,finishAttachment,gw,+ holdRecovery,panel,+ recoverSidRef,resetSession,rpc,scrollRef,setHistoryItems,setSessionStartedAt,+ settleRecovery,sys])+ resumeRef.current = resumeById+const guardBusySessionSwitch = useCallback((what = t('session.lifecycle.switchSessions')) => {if (!getUiState().busy) {