Skip to content

The agent that grows with you

fix(rest): include compression-ancestor messages in /api/sessions/{id}/messages

Yingliang Zhangcf63a03e392d
diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.py
index de8aa5863b2..e9d34a5a4aa 100644
--- a/gateway/platforms/api_server.py
+++ b/gateway/platforms/api_server.py
@@ -3057,7 +3057,14 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):
if db is None:
return []
try:
- return await asyncio.to_thread(db.get_messages_as_conversation, session_id)
+ # Include compression-ancestor messages so the API server returns
+ # the full transcript after a compression rotation, not just the
+ # child continuation (#51058).
+ return await asyncio.to_thread(
+ db.get_messages_as_conversation,
+ session_id,
+ include_ancestors=True,
+ )
except Exception as exc:
logger.warning("Failed to load session history for %s: %s", session_id, exc)
return []
diff --git a/hermes_cli/web_routers/sessions.py b/hermes_cli/web_routers/sessions.py
index 7eadb213892..614355d95b2 100644
--- a/hermes_cli/web_routers/sessions.py
+++ b/hermes_cli/web_routers/sessions.py
@@ -650,9 +650,15 @@ async def get_session_messages(
default_page = limit is None
latest_page = order == "latest" or (order is None and default_page)
_limit = 500 if default_page else min(limit, 500)
+ # Include compression-ancestor messages so the REST transcript
+ # matches the gateway's session.resume (which uses
+ # include_ancestors=True). Without this, the desktop's REST
+ # prefetch only shows the child continuation's messages after a
+ # compression rotation, hiding the pre-compaction transcript
+ # (#51058).
return sid, _limit, db.get_messages(
sid, limit=_limit, offset=offset, latest=latest_page,
- include_compacted=include_compacted)
+ include_compacted=include_compacted, include_ancestors=True)
result = await asyncio.to_thread(_with_db, profile, _read, read_only=True)
if result is None:
diff --git a/hermes_state_messages.py b/hermes_state_messages.py
index 7e34ef49d59..b6e8915e92a 100644
--- a/hermes_state_messages.py
+++ b/hermes_state_messages.py
@@ -1396,16 +1396,29 @@ class SessionMessagesMixin:
def get_messages(self, session_id: str, include_inactive: bool = False, include_compacted: bool = False,
limit: Optional[int] = None, offset: int = 0, latest: bool = False,
- after_id: Optional[int] = None) -> List[Dict[str, Any]]:
+ after_id: Optional[int] = None, include_ancestors: bool = False) -> List[Dict[str, Any]]:
"""Load messages in insertion order (id, never timestamp: clocks regress). ``include_inactive``:
rewind rows too; ``include_compacted``: compaction-archived display history (not rewind rows).
- ``latest`` pages back from the newest but returns chronological order; ``after_id``: keyset paging."""
+ ``latest`` pages back from the newest but returns chronological order; ``after_id``: keyset paging.
+ ``include_ancestors``: also load the compression lineage (root → tip, branch sessions exempt),
+ mirroring ``get_messages_as_conversation(include_ancestors=True)`` — after a compression rotation
+ the full transcript spans parent sessions, not just the child continuation (#51058)."""
if after_id is not None and (latest or offset):
raise ValueError("after_id is incompatible with latest/offset paging")
if after_id is not None and include_compacted:
raise ValueError("after_id is incompatible with include_compacted (deduped display reads use offset paging)")
active_clause = self._active_clause(include_inactive, include_compacted)
- if include_compacted and not include_inactive and self._ensure_display_order(session_id):
+ # Ancestor expansion uses the resume lineage (explicit /branch copies stay single-session).
+ session_ids = self._resume_lineage_ids(session_id) if include_ancestors else [session_id]
+ if len(session_ids) > 1:
+ # Multi-segment lineage: dedupe-then-page on the merged display set, matching the
+ # 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.)
+ rows = 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))
+ 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).
rows = self._read_retrying_ioerr(
lambda conn: self._display_rows_from_conn(
diff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.py
index 76d73b850f6..4aa8110c082 100644
--- a/tests/hermes_state/test_hermes_state.py
+++ b/tests/hermes_state/test_hermes_state.py
@@ -6466,3 +6466,62 @@ class TestFts5SanitizerCharacterClass:
# text; keep % intact there (pre-existing contract).
sanitized = self._sanitize("完成50%")
assert "%" in sanitized
+
+
+class TestGetMessagesAncestors:
+ """get_messages(include_ancestors=True) spans the compression lineage (#51058)."""
+
+ def test_include_ancestors_returns_lineage_messages(self, db):
+ """After a compression rotation, include_ancestors=True returns the
+ parent's rows plus the child continuation in insertion order."""
+ db.create_session("parent", source="tui")
+ db.append_message("parent", role="user", content="early ask")
+ db.append_message("parent", role="assistant", content="early answer")
+
+ db.create_session("child", source="tui", parent_session_id="parent")
+ db.append_message("child", role="user", content="continuation ask")
+ db.append_message("child", role="assistant", content="continuation answer")
+
+ # Without the flag: only the child continuation (legacy behaviour).
+ assert [m["content"] for m in db.get_messages("child")] == [
+ "continuation ask",
+ "continuation answer",
+ ]
+ # With the flag: the full root→tip transcript, insertion order.
+ assert [m["content"] for m in db.get_messages("child", include_ancestors=True)] == [
+ "early ask",
+ "early answer",
+ "continuation ask",
+ "continuation answer",
+ ]
+
+ def test_include_ancestors_explicit_branch_stays_single_session(self, db):
+ """Explicit /branch copies own their copied transcript: the lineage
+ expansion must not pull the parent's rows in (parity with
+ get_messages_as_conversation)."""
+ db.create_session("parent", source="tui")
+ db.append_message("parent", role="user", content="before branch")
+ db.create_session(
+ "branch",
+ source="tui",
+ parent_session_id="parent",
+ model_config={"_branched_from": "parent"},
+ )
+ db.append_message("branch", role="user", content="copied turn")
+
+ assert [m["content"] for m in db.get_messages("branch", include_ancestors=True)] == [
+ "copied turn"
+ ]
+
+ def test_include_ancestors_paging_still_applies(self, db):
+ """Paging applies to the merged lineage set, not per-session."""
+ db.create_session("parent", source="tui")
+ db.append_message("parent", role="user", content="p1")
+ db.create_session("child", source="tui", parent_session_id="parent")
+ for i in range(2, 6):
+ db.append_message("child", role="user", content=f"c{i}")
+
+ rows = db.get_messages("child", include_ancestors=True, limit=3, offset=0)
+ assert [m["content"] for m in rows] == ["p1", "c2", "c3"]
+ rows = db.get_messages("child", include_ancestors=True, limit=3, offset=3)
+ assert [m["content"] for m in rows] == ["c4", "c5"]