The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /save exports the transcript on the shared gateway
Tekniumc242a70d0c2d
diff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 57f144b795b..f3f791e50c3 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -111,6 +111,8 @@ class AuthorityConnection:handlers.update(ancillary_handlers(self))from gateway.session_shell import handlers as shell_handlershandlers.update(shell_handlers(self))+ from gateway.session_tui_ops import handlers as tui_ops_handlers+ handlers.update(tui_ops_handlers(self))from gateway.session_images import attach_bytesfrom functools import partialhandlers['image.attach_bytes'] = partial(attach_bytes, self)diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.pynew file mode 100644index 00000000000..7c53585e42a--- /dev/null+++ b/gateway/session_tui_ops.py@@ -0,0 +1,74 @@+"""Ink's session utilities on the shared owner: ``/save`` (``session.save``).++Main's per-TUI sidecar served these from its own session table, which never holds a shared-gateway+session, so the canonical TUI refused them. Each verb here acts on one authority session (or, for+the documented process-wide ones, on this owner) and reuses main's helpers rather than re-deriving+them; blocking work runs off the loop under the owning profile's runtime scope.+"""+import asyncio+from contextlib import nullcontext+from datetime import datetime+from functools import partial+from pathlib import Path++from gateway.session_busy_controls import authorize+from hermes_state_runtime import RuntimeStoreError+++def handlers(connection):+ return {'session.save': partial(save_session, connection)}+++def _profile_home(authority):+ """The owning profile's home, or None for a symbolic (test peer) id."""+ home = Path(str(authority.profile_id))+ return home if home.is_absolute() and home.is_dir() else None+++def _profile_scope(authority):+ """Bind the owning profile's home + secrets for one off-loop call (enter it IN the thread:+ ``to_thread`` copies the caller's context, so a scope entered on the loop would leak)."""+ home = _profile_home(authority)+ if home is None:+ return nullcontext()+ from gateway.run import _profile_runtime_scope+ return _profile_runtime_scope(home, hydrate_secrets=False)+++def _live_ref(connection, ref, params, fields, capability):+ if set(params) - fields or not isinstance(ref.session_id, str) or not ref.session_id:+ raise RuntimeStoreError('invalid_params')+ authorize(connection, ref, params, capability)+ return connection.authority.sessions[ref.session_id]+++async def save_session(connection, ref, params):+ """``/save``: main's ``session.save`` — the stored transcript as a ``/save json`` snapshot in the+ profile's ``sessions/saved/``. Reads the conversation's CURRENT physical row (a local session's+ reset/compression child), like main's ``_submit_row_target_key``."""+ _live_ref(connection, ref, params, {'session_id', 'profile'}, 'session:read')+ authority = connection.authority+ from gateway.session_ancillary import physical_target+ target = physical_target(authority, ref)+ home = _profile_home(authority)++ def write():+ from hermes_cli.session_export import load_save_snapshot, render_session_for_save+ from hermes_constants import get_hermes_home+ from hermes_state import SessionExportTooLargeError+ with _profile_scope(authority):+ try:+ data = load_save_snapshot(authority.db, target, 'json')+ except SessionExportTooLargeError as exc:+ raise RuntimeStoreError('export_too_large') from exc+ if not data:+ raise RuntimeStoreError('not_found')+ path = ((home or get_hermes_home()) / 'sessions' / 'saved'+ / f'hermes_conversation_{datetime.now():%Y%m%d_%H%M%S}.json')+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(render_session_for_save(data, 'json'), encoding='utf-8')+ except OSError as exc:+ raise RuntimeStoreError('storage_unavailable') from exc+ return {'file': str(path)}+ return await asyncio.to_thread(write)diff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.pynew file mode 100644index 00000000000..012f471a8ed--- /dev/null+++ b/tests/gateway/test_session_tui_ops.py@@ -0,0 +1,31 @@+"""Ink's /save, /reload, /agents pause and /rollback on the shared owner (main's sidecar parity)."""+import asyncio+import json+from pathlib import Path++import pytest++from tests.gateway.test_session_busy_controls import owner, settled+from tests.gateway.fixtures.local_recovery_probe import rpc, websocket++[email protected]("linux")+def test_session_save_exports_the_stored_transcript_under_the_profile_home(tmp_path):+ with owner(tmp_path) as (home, _peer, desc):+ async def probe():+ async with websocket(home, desc) as ws:+ sid = (await rpc(ws, 'session.create', request_id='save', source='tui', toolsets=[]))['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='first', text='SAVE_ME')+ await settled(home)+ saved = await rpc(ws, 'session.save', session_id=sid)+ assert 'result' in saved, saved+ path = saved['result']['file']+ assert path.startswith(str(home / 'sessions' / 'saved' / 'hermes_conversation_')), path+ data = json.loads(await asyncio.to_thread(Path(path).read_text, encoding='utf-8'))+ contents = [m.get('content') for m in data['messages']]+ assert 'SAVE_ME' in contents and 'CONTROL_ACK' in contents, data+ for params, reason in [({'session_id': sid, 'format': 'md'}, 'invalid_params'),+ ({'session_id': sid, 'profile': 'foreign'}, 'profile_mismatch'),+ ({}, 'invalid_params')]:+ assert (await rpc(ws, 'session.save', **params))['error']['message'] == reason+ asyncio.run(probe())diff --git a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts b/ui-tui/src/__tests__/canonicalSlashCommands.test.tsindex 2a59f5a35d1..ab43a024fd7 100644--- a/ui-tui/src/__tests__/canonicalSlashCommands.test.ts+++ b/ui-tui/src/__tests__/canonicalSlashCommands.test.ts@@ -161,7 +161,7 @@ it("/usage renders main's session totals from session.stats and /tools says whatexpect(request.mock.calls.some(([method]) => LEGACY.includes(method))).toBe(false)})-it('/status reads through the gateway; /save, /bg and /btw refuse instead of calling sidecar-only RPCs', async () => {+it('/status reads through the gateway; /bg and /btw refuse instead of calling sidecar-only RPCs', async () => {const { page, request, slash, sys } = harness()slash('/status')@@ -169,7 +169,7 @@ it('/status reads through the gateway; /save, /bg and /btw refuse instead of calexpect(request).toHaveBeenCalledWith('slash.exec', { command: 'status', session_id: 'owner' })expect(page).toHaveBeenCalledWith('Session: owner', expect.any(String))- for (const cmd of ['/save', '/bg check the logs', '/btw what was that']) {+ for (const cmd of ['/bg check the logs', '/btw what was that']) {slash(cmd)}@@ -177,13 +177,13 @@ it('/status reads through the gateway; /save, /bg and /btw refuse instead of calconst methods = request.mock.calls.map(([method]) => method)- for (const method of ['session.status', 'session.save', 'prompt.background', 'prompt.btw']) {+ for (const method of ['session.status', 'prompt.background', 'prompt.btw']) {expect(methods).not.toContain(method)}const notices = sys.mock.calls.map(([text]) => String(text))- for (const name of ['save', 'bg', 'btw']) {+ for (const name of ['bg', 'btw']) {expect(notices).toContain(`/${name} is not available on the shared gateway yet`)}})diff --git a/ui-tui/src/__tests__/canonicalTuiOps.test.ts b/ui-tui/src/__tests__/canonicalTuiOps.test.tsnew file mode 100644index 00000000000..33e866f0fbe--- /dev/null+++ b/ui-tui/src/__tests__/canonicalTuiOps.test.ts@@ -0,0 +1,57 @@+import { beforeEach, expect, it, vi } from 'vitest'++import { createSlashHandler } from '../app/createSlashHandler.js'+import { patchUiState, resetUiState } from '../app/uiStore.js'++// The shared gateway serves Ink's /save, /reload, /agents pause|resume and /rollback through the+// owner verbs in gateway/session_tui_ops.py: each command reaches its verb and renders main's text.++const flush = () => new Promise(resolve => setImmediate(resolve))++function harness(results: Record<string, unknown> = {}) {+ const messages = [+ { role: 'user', text: 'hello' },+ { role: 'assistant', text: 'hi there' }+ ]++ const request = vi.fn(async (method: string, _params?: unknown) => {+ if (method in results) {+ return results[method]+ }++ throw new Error(`unknown_method: ${method}`)+ })++ const sys = vi.fn()+ const page = vi.fn()+ const panel = vi.fn()+ const setHistoryItems = vi.fn()++ const ctx = {+ composer: { enqueue: vi.fn() },+ gateway: { gw: { isCanonical: true, request }, rpc: request },+ local: { getHistoryItems: () => messages, getLastUserMsg: () => '', maybeWarn: vi.fn() },+ session: { resumeById: vi.fn() },+ slashFlightRef: { current: 0 },+ transcript: { page, panel, send: vi.fn(), setHistoryItems, sys, trimLastExchange: (x: unknown[]) => x }+ }++ return { page, panel, request, setHistoryItems, slash: createSlashHandler(ctx as any), sys }+}++const notices = (sys: ReturnType<typeof vi.fn>) => sys.mock.calls.map(([text]) => String(text))++beforeEach(() => {+ resetUiState()+ patchUiState({ sid: 'owner' })+})++it('/save calls session.save on the shared gateway and reports the saved file', async () => {+ const { request, slash, sys } = harness({ 'session.save': { file: '/home/u/.hermes/sessions/saved/x.json' } })++ slash('/save')+ await flush()++ expect(request).toHaveBeenCalledWith('session.save', { session_id: 'owner' })+ expect(notices(sys)).toContain('conversation saved to: /home/u/.hermes/sessions/saved/x.json')+})diff --git a/ui-tui/src/app/slash/commands/core.ts b/ui-tui/src/app/slash/commands/core.tsindex 3489c3c69df..57255aa51f3 100644--- a/ui-tui/src/app/slash/commands/core.ts+++ b/ui-tui/src/app/slash/commands/core.ts@@ -596,10 +596,6 @@ export const coreCommands: SlashCommand[] = [return ctx.transcript.sys(t('slashCmd.core.save.noActiveSession'))}- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'save'))- }-ctx.gateway.rpc<SessionSaveResponse>('session.save', { session_id: ctx.sid }).then(