The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): surface compaction-archived messages in transcript reads (#80680)
zuowen7f71f91a39b80
diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex b747bffa749..7621ffe1ff4 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -684,7 +684,7 @@ export function getSession(id: string, profile?: string | null): Promise<Sessionexport function getSessionMessages(id: string,profile?: string | null,- page: { limit?: number; offset?: number; order?: 'latest' | 'oldest' } = {}+ page: { limit?: number; offset?: number; order?: 'latest' | 'oldest'; includeCompacted?: boolean } = {}): Promise<SessionMessagesResponse> {const query = new URLSearchParams()@@ -704,6 +704,10 @@ export function getSessionMessages(query.set('order', page.order)}+ if (page.includeCompacted !== undefined) {+ query.set('include_compacted', String(page.includeCompacted))+ }+const suffix = query.size ? `?${query.toString()}` : ''return window.hermesDesktop.api<SessionMessagesResponse>({@@ -713,7 +717,10 @@ export function getSessionMessages(}export function getLatestSessionMessages(id: string, profile?: string | null): Promise<SessionMessagesResponse> {- return getSessionMessages(id, profile, { limit: 500, order: 'latest' })+ // includeCompacted: durable display history must include rows preserved by+ // in-place compaction (active=0, compacted=1); without them the transcript+ // silently ends at the compaction boundary and earlier turns are unreachable.+ return getSessionMessages(id, profile, { limit: 500, order: 'latest', includeCompacted: true })}export async function getAllSessionMessages(@@ -732,7 +739,8 @@ export async function getAllSessionMessages(const page = await getSessionMessages(id, profile, {limit: pageSize,offset,- order: 'oldest'+ order: 'oldest',+ includeCompacted: true})resolvedSessionId = page.session_iddiff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.pyindex 5edf271bca1..6d54377448b 100644--- a/hermes_cli/web_routers/sessions.py+++ b/hermes_cli/web_routers/sessions.py@@ -605,6 +605,7 @@ async def get_session_messages(limit: Optional[int] = Query(None, ge=0),offset: int = Query(0, ge=0),order: Optional[str] = Query(None),+ include_compacted: bool = Query(False),):if order not in (None, "oldest", "latest"):raise HTTPException(@@ -632,6 +633,7 @@ async def get_session_messages(limit=_limit,offset=offset,latest=latest_page,+ include_compacted=include_compacted,)finally:db.close()diff --git a/hermes_state.py b/hermes_state.pyindex f4a7b75bd85..845120e324f 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -9142,6 +9142,7 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)self,session_id: str,include_inactive: bool = False,+ include_compacted: bool = False,limit: Optional[int] = None,offset: int = 0,latest: bool = False,@@ -9154,6 +9155,14 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)audit / debug views of rewound history). See:meth:`rewind_to_message` for the soft-delete mechanic.+ Pass ``include_compacted=True`` to additionally load rows preserved+ by in-place context compaction (``active=0, compacted=1``). Those are+ durable display history, not soft-deleted rows — a user-visible+ transcript read must not drop them, or earlier turns silently become+ unreachable once the UI exhausts its active-only window. Soft-deleted+ Undo/Rewind rows (``active=0, compacted=0``) stay excluded; use+ ``include_inactive`` for those.+Ordered by AUTOINCREMENT id (true insertion order) rather thantimestamp — see c03acca50 for the WSL2 clock-regression rationale.@@ -9172,7 +9181,18 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)"""if after_id is not None and (latest or offset):raise ValueError("after_id is incompatible with latest/offset paging")- active_clause = "" if include_inactive else " AND active = 1"+ if after_id is not None and include_compacted:+ raise ValueError("after_id is incompatible with include_compacted (deduped display reads use offset paging)")+ if include_inactive:+ # Audit / debug reads: every row, including soft-deleted.+ active_clause = ""+ elif include_compacted:+ # Display history: active rows plus rows preserved by in-place+ # compaction (active=0, compacted=1), but never soft-deleted+ # Undo/Rewind rows (active=0, compacted=0).+ active_clause = " AND (active = 1 OR compacted = 1)"+ else:+ active_clause = " AND active = 1"keyset_clause = " AND id > ?" if after_id is not None else ""sql = ("SELECT * FROM messages WHERE session_id = ?"@@ -9181,15 +9201,46 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)params: list = [session_id]if after_id is not None:params.append(after_id)- if limit is not None or offset:- # SQLite's OFFSET requires LIMIT; -1 means "no limit".- sql += " LIMIT ? OFFSET ?"- params.extend([-1 if limit is None else limit, offset])- with self._read_ctx() as conn:- cursor = conn.execute(sql, params)- rows = cursor.fetchall()- if latest:- rows.reverse()+ if include_compacted:+ # Compaction epochs copy the protected tail into each new+ # generation, so the same logical message can exist as several+ # rows (identical role/content/timestamp) with different active+ # flags and ids. A display read must surface each message exactly+ # once: prefer the live row, then the newest generation. Read the+ # full display set (a session's rows are bounded; the UI-level+ # 500-row cap lives in the endpoint, not here), dedupe in Python,+ # then apply paging.+ with self._read_ctx() as conn:+ cursor = conn.execute(+ "SELECT * FROM messages WHERE session_id = ?" + active_clause+ + " ORDER BY id ASC",+ [session_id],+ )+ all_rows = cursor.fetchall()+ seen: dict = {}+ for row in all_rows:+ key = (row["role"], row["content"], row["timestamp"])+ cur = seen.get(key)+ if cur is None or (row["active"], row["id"]) > (cur["active"], cur["id"]):+ seen[key] = row+ rows = sorted(seen.values(), key=lambda r: r["id"])+ if latest:+ rows = rows[::-1]+ rows = rows[offset:]+ if limit is not None:+ rows = rows[:limit]+ if latest:+ rows = rows[::-1]+ else:+ if limit is not None or offset:+ # SQLite's OFFSET requires LIMIT; -1 means "no limit".+ sql += " LIMIT ? OFFSET ?"+ params.extend([-1 if limit is None else limit, offset])+ with self._read_ctx() as conn:+ cursor = conn.execute(sql, params)+ rows = cursor.fetchall()+ if latest:+ rows.reverse()result = []for row in rows:msg = dict(row)diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.pyindex ee655e0a3b7..e9c5d2214d6 100644--- a/tests/hermes_cli/test_web_server.py+++ b/tests/hermes_cli/test_web_server.py@@ -1877,6 +1877,74 @@ class TestWebServerEndpoints:assert resp.status_code == 200assert resp.json()["pagination"]["limit"] == 500+ def test_get_session_messages_default_hides_compacted_rows(self):+ """The endpoint default matches get_messages: active rows only.++ Guards the #80680 contract — display reads opt into compacted history+ explicitly; the dashboard default view stays as it was.+ """+ from hermes_state import SessionDB++ db = SessionDB()+ try:+ db.create_session(session_id="compacted-default", source="cli")+ db.append_messages_batch(+ "compacted-default",+ [+ {"role": "user", "content": "old q"},+ {"role": "assistant", "content": "old a"},+ ],+ )+ db.archive_and_compact(+ "compacted-default",+ [+ {"role": "assistant", "content": "summary"},+ {"role": "user", "content": "live q"},+ {"role": "assistant", "content": "live a"},+ ],+ )+ finally:+ db.close()++ resp = self.client.get("/api/sessions/compacted-default/messages")+ assert resp.status_code == 200+ contents = [m["content"] for m in resp.json()["messages"]]+ assert contents == ["summary", "live q", "live a"]++ def test_get_session_messages_include_compacted_surfaces_archived_rows(self):+ """include_compacted=true returns the full display history: archived+ (active=0, compacted=1) rows plus live rows, in insertion order.+ """+ from hermes_state import SessionDB++ db = SessionDB()+ try:+ db.create_session(session_id="compacted-visible", source="cli")+ db.append_messages_batch(+ "compacted-visible",+ [+ {"role": "user", "content": "old q"},+ {"role": "assistant", "content": "old a"},+ ],+ )+ db.archive_and_compact(+ "compacted-visible",+ [+ {"role": "assistant", "content": "summary"},+ {"role": "user", "content": "live q"},+ {"role": "assistant", "content": "live a"},+ ],+ )+ finally:+ db.close()++ resp = self.client.get(+ "/api/sessions/compacted-visible/messages?include_compacted=true"+ )+ assert resp.status_code == 200+ contents = [m["content"] for m in resp.json()["messages"]]+ assert contents == ["old q", "old a", "summary", "live q", "live a"]+def test_get_session_messages_omitted_limit_defaults_to_500(self):"""The dashboard must never load an entire unbounded transcript."""from hermes_state import SessionDBdiff --git a/tests/hermes_state/test_get_messages_include_compacted.py b/tests/hermes_state/test_get_messages_include_compacted.pynew file mode 100644index 00000000000..fabdd27d2ba--- /dev/null+++ b/tests/hermes_state/test_get_messages_include_compacted.py@@ -0,0 +1,207 @@+"""Tests for SessionDB.get_messages(include_compacted=...).++In-place compaction archives earlier turns as ``active=0, compacted=1`` rows+that are durable display history, not soft-deleted rows. A transcript read+that drops them silently cuts the user-visible conversation off at the+compaction boundary (#80680): the UI exhausts its active-only window, "Show+earlier messages" disappears, and earlier turns become unreachable even+though they are still on disk.++``include_compacted=True`` must surface those rows while still excluding+soft-deleted Undo/Rewind rows (``active=0, compacted=0``) — that remains the+job of ``include_inactive`` (audit / debug reads).+"""++import pytest++from hermes_state import SessionDB+++def db(tmp_path):+ return SessionDB(tmp_path / "state.db")+++def _seed(db, sid="s1"):+ """Session with 4 archived (compacted) turns + 2 live turns + 1 rewound row."""+ db.create_session(sid, source="cli")+ old = [+ {"role": "user", "content": "old q1"},+ {"role": "assistant", "content": "old a1"},+ {"role": "user", "content": "old q2"},+ {"role": "assistant", "content": "old a2"},+ ]+ db.append_messages_batch(sid, old)+ db.archive_and_compact(+ sid,+ [+ {"role": "assistant", "content": "summary of old turns"},+ {"role": "user", "content": "live q1"},+ {"role": "assistant", "content": "live a1"},+ ],+ )+ # Soft-delete the last live user turn (active=0, compacted=0) so every+ # row class is present: active=1/compacted=0, active=0/compacted=1,+ # active=0/compacted=0. rewind_to_message requires a user target.+ live = db.get_messages(sid)+ user_msg = next(m for m in reversed(live) if m["role"] == "user")+ db.rewind_to_message(sid, user_msg["id"])+ return db+++def _row_ids(db, sid, **kwargs):+ return [m["id"] for m in db.get_messages(sid, **kwargs)]+++class TestIncludeCompacted:+ def test_default_returns_only_active_rows(self, db):+ """Regression guard: the default read must not change behaviour."""+ sid = "s1"+ db = _seed(db, sid)+ msgs = db.get_messages(sid)+ assert all(m["active"] for m in msgs)+ # Only the compaction summary survived (the rewind soft-deleted+ # the live user turn AND everything after it); the 4 archived rows+ # stay hidden.+ assert len(msgs) == 1++ def test_include_compacted_surfaces_archived_rows(self, db):+ sid = "s1"+ db = _seed(db, sid)+ msgs = db.get_messages(sid, include_compacted=True)+ # 4 archived + 1 live (the summary); the 2 rewound rows are excluded.+ assert len(msgs) == 5+ assert all(m["active"] or m["compacted"] for m in msgs)+ # Archived rows are the oldest — they come first in insertion order.+ assert msgs[0]["content"] == "old q1"+ assert msgs[-1]["content"] == "summary of old turns"++ def test_include_compacted_excludes_soft_deleted_rows(self, db):+ """Undo/Rewind rows (active=0, compacted=0) stay hidden."""+ sid = "s1"+ db = _seed(db, sid)+ msgs = db.get_messages(sid, include_compacted=True)+ assert not any(not m["active"] and not m["compacted"] for m in msgs)++ def test_include_inactive_still_returns_everything(self, db):+ """Audit semantics are unchanged: include_inactive wins."""+ sid = "s1"+ db = _seed(db, sid)+ msgs = db.get_messages(sid, include_inactive=True)+ assert len(msgs) == 7 # 4 archived + 1 live + 2 rewound++ def test_latest_page_with_compacted_rows(self, db):+ """latest=True pages back from the newest message, still in order."""+ sid = "s1"+ db = _seed(db, sid)+ ids = _row_ids(db, sid, include_compacted=True, latest=True)+ all_ids = _row_ids(db, sid, include_compacted=True)+ # The whole display history fits one page; latest pages are returned+ # in chronological order (offset measured back from the newest row).+ assert ids == all_ids+ # A bounded page still lands on the newest rows.+ tail = db.get_messages(sid, include_compacted=True, latest=True, limit=3)+ assert [m["id"] for m in tail] == all_ids[-3:]++ def test_pagination_with_compacted_rows(self, db):+ """limit/offset pages over the combined display history."""+ sid = "s1"+ db = _seed(db, sid)+ page = db.get_messages(sid, include_compacted=True, limit=3, offset=2)+ all_ids = _row_ids(db, sid, include_compacted=True)+ assert [m["id"] for m in page] == all_ids[2:5]+++class TestDisplayDedupe:+ """Compaction epochs copy the protected tail into each new generation, so+ the same logical message exists as several rows (identical+ role/content/timestamp). The display read must surface it exactly once.+ """++ def _copy_tail_as_new_generation(self, db, sid, ids):+ """Simulate one compaction epoch: duplicate rows as active=0,+ compacted=1 with the SAME content and timestamp (the real+ copy-protected-tail behaviour)."""++ def _do(conn):+ placeholders = ",".join("?" * len(ids))+ conn.execute(+ f"""+ INSERT INTO messages+ (session_id, role, content, tool_call_id, tool_calls,+ tool_name, timestamp, active, compacted)+ SELECT session_id, role, content, tool_call_id, tool_calls,+ tool_name, timestamp, 0, 1+ FROM messages+ WHERE session_id = ? AND id IN ({placeholders})+ """,+ [sid, *ids],+ )++ db._execute_write(_do)++ def test_copied_protected_tail_is_surfaced_once(self, db):+ """A message copied across compaction epochs appears exactly once."""+ sid = "s1"+ db.create_session(sid, source="cli")+ db.append_messages_batch(+ sid,+ [+ {"role": "user", "content": "turn 1"},+ {"role": "assistant", "content": "answer 1"},+ ],+ )+ orig = _row_ids(db, sid)+ self._copy_tail_as_new_generation(db, sid, orig)+ msgs = db.get_messages(sid, include_compacted=True)+ # 2 logical messages, not 4 (the copies are duplicates).+ assert len(msgs) == 2+ assert [m["content"] for m in msgs] == ["turn 1", "answer 1"]++ def test_dedupe_prefers_live_row_then_newest_generation(self, db):+ """When generations conflict, the live row wins; otherwise the newest+ generation (highest id) wins."""+ sid = "s1"+ db.create_session(sid, source="cli")+ db.append_messages_batch(sid, [{"role": "user", "content": "dup q"}])+ gen1 = _row_ids(db, sid)+ self._copy_tail_as_new_generation(db, sid, gen1) # compacted copy+ msgs = db.get_messages(sid, include_compacted=True)+ assert len(msgs) == 1+ assert msgs[0]["active"] == 1 # live row wins++ # Archive the live row and copy again: the newest compacted copy wins.+ db._execute_write(+ lambda conn: conn.execute(+ "UPDATE messages SET active = 0, compacted = 1 WHERE session_id = ?",+ [sid],+ )+ )+ self._copy_tail_as_new_generation(db, sid, gen1)+ newest_id = max(m["id"] for m in db.get_messages(sid, include_inactive=True))+ msgs = db.get_messages(sid, include_compacted=True)+ assert len(msgs) == 1+ assert msgs[0]["id"] == newest_id # newest generation wins++ def test_dedupe_applies_before_paging(self, db):+ """Deduping happens over the full display set, not per page, so+ offset paging never surfaces a duplicate."""+ sid = "s1"+ db.create_session(sid, source="cli")+ db.append_messages_batch(+ sid,+ [+ {"role": "user", "content": "q1"},+ {"role": "assistant", "content": "a1"},+ {"role": "user", "content": "q2"},+ {"role": "assistant", "content": "a2"},+ ],+ )+ orig = _row_ids(db, sid)+ self._copy_tail_as_new_generation(db, sid, orig)+ all_ids = _row_ids(db, sid, include_compacted=True)+ assert len(all_ids) == 4 # deduped, no copies+ # Paginate past where the copies would have landed.+ page = db.get_messages(sid, include_compacted=True, limit=2, offset=2)+ assert [m["id"] for m in page] == all_ids[2:]+ assert len(page) == 2