Skip to content

The agent that grows with you

fix(tui): defer stale subscription disposal until attachments settle

David Dudok de Wit7050637285b9
diff --git a/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx b/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx
new file mode 100644
index 00000000000..fa6ffb1fe10
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalDetachOrdering.test.tsx
@@ -0,0 +1,139 @@
+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'
+
+type AttachmentAction = 'resumeById' | 'activateLiveSession'
+
+function fixture() {
+ const home = mkdtempSync(join(tmpdir(), 'ink-detach-order-'))
+ vi.stubEnv('HERMES_HOME', home)
+ resetUiState()
+ const subscriptions = new Map<string, string>()
+ const pending: Array<{ resolve: () => void; reject: () => void; invalid: () => void }> = []
+ let nextToken = 0
+
+ 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') {
+ // The real owner reuses a token for repeated attaches by the same actor.
+ const token = subscriptions.get(sid) ?? `sub-${++nextToken}`
+ 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, reject) => pending.push({ resolve: () => resolve(result),
+ reject: () => reject(new Error('fixture response failed')), invalid: () => resolve(null) }))
+ }
+
+ 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>viewer ordering</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 { subscriptions, pending, request,
+ attach: (method: AttachmentAction, sid: string) => lifecycle[method](sid),
+ async initial() {
+ lifecycle.resumeById('x')
+ await vi.waitFor(() => expect(pending).toHaveLength(1))
+ pending.shift()!.resolve()
+ await vi.waitFor(() => expect(getUiState().sid).toBe('x'))
+ },
+ cleanup() {
+ instance.unmount()
+ resetUiState()
+ vi.unstubAllEnvs()
+ rmSync(home, { recursive: true, force: true })
+ } }
+}
+
+const pairs: [AttachmentAction, AttachmentAction][] = [
+ ['resumeById', 'resumeById'], ['activateLiveSession', 'activateLiveSession'],
+ ['resumeById', 'activateLiveSession'], ['activateLiveSession', 'resumeById']
+]
+
+it.each(pairs.flatMap(([first, second]) => [true, false].map(staleFirst => ({ first, second, staleFirst }))))(
+ 'keeps the winning token for $first -> $second, staleFirst=$staleFirst', async ({ first, second, staleFirst }) => {
+ const f = fixture()
+
+ try {
+ await f.initial()
+ f.attach(first, 'a')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(1))
+ f.attach(second, 'a')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(2))
+ const [older, newer] = f.pending.splice(0)
+ const token = f.subscriptions.get('a')
+
+ for (const response of staleFirst ? [older, newer] : [newer, older]) {
+ response.resolve()
+ await new Promise(resolve => setImmediate(resolve))
+ }
+
+ await vi.waitFor(() => expect(getUiState().sid).toBe('a'))
+ expect(f.subscriptions.get('a')).toBe(token)
+ expect(f.subscriptions.has('x')).toBe(false)
+ expect(f.request).not.toHaveBeenCalledWith('session.detach', { session_id: 'a', subscription_id: token })
+ } finally {
+ f.cleanup()
+ }
+ }
+)
+
+it.each((['resumeById', 'activateLiveSession'] as const).flatMap(method =>
+ (['reject', 'invalid'] as const).map(outcome => ({ method, outcome }))))(
+ 'disposes deferred unadopted tokens when newer $method returns $outcome', async ({ method, outcome }) => {
+ const f = fixture()
+
+ try {
+ await f.initial()
+ f.attach(method, 'a')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(1))
+ f.attach(method, 'a')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(2))
+ const [older, newer] = f.pending.splice(0)
+ older.resolve()
+ await new Promise(resolve => setImmediate(resolve))
+ expect(f.subscriptions.has('a')).toBe(true)
+ newer[outcome]()
+ await vi.waitFor(() => expect(f.subscriptions.has('a')).toBe(false))
+ expect(getUiState().sid).toBe('x')
+ expect(f.subscriptions.has('x')).toBe(true)
+ } finally {
+ f.cleanup()
+ }
+ }
+)
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 8d2af4a3014..136e3fdbb3c 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -147,8 +147,10 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const cancelResumeScrollRef = useRef<null | (() => void)>(null)
const attachmentFlight = useRef(0)
+ const pendingAttachments = useRef(new Set<number>())
const canonicalSubscriptions = useRef(new Map<string, string>())
const canonicalDetachFlights = useRef(new Map<string, Promise<void>>())
+ const staleAttachments = useRef(new Map<string, { session_id: string; subscription_id: string }>())
const detachCanonical = useCallback((sessionId?: null | string, subscriptionId?: null | string) => {
if (!gw.isCanonical || !sessionId || !subscriptionId) {
@@ -174,14 +176,36 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
})
}, [gw.isCanonical, rpc])
- const discardStaleAttachment = useCallback((result?: null | { session_id: string; subscription_id?: string }) => {
- const subscriptionId = result?.subscription_id
+ 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.
+ if (pendingAttachments.current.size) {return}
+
+ const stale = [...staleAttachments.current.values()]
+ staleAttachments.current.clear()
- if (result && subscriptionId && canonicalSubscriptions.current.get(result.session_id) !== subscriptionId) {
- detachCanonical(result.session_id, subscriptionId)
+ for (const result of stale) {
+ if (canonicalSubscriptions.current.get(result.session_id) !== result.subscription_id) {
+ detachCanonical(result.session_id, result.subscription_id)
+ }
}
}, [detachCanonical])
+ const finishAttachment = useCallback((flight: number) => {
+ pendingAttachments.current.delete(flight)
+ disposeStaleAttachments()
+ }, [disposeStaleAttachments])
+
+ const discardStaleAttachment = useCallback((result?: null | { session_id: string; subscription_id?: string }) => {
+ if (result?.subscription_id) {
+ staleAttachments.current.set(JSON.stringify([result.session_id, result.subscription_id]), {
+ session_id: result.session_id, subscription_id: result.subscription_id
+ })
+ }
+
+ disposeStaleAttachments()
+ }, [disposeStaleAttachments])
+
const adoptAttachment = useCallback((
result: { session_id: string; subscription_id?: string },
previousSid?: null | string,
@@ -246,99 +270,105 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const flight = ++attachmentFlight.current
const previousSid = getUiState().sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
- const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})
+ pendingAttachments.current.add(flight)
- if (flight !== attachmentFlight.current) {return null}
+ try {
+ const setup = gw.isCanonical ? null : await rpc<SetupStatusResponse>('setup.status', {})
- if (setup?.provider_configured === false) {
- panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
- patchUiState({ status: 'setup required' })
+ if (flight !== attachmentFlight.current) {return null}
- return null
- }
+ if (setup?.provider_configured === false) {
+ panel(SETUP_REQUIRED_TITLE, buildSetupRequiredSections())
+ patchUiState({ status: 'setup required' })
- if (!keepCurrent) {
- await closeSession(previousSid)
+ return null
+ }
- if (flight !== attachmentFlight.current) {return null}
- }
+ if (!keepCurrent) {
+ await closeSession(previousSid)
- const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
- ? { request_id: randomUUID(), ...localCreationOptions() } : { cols: colsRef.current })
+ if (flight !== attachmentFlight.current) {return null}
+ }
- if (flight !== attachmentFlight.current) {
- discardStaleAttachment(r)
+ const r = await rpc<SessionCreateResponse>('session.create', gw.isCanonical
+ ? { request_id: randomUUID(), ...localCreationOptions() } : { cols: colsRef.current })
- return null
- }
+ if (flight !== attachmentFlight.current) {
+ discardStaleAttachment(r)
- if (!r) {
- patchUiState({ status: 'ready' })
+ return null
+ }
- return null
- }
+ if (!r) {
+ patchUiState({ status: 'ready' })
- const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null
- const requestedTitle = title?.trim() ?? ''
+ return null
+ }
- resetSession()
- setSessionStartedAt(Date.now())
+ const info = r.info ? { ...r.info, stored_session_id: r.stored_session_id || r.info.stored_session_id } : null
+ const requestedTitle = title?.trim() ?? ''
- writeActiveSessionFile(r.session_id)
- patchUiState({
- info,
- sid: r.session_id,
- status: gw.isCanonical || info?.version ? 'ready' : 'starting agent…',
- usage: usageFrom(info)
- })
+ resetSession()
+ setSessionStartedAt(Date.now())
- if (info) {
- setHistoryItems([introMsg(info)])
- }
+ writeActiveSessionFile(r.session_id)
+ patchUiState({
+ info,
+ sid: r.session_id,
+ status: gw.isCanonical || info?.version ? 'ready' : 'starting agent…',
+ usage: usageFrom(info)
+ })
- if (info?.credential_warning) {
- sys(`warning: ${info.credential_warning}`)
- }
+ if (info) {
+ setHistoryItems([introMsg(info)])
+ }
- if (info?.config_warning) {
- sys(`warning: ${info.config_warning}`)
- }
+ if (info?.credential_warning) {
+ sys(`warning: ${info.credential_warning}`)
+ }
- if (msg) {
- sys(msg)
- }
+ if (info?.config_warning) {
+ sys(`warning: ${info.config_warning}`)
+ }
- if (requestedTitle) {
- rpc<SessionTitleResponse>('session.title', {
- session_id: r.session_id,
- title: requestedTitle
- })
- .then(result => {
- if (!result || getUiState().sid !== r.session_id) {
- return
- }
+ if (msg) {
+ sys(msg)
+ }
- const nextTitle = (result.title ?? requestedTitle).trim()
- const suffix = result.pending ? ' (queued while session initializes)' : ''
- patchUiState({ sessionTitle: nextTitle })
- sys(`session title set: ${nextTitle}${suffix}`)
+ if (requestedTitle) {
+ rpc<SessionTitleResponse>('session.title', {
+ session_id: r.session_id,
+ title: requestedTitle
})
- .catch((err: unknown) => {
- if (getUiState().sid !== r.session_id) {
- return
- }
+ .then(result => {
+ if (!result || getUiState().sid !== r.session_id) {
+ return
+ }
+
+ const nextTitle = (result.title ?? requestedTitle).trim()
+ const suffix = result.pending ? ' (queued while session initializes)' : ''
+ patchUiState({ sessionTitle: nextTitle })
+ sys(`session title set: ${nextTitle}${suffix}`)
+ })
+ .catch((err: unknown) => {
+ if (getUiState().sid !== r.session_id) {
+ return
+ }
- const message = err instanceof Error ? err.message : String(err)
- sys(`warning: failed to set session title: ${message}`)
- })
- }
+ const message = err instanceof Error ? err.message : String(err)
+ sys(`warning: failed to set session title: ${message}`)
+ })
+ }
- signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
- adoptAttachment(r, previousSid, previousSubscription)
+ signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
+ adoptAttachment(r, previousSid, previousSubscription)
- return r.session_id
+ return r.session_id
+ } finally {
+ finishAttachment(flight)
+ }
},
- [adoptAttachment, closeSession, colsRef, discardStaleAttachment, gw.isCanonical, onFreshSessionStarted, panel,
+ [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw.isCanonical, onFreshSessionStarted, panel,
resetSession, rpc, setHistoryItems, setSessionStartedAt, sys]
)
@@ -359,6 +389,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const activateLiveSession = useCallback(
(id: string) => {
const flight = ++attachmentFlight.current
+ pendingAttachments.current.add(flight)
const previousSid = getUiState().sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
patchOverlayState({ sessions: false })
@@ -413,13 +444,15 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
+ .finally(() => finishAttachment(flight))
},
- [adoptAttachment, discardStaleAttachment, gw, resetSession, scrollRef, setHistoryItems, setSessionStartedAt, sys]
+ [adoptAttachment, discardStaleAttachment, finishAttachment, gw, resetSession, scrollRef, setHistoryItems, setSessionStartedAt, sys]
)
const resumeById = useCallback(
(id: string) => {
const flight = ++attachmentFlight.current
+ pendingAttachments.current.add(flight)
const current = captureDestination()
const previousSid = current.sid
const previousSubscription = previousSid ? canonicalSubscriptions.current.get(previousSid) : undefined
@@ -446,7 +479,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
? gw.request<SessionResumeResponse>('session.resume', { cols: colsRef.current, session_id: id }) : null)
: gw.request<SessionResumeResponse>('session.resume', { cols: colsRef.current, session_id: id })
- request
+ return request
.then(raw => {
const r = asRpcResult<SessionResumeResponse>(raw)
@@ -501,9 +534,9 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
sys(`error: ${e.message}`)
patchUiState({ status: 'ready' })
})
- })
+ }).finally(() => finishAttachment(flight))
},
- [adoptAttachment, closeSession, colsRef, discardStaleAttachment, gw, panel, resetSession, rpc, scrollRef,
+ [adoptAttachment, closeSession, colsRef, discardStaleAttachment, finishAttachment, gw, panel, resetSession, rpc, scrollRef,
setHistoryItems, setSessionStartedAt, sys]
)