Skip to content

The agent that grows with you

fix(tui): retain native legacy history in canonical session picker

unsupportedpastels2171365a3fcb
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index ddf57798dc6..eb88d6f0f0e 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -4804,6 +4804,7 @@ export interface CanonicalResumeParams {
}
export interface CanonicalListParams {
profile?: string | null
+ scope?: 'live' | 'stored'
limit?: number
title?: string | null
include_hidden?: boolean
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index 6b4c191c301..36a7bb13e70 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -8895,6 +8895,15 @@
"default": null,
"title": "Profile"
},
+ "scope": {
+ "default": "live",
+ "enum": [
+ "live",
+ "stored"
+ ],
+ "title": "Scope",
+ "type": "string"
+ },
"limit": {
"default": 200,
"title": "Limit",
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 856dc8a0cdd..dae45c7d1c4 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -326,8 +326,14 @@ class AuthorityConnection:
if 'session:read' not in self.actor.capabilities:
raise RuntimeStoreError('permission_denied')
limit = params.get('limit', 200)
- if set(params) - {'limit', 'title', 'include_hidden'} or type(limit) is not int or not 1 <= limit <= 200:
+ if set(params) - {'limit', 'title', 'include_hidden', 'scope'} or type(limit) is not int or not 1 <= limit <= 200:
raise RuntimeStoreError('invalid_params')
+ if params.get('scope', 'live') not in {'live', 'stored'} or ('title' in params and 'scope' in params):
+ raise RuntimeStoreError('invalid_params')
+ if params.get('scope') == 'stored':
+ from gateway.session_listing import stored_picker_sessions
+ return await asyncio.to_thread(stored_picker_sessions, self.authority, self.actor,
+ limit=limit, include_hidden=params.get('include_hidden', False))
if 'title' in params:
# Title-as-identity lookup (the Bots roster's forever-chat registry): the same
# resolver `session.resume title=` uses, so a hidden canonical chat answers here
diff --git a/gateway/session_listing.py b/gateway/session_listing.py
new file mode 100644
index 00000000000..c78e94f0d98
--- /dev/null
+++ b/gateway/session_listing.py
@@ -0,0 +1,46 @@
+"""Read-only native picker history; enumeration never adopts a transcript."""
+from hermes_state_local_migration import validate_legacy_row
+from hermes_state_mutation_binding import authorize_history
+from hermes_state_runtime import RuntimeStoreError
+
+
+def stored_picker_sessions(authority, actor, *, limit, include_hidden=False):
+ """Offer legacy local rows only to the same native transport that may resume them.
+
+ Canonical sessions are already in the live feed. Old local rows have no policy
+ receipt until explicit resume; listing them must not claim or restore anything.
+ """
+ if actor.profile_id != authority.profile_id:
+ raise RuntimeStoreError('profile_mismatch')
+ if (getattr(authority, '_native_legacy_transports', {}).get(actor.transport_id) != actor
+ or not {'session:read', 'session:create'} <= actor.capabilities):
+ return {'sessions': [], 'scope': 'stored'}
+ db = authority.db
+ sessions, offset = [], 0
+ while len(sessions) < limit:
+ rows = db.list_sessions_rich(sources=['cli', 'tui', 'gui'], 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
+ try:
+ validate_legacy_row(db, tip)
+ with db._read_ctx() as conn:
+ if not authorize_history(conn, actor, sid):
+ continue
+ except RuntimeStoreError as exc:
+ if exc.reason not in {'not_found', 'permission_denied'}:
+ raise
+ continue
+ 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})
+ if len(sessions) == limit:
+ break
+ if len(rows) < 200:
+ break
+ offset += len(rows)
+ return {'sessions': sessions, 'scope': 'stored'}
diff --git a/tests/gateway/test_stored_session_picker.py b/tests/gateway/test_stored_session_picker.py
new file mode 100644
index 00000000000..d233eade149
--- /dev/null
+++ b/tests/gateway/test_stored_session_picker.py
@@ -0,0 +1,75 @@
+"""The native picker enumerates old transcripts without adopting them on read."""
+from types import SimpleNamespace
+
+import pytest
+
+
+async def test_stored_picker_survives_upgrade_and_resumes_without_copying(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
+ from gateway.session_controls import AuthorityConnection
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ db = store._db
+ for sid, source in [('old-cli', 'cli'), ('old-tui', 'tui'), ('old-gui', 'gui'),
+ ('internal', 'tool'), ('bot', 'telegram'), ('hidden', 'cli'),
+ ('archived', 'tui'), ('foreign', 'cli'), ('imported-other', 'cli')]:
+ db.create_session(sid, source=source, model='old-model', cwd=str(tmp_path),
+ profile_name='other' if sid == 'foreign' else None)
+ db.append_message(sid, 'user', sid + ' question')
+ db.append_message(sid, 'assistant', sid + ' answer')
+ db.end_session(sid, 'cli_exit')
+ db.reopen_session('old-tui')
+ assert db.try_acquire_compression_lock('old-tui', 'fixture')
+ try:
+ db.publish_compression_child(parent_session_id='old-tui', child_session_id='tui-tip',
+ source='tui', model='old-model', messages=[{'role': 'user', 'content': 'compressed question'},
+ {'role': 'assistant', 'content': 'compressed answer'}],
+ compression_lock_holder='fixture')
+ finally:
+ db.release_compression_lock('old-tui', 'fixture')
+ db.set_session_hidden('hidden', True)
+ db.set_session_archived('archived', True)
+ from hermes_state_mutation_binding import BINDING_PREFIX
+ db._write_sql('INSERT INTO state_meta(key,value) VALUES(?,?)',
+ (BINDING_PREFIX + 'imported-other', '["other-profile","other-user"]'))
+ runner = SimpleNamespace(session_store=store, _session_db=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')
+ native = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': 'native',
+ 'profile_id': str(tmp_path), 'instance_id': 'owner'})
+
+ async def listing(connection, **params):
+ return await connection.dispatch({'id': 1, 'method': 'session.list', 'params': params})
+
+ before = db._conn.total_changes
+ result = await listing(native, scope='stored')
+ assert 'result' in result, result
+ assert result['result']['scope'] == 'stored'
+ assert {r['id'] for r in result['result']['sessions']} == {'old-cli', 'tui-tip', 'old-gui'}
+ assert db._conn.total_changes == before
+ assert authority.sessions == {}
+ assert (await listing(native))['result'] == {'scope': 'live', 'sessions': []}
+ assert len((await listing(native, scope='stored', limit=1))['result']['sessions']) == 1
+
+ remote = AuthorityConnection(authority, object(), {'provider': 'remote', 'user_id': 'remote',
+ 'profile_id': str(tmp_path), 'instance_id': 'owner'}, operator=True)
+ assert (await listing(remote, scope='stored'))['result']['sessions'] == []
+ denied = await listing(native, scope='stored', profile='other')
+ assert 'error' in denied
+
+ resumed = await native.dispatch({'id': 2, 'method': 'session.resume', 'params': {'session_id': 'old-cli'}})
+ assert 'result' in resumed, resumed
+ assert [m['content'] for m in resumed['result']['messages']] == ['old-cli question', 'old-cli answer']
+ assert db._conn.execute('SELECT COUNT(*) FROM messages WHERE session_id=?', ('old-cli',)).fetchone()[0] == 2
+ assert 'old-cli' not in {r['id'] for r in (await listing(native, scope='stored'))['result']['sessions']}
+ assert 'old-cli' in {r['id'] for r in (await listing(native))['result']['sessions']}
+ compressed = await native.dispatch({'id': 3, 'method': 'session.resume', 'params': {'session_id': 'tui-tip'}})
+ assert 'result' in compressed, compressed
+ assert [m['content'] for m in compressed['result']['messages']] == ['compressed question', 'compressed answer']
diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.py
index e3967ef2b67..142b01eea92 100644
--- a/tui_gateway/contracts/canonical_sessions.py
+++ b/tui_gateway/contracts/canonical_sessions.py
@@ -116,6 +116,7 @@ class CanonicalSnapshot(Result):
class CanonicalListParams(ProfileParams):
+ scope: Literal['live', 'stored'] = 'live'
limit: int = 200
title: str | None = None
include_hidden: bool = False
diff --git a/ui-tui/src/__tests__/canonicalStoredPicker.test.tsx b/ui-tui/src/__tests__/canonicalStoredPicker.test.tsx
new file mode 100644
index 00000000000..0a2dd3ac1af
--- /dev/null
+++ b/ui-tui/src/__tests__/canonicalStoredPicker.test.tsx
@@ -0,0 +1,76 @@
+import { PassThrough } from 'node:stream'
+
+import { renderSync } from '@hermes/ink'
+import React from 'react'
+import { expect, it, vi } from 'vitest'
+
+import { ActiveSessionSwitcher } from '../components/activeSessionSwitcher.js'
+import { DEFAULT_THEME } from '../theme.js'
+
+it('renders and resumes stored history alongside live canonical sessions', async () => {
+ const request = vi.fn(async (_method: string, params: { scope?: string }) => ({
+ scope: params.scope ?? 'live',
+ sessions:
+ params.scope === 'stored'
+ ? [
+ {
+ id: 'old',
+ session_id: 'old',
+ title: 'Retained old conversation',
+ source: 'cli',
+ started_at: 1,
+ message_count: 2
+ }
+ ]
+ : [
+ {
+ id: 'live',
+ session_id: 'live',
+ title: 'Current conversation',
+ started_at: 2,
+ message_count: 1,
+ running: false
+ }
+ ]
+ }))
+ 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 })
+ let output = ''
+ stdout.on('data', chunk => {
+ output += chunk.toString()
+ })
+ const onResume = vi.fn()
+ const element = (
+ <ActiveSessionSwitcher
+ currentSessionId="live"
+ gw={{ isCanonical: true, request } as any}
+ onCancel={vi.fn()}
+ onClose={vi.fn()}
+ onNew={vi.fn()}
+ onNewPrompt={vi.fn()}
+ onResume={onResume}
+ 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
+ })
+ try {
+ await vi.waitFor(() => expect(request).toHaveBeenCalledWith('session.list', { limit: 200, scope: 'stored' }))
+ instance.rerender(element)
+ await vi.waitFor(() => expect(output).toContain('Retained old conversation'))
+ expect(output).toContain('Current conversation')
+ stdin.write('\u001B[B')
+ await vi.waitFor(() => {
+ instance.rerender(React.cloneElement(element))
+ stdin.write('\r')
+ expect(onResume).toHaveBeenCalledWith('old')
+ })
+ } finally {
+ instance.unmount()
+ }
+})
diff --git a/ui-tui/src/components/activeSessionSwitcher.tsx b/ui-tui/src/components/activeSessionSwitcher.tsx
index 4ae8ea21e48..400053966d7 100644
--- a/ui-tui/src/components/activeSessionSwitcher.tsx
+++ b/ui-tui/src/components/activeSessionSwitcher.tsx
@@ -387,11 +387,12 @@ export function ActiveSessionSwitcher({
}))
}))
: gw.request<SessionActiveListResponse>('session.active_list', { current_session_id: currentSessionId }),
- canonicalList
- ? Promise.resolve({ sessions: [] })
- : includeHistory
- ? gw.request<SessionListResult>('session.list', { limit: 200 })
- : Promise.resolve(null)
+ includeHistory
+ ? gw.request<SessionListResult>('session.list', {
+ limit: 200,
+ ...(canonicalList ? { scope: 'stored' } : {})
+ })
+ : Promise.resolve(null)
])
const r = liveRes.status === 'fulfilled' ? asRpcResult<SessionActiveListResponse>(liveRes.value) : null
diff --git a/website/docs/developer-guide/gateway-local-sessions.md b/website/docs/developer-guide/gateway-local-sessions.md
index 617a55d6f2c..173ed3e5c41 100644
--- a/website/docs/developer-guide/gateway-local-sessions.md
+++ b/website/docs/developer-guide/gateway-local-sessions.md
@@ -95,8 +95,12 @@ OpenAI API-to-local session affinity; those remain separate integration paths.
stamps a session-token identity and also supports creation. Callers cannot provide an
identity in RPC parameters, and operator scope does not promote resume-only capabilities
to `session:create`.
-- `session.list({limit})` returns authorized **live** authority sessions (`scope: "live"`),
- not the full historical session picker. `session.info({session_id})` is a lightweight,
+- `session.list({limit})` returns authorized **live** authority sessions (`scope: "live"`).
+ The native TUI picker also requests `session.list({limit, scope: "stored"})` for pre-authority
+ CLI/TUI/GUI history. This read-only feed uses the native legacy-resume ownership checks,
+ excludes hidden/archived/internal and foreign-owned rows, and never adopts a session merely
+ by listing it. Explicit resume performs adoption; the default live feed is unchanged.
+ `session.info({session_id})` is a lightweight,
authorized view of source, current model, lazy-agent status, and profile ID.
- `ping({})` returns `{pong: true}`. `runtime.describe({})` exposes only authority identity,
epoch, capabilities, and the creation contract (`session_create.sources` and