Skip to content

The agent that grows with you

fix(tui): closing a canonical view stamps the row as main's session.close did

Tekniumac93134d03aa
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 18f3d2081e1..af7506826fb 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4938,6 +4938,7 @@ export interface CanonicalSessionListRow {
started_at: number | null
message_count: number
running: boolean
+ model?: string | null
resolved_id?: string | null
root_title?: string | null
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 33359e58541..3aefb9f825a 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -10242,6 +10242,18 @@
"title": "Running",
"type": "boolean"
},
+ "model": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Model"
+ },
"resolved_id": {
"anyOf": [
{
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 0a35433cbec..57f144b795b 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -394,9 +394,14 @@ class AuthorityConnection:
if row.get('source') in INTERNAL_LISTING_SOURCES or (
not params.get('include_hidden') and (row.get('hidden') or row.get('archived'))):
continue
+ from gateway.session_local_close import closed_and_unviewed
+ if closed_and_unviewed(self.authority, sid, handle):
+ # Closed by its last viewer and idle: main lists it as resumable (the stored
+ # feed), not as a live session.
+ continue
sessions.append({'session_id': sid, 'id': sid, 'title': row.get('title') or '',
'source': row.get('source'), 'started_at': row.get('started_at'),
- 'message_count': row.get('message_count', 0),
+ 'message_count': row.get('message_count', 0), 'model': row.get('model'),
'running': handle.execution_state == 'running'})
sessions.sort(key=lambda row: row['started_at'] or 0, reverse=True)
return {'sessions': sessions[:limit], 'scope': 'live'}
diff --git a/gateway/session_listing.py b/gateway/session_listing.py
index c2a88f54142..45b4103dc7d 100644
--- a/gateway/session_listing.py
+++ b/gateway/session_listing.py
@@ -16,15 +16,23 @@ def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):
or not {'session:read', 'session:create'} <= actor.capabilities):
return {'sessions': [], 'scope': 'stored'}
db = authority.db
- sessions, offset = [], 0
+ sessions, offset, seen = [], 0, set()
while len(sessions) < limit:
- rows = db.list_sessions_rich(sources=['cli', 'tui', 'gui', 'desktop'], limit=200, offset=offset,
+ rows = db.list_sessions_rich(sources=['cli', 'tui', 'gui', 'desktop', 'local'], limit=200, offset=offset,
order_by_last_active=True, compact_rows=True, include_hidden=include_hidden)
for row in rows:
sid = db.get_compression_tip(row['id']) or row['id']
tip = db.get_session(sid)
if tip is None:
continue
+ closed = _closed_local_session(authority, actor, row, tip)
+ if closed is not None:
+ if closed['id'] not in seen:
+ seen.add(closed['id'])
+ sessions.append(closed)
+ if len(sessions) == limit:
+ break
+ continue
try:
validate_legacy_row(db, tip)
with db._read_ctx() as conn:
@@ -37,10 +45,31 @@ def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):
sessions.append({'id': row['id'], 'session_id': sid, 'resolved_id': sid,
'title': row.get('title') or '', 'source': tip['source'],
'started_at': row.get('started_at'), 'message_count': row.get('message_count', 0),
- 'running': False})
+ 'model': tip.get('model'), 'running': False})
if len(sessions) == limit:
break
if len(rows) < 200:
break
offset += len(rows)
return {'sessions': sessions, 'scope': 'stored'}
+
+
+def _closed_local_session(authority, actor, row, tip):
+ """A canonical local session (created here, or adopted from main) its last viewer closed: main's
+ picker listed it as resumable. None for anything else, including a session another principal owns."""
+ from gateway.session_contract import SessionRef
+ from gateway.session_local_close import closed_and_unviewed
+ owner = tip.get('chat_id')
+ live = authority.sessions.get(owner) if owner else None
+ if live is None:
+ return None
+ try:
+ handle = authority._handle(SessionRef(authority.profile_id, owner))
+ authority.authorize(actor, handle.ref, 'session:read')
+ except RuntimeStoreError:
+ return None
+ if not closed_and_unviewed(authority, owner, handle):
+ return None
+ return {'id': owner, 'session_id': owner, 'resolved_id': owner, 'title': tip.get('title') or row.get('title') or '',
+ 'source': tip['source'], 'started_at': row.get('started_at'),
+ 'message_count': row.get('message_count', 0), 'model': tip.get('model'), 'running': False}
diff --git a/gateway/session_local_close.py b/gateway/session_local_close.py
new file mode 100644
index 00000000000..8fbadd0c373
--- /dev/null
+++ b/gateway/session_local_close.py
@@ -0,0 +1,26 @@
+"""The picker's view of a canonical local session its last viewer closed, as main listed it.
+
+Main's sidecar stamped ``tui_close`` (``/new``, a resume switch) and ``tui_shutdown`` (exit) on the
+session row it owned; pickers then listed it as resumable. The stamp itself is the owner's
+``session.detach {end_reason}`` (``session_acp_lifecycle.end_idle_viewer_session``); this module only
+decides which live rows read as closed.
+"""
+from hermes_state_local import local_receipt
+from hermes_state_runtime import RuntimeStoreError
+
+
+def _local_target(authority, session_id):
+ try:
+ return local_receipt(authority.db, session_id)['entry']['session_id']
+ except (RuntimeStoreError, KeyError, TypeError):
+ return None # not a local session (API binding, malformed receipt): nothing to read as closed
+
+
+def closed_and_unviewed(authority, session_id, handle):
+ """A live-feed row main would list as resumable: closed, idle and with no viewer left."""
+ live = authority.sessions.get(session_id)
+ if live is None or live.subscribers or handle.execution_state != 'idle':
+ return False
+ target = _local_target(authority, session_id)
+ row = authority.db.get_session(target) if target else None
+ return bool(row and row.get('ended_at') is not None)
diff --git a/tests/gateway/test_tui_detach_end_stamp.py b/tests/gateway/test_tui_detach_end_stamp.py
new file mode 100644
index 00000000000..6790affd20e
--- /dev/null
+++ b/tests/gateway/test_tui_detach_end_stamp.py
@@ -0,0 +1,82 @@
+"""The TUI's close of a canonical session stamps the row as main's sidecar did (PR #106742 rows 28/35/38).
+
+Main's TUI closed its session on ``/new`` / resume-switch (``tui_close``) and on exit (``tui_shutdown``),
+and the picker then listed it as resumable rather than live. On the canonical owner the TUI detaches with
+that ``end_reason``; the owner stamps it only when no other viewer remains and the FIFO is idle, and the
+picker's live feed drops a closed, idle, unviewed session into the stored (resumable) feed.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+
+async def _owner(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='owner')
+ return store._db, authority
+
+
+def _native(authority, tmp_path):
+ from gateway.session_controls import AuthorityConnection
+ return AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {
+ 'provider': 'local', 'user_id': 'native', 'profile_id': str(tmp_path), 'instance_id': 'owner'})
+
+
+async def _call(conn, method, **params):
+ reply = await conn.dispatch({'id': 1, 'method': method, 'params': params})
+ assert 'result' in reply, reply
+ return reply['result']
+
+
[email protected]('reason', ['tui_close', 'tui_shutdown'])
+async def test_tui_detach_stamps_end_reason_and_moves_row_to_resumable(tmp_path, monkeypatch, reason):
+ db, authority = await _owner(tmp_path, monkeypatch)
+ db.create_session('old-tui', source='tui', model='fake-model', cwd=str(tmp_path))
+ db.append_message('old-tui', 'user', 'q')
+ db.append_message('old-tui', 'assistant', 'a')
+ viewer = _native(authority, tmp_path)
+ resumed = await _call(viewer, 'session.resume', session_id='old-tui')
+ # Opening a closed chat reopens it only on the first turn; reopen to model an active session.
+ db.reopen_session('old-tui')
+ live = await _call(viewer, 'session.list')
+ assert [(r['id'], r['model']) for r in live['sessions']] == [('old-tui', 'fake-model')]
+
+ # A second viewer holds the session open: no stamp.
+ other = _native(authority, tmp_path)
+ second = await _call(other, 'session.resume', session_id='old-tui')
+ out = await _call(viewer, 'session.detach', session_id='old-tui',
+ subscription_id=resumed['subscription_id'], end_reason=reason)
+ assert out['detached'] is True
+ assert db.get_session('old-tui')['end_reason'] is None
+
+ await _call(other, 'session.detach', session_id='old-tui',
+ subscription_id=second['subscription_id'], end_reason=reason)
+ row = db.get_session('old-tui')
+ assert (row['end_reason'], row['ended_at'] is not None, row['source']) == (reason, True, 'tui')
+
+ fresh = _native(authority, tmp_path)
+ assert (await _call(fresh, 'session.list'))['sessions'] == []
+ stored = await _call(fresh, 'session.list', scope='stored')
+ assert [r['id'] for r in stored['sessions']] == ['old-tui']
+
+
+async def test_plain_detach_never_stamps(tmp_path, monkeypatch):
+ db, authority = await _owner(tmp_path, monkeypatch)
+ db.create_session('old-tui', source='tui', model='fake-model', cwd=str(tmp_path))
+ db.append_message('old-tui', 'user', 'q')
+ viewer = _native(authority, tmp_path)
+ resumed = await _call(viewer, 'session.resume', session_id='old-tui')
+ await _call(viewer, 'session.detach', session_id='old-tui', subscription_id=resumed['subscription_id'])
+ assert db.get_session('old-tui')['end_reason'] is None
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index 03a5dc7d8e4..f98615784ee 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -151,6 +151,7 @@ class CanonicalSessionListRow(Result):
started_at: float | None
message_count: int
running: bool
+ model: str | None = None
resolved_id: str | None = None
root_title: str | None = None
diff --git a/ui-tui/src/__tests__/canonicalDetachClose.test.tsx b/ui-tui/src/__tests__/canonicalDetachClose.test.tsx
new file mode 100644
index 00000000000..40497381dc1
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalDetachClose.test.tsx
@@ -0,0 +1,121 @@
+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'
+
+// TUI parity (PR #106742 rows 35/38): the view's close carries main's `session.close` stamp.
+
+function fixture() {
+ const home = mkdtempSync(join(tmpdir(), 'ink-detach-close-'))
+ 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, lifecycle: () => lifecycle,
+ 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 detaches = (request: ReturnType<typeof vi.fn>) =>
+ request.mock.calls.filter(([method]) => method === 'session.detach').map(([, params]) => params)
+
+it('a resume switch closes the previous view with tui_close; a live switch only detaches', async () => {
+ const f = fixture()
+
+ try {
+ await f.initial()
+ f.attach('resumeById', 'a')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(1))
+ f.pending.shift()!.resolve()
+ await vi.waitFor(() => expect(getUiState().sid).toBe('a'))
+ await vi.waitFor(() => expect(detaches(f.request)).toHaveLength(1))
+ expect(detaches(f.request)[0]).toEqual({ session_id: 'x', subscription_id: 'sub-1', end_reason: 'tui_close' })
+
+ f.attach('activateLiveSession', 'b')
+ await vi.waitFor(() => expect(f.pending).toHaveLength(1))
+ f.pending.shift()!.resolve()
+ await vi.waitFor(() => expect(getUiState().sid).toBe('b'))
+ await vi.waitFor(() => expect(detaches(f.request)).toHaveLength(2))
+ expect(detaches(f.request)[1]).toEqual({ session_id: 'a', subscription_id: 'sub-2' })
+ } finally {
+ f.cleanup()
+ }
+})
+
+it('exit closes every held view with tui_shutdown', async () => {
+ const f = fixture()
+
+ try {
+ await f.initial()
+ await f.lifecycle().closeForExit()
+ expect(detaches(f.request)).toEqual([{ session_id: 'x', subscription_id: 'sub-1', end_reason: 'tui_shutdown' }])
+ } finally {
+ f.cleanup()
+ }
+})
diff --git a/ui-tui/src/app/useMainApp.ts b/ui-tui/src/app/useMainApp.ts
index c15c199199b..64aacc594b6 100644
--- a/ui-tui/src/app/useMainApp.ts
+++ b/ui-tui/src/app/useMainApp.ts
@@ -593,7 +593,22 @@ export function useMainApp(gw: GatewayClient) {
const gateway = useMemo(() => ({ gw, rpc }), [gw, rpc])
+ // Exit closes this view's canonical sessions first (main stamped `tui_shutdown` at sidecar exit),
+ // bounded so a dead socket never holds the terminal.
+ const dieFlight = useRef(false)
+ const closeForExitRef = useRef<() => Promise<void>>(async () => undefined)
+
+ const closeViewsForExit = () =>
+ Promise.race([closeForExitRef.current().catch(() => undefined), new Promise(resolve => setTimeout(resolve, 1500))])
+
const die = useCallback(() => {
+ if (gw.isCanonical && !dieFlight.current) {
+ dieFlight.current = true
+ void closeViewsForExit().then(() => die())
+
+ return
+ }
+
gw.kill('app.die')
exit()
// Ink's exit() calls unmount() which resets terminal modes but does NOT
@@ -607,6 +622,13 @@ export function useMainApp(gw: GatewayClient) {
const dieWithCode = useCallback(
(code: number) => {
+ if (gw.isCanonical && !dieFlight.current) {
+ dieFlight.current = true
+ void closeViewsForExit().then(() => dieWithCode(code))
+
+ return
+ }
+
gw.kill(`app.dieWithCode:${code}`)
exit()
process.exit(code)
@@ -631,6 +653,8 @@ export function useMainApp(gw: GatewayClient) {
sys
})
+ closeForExitRef.current = session.closeForExit
+
useEffect(() => {
if (dashboardFreshSessionId) {
forceRedraw(stdout ?? process.stdout)
diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.ts
index 4554424c590..68e730f722f 100644
--- a/ui-tui/src/app/useSessionLifecycle.ts
+++ b/ui-tui/src/app/useSessionLifecycle.ts
@@ -132,6 +132,8 @@ const trimTail = (items: Msg[]) => {
return q
}
+type CanonicalEndReason = 'tui_close' | 'tui_shutdown'
+
export interface UseSessionLifecycleOptions {
colsRef: { current: number }
composerActions: ComposerActions
@@ -191,8 +193,10 @@ 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 }>())
+ // `endReason`: main's `session.close` stamp for a view this TUI closes for good (`tui_close` on /new or
+ // a resume switch, `tui_shutdown` on exit); the owner applies it once no other viewer remains.
const detachCanonical = useCallback(
- (sessionId?: null | string, subscriptionId?: null | string) => {
+ (sessionId?: null | string, subscriptionId?: null | string, endReason?: CanonicalEndReason) => {
if (!gw.isCanonical || !sessionId || !subscriptionId) {
return
}
@@ -200,7 +204,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
const detach = () =>
rpc<SessionDetachResponse>('session.detach', {
session_id: sessionId,
- subscription_id: subscriptionId
+ subscription_id: subscriptionId,
+ ...(endReason ? { end_reason: endReason } : {})
})
.then(result => {
if (result?.detached && canonicalSubscriptions.current.get(sessionId) === subscriptionId) {
@@ -218,10 +223,19 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
canonicalDetachFlights.current.delete(sessionId)
}
})
+
+ return pending
},
[gw.isCanonical, rpc]
)
+ // Exit (`/quit`, Ctrl+D): main's sidecar stamped every session it held `tui_shutdown` at shutdown.
+ const closeForExit = useCallback(async () => {
+ const open = [...canonicalSubscriptions.current.entries()]
+
+ await Promise.all(open.map(([sessionId, subscriptionId]) => detachCanonical(sessionId, subscriptionId, 'tui_shutdown')))
+ }, [detachCanonical])
+
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.
@@ -265,7 +279,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
(
result: { session_id: string; subscription_id?: string },
previousSid?: null | string,
- previousSubscription?: null | string
+ previousSubscription?: null | string,
+ closePrevious = false
) => {
if (!gw.isCanonical || !result.subscription_id) {
return
@@ -278,7 +293,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
previousSubscription &&
(previousSid !== result.session_id || previousSubscription !== result.subscription_id)
) {
- detachCanonical(previousSid, previousSubscription)
+ detachCanonical(previousSid, previousSubscription, closePrevious && previousSid !== result.session_id ? 'tui_close' : undefined)
}
},
[detachCanonical, gw.isCanonical]
@@ -432,7 +447,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
}
signalFreshSessionBoundary(previousSid, r.session_id, onFreshSessionStarted)
- adoptAttachment(r, previousSid, previousSubscription)
+ // Main closed the previous session here (`closeSession` → `tui_close`) unless kept live.
+ adoptAttachment(r, previousSid, previousSubscription, !keepCurrent)
return r.session_id
} finally {
@@ -665,7 +681,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
void closeSession(previousSid)
}
- adoptAttachment(r, previousSid, previousSubscription)
+ adoptAttachment(r, previousSid, previousSubscription, true)
})
.catch((e: Error) => {
if (flight !== attachmentFlight.current) {
@@ -712,6 +728,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
return useMemo(
() => ({
activateLiveSession,
+ closeForExit,
closeSession,
guardBusySessionSwitch,
newLiveSession,
@@ -723,6 +740,7 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {
}),
[
activateLiveSession,
+ closeForExit,
closeSession,
guardBusySessionSwitch,
newLiveSession,