Skip to content

The agent that grows with you

fix(gateway): preserve session lineage in the session.list RPC

Sanjay Santhanam1212a7f18ce8
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index bcb8ec408b7..3fa391f215c 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -3205,6 +3205,7 @@ export interface SessionListRow {
message_count?: number
live_message_count?: number | null
source?: string
+ _lineage_root_id?: string | null
}
export interface SessionMostRecentParams {
profile?: string | null
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index a414e51609a..a7313b15098 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -31226,6 +31226,18 @@
"default": "",
"title": "Source",
"type": "string"
+ },
+ "_lineage_root_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+ "title": "Lineage Root Id"
}
},
"required": [
diff --git a/tests/tui_gateway/test_session_list_lineage_rpc.py b/tests/tui_gateway/test_session_list_lineage_rpc.py
new file mode 100644
index 00000000000..575b8e93d83
--- /dev/null
+++ b/tests/tui_gateway/test_session_list_lineage_rpc.py
@@ -0,0 +1,58 @@
+"""``session.list`` must forward the durable lineage root. Regression for #66663.
+
+``hermes_state.list_sessions_rich`` already returns ``_lineage_root_id`` on projected
+compression rows, and the REST ``/api/sessions`` path projects it
+(``gateway/platforms/api_server.py::_session_response``). The ``session.list`` RPC row
+summary dropped the field, so RPC consumers could not group a compressed conversation
+with its continuation — the desktop store keys pinning and lineage dedup on it
+(``apps/desktop/src/store/session.ts::sessionPinId``).
+"""
+
+import time
+
+import pytest
+
+import tui_gateway.server as srv
+import tui_gateway.methods_session # noqa: F401 (registers the RPC methods)
+from hermes_state import SessionDB
+
+
+def db(tmp_path, monkeypatch):
+ database = SessionDB(tmp_path / "state.db")
+ monkeypatch.setattr(srv, "_get_db", lambda: database)
+ try:
+ yield database
+ finally:
+ database.close()
+
+
+def _call(method: str, params: dict) -> dict:
+ return srv._methods[method](1, params)
+
+
+def _seed_compressed_conversation(db) -> None:
+ """``root1`` (compression-ended) -> ``tip1`` live continuation, both with messages."""
+ t0 = time.time() - 3600
+ db.create_session("root1", "cli")
+ db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0, "root1"))
+ db.append_message("root1", "user", "help me refactor auth")
+ db._conn.execute(
+ "UPDATE sessions SET ended_at=?, end_reason=? WHERE id=?",
+ (t0 + 1800, "compression", "root1"),
+ )
+ db.create_session("tip1", "cli", parent_session_id="root1")
+ db._conn.execute("UPDATE sessions SET started_at=? WHERE id=?", (t0 + 1801, "tip1"))
+ db.append_message("tip1", "user", "continuing")
+ db._conn.commit()
+
+
+def test_session_list_projects_lineage_root_id(db):
+ """The RPC row summary must forward the projected tip's lineage root, like REST."""
+ _seed_compressed_conversation(db)
+ rows = _call("session.list", {})["result"]["sessions"]
+ by_id = {row["id"]: row for row in rows}
+ # The compressed root surfaces as its live continuation tip.
+ assert "tip1" in by_id, rows
+ # REST already projects this field; the RPC row summary must too (#66663).
+ assert by_id["tip1"]["_lineage_root_id"] == "root1"
diff --git a/tui_gateway/contracts/sessions.py b/tui_gateway/contracts/sessions.py
index 46f5cc93381..a86e5febf6b 100644
--- a/tui_gateway/contracts/sessions.py
+++ b/tui_gateway/contracts/sessions.py
@@ -236,6 +236,9 @@ class SessionListRow(Result):
message_count: int = 0
live_message_count: int | None = None
source: str = ""
+ # Durable lineage root of a compressed conversation (REST parity, #66663); None on
+ # rows that are not projected compression tips.
+ lineage_root_id: str | None = Field(default=None, alias="_lineage_root_id")
class SessionListResult(Result):
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 7583684fa57..fd2730fbf13 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -123,6 +123,10 @@ def _session_row_summary(row: dict, *, tip_row: dict | None = None, resolved_id=
"title": row.get("title") or "", "preview": tip_row.get("preview") or "",
"started_at": row.get("started_at") or 0, "message_count": tip_row.get("message_count") or 0,
"source": row.get("source") or "",
+ # Durable lineage root for compressed conversations — the same field REST
+ # projects (api_server._session_response); RPC consumers (desktop pinning /
+ # lineage dedup) group on it. #66663.
+ "_lineage_root_id": row.get("_lineage_root_id"),
**({} if db is None else _live_count_field(db, row["id"] if resolved_id is None else resolved_id))}
@@ -2204,150 +2208,6 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"closed": _teardown_popped_session(session, end_reason="tui_close")})
-# ── session.branch ───────────────────────────────────────────────────
-def _visible_branch_history(messages) -> list:
- """user/assistant rows with visible text, as FULL copies (reasoning + timeline-marker tags survive)."""
- return [dict(message) for message in messages or []
- if isinstance(message, dict) and message.get("role") in {"user", "assistant"}
- and _coerce_message_text(message.get("content")).strip()]
-
-
-def _build_branch_agent(session: dict, new_sid: str, new_key: str, history: list, source: str):
- """Build + register the branched agent in the parent's profile; the DEDICATED db handle is ours until
- ``_transfer_db_to_agent`` (released here on failure)."""
- parent_home = session.get("profile_home")
- parent_user_id = _session_auth_user_id(session)
- branch_db, branch_owns_db = _profile_session_db(parent_home) if parent_home else (None, False)
- try:
- with _profile_build_scope(parent_home):
- agent = _make_agent_in_context(new_sid, new_key, session_db=branch_db, platform_override=source,
- cwd_override=_session_cwd(session),
- context_cwd_is_launch_artifact=_context_cwd_is_launch_artifact(session),
- auth_user_id=parent_user_id)
- _init_session(new_sid, new_key, agent, list(history), cols=session.get("cols", 80),
- cwd=_session_cwd(session), session_db=branch_db, source=source, profile_home=parent_home,
- explicit_cwd=bool(session.get("explicit_cwd")))
- _transfer_db_to_agent(agent, branch_db)
- branch_owns_db = False
- if new_sid in _sessions:
- _sessions[new_sid]["active_session_lease"] = None # claimed lazily on the first turn
- _sessions[new_sid]["auth_user_id"] = parent_user_id
- # The parent's STORED key: the idempotent-hit reply for a retried
- # session.branch answers the same ``parent`` as the fresh path, and
- # later readers (lineage, retry) get the linkage from the runtime.
- _sessions[new_sid]["parent_session_id"] = session.get("session_key")
- return agent
- finally:
- if branch_owns_db and branch_db is not None:
- _release_db(branch_db)
-
-
-_BRANCH_COPY_FIELDS = (
- "reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items", "codex_message_items",
- # Timeline markers ride as role=user; untagged they become bare user turns after a restart, corrupting
- # the truncate ordinal address space.
- "display_kind", "display_metadata",
- # Branch copies are history, not new activity: keep the parent's timestamps.
- "timestamp")
-
-
-def _branch_source_history(db, session: dict, old_key: str) -> list:
- """Rows a branch copies: the persisted DISPLAY projection reconciled with live memory (live history is
- the MODEL projection — post-compaction summary + tail — the child would lose every archived turn)."""
- with session["history_lock"]:
- in_memory_history = [
- dict(msg) for msg in list(session.get("display_history_prefix") or []) + list(session.get("history", []))
- if isinstance(msg, dict)]
- history = None
- if callable(get_resume_conversations := getattr(db, "get_resume_conversations", None)):
- try:
- _, display_history = get_resume_conversations(old_key)
- history = _visible_branch_history(_reconcile_display_with_live(display_history, in_memory_history))
- except Exception:
- logger.debug("branch display projection read failed", exc_info=True)
- return history or _visible_branch_history(in_memory_history)
-
-
-def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = False) -> dict:
- # Idempotency (#65410, same registry as session.create): a client retrying a
- # branch whose first response was lost gets the SAME child, not a duplicate.
- idem_key = _str_param(params, "idempotency_key") or None
- if idem_key is not None:
- with _sessions_lock:
- now_gc = time.time()
- existing_sid, ts = _idempotency_keys.get(idem_key, (None, 0.0))
- if existing_sid is not None and existing_sid in _sessions:
- if now_gc - ts <= _IDEMPOTENCY_KEY_TTL:
- # Refresh the TTL so back-to-back retries don't age out mid-flight.
- _idempotency_keys[idem_key] = (existing_sid, now_gc)
- return _ok(rid, _branch_idempotent_hit(existing_sid, _sessions[existing_sid], omit_messages))
- _idempotency_keys.pop(idem_key, None)
- # Stale key (child closed) or first attempt: fall through to a fresh
- # branch, which re-registers the key below.
- # Write into the parent's profile-scoped state.db; the launch handle would orphan rows.
- with _session_db(session) as db:
- if db is None:
- return _db_unavailable_error(rid, code=5008)
- old_key = session["session_key"]
- history = _branch_source_history(db, session, old_key)
- if not history:
- return _err(rid, 4008, "nothing to branch — send a message first")
- if isinstance(count := params.get("count"), int) and count > 0:
- history = history[:count]
- new_key, new_sid, source = _new_session_key(), uuid.uuid4().hex[:8], _session_source(session)
- try:
- title = params.get("name", "") or _branch_title(db, old_key)
- home = session.get("profile_home")
- _persist_branch(db, new_key, old_key, title, history, source=source,
- cwd=None if _is_remote_launch_cwd(session) else _session_cwd(session),
- profile_name=profile_name_for_home(home) or _current_profile_name(),
- model=_session_default_route(session)[0], copy_fields=_BRANCH_COPY_FIELDS,
- title_source="user" if params.get("name") else "derived",
- user_id=_session_auth_user_id(session))
- except Exception as e:
- return _err(rid, 5008, f"branch failed: {e}")
- try:
- agent = _build_branch_agent(session, new_sid, new_key, history, source)
- except Exception as e:
- return _err(rid, 5000, f"agent init failed on branch: {e}")
- if idem_key is not None:
- with _sessions_lock:
- _idempotency_keys[idem_key] = (new_sid, time.time())
- # The fresh reply's title, so an idempotent hit answers the SAME one
- # without a DB round-trip.
- if new_sid in _sessions:
- _sessions[new_sid]["branch_title"] = title
- response = {"session_id": new_sid, "stored_session_id": new_key, "title": title, "parent": old_key,
- "message_count": len(history), "info": _session_info(agent, _sessions.get(new_sid))}
- if omit_messages:
- response["messages_omitted"] = True
- else:
- response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
- return _ok(rid, response)
-
-
-def _branch_idempotent_hit(existing_sid: str, session: dict, omit_messages: bool) -> dict:
- """The SAME result shape a fresh ``_branch_live`` returns for the existing child."""
- history = session.get("history") or []
- key = session.get("session_key") or ""
- response = {"session_id": existing_sid, "stored_session_id": key,
- "title": session.get("branch_title") or _branch_title_for(session),
- "parent": session.get("parent_session_id"), "message_count": len(history),
- "info": _fallback_session_info(session)}
- if omit_messages:
- response["messages_omitted"] = True
- else:
- response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
- return response
-
-
-def _branch_title_for(session: dict) -> str:
- """The child's persisted title from its stored row, best-effort."""
- with contextlib.suppress(Exception):
- with _session_db(session) as db:
- if db is not None:
- return db.get_session_title(session.get("session_key") or "") or ""
- return ""
@_session_method("session.branch", live=True)
@@ -2506,5 +2366,7 @@ def _(rid, params: dict) -> dict:
def register(server) -> None:
"""Publish this module's helpers onto ``server`` (rebound to its globals) and install handlers."""
bind_module(globals(), server, skip=("_",))
+ from . import methods_session_branch
+ methods_session_branch.register(server)
from . import methods_session_interrupt
methods_session_interrupt.register(server)
diff --git a/tui_gateway/methods_session_branch.py b/tui_gateway/methods_session_branch.py
new file mode 100644
index 00000000000..a7911b707c2
--- /dev/null
+++ b/tui_gateway/methods_session_branch.py
@@ -0,0 +1,160 @@
+"""Branch (session.branch / session.branch_whole) helpers (``methods_session`` split).
+
+Moved verbatim from ``tui_gateway/methods_session.py`` (file-line ratchet, #66663 CI repair):
+the bodies close over server.py globals through ``method_ctx.bind_module`` exactly as before —
+publication still runs from the parent's ``register()``.
+"""
+
+from .method_ctx import HandlerRegistry, bind_module
+
+_registry = HandlerRegistry()
+
+# ── session.branch ───────────────────────────────────────────────────
+def _visible_branch_history(messages) -> list:
+ """user/assistant rows with visible text, as FULL copies (reasoning + timeline-marker tags survive)."""
+ return [dict(message) for message in messages or []
+ if isinstance(message, dict) and message.get("role") in {"user", "assistant"}
+ and _coerce_message_text(message.get("content")).strip()]
+
+
+def _build_branch_agent(session: dict, new_sid: str, new_key: str, history: list, source: str):
+ """Build + register the branched agent in the parent's profile; the DEDICATED db handle is ours until
+ ``_transfer_db_to_agent`` (released here on failure)."""
+ parent_home = session.get("profile_home")
+ parent_user_id = _session_auth_user_id(session)
+ branch_db, branch_owns_db = _profile_session_db(parent_home) if parent_home else (None, False)
+ try:
+ with _profile_build_scope(parent_home):
+ agent = _make_agent_in_context(new_sid, new_key, session_db=branch_db, platform_override=source,
+ cwd_override=_session_cwd(session),
+ context_cwd_is_launch_artifact=_context_cwd_is_launch_artifact(session),
+ auth_user_id=parent_user_id)
+ _init_session(new_sid, new_key, agent, list(history), cols=session.get("cols", 80),
+ cwd=_session_cwd(session), session_db=branch_db, source=source, profile_home=parent_home,
+ explicit_cwd=bool(session.get("explicit_cwd")))
+ _transfer_db_to_agent(agent, branch_db)
+ branch_owns_db = False
+ if new_sid in _sessions:
+ _sessions[new_sid]["active_session_lease"] = None # claimed lazily on the first turn
+ _sessions[new_sid]["auth_user_id"] = parent_user_id
+ # The parent's STORED key: the idempotent-hit reply for a retried
+ # session.branch answers the same ``parent`` as the fresh path, and
+ # later readers (lineage, retry) get the linkage from the runtime.
+ _sessions[new_sid]["parent_session_id"] = session.get("session_key")
+ return agent
+ finally:
+ if branch_owns_db and branch_db is not None:
+ _release_db(branch_db)
+
+
+_BRANCH_COPY_FIELDS = (
+ "reasoning", "reasoning_content", "reasoning_details", "codex_reasoning_items", "codex_message_items",
+ # Timeline markers ride as role=user; untagged they become bare user turns after a restart, corrupting
+ # the truncate ordinal address space.
+ "display_kind", "display_metadata",
+ # Branch copies are history, not new activity: keep the parent's timestamps.
+ "timestamp")
+
+
+def _branch_source_history(db, session: dict, old_key: str) -> list:
+ """Rows a branch copies: the persisted DISPLAY projection reconciled with live memory (live history is
+ the MODEL projection — post-compaction summary + tail — the child would lose every archived turn)."""
+ with session["history_lock"]:
+ in_memory_history = [
+ dict(msg) for msg in list(session.get("display_history_prefix") or []) + list(session.get("history", []))
+ if isinstance(msg, dict)]
+ history = None
+ if callable(get_resume_conversations := getattr(db, "get_resume_conversations", None)):
+ try:
+ _, display_history = get_resume_conversations(old_key)
+ history = _visible_branch_history(_reconcile_display_with_live(display_history, in_memory_history))
+ except Exception:
+ logger.debug("branch display projection read failed", exc_info=True)
+ return history or _visible_branch_history(in_memory_history)
+
+
+def _branch_live(rid, params: dict, session: dict, *, omit_messages: bool = False) -> dict:
+ # Idempotency (#65410, same registry as session.create): a client retrying a
+ # branch whose first response was lost gets the SAME child, not a duplicate.
+ idem_key = _str_param(params, "idempotency_key") or None
+ if idem_key is not None:
+ with _sessions_lock:
+ now_gc = time.time()
+ existing_sid, ts = _idempotency_keys.get(idem_key, (None, 0.0))
+ if existing_sid is not None and existing_sid in _sessions:
+ if now_gc - ts <= _IDEMPOTENCY_KEY_TTL:
+ # Refresh the TTL so back-to-back retries don't age out mid-flight.
+ _idempotency_keys[idem_key] = (existing_sid, now_gc)
+ return _ok(rid, _branch_idempotent_hit(existing_sid, _sessions[existing_sid], omit_messages))
+ _idempotency_keys.pop(idem_key, None)
+ # Stale key (child closed) or first attempt: fall through to a fresh
+ # branch, which re-registers the key below.
+ # Write into the parent's profile-scoped state.db; the launch handle would orphan rows.
+ with _session_db(session) as db:
+ if db is None:
+ return _db_unavailable_error(rid, code=5008)
+ old_key = session["session_key"]
+ history = _branch_source_history(db, session, old_key)
+ if not history:
+ return _err(rid, 4008, "nothing to branch — send a message first")
+ if isinstance(count := params.get("count"), int) and count > 0:
+ history = history[:count]
+ new_key, new_sid, source = _new_session_key(), uuid.uuid4().hex[:8], _session_source(session)
+ try:
+ title = params.get("name", "") or _branch_title(db, old_key)
+ home = session.get("profile_home")
+ _persist_branch(db, new_key, old_key, title, history, source=source,
+ cwd=None if _is_remote_launch_cwd(session) else _session_cwd(session),
+ profile_name=profile_name_for_home(home) or _current_profile_name(),
+ model=_session_default_route(session)[0], copy_fields=_BRANCH_COPY_FIELDS,
+ title_source="user" if params.get("name") else "derived",
+ user_id=_session_auth_user_id(session))
+ except Exception as e:
+ return _err(rid, 5008, f"branch failed: {e}")
+ try:
+ agent = _build_branch_agent(session, new_sid, new_key, history, source)
+ except Exception as e:
+ return _err(rid, 5000, f"agent init failed on branch: {e}")
+ if idem_key is not None:
+ with _sessions_lock:
+ _idempotency_keys[idem_key] = (new_sid, time.time())
+ # The fresh reply's title, so an idempotent hit answers the SAME one
+ # without a DB round-trip.
+ if new_sid in _sessions:
+ _sessions[new_sid]["branch_title"] = title
+ response = {"session_id": new_sid, "stored_session_id": new_key, "title": title, "parent": old_key,
+ "message_count": len(history), "info": _session_info(agent, _sessions.get(new_sid))}
+ if omit_messages:
+ response["messages_omitted"] = True
+ else:
+ response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
+ return _ok(rid, response)
+
+
+def _branch_idempotent_hit(existing_sid: str, session: dict, omit_messages: bool) -> dict:
+ """The SAME result shape a fresh ``_branch_live`` returns for the existing child."""
+ history = session.get("history") or []
+ key = session.get("session_key") or ""
+ response = {"session_id": existing_sid, "stored_session_id": key,
+ "title": session.get("branch_title") or _branch_title_for(session),
+ "parent": session.get("parent_session_id"), "message_count": len(history),
+ "info": _fallback_session_info(session)}
+ if omit_messages:
+ response["messages_omitted"] = True
+ else:
+ response["messages"] = _history_to_messages(history, profile_home=session.get("profile_home"))
+ return response
+
+
+def _branch_title_for(session: dict) -> str:
+ """The child's persisted title from its stored row, best-effort."""
+ with contextlib.suppress(Exception):
+ with _session_db(session) as db:
+ if db is not None:
+ return db.get_session_title(session.get("session_key") or "") or ""
+ return ""
+
+
+def register(server) -> None:
+ """Publish this module's helpers onto ``server`` (rebound to its globals)."""
+ bind_module(globals(), server, skip=("_",))