The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): show the whole history when resuming a compressed conversation
David Dudok de Wit4af8fdef6152
diff --git a/acp_adapter/gateway_commands.py b/acp_adapter/gateway_commands.pyindex 241de1ae8e6..924d754111d 100644--- a/acp_adapter/gateway_commands.py+++ b/acp_adapter/gateway_commands.py@@ -208,7 +208,7 @@ async def _refresh_context(agent, client, session_id, operation):stats = await client.rpc('session.stats', session_id=session_id)if stats.get('context_length') is None:from agent.model_metadata import estimate_request_tokens_rough- messages = agent._snapshots[session_id].get('messages') or []+ messages = [m for m in agent._snapshots[session_id].get('messages') or [] if not m.get('archived')]stats = {**stats, 'context_length': (agent._usage.get(session_id) or {}).get('context_length'),'context_tokens': estimate_request_tokens_rough(messages) if operation == 'compress' else 0}await agent._project_usage(session_id, agent._editor_id(session_id), stats)diff --git a/acp_adapter/gateway_server.py b/acp_adapter/gateway_server.pyindex fe74fc90bf0..307fc20ccc0 100644--- a/acp_adapter/gateway_server.py+++ b/acp_adapter/gateway_server.py@@ -347,7 +347,10 @@ class GatewayACPAgent(GatewayReplyMixin, acp.Agent):self._editor_mcp[session_id] = resume_params['editor']from acp_adapter.server import _history_replay_updatesif self._conn:- for update in _history_replay_updates(snapshot["messages"]):+ # The editor replays the live transcript in stored order, as main's ACP did; archived rows+ # (summarized away by a compression) are display-only.+ live = sorted((m for m in snapshot["messages"] if not m.get("archived")), key=lambda m: m.get("row_id") or 0)+ for update in _history_replay_updates(live):await self._conn.session_update(session_id=held_id, update=update)for pending in snapshot.get("prompts", []):self._permission(session_id, pending)diff --git a/apps/desktop/src/lib/chat-messages/hydration.ts b/apps/desktop/src/lib/chat-messages/hydration.tsindex ad6aa2e1b2e..8e155fb1e14 100644--- a/apps/desktop/src/lib/chat-messages/hydration.ts+++ b/apps/desktop/src/lib/chat-messages/hydration.ts@@ -205,6 +205,12 @@ function parseDisplayMetadata(metadata: SessionMessage['display_metadata']): nulreturn parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>) : null}+// A micro-compaction merge (`display_metadata.model_only`) is the model's copy of prompts whose originals+// the history shows: the owner's resume snapshot keeps it as an undo target, and it is never painted.+function isPainted(message: SessionMessage): boolean {+ return parseDisplayMetadata(message.display_metadata)?.model_only !== true+}+// `agent/conversation_loop.py::_failed_turn_display_metadata`: the failed turn's error card,// kept on its boundary row so a reopened session shows it after the live frame is gone.function failedTurnError(@@ -417,7 +423,7 @@ export function toChatMessages(messages: SessionMessage[]): ChatMessage[] {clearPendingTools()}- messages.forEach((message, index) => {+ messages.filter(isPainted).forEach((message, index) => {if (message.role === 'assistant') {nearestAssistant = message} else if (message.role === 'user' || message.role === 'system') {diff --git a/gateway/session_authority.py b/gateway/session_authority.pyindex a3b7011b029..fa15ef4a0f9 100644--- a/gateway/session_authority.py+++ b/gateway/session_authority.py@@ -260,8 +260,9 @@ class SessionAuthority:async def attach(self, actor, ref):self.authorize(actor, ref, 'session:read')+ from gateway.session_local_recovery import local_history, prepare_history+ prepared = await prepare_history(self, ref) # the lineage read stays off the loop and the locklive = self.sessions[ref.session_id]- from gateway.session_local_recovery import local_historyfrom gateway.session_queued_controls import pending_rowswith live.event_stream.lock:subscription = next((key for key, member in live.subscribers.items()@@ -279,7 +280,7 @@ class SessionAuthority:prompts = live.controls.snapshot(ref.session_id, active_generation)epoch, sequence = live.event_stream.watermark()snapshot = SubscriptionSnapshot(subscription, handle, epoch,- sequence, tuple(local_history(self, ref)),+ sequence, tuple(local_history(self, ref, prepared)),tuple(self._pending_receipt(r) for r in pending_rows(self, ref)), prompts)from gateway.session_viewer_close import cancel_persisted_closeawait asyncio.to_thread(cancel_persisted_close, self, ref.session_id) # the viewer cancels itdiff --git a/gateway/session_controls.py b/gateway/session_controls.pyindex 1e01a6ee901..0ef201893ec 100644--- a/gateway/session_controls.py+++ b/gateway/session_controls.py@@ -103,6 +103,13 @@ def display_projection(history, profile_home):return server._history_to_messages(rows, profile_home=profile_home)+def model_only(row):+ """A live row the model reads but nobody typed as one message (a micro-compaction merge): never rendered."""+ from agent.context_compressor import MODEL_ONLY_DISPLAY_METADATA_KEY+ metadata = row.get('display_metadata')+ return isinstance(metadata, dict) and bool(metadata.get(MODEL_ONLY_DISPLAY_METADATA_KEY))++class AuthorityConnection:def __init__(self, authority, transport, identity, *, operator=False):self.authority = authority@@ -612,7 +619,9 @@ class AuthorityConnection: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)+ # A micro-compaction merge stays in ``messages`` (an undo target); its originals are what shows.+ display['display_messages'] = display_projection(+ [row for row in snapshot.history if not model_only(row)], self.authority.profile_id)return {'session_id': ref.session_id, 'stored_session_id': ref.session_id,'messages': list(snapshot.history), **display, 'message_count': len(snapshot.history),'running': snapshot.handle.execution_state == 'running',diff --git a/gateway/session_hosted_rpc.py b/gateway/session_hosted_rpc.pyindex 5ada51e5fc3..87e7ec61081 100644--- a/gateway/session_hosted_rpc.py+++ b/gateway/session_hosted_rpc.py@@ -197,9 +197,10 @@ class HostedRoomAuthorityRPC:self._terminal(row, task, generation)async def _history(self, params):- from gateway.session_local_recovery import local_history+ from gateway.session_local_recovery import local_history, prepare_history+ prepared = await prepare_history(self.authority, self.ref)rows = self._rows()- history = list(local_history(self.authority, self.ref))+ history = list(local_history(self.authority, self.ref, prepared))for row, task, generation in rows:if row['status'] == 'terminal':receipt = self._terminal(row, task, generation)diff --git a/gateway/session_local_recovery.py b/gateway/session_local_recovery.pyindex f1f02a43207..28fd17837ed 100644--- a/gateway/session_local_recovery.py+++ b/gateway/session_local_recovery.py@@ -1,4 +1,6 @@"""Restore only private, profile-bound local policy into the existing authority."""+import asyncio+import jsonimport loggingfrom pathlib import Path@@ -205,16 +207,83 @@ def transcript_target(authority, ref):return authority.physical_target(ref)-def local_history(authority, ref):- """Display history from the current physical transcript; *ref* stays the logical root.+# A resume reply's rows reach Ink twice (``messages`` and ``display_messages``). Archived rows are display-only+# and fill only what the live rows leave of this budget, so they keep the reply well under the gateway clients'+# 8 MiB WebSocket frame cap (``hermes_cli/gateway_client.py``) and never push a reply main could send past it.+# Live rows are never dropped.+RESUME_HISTORY_BYTES = 3 * 1024 * 1024+++def display_rows(db, target):+ """``(live row ids, display rows, truncated)`` of physical *target*, the live ids read first+ (``local_history``'s fence). The display rows are the compression lineage as main's resume and the+ REST transcript show it: every live row, and the newest compaction-archived rows that fit what the+ live rows leave of ``RESUME_HISTORY_BYTES`` (``truncated`` when older ones were left out). A lineage+ over the resume cap shows only the live rows."""+ from hermes_state import SessionResumeTooLargeError+ live_rows = db.get_messages_as_conversation(target, include_row_ids=True)+ live = {row['_row_id'] for row in live_rows}+ try:+ db.assert_resume_safe(target)+ except SessionResumeTooLargeError:+ return live, [], False+ kept, used, truncated = [], sum(len(json.dumps(row, default=str)) for row in live_rows), False+ for row in reversed(db.get_messages_as_conversation(target, include_ancestors=True, include_compacted=True,+ include_row_ids=True)):+ if row['_row_id'] not in live:+ used += len(json.dumps(row, default=str))+ truncated = truncated or used > RESUME_HISTORY_BYTES+ if truncated:+ continue+ kept.append(row)+ return live, kept[::-1], truncated+++async def prepare_history(authority, ref):+ """``local_history``'s lineage read, off the owner loop; the locked part re-reads only the live tip."""+ target = transcript_target(authority, ref)+ return target, await asyncio.to_thread(display_rows, authority.db, target)+++def local_history(authority, ref, prepared=None):+ """Display history of logical *ref*: every stored row the user saw, in display order.++ A row outside the current physical transcript's active set (summarized away by a compression)+ carries ``archived: true``: it is shown, never live, so no undo, retry or rewind may target it.+ The rows without it are exactly the live transcript's, so a client choosing among live rows sees+ what it saw before. That includes a micro-compaction merge (``display_metadata.model_only``): its+ originals are the archived rows renderers show, so renderers skip the merge itself.Each row carries its durable ``messages.id`` as ``row_id`` (the ``TranscriptMessage`` fieldDesktop hydration and the legacy ``session.history`` already use): a ``session.mutate`` rewindaddresses its ``target_message_id`` by it, so a snapshot without it leaves no way to undo/retry.+ *prepared* (``prepare_history``) is kept while every row it read as live still is; a rewind or+ compaction since then re-reads the lineage here. When the byte budget left older archived rows out+ (``display_rows``), the first row carries ``archived_truncated: true``."""- rows = authority.db.get_messages_as_conversation(transcript_target(authority, ref), include_row_ids=True)- return [{**{k: v for k, v in row.items() if k != '_row_id'}, 'row_id': row['_row_id']}- if '_row_id' in row else row for row in rows]+ db = authority.db+ target = transcript_target(authority, ref)+ read_live, display, truncated = (prepared[1] if prepared is not None and prepared[0] == target+ else display_rows(db, target))+ live = db.get_messages_as_conversation(target, include_row_ids=True)+ if not read_live <= {row['_row_id'] for row in live}:+ read_live, display, truncated = display_rows(db, target)+ live = db.get_messages_as_conversation(target, include_row_ids=True)+ current = {row['_row_id']: row for row in live}+ shown = {row['_row_id'] for row in display}+ unshown = [row for row in live if row['_row_id'] not in shown] # hidden by the display, or appended since+ rows = []+ for row in display:+ if row['_row_id'] not in current:+ rows.append({**row, 'archived': True})+ continue+ while unshown and unshown[0]['_row_id'] < row['_row_id']:+ rows.append(unshown.pop(0))+ rows.append(current[row['_row_id']])+ rows = [{**{k: v for k, v in row.items() if k != '_row_id'}, 'row_id': row['_row_id']} for row in rows + unshown]+ if truncated and rows:+ rows[0]['archived_truncated'] = True # earlier archived history was left out (the byte budget)+ return rowsdef reopen_local_session(authority, ref):diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.pyindex 9afebd01044..bfac78b6590 100644--- a/hermes_cli/gateway_agent.py+++ b/hermes_cli/gateway_agent.py@@ -500,7 +500,8 @@ class GatewayAgent:compressor.compression_count += 1compressor.last_prompt_tokens = -1self._turn_base_usage_anchor = None- return [{k: v for k, v in m.items() if k != "row_id"} for m in after.get("messages") or []], system_message+ return [{k: v for k, v in m.items() if k != "row_id"} for m in after.get("messages") or []+ if not m.get("archived")], system_messagedef steer(self, text):return self._correct("steer", text)diff --git a/hermes_cli/gateway_chat.py b/hermes_cli/gateway_chat.pyindex 7b42222168d..378ef79e843 100644--- a/hermes_cli/gateway_chat.py+++ b/hermes_cli/gateway_chat.py@@ -236,7 +236,9 @@ async def run_gateway_chat(args, emitter=None):view.resume_footer = oneshot and not quietif (getattr(args, "resume", None) or title or latest) and not quiet:for row in snapshot.get("messages", []):- if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str):+ # A micro-compaction merge (model_only) is not printed: its original prompts are.+ merged = isinstance(row.get("display_metadata"), dict) and row["display_metadata"].get("model_only")+ if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str) and not merged:print(f"{row['role']}: {row['content']}")return await view.run(query, oneshot=oneshot)diff --git a/hermes_cli/gateway_chat_commands.py b/hermes_cli/gateway_chat_commands.pyindex cb413502ec2..949f00df381 100644--- a/hermes_cli/gateway_chat_commands.py+++ b/hermes_cli/gateway_chat_commands.py@@ -40,12 +40,13 @@ def refusal(name):def _user_turns(snapshot):- """Human-authored user rows (``row_id`` = durable ``messages.id``), oldest first: no display-only- kind other than a typed /steer, never a compaction handoff carrier."""+ """Human-authored live user rows (``row_id`` = durable ``messages.id``), oldest first: no display-only+ kind other than a typed /steer, never a compaction handoff carrier, never a row a compression+ archived (shown in the snapshot's history, not a turn to rewind to)."""from agent.context_compressor import is_user_originated_turnreturn [row for row in snapshot.get("messages", [])if type(row.get("row_id")) is int and row.get("display_kind") in (None, "", "steer")- and is_user_originated_turn(row)]+ and not row.get("archived") and is_user_originated_turn(row)]def _rewind_to(turns_back, *, retry=False):diff --git a/hermes_cli/gateway_rollback.py b/hermes_cli/gateway_rollback.pyindex c66cbcfa930..914d7c93e11 100644--- a/hermes_cli/gateway_rollback.py+++ b/hermes_cli/gateway_rollback.py@@ -78,5 +78,5 @@ def _restored(cli, connection, result, file_path):snapshot = connection.call("session.resume", session_id=cli.session_id)connection.state(cli.session_id).adopt_snapshot(snapshot)cli.conversation_history = [{k: v for k, v in m.items() if k != "row_id"}- for m in snapshot.get("messages") or []]+ for m in snapshot.get("messages") or [] if not m.get("archived")]print(f" {_t('rollback.chat_turn_undone')}")diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.pyindex 1d3c1192afb..0a5d16e2b7a 100644--- a/hermes_cli/gateway_session_store.py+++ b/hermes_cli/gateway_session_store.py@@ -223,7 +223,7 @@ class GatewaySessionStore:from hermes_state_rewind import (_HISTORY_CHANGED, RewindOutcome, RewindTargetUnavailableError, _comparison_content, _user_indices)snapshot = self.call("session.resume", session_id=session_id)- durable = list(snapshot.get("messages") or [])+ durable = [m for m in snapshot.get("messages") or [] if not m.get("archived")] # the live rowsdurable_user = _user_indices(durable)if user_ordinal < 0:user_ordinal = max(len(durable_user) + user_ordinal, 0)diff --git a/hermes_state_messages.py b/hermes_state_messages.pyindex 299e8b59d46..f6976293ec4 100644--- a/hermes_state_messages.py+++ b/hermes_state_messages.py@@ -24,7 +24,7 @@ from hermes_state_common import (_json_or, _legacy_reset_child_sql, _placeholders, _sql_json_extract)from hermes_state_detached_results import SessionDetachedResultsMixinfrom hermes_state_identity import (- _absorbed_uids_json, _restore_identity_columns, _stable_tool_key, _tool_call_uid_map, _tool_call_uid_or_none, _tool_call_uids_json)+ _absorbed_uids_json, _restore_identity_columns, _stable_tool_key, _tool_call_uid_map, _tool_call_uid_or_none, _tool_call_uids_json, _uid_list)logger = logging.getLogger("hermes_state") # caplog tests pin the origin module's name@@ -1200,23 +1200,43 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):"""Fixed-width durable identity for indexed display-generation lookup."""return hashlib.sha256(repr(key).encode("utf-8", "surrogatepass")).digest()- def _dedupe_display_generations(self, rows):+ def _dedupe_display_generations(self, rows, *, drop_removed: bool = False):"""Collapse compaction generations so each logical message appears once (the protected tail is copiedinto each generation: same role/content/timestamp, different ``active``/id); prefer the live row, then- the newest. The ONE definition every display projection shares. *rows* must be ordered by ``id``."""+ the newest. The ONE definition every display projection shares. *rows* must be ordered by ``id``.++ *drop_removed*: *rows* also hold the removed rows (``active=0, compacted=0``: rewound, or replaced by a+ newer copy) and ``compacted``. A message whose newest copy is removed is not shown, so a rewind in a+ compression child never brings back the parent's copy. Copies share the display key or ``message_uid``+ (a micro-compaction merge also stands for the rows it absorbed)."""seen: dict[tuple[Any, ...], Any] = {}first_id: dict[tuple[Any, ...], int] = {}+ removed: dict[Any, bool] = {} # copy identity -> its newest copy is removed (rows come in id order)+ identities: dict[tuple[Any, ...], list[Any]] = {}for row in rows:+ copies = None+ if drop_removed:+ key = self._display_dedupe_key(row)+ copies = [key, *(("uid", uid) for uid in (row["message_uid"],+ *_uid_list(row["absorbed_message_uids"])) if uid)]+ gone = not row["active"] and not row["compacted"]+ removed.update(dict.fromkeys(copies, gone))+ if gone:+ continueif self._is_model_only_row(row):continue- key = self._display_dedupe_key(row)+ key = copies[0] if copies else self._display_dedupe_key(row)cur = seen.get(key)if cur is None or (row["active"], row["id"]) > (cur["active"], cur["id"]):seen[key] = row+ identities[key] = copiesfirst_id[key] = min(first_id.get(key, row["id"]), row["id"])# Order by the logical message's FIRST row, not the chosen representative's: a protected-tail# copy in a newer generation has a higher id than messages emitted after the original.- return [seen[key] for key in sorted(seen, key=first_id.__getitem__)]+ keys = sorted(seen, key=first_id.__getitem__)+ if drop_removed:+ keys = [key for key in keys if not any(removed[copy] for copy in identities[key])]+ return [seen[key] for key in keys]def _reconcile_display_orders(self, conn, session_id: str) -> None:"""Re-fold split display generations by the recomputed display key.@@ -1409,8 +1429,10 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):# canonical multi-segment projection in get_messages_as_conversation(include_ancestors=True).# (display_order is per-segment and not comparable across segments, so the per-segment# display_order paging below does not apply across a lineage.)+ display = include_compacted and not include_inactive # removed rows too: see drop_removedrows = self._dedupe_display_generations(self._read_all(- f"SELECT * FROM messages WHERE session_id IN ({_placeholders(session_ids)})" + active_clause + " ORDER BY id ASC", session_ids))+ f"SELECT * FROM messages WHERE session_id IN ({_placeholders(session_ids)})"+ + ("" if display else active_clause) + " ORDER BY id ASC", session_ids), drop_removed=display)rows = rows[::-1][offset:][:limit][::-1] if latest else rows[offset:][:limit]elif include_compacted and not include_inactive and self._ensure_display_order(session_id):# _read_retrying_ioerr: mode=ro pooled readers see a transient IOERR mid-checkpoint (#100871).@@ -1506,11 +1528,13 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):seen.add(current)return best if best is not None else session_id- def _fetch_conversation_rows(self, session_ids: list[str], active_clause: str, *, with_session_id: bool):+ def _fetch_conversation_rows(self, session_ids: list[str], active_clause: str, *, with_session_id: bool,+ with_compacted: bool = False):"""``_CONVERSATION_ROW_COLUMNS`` rows for *session_ids* ORDER BY id (timestamps are not monotonic- and would break tool-call adjacency)."""+ and would break tool-call adjacency). ``with_compacted``: also the ``compacted`` column."""return self._read_all(- f"SELECT {'session_id, ' if with_session_id else ''}{self._CONVERSATION_ROW_COLUMNS} "+ f"SELECT {'session_id, ' if with_session_id else ''}{'compacted, ' if with_compacted else ''}"+ f"{self._CONVERSATION_ROW_COLUMNS} "f"FROM messages WHERE session_id IN ({_placeholders(session_ids)})"f"{active_clause} ORDER BY id", tuple(session_ids))@@ -1523,11 +1547,13 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):repairs the loaded list for LIVE REPLAY callers (a durable ``user;user`` pair would re-trigger theper-request repair forever), preserving summary markers before repair so derivative contextcannot merge with an original user turn; the stored transcript is never mutated."""+ display = include_compacted and not include_inactive # removed rows too: see drop_removedrows = self._fetch_conversation_rows(self._resume_lineage_ids(session_id) if include_ancestors else [session_id],- self._active_clause(include_inactive, include_compacted), with_session_id=False)+ "" if display else self._active_clause(include_inactive, include_compacted), with_session_id=False,+ with_compacted=display)if include_compacted:- rows = self._dedupe_display_generations(rows)+ rows = self._dedupe_display_generations(rows, drop_removed=display)return self._rows_to_conversation(rows, session_id=session_id, include_ancestors=include_ancestors,repair_alternation=repair_alternation, include_row_ids=include_row_ids,include_summary_markers=repair_alternation)@@ -1661,7 +1687,7 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):always included them) disagreed with this one about the same session (#92080)."""rows = self._fetch_conversation_rows(- self._resume_lineage_ids(session_id), _DISPLAY_ACTIVE_CLAUSE, with_session_id=True)+ self._resume_lineage_ids(session_id), "", with_session_id=True, with_compacted=True)# The model projection stays active-only: it is the compressed working context. The gateway's# first-turn ``session_meta`` marker (tools/model/platform bookkeeping) is transcript logging,# never LLM input: a resuming surface that fed it to the agent would count it in the history@@ -1671,7 +1697,7 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):session_id=session_id,include_ancestors=False, repair_alternation=True, include_row_ids=True, include_summary_markers=True)display_history = self._rows_to_conversation(- self._dedupe_display_generations(rows), session_id=session_id,+ self._dedupe_display_generations(rows, drop_removed=True), session_id=session_id,include_ancestors=True, repair_alternation=False, include_row_ids=True)return model_history, display_history@@ -1743,8 +1769,8 @@ class SessionMessagesMixin(SessionDetachedResultsMixin):session_ids = self._resume_lineage_ids(session_id)if len(session_ids) <= 1:return []- rows = self._dedupe_display_generations(- self._fetch_conversation_rows(session_ids, _DISPLAY_ACTIVE_CLAUSE, with_session_id=True))+ rows = self._dedupe_display_generations(self._fetch_conversation_rows(+ session_ids, "", with_session_id=True, with_compacted=True), drop_removed=True)ancestor_ids = {int(row["id"]) for row in rows if row["session_id"] != session_id and row["id"] is not None}if not ancestor_ids:return []diff --git a/tests/gateway/test_legacy_session_migration.py b/tests/gateway/test_legacy_session_migration.pyindex 29959170465..9a87f9e0f38 100644--- a/tests/gateway/test_legacy_session_migration.py+++ b/tests/gateway/test_legacy_session_migration.py@@ -77,7 +77,8 @@ async def test_legacy_history_adoption_is_native_owned_atomic_and_retryable(tmp_finally:db.release_compression_lock(ref.session_id, 'fixture')snapshot = await authority.attach(native, ref)- assert [m['content'] for m in snapshot.history] == ['COMPRESSED', 'RETAINED']+ assert [m['content'] for m in snapshot.history if not m.get('archived')] == ['COMPRESSED', 'RETAINED']+ assert [m['content'] for m in snapshot.history if m.get('archived')] == ['OLD_QUESTION', 'OLD_ANSWER']assert resolve_titled_session(authority, native, 'old-cli') == refassert local_receipt(db, ref.session_id)['policy'] == receipt['policy']with pytest.raises(RuntimeStoreError, match='permission_denied'):diff --git a/tests/gateway/test_local_session_recovery.py b/tests/gateway/test_local_session_recovery.pyindex ec272676883..bee095002ac 100644--- a/tests/gateway/test_local_session_recovery.py+++ b/tests/gateway/test_local_session_recovery.py@@ -97,10 +97,11 @@ def test_messaging_session_history_follows_the_compression_tip(tmp_path, monkeyphistory = local_history(authority, SessionRef('owned', 'root'))contents = [m['content'] for m in history]assert 'AFTER_COMPRESSION' in contents- assert 'BEFORE_COMPRESSION' not in contents+ # The root's turn is still shown, marked archived: display history, never a live row.+ assert [m['content'] for m in history if m.get('archived')] == ['BEFORE_COMPRESSION']# Snapshot rows carry their durable row id (a session.mutate rewind's target_message_id),# under the public TranscriptMessage name, never the internal ``_row_id``.- assert [m['row_id'] for m in history] == [m['id'] for m in db.get_messages('child')]+ assert [m['row_id'] for m in history if not m.get('archived')] == [m['id'] for m in db.get_messages('child')]assert not any('_row_id' in m for m in history)diff --git a/tests/gateway/test_resume_display_history.py b/tests/gateway/test_resume_display_history.pynew file mode 100644index 00000000000..6c3b5fcd80a--- /dev/null+++ b/tests/gateway/test_resume_display_history.py@@ -0,0 +1,152 @@+"""A resume after a compression shows the whole display history: the turns the compression+summarized away come back marked ``archived``, and only the live rows stay undo/retry targets. An undone+turn stays gone, a merged prompt shows once, and the archived part of the reply is bounded.++Real store, authority, local session, compaction verbs and ``AuthorityConnection.resume``; the runner+is a stand-in with no cached agent, and the resume ``info`` block is stubbed out.+"""+from types import SimpleNamespace++import pytest++from agent.context_compressor import SUMMARY_PREFIX++SUMMARY = SUMMARY_PREFIX + '\nearlier turns summarized'+++async def _local_session(tmp_path, monkeypatch):+ from gateway import run, session_local+ from gateway.config import GatewayConfig+ from gateway.session import SessionStore+ from gateway.session_authority import initialize_session_authority+ from gateway.session_contract import Principal+ from hermes_state_local import local_receipt+ monkeypatch.setattr(run, '_load_gateway_config', dict)+ monkeypatch.setattr(session_local, 'local_session_info', lambda *a: {})+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,+ _cached_agent_for=lambda *a, **k: None, _evict_cached_agent=lambda *a, **k: None)+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)+ authority = await initialize_session_authority(runner, profile_id='fixture', instance_id='first')+ actor = Principal('owner', 'fixture', frozenset({'session:create', 'session:read', 'session:control'}), 'sock')+ ref = session_local.create_local_session(authority, actor, dict(+ request_id='resume', source='gui', cwd=str(tmp_path), model='frozen', toolsets=[]))+ return authority, actor, ref, local_receipt(authority.db, ref.session_id)['entry']['session_id']+++async def _resume(authority, actor, ref, **params):+ from gateway.session_controls import AuthorityConnection+ conn = AuthorityConnection(authority, object(), {'user_id': 'owner'})+ conn.actor = actor+ authority.events[actor.transport_id] = object()+ return await conn.resume(ref, {'session_id': ref.session_id, **params})+++def _append(db, sid, *texts):+ for role, text in zip(('user', 'assistant') * len(texts), texts):+ db.append_message(sid, role, text)+++def _compact(db, physical, mode):+ compacted = [{'role': 'user', 'content': SUMMARY}, {'role': 'user', 'content': 'TAIL_Q'},+ {'role': 'assistant', 'content': 'TAIL_A'}]+ if mode == 'in_place':+ db.archive_and_compact(physical, compacted, tail_count=2)+ return physical+ assert db.try_acquire_compression_lock(physical, 'fixture')+ try:+ db.publish_compression_child(parent_session_id=physical, child_session_id='child', source='gui',+ messages=compacted, compression_lock_holder='fixture')+ finally:+ db.release_compression_lock(physical, 'fixture')+ return 'child'++[email protected]('mode', ['in_place', 'rotated'])+async def test_resume_shows_the_turns_a_compression_archived(tmp_path, monkeypatch, mode):+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)+ db = authority.db+ _append(db, physical, 'OLD_Q', 'OLD_A', 'REWOUND_Q', 'REWOUND_A')+ db.rewind_to_message(physical, next(m['id'] for m in db.get_messages(physical) if m['content'] == 'REWOUND_Q'))+ _append(db, physical, 'TAIL_Q', 'TAIL_A')+ tip = _compact(db, physical, mode)+ rows = (await _resume(authority, actor, ref))['messages']+ # The earlier turns are shown and marked archived; the carried tail appears once; a rewound turn stays out.+ assert [(r['content'], bool(r.get('archived'))) for r in rows if r['content'] != SUMMARY] == [+ ('OLD_Q', True), ('OLD_A', True), ('TAIL_Q', False), ('TAIL_A', False)]+ # The rows not archived are exactly the live transcript, each with its durable row id.+ assert sorted(r['row_id'] for r in rows if not r.get('archived')) == [m['id'] for m in db.get_messages(tip)]+++async def test_undo_and_retry_choose_only_among_live_turns(tmp_path, monkeypatch):+ from hermes_cli.gateway_chat_commands import _rewind_to+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)+ db = authority.db+ _append(db, physical, 'OLD_Q', 'OLD_A', 'TAIL_Q', 'TAIL_A')+ _compact(db, physical, 'in_place')+ _append(db, physical, 'NEW_Q', 'NEW_A')+ snapshot = await _resume(authority, actor, ref)+ live = {r['content']: r['row_id'] for r in snapshot['messages'] if not r.get('archived')}+ assert _rewind_to(3)(snapshot) is None # two live turns: the archived OLD_Q is never a target+ assert _rewind_to(2)(snapshot) == {'target_message_id': live['TAIL_Q']}+ assert _rewind_to(1, retry=True)(snapshot) == {'target_message_id': live['NEW_Q']}+++async def test_an_undone_turn_stays_gone_after_a_rotated_compression(tmp_path, monkeypatch):+ """The rewind removes the child's copies; the parent's copies of the same turn must not come back."""+ from gateway.session_mutations import mutate_session+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)+ db = authority.db+ _append(db, physical, 'OLD_Q', 'OLD_A', 'TAIL_Q', 'TAIL_A')+ tip = _compact(db, physical, 'rotated')+ handle = authority._handle(ref)+ await mutate_session(authority, actor, ref, {+ 'session_id': ref.session_id, 'request_id': 'undo', 'operation': 'rewind',+ 'expected_revision': handle.revision, 'expected_generation': handle.execution_generation,+ 'payload': {'target_message_id': next(m['id'] for m in db.get_messages(tip) if m['content'] == 'TAIL_Q')}})+ rows = (await _resume(authority, actor, ref))['messages']+ assert [(r['content'], bool(r.get('archived'))) for r in rows] == [+ ('OLD_Q', True), ('OLD_A', True), (SUMMARY, False)]+++async def test_a_micro_compaction_merge_shows_its_prompts_once(tmp_path, monkeypatch):+ """A merged prompt row (``model_only``) stays a live undo target but is not painted next to its originals."""+ from hermes_cli.gateway_chat_commands import _rewind_to+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)+ db = authority.db+ _append(db, physical, 'Q1', 'A1', 'Q2', 'A2', 'Q3', 'A3')+ db.archive_and_compact(physical, [+ {'role': 'user', 'content': 'Q1\n\nQ2', 'display_metadata': {'model_only': True}},+ {'role': 'assistant', 'content': SUMMARY}, {'role': 'user', 'content': 'Q3'},+ {'role': 'assistant', 'content': 'A3'}], tail_count=2)+ snapshot = await _resume(authority, actor, ref, display_projection=True)+ assert [m['text'] for m in snapshot['display_messages'] if m['role'] == 'user'] == ['Q1', 'Q2', 'Q3']+ merged = next(r for r in snapshot['messages'] if r['content'] == 'Q1\n\nQ2')+ assert not merged.get('archived') and _rewind_to(2)(snapshot) == {'target_message_id': merged['row_id']}+++async def test_a_long_archived_history_keeps_the_resume_reply_bounded(tmp_path, monkeypatch):+ """Archived history is cut to the newest rows that fit what the live rows leave of a byte budget, so the+ reply (with Ink's ``display_messages``) stays under the gateway clients' 8 MiB frame cap whenever main's+ live-only reply does, large live rows included; live rows all stay."""+ import json+ authority, actor, ref, physical = await _local_session(tmp_path, monkeypatch)+ db = authority.db+ for n in range(40):+ _append(db, physical, f'Q{n} ' + 'x' * 120_000, f'A{n}')+ _append(db, physical, 'TAIL_Q', 'TAIL_A')+ tip = _compact(db, physical, 'in_place')+ for n in range(24): # 2.3 MiB of live rows: main's reply (twice that for Ink) fits the frame+ _append(db, tip, f'LIVE{n} ' + 'l' * 100_000, f'R{n}')+ reply = await _resume(authority, actor, ref, display_projection=True)+ assert len(json.dumps(reply)) < 8 * 1024 * 1024+ rows = reply['messages']+ assert rows[0]['archived_truncated'] and rows[-1]['content'] == 'R23'+ assert sorted(r['row_id'] for r in rows if not r.get('archived')) == [m['id'] for m in db.get_messages(tip)]+ archived = [r['content'][:4] for r in rows if r.get('archived') and r['role'] == 'user']+ assert archived and archived[-1] == 'Q39 ' and 'Q0 x' not in archived # the newest are keptdiff --git a/tests/gateway/test_stored_session_picker.py b/tests/gateway/test_stored_session_picker.pyindex d233eade149..31786854773 100644--- a/tests/gateway/test_stored_session_picker.py+++ b/tests/gateway/test_stored_session_picker.py@@ -72,4 +72,6 @@ async def test_stored_picker_survives_upgrade_and_resumes_without_copying(tmp_paassert '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']+ messages = compressed['result']['messages']+ assert [m['content'] for m in messages if not m.get('archived')] == ['compressed question', 'compressed answer']+ assert [m['content'] for m in messages if m.get('archived')] == ['old-tui question', 'old-tui answer']diff --git a/tests/hermes_state/test_runtime_rewind_mutations.py b/tests/hermes_state/test_runtime_rewind_mutations.pyindex 85b56073613..d37646b6e56 100644--- a/tests/hermes_state/test_runtime_rewind_mutations.py+++ b/tests/hermes_state/test_runtime_rewind_mutations.py@@ -74,3 +74,20 @@ def test_rewind_refuses_a_target_that_is_not_a_live_user_row(tmp_path, target):with pytest.raises(rt.RuntimeStoreError, match='invalid_params'):_rewind_to(db, epoch, 99999 if target == 'missing' else shown['A3'])assert [m['content'] for m in db.get_messages('s')][-2:] == ['Q3', 'A3']+++def test_rewind_refuses_a_row_a_compression_archived(tmp_path):+ """A compacted row is still shown in history, but it is not live: a rewind to it would deactivate+ every live row after it, the whole conversation since the compression."""+ with SessionDB(db_path=tmp_path / 'state.db') as db:+ db.create_session('s', source='test')+ db.append_messages_batch('s', [{'role': 'user', 'content': 'old'}, {'role': 'assistant', 'content': 'reply'}])+ archived = db.get_messages('s')[0]['id']+ db.archive_and_compact('s', [{'role': 'user', 'content': '[CONTEXT COMPACTION] earlier turns'}])+ db.append_messages_batch('s', [{'role': 'user', 'content': 'live'}, {'role': 'assistant', 'content': 'answer'}])+ live = [m['content'] for m in db.get_messages('s')]+ epoch = rt.begin_runtime_epoch(db, instance_id='owner')+ with pytest.raises(rt.RuntimeStoreError, match='invalid_params'):+ rt.mutate_runtime_session(db, epoch=epoch, principal_id='human', session_id='s', request_id='rewind',+ expected_revision=0, expected_generation=0, operation='rewind', payload={'target_message_id': archived})+ assert [m['content'] for m in db.get_messages('s')] == livediff --git a/ui-tui/src/app/slash/canonicalSessionCommands.ts b/ui-tui/src/app/slash/canonicalSessionCommands.tsindex efad1faee2e..e0f89be5b00 100644--- a/ui-tui/src/app/slash/canonicalSessionCommands.ts+++ b/ui-tui/src/app/slash/canonicalSessionCommands.ts@@ -17,12 +17,14 @@ import { usageTotalsSections } from './usagePanel.js'const COMPACTION_MARKERS = ['[CONTEXT COMPACTION', '[CONTEXT SUMMARY]:', '[END OF PRIOR CONTEXT']-/** A human-authored user turn (`agent/context_compressor.py::split_user_originated_turn`): no- * display-only kind other than a typed /steer, and not a compaction handoff carrier. */+/** A human-authored live user turn (`agent/context_compressor.py::split_user_originated_turn`): no+ * display-only kind other than a typed /steer, not a compaction handoff carrier, and not a row a+ * compression archived (history the snapshot shows, never a turn to rewind to). */const isUserTurn = (row: Record<string, unknown>) =>row.role === 'user' &&(!row.display_kind || row.display_kind === 'steer') &&Number.isSafeInteger(row.row_id) &&+ !row.archived &&!(typeof row.content === 'string' && COMPACTION_MARKERS.some(marker => row.content!.toString().includes(marker)))/** The rewind payload for the newest user turn in the snapshot the CAS tuple came from. */