The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway,tui): /rollback lists, diffs and restores checkpoints on the shared gateway
Teknium2269e88f1d42
diff --git a/gateway/session_tui_ops.py b/gateway/session_tui_ops.pyindex da170a6387e..12c00e49648 100644--- a/gateway/session_tui_ops.py+++ b/gateway/session_tui_ops.py@@ -1,5 +1,6 @@"""Ink's session utilities on the shared owner: ``/save`` (``session.save``), ``/reload``-(``reload.env``) and ``/agents pause|resume`` (``delegation.pause``).+(``reload.env``), ``/agents pause|resume`` (``delegation.pause``) and ``/rollback``+(``rollback.list`` / ``rollback.diff`` / ``rollback.restore``).Main's per-TUI sidecar served these from its own session table, which never holds a shared-gatewaysession, so the canonical TUI refused them. Each verb reuses main's helpers rather than re-deriving@@ -8,6 +9,8 @@ them. ``dispatch`` already runs every handler under the owning profile's scope ("""import asynciofrom datetime import datetime+import json+import uuidfrom functools import partialfrom pathlib import Path@@ -18,7 +21,10 @@ from hermes_state_runtime import RuntimeStoreErrordef handlers(connection):return {'session.save': partial(save_session, connection),'reload.env': partial(reload_env, connection),- 'delegation.pause': partial(pause_delegation, connection)}+ 'delegation.pause': partial(pause_delegation, connection),+ 'rollback.list': partial(rollback, connection, kind='list'),+ 'rollback.diff': partial(rollback, connection, kind='diff'),+ 'rollback.restore': partial(rollback, connection, kind='restore')}def _profile_home(authority):@@ -129,3 +135,106 @@ async def pause_delegation(connection, ref, params):raise RuntimeStoreError('profile_mismatch')from tools.delegate_tool_registry import set_spawn_pausedreturn {'paused': set_spawn_paused(paused)}+++_ROLLBACK_FIELDS = {'list': {'session_id', 'profile'}, 'diff': {'session_id', 'profile', 'hash'},+ 'restore': {'session_id', 'profile', 'hash', 'file_path'}}+++async def rollback(connection, ref, params, *, kind):+ """``/rollback [list] | diff <n|hash> | <n|hash> [file]``: main's ``rollback.*`` over this+ session's checkpoints (the shared ``<profile>/checkpoints`` store, keyed by the frozen launch cwd).++ The manager is built from the session's frozen ``checkpoints`` policy rather than read off the+ resident agent (main's ``agent._checkpoint_mgr``, built from the same config): it carries no+ per-session state these reads need, and a restarted owner or a just-rewound session has no+ resident agent. A whole-tree restore also rewinds the transcript to before the newest user turn+ (main's ``_rewind_active_session_history``) through the owner's fenced ``rewind`` mutation."""+ fields = _ROLLBACK_FIELDS[kind]+ if any(key in params and (not isinstance(params[key], str) or (key == 'hash' and not params[key]))+ for key in ('hash', 'file_path')) or (kind != 'list' and 'hash' not in params):+ raise RuntimeStoreError('invalid_params')+ live = _live_ref(connection, ref, params, fields, 'session:read' if kind != 'restore' else 'session:control')+ authority = connection.authority+ from gateway.session_policy import policy_for_source+ policy = policy_for_source(authority.runner, live.source)+ if policy is None:+ raise RuntimeStoreError('permission_denied')+ file_path = params.get('file_path') or ''+ if kind == 'restore' and not file_path and authority._handle(ref).execution_state != 'idle':+ # Main refuses a full-history rollback mid-turn; a file-scoped restore only touches disk.+ raise RuntimeStoreError('session_busy')+ from gateway.session_ancillary import physical_target+ task_id = physical_target(authority, ref)+ from gateway.run import _checkpoint_agent_kwargs+ kwargs = _checkpoint_agent_kwargs(policy.config(authority, secrets=False))+ terminal = json.loads(policy.terminal_json)++ def run():+ from tools.checkpoint_manager import CheckpointManager+ from tui_gateway.checkpoints import _resolve_checkpoint_hash+ mgr = CheckpointManager(enabled=bool(kwargs['checkpoints_enabled']), **{+ key[len('checkpoint_'):]: value for key, value in kwargs.items() if key.startswith('checkpoint_')})+ cwd = policy.cwd+ if kind == 'list':+ if not mgr.enabled:+ return {'enabled': False, 'checkpoints': []}+ # The TUI renders ``message``; the manager calls it ``reason``.+ return {'enabled': True, 'checkpoints': [+ {'hash': c.get('hash', ''), 'timestamp': c.get('timestamp', ''), 'message': c.get('reason', '')}+ for c in mgr.list_checkpoints(cwd)]}+ # Host checkpoints are not a container-backed session's tree (main's _container_checkpoint_refusal),+ # classified under the session's frozen terminal policy, not the owner's ambient one.+ from tools.terminal_scope import reset_terminal_scope, set_terminal_scope+ token = set_terminal_scope(terminal)+ try:+ refusal = mgr.unsupported_backend_reason(task_id)+ finally:+ reset_terminal_scope(token)+ try:+ target = _resolve_checkpoint_hash(mgr, cwd, params['hash'])+ except ValueError as exc:+ if kind == 'diff':+ raise RuntimeStoreError('invalid_checkpoint') from exc+ return {'success': False, 'error': str(exc)}+ if kind == 'diff':+ if refusal:+ raise RuntimeStoreError('unsupported_terminal_backend')+ from tui_gateway.render import render_diff+ result = mgr.diff(cwd, target)+ raw = result.get('diff', '')[:4000]+ payload = {'stat': result.get('stat', ''), 'diff': raw}+ if rendered := render_diff(raw, 80):+ payload['rendered'] = rendered+ return payload+ if refusal:+ return {'success': False, 'error': refusal}+ return mgr.restore(cwd, target, file_path=file_path or None)+ result = await asyncio.to_thread(run)+ if kind == 'restore' and result.get('success') and not file_path:+ result['history_removed'] = await _rewind_last_turn(connection, ref)+ return result+++async def _rewind_last_turn(connection, ref):+ """Drop the newest user turn and everything after it (main's full ``/rollback`` restore) via the+ owner's revision-fenced ``rewind`` mutation; 0 when the transcript has no user turn."""+ authority = connection.authority+ from agent.context_compressor import user_originated_turn_view+ from gateway.session_local_recovery import local_history+ rows = await asyncio.to_thread(local_history, authority, ref)+ target = next((row['row_id'] for row in reversed(rows)+ if isinstance(row.get('row_id'), int) and user_originated_turn_view(row) is not None), None)+ if target is None:+ return 0+ from gateway.session_mutations import mutate_session+ from hermes_state_mutation_guards import MUTATION_GUARD_REFUSALS+ handle = authority._handle(ref)+ try:+ result = await mutate_session(authority, connection.actor, ref, {+ 'session_id': ref.session_id, 'request_id': f'rollback:{uuid.uuid4().hex}',+ 'expected_revision': handle.revision, 'expected_generation': handle.execution_generation,+ 'operation': 'rewind', 'payload': {'target_message_id': target}})+ except MUTATION_GUARD_REFUSALS as exc:+ raise RuntimeStoreError('session_busy') from exc+ return int(result.get('rewound_count') or 0)diff --git a/tests/gateway/test_session_tui_ops.py b/tests/gateway/test_session_tui_ops.pyindex d39d512997b..567eadbc111 100644--- a/tests/gateway/test_session_tui_ops.py+++ b/tests/gateway/test_session_tui_ops.py@@ -67,3 +67,88 @@ def test_delegation_pause_toggles_the_spawn_gate_and_status_reports_it(tmp_path)assert (await rpc(ws, 'delegation.pause', **params))['error']['message'] == reasonassert (await rpc(ws, 'delegation.status'))['result']['paused'] is Falseasyncio.run(probe())+++async def _git_rpc(ws, method, **params):+ """``rpc`` with room for checkpoint git calls: each one resolves Hermes' managed git first, which+ can take a second per call on a cold test home (the shared helper waits 20 s)."""+ await ws.send(json.dumps({'jsonrpc': '2.0', 'id': method, 'method': method, 'params': params}))+ async with asyncio.timeout(120):+ while True:+ reply = json.loads(await ws.recv())+ if reply.get('id') == method:+ return reply+++def _checkpoint(home, cwd, reason):+ """A checkpoint in the owner profile's shared store (what the agent takes before a write)."""+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from tools.checkpoint_manager import CheckpointManager+ token = set_hermes_home_override(str(home))+ try:+ assert CheckpointManager(enabled=True).ensure_checkpoint(str(cwd), reason)+ finally:+ reset_hermes_home_override(token)++[email protected]("linux")+def test_rollback_lists_diffs_and_restores_the_session_cwd_and_rewinds_the_last_turn(tmp_path):+ with owner(tmp_path) as (home, peer, desc):+ work = tmp_path / 'work'+ work.mkdir()+ (work / 'a.txt').write_text('original\n')+ (work / 'b.txt').write_text('original b\n')++ async def probe():+ async with websocket(home, desc) as ws:+ plain = (await rpc(ws, 'session.create', request_id='plain', source='tui', toolsets=[],+ cwd=str(work)))['result']['session_id']+ assert (await _git_rpc(ws, 'rollback.list', session_id=plain))['result'] == {'enabled': False, 'checkpoints': []}+ sid = (await rpc(ws, 'session.create', request_id='rollback', source='tui', toolsets=[],+ cwd=str(work), checkpoints=True))['result']['session_id']+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='first', text='FIRST')+ await settled(home)+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='second', text='SECOND')+ await settled(home)+ await asyncio.to_thread(_checkpoint, home, work, 'before write_file')+ (work / 'a.txt').write_text('edited\n')+ (work / 'b.txt').write_text('edited b\n')+ listed = await _git_rpc(ws, 'rollback.list', session_id=sid)+ assert listed.get('result', {}).get('enabled') is True, listed+ [row] = listed['result']['checkpoints']+ assert row['message'] == 'before write_file' and row['hash'], row+ diff = (await _git_rpc(ws, 'rollback.diff', session_id=sid, hash='1'))['result']+ assert 'a.txt' in diff['stat'] and 'edited' in diff['diff'], diff+ one = (await _git_rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash'], file_path='a.txt'))['result']+ assert one['success'] is True and 'history_removed' not in one, one+ assert (work / 'a.txt').read_text() == 'original\n' and (work / 'b.txt').read_text() == 'edited b\n'+ # A whole-tree restore rewinds the transcript too: refused while a turn runs (main's busy check).+ peer.blocked.clear()+ peer.release.clear()+ await rpc(ws, 'prompt.submit', session_id=sid, input_id='block', text='BLOCK_REDIRECT')+ assert await asyncio.to_thread(peer.blocked.wait, 25)+ busy = await _git_rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash'])+ assert busy['error']['message'] == 'session_busy', busy+ assert (work / 'b.txt').read_text() == 'edited b\n'+ peer.release.set()+ await settled(home)+ before = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ # The file restore took a pre-rollback snapshot, now checkpoint 1: restore the original by hash.+ full = await _git_rpc(ws, 'rollback.restore', session_id=sid, hash=row['hash'])+ assert 'result' in full, full+ full = full['result']+ assert full['success'] is True and full['history_removed'] == 2, full+ assert (work / 'b.txt').read_text() == 'original b\n'+ after = (await rpc(ws, 'session.resume', session_id=sid))['result']['messages']+ assert [m['content'] for m in after] == [m['content'] for m in before[:-2]], (before, after)+ assert after[-1]['content'] == 'CONTROL_ACK' and after[-2]['content'] == 'SECOND', after+ for method, params, reason in [+ ('rollback.diff', {'session_id': sid}, 'invalid_params'),+ ('rollback.restore', {'session_id': sid, 'hash': ''}, 'invalid_params'),+ ('rollback.diff', {'session_id': sid, 'hash': '9'}, 'invalid_checkpoint'),+ ('rollback.list', {'session_id': sid, 'profile': 'foreign'}, 'profile_mismatch'),+ ]:+ assert (await rpc(ws, method, **params))['error']['message'] == reason+ bad = (await _git_rpc(ws, 'rollback.restore', session_id=sid, hash='9'))['result']+ assert bad['success'] is False and 'Invalid checkpoint number' in bad['error'], bad+ asyncio.run(probe())diff --git a/ui-tui/src/__tests__/canonicalRollbackRefusal.test.ts b/ui-tui/src/__tests__/canonicalRollbackRefusal.test.tsdeleted file mode 100644index 33d6fbb17af..00000000000--- a/ui-tui/src/__tests__/canonicalRollbackRefusal.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { beforeEach, expect, it, vi } from 'vitest'--import { createSlashHandler } from '../app/createSlashHandler.js'-import { patchUiState, resetUiState } from '../app/uiStore.js'--const flush = () => new Promise(resolve => setImmediate(resolve))--beforeEach(() => {- resetUiState()- patchUiState({ sid: 'owner' })-})--// The rollback.* handlers are sidecar live-session RPCs: on the shared gateway they look the-// owner's session id up in the sidecar's own map and always answer "session not found".-it('/rollback says it is not available on the shared gateway instead of "session not found"', async () => {- const request = vi.fn(async (method: string) => {- if (method.startsWith('rollback.')) {- throw new Error('session not found')- }-- return {}- })-- const sys = vi.fn()-- const slash = createSlashHandler({- composer: { enqueue: vi.fn() },- gateway: { gw: { isCanonical: true, request }, rpc: request },- local: { getHistoryItems: () => [], getLastUserMsg: () => '', maybeWarn: vi.fn() },- session: { resumeById: vi.fn() },- slashFlightRef: { current: 0 },- transcript: {- page: vi.fn(),- panel: vi.fn(),- send: vi.fn(),- setHistoryItems: vi.fn(),- sys,- trimLastExchange: (x: unknown[]) => x- }- } as any)-- for (const cmd of ['/rollback', '/rollback diff abc123', '/rollback abc123 src/a.py']) {- slash(cmd)- }-- await flush()-- expect(request.mock.calls.map(([method]) => method).filter(method => method.startsWith('rollback.'))).toEqual([])- expect(sys.mock.calls.map(([text]) => String(text))).toEqual(- Array(3).fill('/rollback 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.tsindex b28e17afcd1..e69e281bed3 100644--- a/ui-tui/src/__tests__/canonicalTuiOps.test.ts+++ b/ui-tui/src/__tests__/canonicalTuiOps.test.ts@@ -81,3 +81,31 @@ it('/agents pause and resume call delegation.pause on the shared gateway with maexpect(request).toHaveBeenCalledWith('delegation.pause', { paused: false })expect(notices(sys)).toEqual(['delegation · paused', 'delegation · resumed'])})++it('/rollback list, diff and restore call the owner\'s rollback verbs with main\'s rendering', async () => {+ const { page, panel, request, setHistoryItems, slash, sys } = harness({+ 'rollback.list': { enabled: true, checkpoints: [{ hash: 'abcdef1234567', timestamp: 't1', message: 'before write_file' }] },+ 'rollback.diff': { stat: ' a.txt | 2 +-', diff: '-old\n+new' },+ 'rollback.restore': { success: true, reason: 'before write_file', history_removed: 2 }+ })++ for (const cmd of ['/rollback', '/rollback diff 1', '/rollback 1 src/a.py', '/rollback 1']) {+ slash(cmd)+ await flush()+ }++ expect(request.mock.calls.filter(([method]) => String(method).startsWith('rollback.'))).toEqual([+ ['rollback.list', { session_id: 'owner' }],+ ['rollback.diff', { hash: '1', session_id: 'owner' }],+ ['rollback.restore', { file_path: 'src/a.py', hash: '1', session_id: 'owner' }],+ ['rollback.restore', { hash: '1', session_id: 'owner' }]+ ])+ expect(panel).toHaveBeenCalledWith('Rollback checkpoints', [{ rows: [['1. abcdef1234', 't1 · before write_file']] }])+ expect(page).toHaveBeenCalledWith(' a.txt | 2 +-\n\n-old\n+new', expect.any(String))+ expect(notices(sys)).toEqual([+ 'rollback restored src/a.py: before write_file',+ 'rollback restored workspace: before write_file'+ ])+ // A whole-tree restore rewound the transcript (history_removed > 0): the view drops the exchange.+ expect(setHistoryItems).toHaveBeenCalled()+})diff --git a/ui-tui/src/app/slash/commands/ops.ts b/ui-tui/src/app/slash/commands/ops.tsindex a52d25db777..3aae87fa902 100644--- a/ui-tui/src/app/slash/commands/ops.ts+++ b/ui-tui/src/app/slash/commands/ops.ts@@ -249,12 +249,6 @@ export const opsCommands: SlashCommand[] = [return ctx.transcript.sys(t('slashCmd.ops.rollback.noSession'))}- // Checkpoints live in the legacy sidecar's per-session map, which never holds a- // shared-gateway session; the owner serves no rollback verb yet.- if (ctx.gateway.gw?.isCanonical) {- return ctx.transcript.sys(t('canonical.controls.notAvailable', 'rollback'))- }-const trimmed = arg.trim()const [first = '', ...rest] = trimmed.split(/\s+/).filter(Boolean)const lower = first.toLowerCase()