Skip to content

The agent that grows with you

Revert "fix(tui): a /new, /resume or live-session pick during reconnect wins over recovery"

Teknium1d95ec3696c6
diff --git a/ui-tui/src/__tests__/reconnectUserAttachWins.test.ts b/ui-tui/src/__tests__/reconnectUserAttachWins.test.ts
deleted file mode 100644
index 61bebb32855..00000000000
--- a/ui-tui/src/__tests__/reconnectUserAttachWins.test.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-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.ts
index 7f8500cc757..91cfac825e7 100644
--- a/ui-tui/src/app/createGatewayEventHandler.ts
+++ b/ui-tui/src/app/createGatewayEventHandler.ts
@@ -959,13 +959,6 @@ 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.ts
index be47fa6b097..4df40528a62 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -627,7 +627,6 @@ 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.ts
index 9d99a040f42..a6ec80f3246 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 MutableRefObject, type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'
+import { type RefObject, useCallback, useEffect, useMemo, useRef } from 'react'
import { localCreationOptions } from '../canonicalGateway.js'
import { STARTUP_WORKSPACE_CWD } from '../config/env.js'
@@ -138,8 +138,6 @@ export interface UseSessionLifecycleOptions {
gw: GatewayClient
onFreshSessionStarted?: (sessionId: string) => void
panel: (title: string, sections: PanelSection[]) => void
- /** The session gateway.ready resumes after a transport loss (owned by useMainApp). */
- recoverSidRef?: MutableRefObject<null | string>
rpc: GatewayRpc
scrollRef: RefObject<null | ScrollBoxHandle>
setHistoryItems: StateSetter<Msg[]>
@@ -158,7 +156,6 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
gw,
onFreshSessionStarted,
panel,
- recoverSidRef,
rpc,
scrollRef,
setHistoryItems,
@@ -176,9 +173,7 @@ 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 }) : null
if (!deferMessages) {
closed?.messages?.forEach(message => sys(message))
@@ -196,48 +191,6 @@ 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) {
@@ -378,8 +331,6 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const flight = ++attachmentFlight.current
const previousSid = getUiState().sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
- const holding = holdRecovery()
- let bound = false
pendingAttachments.current.add(flight)
try {
@@ -482,11 +433,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
adoptAttachment(r, previousSid, previousSubscription)
- bound = true
return r.session_id
} finally {
- settleRecovery(flight, bound, holding)
finishAttachment(flight)
}
},
@@ -497,14 +446,12 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
discardStaleAttachment,
finishAttachment,
gw,
- holdRecovery,
onFreshSessionStarted,
panel,
resetSession,
rpc,
setHistoryItems,
setSessionStartedAt,
- settleRecovery,
sys
]
)
@@ -529,8 +476,6 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
pendingAttachments.current.add(flight)
const previousSid = getUiState().sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
- const holding = holdRecovery(id)
- let bound = false
patchOverlayState({ sessions: false })
patchUiState({ status: t('session.status.switchingSession') })
// The card belongs to the session being left; the activated one answers with its own.
@@ -595,7 +540,6 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
cancelResumeScrollRef.current?.()
cancelResumeScrollRef.current = scheduleResumeScrollToBottom(scrollRef)
adoptAttachment(r, previousSid, previousSubscription)
- bound = true
})
.catch((e: Error) => {
if (flight !== attachmentFlight.current) {
@@ -605,22 +549,17 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
- .finally(() => {
- settleRecovery(flight, bound, holding)
- finishAttachment(flight)
- })
+ .finally(() => finishAttachment(flight))
},
[
adoptAttachment,
discardStaleAttachment,
finishAttachment,
gw,
- holdRecovery,
resetSession,
scrollRef,
setHistoryItems,
setSessionStartedAt,
- settleRecovery,
sys
]
)
@@ -632,8 +571,6 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const current = captureDestination()
const previousSid = current.sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
- const holding = holdRecovery(id)
- let bound = false
const destination =
current.sid === id || current.storedSid === id ? current : { ...current, sid: id, storedSid: id }
@@ -721,11 +658,6 @@ 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) {
@@ -736,10 +668,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
patchUiState({ status: 'ready' })
})
})
- .finally(() => {
- settleRecovery(flight, bound, holding)
- finishAttachment(flight)
- })
+ .finally(() => finishAttachment(flight))
},
[
adoptAttachment,
@@ -748,21 +677,16 @@ 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) {