The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): resumed canonical sessions render main's display projection
Teknium607f67bfae86
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 21c7429a380..ec347c19c12 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -4817,6 +4817,7 @@ export interface CanonicalSnapshot {session_id: stringstored_session_id: stringmessages: TranscriptMessage[]+ display_messages?: TranscriptMessage[] | nullmessage_count: numberrunning: booleanauthority_epoch: number@@ -4901,6 +4902,7 @@ export interface CanonicalResumeParams {defer_history?: booleanomit_messages?: booleancols?: number | null+ display_projection?: boolean}export interface CanonicalListParams {profile?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex a4bdfc26fbb..4913c688fea 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -9578,6 +9578,11 @@],"default": null,"title": "Cols"+ },+ "display_projection": {+ "default": false,+ "title": "Display Projection",+ "type": "boolean"}},"title": "CanonicalResumeParams",@@ -10342,6 +10347,21 @@"title": "Messages","type": "array"},+ "display_messages": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/TranscriptMessage"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Display Messages"+ },"message_count": {"title": "Message Count","type": "integer"diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 29686a71f95..b84269d1429 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -21,6 +21,15 @@ _PROFILE_IMPLICIT = frozenset({'session.create', 'session.list', 'session.info','approval.respond', 'clarify.respond'})+def display_projection(history, profile_home):+ """Main's TUI display rows for a snapshot's stored rows: the sidecar's own+ ``_history_to_messages`` (compaction handoffs stripped, ``/steer`` unwrapped, tool rows+ labelled from the paired assistant ``tool_calls``), never a re-implementation."""+ from tui_gateway import server+ rows = [{**row, '_row_id': row['row_id']} if 'row_id' in row else row for row in history]+ return server._history_to_messages(rows, profile_home=profile_home)++class AuthorityConnection:def __init__(self, authority, transport, identity, *, operator=False):self.authority = authority@@ -427,8 +436,11 @@ class AuthorityConnection:source = self.authority.sessions[snapshot.handle.ref.session_id].sourceif source is not None and source.platform == Platform.LOCAL:info = await snapshot_info(self.authority, snapshot.handle.ref)+ display = {}+ if params.get('display_projection'):+ display['display_messages'] = display_projection(snapshot.history, self.authority.profile_id)return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,- 'messages': list(snapshot.history), 'message_count': len(snapshot.history),+ 'messages': list(snapshot.history), **display, 'message_count': len(snapshot.history),'running': snapshot.handle.execution_state == 'running','authority_epoch': snapshot.handle.authority_epoch,'replay_epoch': snapshot.replay_epoch, 'last_sequence': snapshot.last_sequence,diff --git a/tests/gateway/test_canonical_resume_display_projection.py b/tests/gateway/test_canonical_resume_display_projection.pynew file mode 100644index 00000000000..a46dcf76ec4--- /dev/null+++ b/tests/gateway/test_canonical_resume_display_projection.py@@ -0,0 +1,81 @@+"""A resumed canonical session renders through main's display projection (TUI parity, PR #106742).++Main's TUI sidecar answered ``session.resume`` with ``tui_gateway.session_history._history_to_messages``:+compaction handoffs stripped, ``/steer`` rows unwrapped to the user's words, tool rows labelled from the+paired assistant ``tool_calls``. The canonical snapshot carries raw stored rows (the controls need their+``content``/``row_id``), so a client that renders asks for ``display_projection`` and receives the same+projection main produced, alongside the raw rows.+"""+import json+from types import SimpleNamespace++import pytest+++async def _native(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())+ 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')+ native = AuthorityConnection(authority, object(), {'provider': 'local', 'user_id': 'native',+ 'profile_id': str(tmp_path), 'instance_id': 'owner'})+ return store._db, native+++def _seed(db):+ from agent.context_compressor import SUMMARY_PREFIX+ from agent.prompt_builder import steer_user_row+ db.create_session('old-tui', source='tui', model='fake-model')+ db.append_message('old-tui', 'user', SUMMARY_PREFIX + '\nUser Messages (verbatim, newest first)\nEND OF CONTEXT SUMMARY')+ db.append_message('old-tui', 'user', 'run the tool')+ db.append_message('old-tui', 'assistant', '', tool_calls=[{+ 'id': 'call_1', 'type': 'function',+ 'function': {'name': 'read_file', 'arguments': json.dumps({'path': 'notes.txt'})}}])+ db.append_message('old-tui', 'tool', 'file body', tool_name='read_file', tool_call_id='call_1')+ steer = steer_user_row('focus on the numbers')+ db.append_message('old-tui', 'user', steer['content'], display_kind=steer['display_kind'])+ db.append_message('old-tui', 'assistant', 'done')+ db.end_session('old-tui', 'tui_shutdown')+++async def test_resume_display_projection_matches_main(tmp_path, monkeypatch):+ db, native = await _native(tmp_path, monkeypatch)+ _seed(db)+ reply = await native.dispatch({'id': 1, 'method': 'session.resume',+ 'params': {'session_id': 'old-tui', 'display_projection': True}})+ assert 'result' in reply, reply+ result = reply['result']+ shown = result['display_messages']+ # Main's projection, byte-for-byte, over the same stored rows.+ from tui_gateway import server+ raw = db.get_messages_as_conversation('old-tui', include_row_ids=True)+ assert shown == server._history_to_messages(raw, profile_home=str(tmp_path))+ texts = json.dumps(shown)+ assert 'CONTEXT COMPACTION' not in texts and 'END OF CONTEXT SUMMARY' not in texts+ assert 'OUT-OF-BAND' not in texts+ steer = [m for m in shown if m.get('display_kind') == 'steer']+ assert [m['text'].strip() for m in steer] == ['focus on the numbers']+ tool = next(m for m in shown if m['role'] == 'tool')+ assert (tool['name'], tool['context']) == ('read_file', 'notes.txt')+ # The raw rows stay for rewind targeting (content + row_id).+ assert all('row_id' in m for m in result['messages'])+ assert result['message_count'] == len(result['messages'])+++async def test_resume_without_projection_is_unchanged(tmp_path, monkeypatch):+ db, native = await _native(tmp_path, monkeypatch)+ _seed(db)+ reply = await native.dispatch({'id': 1, 'method': 'session.resume', 'params': {'session_id': 'old-tui'}})+ assert 'result' in reply, reply+ assert 'display_messages' not in reply['result']diff --git a/tui_gateway/contracts/canonical_sessions.py b/tui_gateway/contracts/canonical_sessions.pyindex 67812e0e1af..03a5dc7d8e4 100644--- a/tui_gateway/contracts/canonical_sessions.py+++ b/tui_gateway/contracts/canonical_sessions.py@@ -62,6 +62,9 @@ class CanonicalResumeParams(ProfileParams):defer_history: bool = Falseomit_messages: bool = Falsecols: int | None = None+ # A renderer (the Ink TUI) asks for main's display projection of the same rows+ # (``tui_gateway.session_history._history_to_messages``) as ``display_messages``.+ display_projection: bool = Falseclass CanonicalSessionHandle(Result):@@ -118,6 +121,8 @@ class CanonicalSnapshot(Result):session_id: strstored_session_id: strmessages: list[TranscriptMessage]+ # Present only when ``display_projection`` was asked: the rows as main's TUI rendered them.+ display_messages: list[TranscriptMessage] | None = Nonemessage_count: intrunning: boolauthority_epoch: intdiff --git a/ui-tui/src/__tests__/canonicalResumeDisplayProjection.test.ts b/ui-tui/src/__tests__/canonicalResumeDisplayProjection.test.tsnew file mode 100644index 00000000000..77cbe6b0fec--- /dev/null+++ b/ui-tui/src/__tests__/canonicalResumeDisplayProjection.test.ts@@ -0,0 +1,49 @@+import { expect, it } from 'vitest'++import { lastTurnRewind } from '../app/slash/canonicalSessionCommands.js'+import { canonicalRequest, canonicalResult } from '../canonicalGateway.js'+import { toTranscriptMessages } from '../domain/messages.js'++// TUI parity (PR #106742 rows 12b/31/32): a resumed canonical session renders main's display+// projection (`display_messages`, the sidecar's `_history_to_messages`), not the raw stored rows.++it('asks the owner for the display projection on every rendering resume', () => {+ expect(canonicalRequest('session.resume', { session_id: 's', cols: 80 }).params).toEqual({ session_id: 's', display_projection: true })+ expect(canonicalRequest('session.activate', { session_id: 's' })).toEqual({ method: 'session.resume', params: { session_id: 's', display_projection: true } })+ // A metadata-only activation never asked for rows.+ expect(canonicalRequest('session.activate', { session_id: 's', omit_messages: true }).params).toEqual({ session_id: 's' })+})++it('renders display_messages and keeps the stored rows for rewind targeting', () => {+ const marker = '[OUT-OF-BAND USER MESSAGE — a direct message from the user]\nfocus on the numbers\n[/OUT-OF-BAND USER MESSAGE]'++ const stored = [+ { role: 'user', content: '[CONTEXT COMPACTION — REFERENCE ONLY] summary END OF CONTEXT SUMMARY', row_id: 1 },+ { role: 'user', content: 'run the tool', row_id: 2 },+ { role: 'assistant', content: '', tool_calls: [{ id: 'c1', function: { name: 'read_file', arguments: '{"path":"notes.txt"}' } }], row_id: 3 },+ { role: 'tool', content: 'body', tool_name: 'read_file', tool_call_id: 'c1', row_id: 4 },+ { role: 'user', content: marker, display_kind: 'steer', row_id: 5 },+ { role: 'assistant', content: 'done', row_id: 6 }+ ]++ // The tool trail rides on the next assistant row, as main renders it.+ const display = [+ { role: 'user', text: 'run the tool', row_id: 2 },+ { role: 'tool', name: 'read_file', context: 'notes.txt', tool_call_id: 'c1', args: { path: 'notes.txt' } },+ { role: 'assistant', text: 'read it', row_id: 7 },+ { role: 'user', text: 'focus on the numbers', display_kind: 'steer', row_id: 5 },+ { role: 'assistant', text: 'done', row_id: 6 }+ ]++ const snapshot = canonicalResult('session.resume', { session_id: 's', stored_session_id: 's', authority_epoch: 1,+ execution_generation: 0, messages: stored, display_messages: display, info: {} })++ const rendered = toTranscriptMessages(snapshot.messages)+ const text = JSON.stringify(rendered)+ expect(text).not.toContain('CONTEXT COMPACTION')+ expect(text).not.toContain('OUT-OF-BAND')+ expect(rendered.filter(row => row.role === 'user').map(row => row.text)).toEqual(['run the tool', 'focus on the numbers'])+ expect(text).toContain('notes.txt')+ // Controls still see the stored rows: /undo targets the steer row by its durable id.+ expect(lastTurnRewind(snapshot)).toEqual({ target_message_id: 5 })+})diff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.tsindex 3d3038c7d48..d39d5bf1037 100644--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts@@ -24,7 +24,7 @@ const isUserTurn = (row: Record<string, unknown>) =>/** The rewind payload for the newest user turn in the snapshot the CAS tuple came from. */export function lastTurnRewind(snapshot: MutationSnapshot): null | { target_message_id: number } {- const target = (snapshot.messages ?? []).findLast(isUserTurn)+ const target = (snapshot.stored_messages ?? snapshot.messages ?? []).findLast(isUserTurn)return target ? { target_message_id: target.row_id as number } : null}@@ -56,7 +56,7 @@ function retryText(content: unknown): null | string {/** /retry's rewind payload: validated on the CAS snapshot, so a refusal archives nothing. */export function retryTurnRewind(snapshot: MutationSnapshot): null | { target_message_id: number } {- const target = (snapshot.messages ?? []).findLast(isUserTurn)+ const target = (snapshot.stored_messages ?? snapshot.messages ?? []).findLast(isUserTurn)const text = target ? retryText(target.content) : ''if (text === null) {diff --git a/ui-tui/src/app/slash/canonicalSessionControls.ts b/ui-tui/src/app/slash/canonicalSessionControls.tsindex 264ad52f71f..7673569fc5e 100644--- a/ui-tui/src/app/slash/canonicalSessionControls.ts+++ b/ui-tui/src/app/slash/canonicalSessionControls.ts@@ -50,6 +50,8 @@ export type CanonicalOperation = 'model' | 'branch' | 'compress' | 'rename' | 'r/** The snapshot a mutation's CAS tuple was read from; `payload` may derive its target from it. */export interface MutationSnapshot {messages?: Array<Record<string, unknown>>+ /** The stored rows (content + row_id) behind a display-projected `messages`. */+ stored_messages?: Array<Record<string, unknown>>revision: numberexecution_generation: number}diff --git a/ui-tui/src/canonicalGateway.ts b/ui-tui/src/canonicalGateway.tsindex 7a64dbbd277..271b67429bb 100644--- a/ui-tui/src/canonicalGateway.ts+++ b/ui-tui/src/canonicalGateway.ts@@ -28,8 +28,13 @@ export function canonicalRequest(method: string, original: Record<string, unknowif (method === 'session.resume' || method === 'session.activate') {method = 'session.resume'+ // A rendering resume asks for main's display projection of the same rows (`display_messages`);+ // a metadata-only activation (`omit_messages`) never paints a transcript.+ const renders = !params.omit_messagesdelete params.colsdelete params.omit_messages++ if (renders) { params.display_projection = true }}return { method, params }@@ -48,12 +53,18 @@ export function canonicalResult(method: string, value: any, request: Record<stri// Canonical snapshots contain stored conversation rows (`content`), not// the legacy TUI's display rows (`text`). Without this translation only// live events render, making reconnect depend on catching the final delta.- const messages = Array.isArray(value.messages) ? value.messages.map((row: any) =>+ const stored = Array.isArray(value.messages) ? value.messages.map((row: any) =>row && typeof row === 'object'? { ...row, text: rowText(row.content), name: row.tool_name }: row) : value.messages- return { ...value, messages, info: { ...value.info, stored_session_id: value.stored_session_id,+ // Renderers read `messages`: main's display projection when the owner sent it (compaction+ // handoffs stripped, /steer unwrapped, tool rows labelled), as the sidecar's resume did.+ // `stored_messages` keeps the raw rows (content + row_id) the rewind controls target.+ const { display_messages: display, ...rest } = value+ const messages = Array.isArray(display) ? display : stored++ return { ...rest, messages, stored_messages: stored, info: { ...value.info, stored_session_id: value.stored_session_id,execution_epoch: String(value.authority_epoch), execution_generation: value.execution_generation,running: value.running, pending_submissions: pendingSubmissions(value.pending) } }}