hermes_state_session_list.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. """Session-list page projection for ``SessionDB.list_sessions_rich``."""
  2. from typing import Any
  3. def project_compression_tips(db, sessions: list[dict[str, Any]], compact_rows: bool) -> list[dict[str, Any]]:
  4. """Replace each compression root's surfaced fields with its live tip's (root ``started_at`` kept
  5. for stable ordering), one batched query. ``_lineage_ids`` carries every chain id (a tile may
  6. hold a MIDDLE segment's id)."""
  7. chain_by_root: dict[str, list[str]] = {} # only roots whose tip differs from themselves
  8. for s in sessions:
  9. if s.get("end_reason") == "compression":
  10. chain = db.get_compression_chain(s["id"])
  11. if chain and chain[-1] != s["id"]:
  12. chain_by_root[s["id"]] = chain
  13. tip_rows = (
  14. db._get_session_rich_rows_batch(
  15. {chain[-1] for chain in chain_by_root.values()}, compact_rows=compact_rows,
  16. ) if chain_by_root else {}
  17. )
  18. projected = []
  19. for s in sessions:
  20. chain = chain_by_root.get(s["id"])
  21. tip_row = tip_rows.get(chain[-1]) if chain else None
  22. if not tip_row:
  23. projected.append(s)
  24. continue
  25. merged = dict(s)
  26. for key in (
  27. "id", "ended_at", "end_reason", "message_count", "tool_call_count", "title", "last_active",
  28. "preview", "model", "system_prompt", "cwd", "git_branch", "git_repo_root",
  29. ):
  30. if key in tip_row:
  31. merged[key] = tip_row[key]
  32. if merged.get("title") is None:
  33. # The title is carried root->tip AFTER the publish transaction; a rotation cut off in
  34. # between leaves it on the ended root, and exact-title lookups (`hermes peer dm` ->
  35. # canonical "Bot Chat") must still see the lineage under its name (#106165).
  36. merged["title"] = s.get("title")
  37. merged["_lineage_root_id"] = s["id"]
  38. merged["_lineage_ids"] = chain
  39. # #121148: the projected row IS an automatic continuation, not a fresh conversation and
  40. # not a user branch. The server already classifies the edge (_COMPRESSION_CHILD_SQL) but
  41. # only ever used it to hide rows — surface the kind so clients can label the provenance
  42. # instead of rendering a sealed-and-rotated chat as a brand-new session.
  43. merged["continuation_kind"] = "compression"
  44. projected.append(merged)
  45. return projected