Skip to content

The agent that grows with you

fix(cli): list, browse and stats read gateway rows by created surface

David Dudok de Wit1b3ad1f79b0f
diff --git a/gateway/session_a2a.py b/gateway/session_a2a.py
index 32cd10411db..9c55f19f621 100644
--- a/gateway/session_a2a.py
+++ b/gateway/session_a2a.py
@@ -73,7 +73,8 @@ def storage_source(db, source, session_id, fallback):
if 'legacy_session_id' in receipt:
root = db.get_session(receipt['legacy_session_id'])
return (root or {}).get('source') or label
- return fallback if label in {'cli', 'tui', 'gui', 'acp'} else label
+ from gateway.session_policy import STORED_AS_LOCAL
+ return fallback if label in STORED_AS_LOCAL else label
async def forward(connection, params):
diff --git a/hermes_cli/gateway_session_store.py b/hermes_cli/gateway_session_store.py
index 33911f3b75f..db36771e319 100644
--- a/hermes_cli/gateway_session_store.py
+++ b/hermes_cli/gateway_session_store.py
@@ -382,9 +382,9 @@ class GatewaySessionStore:
}
-# Interactive surfaces whose gateway rows are labelled ``local`` (``created_source`` keeps the surface;
-# gateway/session_a2a.storage_source). Producer labels (oneshot, tool, kanban, ...) are stored as is.
-_LOCAL_LABELLED = frozenset({"cli", "tui", "gui"})
+# Built from session_policy.SURFACES and STORED_AS_LOCAL. gui and desktop are one
+# conversation (in-process agent is desktop; the managed worker creates with gui).
+# acp is stored local too. tool and oneshot are not cli aliases.
class SurfaceLabelReader:
@@ -409,14 +409,35 @@ class SurfaceLabelReader:
self._has_column = any(row[1] == "created_source" for row in rows)
return self._has_column
- def _labelled(self, requested, limit, offset, call):
+ def _groups(self):
+ from gateway.session_policy import surface_groups
+ return surface_groups()
+
+ def _expand(self, requested):
+ """``(live source labels, created_source labels)`` or None for a raw source filter.
+
+ Live labels include the other name of a gui/desktop pair, so a row that has not been
+ peer-refreshed (``source='gui'``) still matches ``--source desktop``.
+ """
wanted = {requested} if isinstance(requested, str) else set(requested or ())
- surfaces = wanted & _LOCAL_LABELLED
+ created = set()
+ live = set(wanted)
+ for name, group in self._groups().items():
+ if name in wanted:
+ live |= group
+ created |= group
+ if not created or not self._has_created_source_column():
+ return None
+ return sorted(live | {"local"}), sorted(created)
+
+ def _labelled(self, requested, limit, offset, call):
+ expanded = self._expand(requested)
# No column (and so no gateway ``local`` rows yet): naming it would raise, and the caller
# swallows that into an empty page.
- if not surfaces or not self._has_created_source_column():
+ if expanded is None:
return call(requested, limit, offset, None)
- return call(sorted(wanted | {"local"}), limit, offset, sorted(surfaces))
+ live, surfaces = expanded
+ return call(live, limit, offset, surfaces)
def search_sessions(self, source=None, limit=20, offset=0, **kw):
return self._labelled(
@@ -433,6 +454,16 @@ class SurfaceLabelReader:
lambda src, lim, off, surfaces: self._wrapped.list_sessions_rich(
sources=src, limit=lim, offset=off, local_created_sources=surfaces, **kw))
+ def session_count(self, source=None, sources=None, **kw):
+ requested = sources if sources else ([source] if source else None)
+ if not requested:
+ return self._wrapped.session_count(source=source, sources=sources, **kw)
+ expanded = self._expand(requested)
+ if expanded is None:
+ return self._wrapped.session_count(source=source, sources=sources, **kw)
+ live, surfaces = expanded
+ return self._wrapped.session_count(sources=live, local_created_sources=surfaces, **kw)
+
_CANONICAL_LOCAL_ID = re.compile(r"^local-([0-9a-f]{8})[0-9a-f]{56}$")
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 59aa12953b5..bb321c2ffe9 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -278,12 +278,18 @@ def _default_exclude(args):
return None if getattr(args, "source", None) else ["tool"]
+def _surface_reader(db):
+ """``--source cli`` also matches a gateway row stored as ``local`` with that created surface."""
+ from hermes_cli.gateway_session_store import SurfaceLabelReader
+ return SurfaceLabelReader(db)
+
+
def _cmd_list(db, args):
from hermes_state_sessions import workspace_key as _ws_key
# LIMIT lives in the query, so probe one row past the cap: it is the only way to know the
# page was cut without a second COUNT query (``--limit 0`` is ``LIMIT 0``: no rows, no probe).
limit = args.limit
- sessions = db.list_sessions_rich(
+ sessions = _surface_reader(db).list_sessions_rich(
source=args.source, exclude_sources=_default_exclude(args), limit=limit + 1 if limit > 0 else limit,
)
truncated = limit > 0 and len(sessions) > limit
@@ -918,7 +924,7 @@ def _cmd_retitle_skills(db, args):
def _cmd_browse(db, args):
limit = getattr(args, "limit", 500) or 500
- sessions = db.list_sessions_rich(
+ sessions = _surface_reader(db).list_sessions_rich(
source=getattr(args, "source", None), exclude_sources=_default_exclude(args), limit=limit
)
if not sessions:
@@ -1220,9 +1226,10 @@ def _cmd_repair_prompts(db, args):
def _cmd_stats(db, args):
+ reader = _surface_reader(db)
print(f"Total sessions: {db.session_count()}\nTotal messages: {db.message_count()}")
for src in ("cli", "telegram", "discord", "whatsapp", "slack"):
- if (c := db.session_count(source=src)) > 0:
+ if (c := reader.session_count(source=src)) > 0:
print(f" {src}: {c} sessions")
if db.db_path.exists():
print(f"Database size: {_size_mb(db.db_path):.1f} MB")
diff --git a/hermes_state_sessions.py b/hermes_state_sessions.py
index d3f28a7c0c3..044640f59ee 100644
--- a/hermes_state_sessions.py
+++ b/hermes_state_sessions.py
@@ -1573,12 +1573,14 @@ class SessionSessionsMixin:
self, source: str | None = None, sources: list[str] | None = None, cwd_prefix: str | None = None,
min_message_count: int = 0, include_archived: bool = False, archived_only: bool = False,
exclude_children: bool = False, exclude_sources: list[str] | None = None, include_subagents: bool = False,
+ local_created_sources: Sequence[str] | None = None,
) -> int:
"""Count sessions with list_sessions_rich's filters so a paired "load more" total matches."""
where_clauses, params = _session_filter_where(
exclude_children=exclude_children, source=source, sources=sources,
exclude_sources=exclude_sources, cwd_prefix=cwd_prefix, min_message_count=min_message_count,
archived_only=archived_only, include_archived=include_archived, include_subagents=include_subagents,
+ local_created_sources=local_created_sources,
)
if exclude_children:
from hermes_state_local import exclude_superseded_segments
diff --git a/tests/gateway/test_resume_latest_local_cli.py b/tests/gateway/test_resume_latest_local_cli.py
index b8801b19b1a..67cd166d457 100644
--- a/tests/gateway/test_resume_latest_local_cli.py
+++ b/tests/gateway/test_resume_latest_local_cli.py
@@ -223,3 +223,32 @@ async def test_worker_create_after_peer_refresh_still_resumes(tmp_path, monkeypa
finally:
await owner.close()
store.close_all_db_handles()
+
+
+def _listed(db, source, capsys):
+ from argparse import Namespace
+ from hermes_cli.sessions_cmd import _cmd_list
+ _cmd_list(db, Namespace(limit=20, source=source, workspace=None))
+ return capsys.readouterr().out
+
+
[email protected](('surface', 'labels'), [('gui', ('gui', 'desktop')), ('acp', ('acp',))])
+async def test_gui_and_acp_list_under_the_policy_label_and_the_agent_surface(
+ tmp_path, monkeypatch, capsys, surface, labels):
+ """session.create stamps the agent surface (gui is desktop). --source accepts
+ either name, before the peer refresh and after the row is stored as local."""
+ store, authority, owner = _owner(tmp_path / 'home', monkeypatch)
+ try:
+ created = await _call(owner, 'session.create', request_id=surface, source=surface,
+ cwd=str(tmp_path), toolsets=[], model='m')
+ sid = created['session_id']
+ for label in labels:
+ assert sid in _listed(authority.db, label, capsys), (surface, label, 'before peer')
+ live = authority.sessions[sid]
+ store._record_gateway_session_peer(sid, live.route, live.source)
+ for label in labels:
+ assert sid in _listed(authority.db, label, capsys), (surface, label, 'after peer')
+ finally:
+ await owner.close()
+ store.close_all_db_handles()
diff --git a/tests/hermes_cli/test_sessions_source_local.py b/tests/hermes_cli/test_sessions_source_local.py
new file mode 100644
index 00000000000..ec3f86fbe02
--- /dev/null
+++ b/tests/hermes_cli/test_sessions_source_local.py
@@ -0,0 +1,85 @@
+"""``hermes sessions list|browse|stats --source cli`` must see gateway rows stored as ``local``."""
+from argparse import Namespace
+
+from hermes_state import SessionDB
+
+
+def test_list_and_browse_source_cli_include_the_gateway_row(tmp_path, capsys, monkeypatch):
+ from hermes_cli.sessions_cmd import _cmd_browse, _cmd_list
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("cli-session", source="local")
+ db.create_session("desk-session", source="local")
+ with db._lock:
+ db._conn.executemany(
+ "UPDATE sessions SET created_source=?, started_at=? WHERE id=?",
+ [("cli", 1, "cli-session"), ("desktop", 2, "desk-session")],
+ )
+ db._conn.commit()
+
+ _cmd_list(db, Namespace(limit=20, source="cli", workspace=None))
+ listed = capsys.readouterr().out
+ assert "cli-session" in listed
+ assert "desk-session" not in listed
+ assert "No sessions found." not in listed
+
+ offered = {}
+
+ def picker(sessions, session_db=None):
+ offered["ids"] = [row["id"] for row in sessions]
+
+ monkeypatch.setattr("hermes_cli.sessions_cmd._session_browse_picker", picker)
+ _cmd_browse(db, Namespace(limit=20, source="cli"))
+ assert offered["ids"] == ["cli-session"]
+ assert "No sessions found." not in capsys.readouterr().out
+
+
+def test_stats_counts_cli_segments_while_list_shows_one_conversation(tmp_path, capsys):
+ """Stats counts every cli segment. List shows the conversation once, as its tip."""
+ from hermes_cli.sessions_cmd import _cmd_list, _cmd_stats
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("segment-root", source="local")
+ with db._lock:
+ db._conn.execute("UPDATE sessions SET created_source=? WHERE id=?", ("cli", "segment-root"))
+ db._conn.commit()
+ db.append_message("segment-root", role="user", content="hi")
+ db.publish_compression_child(
+ parent_session_id="segment-root", child_session_id="segment-tip", source="local",
+ messages=[{"role": "user", "content": "hi"}], require_compression_lease=False)
+ _cmd_list(db, Namespace(limit=20, source="cli", workspace=None))
+ listed = capsys.readouterr().out
+ assert "segment-tip" in listed
+ assert "segment-root" not in listed
+ _cmd_stats(db, Namespace())
+ assert "cli: 2 sessions" in capsys.readouterr().out
+
+
+def test_reader_session_count_includes_gateway_rows_and_a_pre_column_store(tmp_path):
+ """session_count through the reader matches a local/cli row, and a read-only
+ store from before the column still counts its source=cli rows without migrating."""
+ from hermes_cli.gateway_session_store import SurfaceLabelReader
+
+ db = SessionDB(db_path=tmp_path / "state.db")
+ db.create_session("gateway-cli", source="local")
+ with db._lock:
+ db._conn.execute("UPDATE sessions SET created_source=? WHERE id=?", ("cli", "gateway-cli"))
+ db._conn.commit()
+ assert SurfaceLabelReader(db).session_count(source="cli") == 1
+ db.close()
+
+ path = tmp_path / "old.db"
+ writer = SessionDB(db_path=path)
+ writer.create_session("legacy-cli", source="cli")
+ with writer._lock:
+ writer._conn.execute("DROP INDEX IF EXISTS idx_sessions_local_created_started")
+ writer._conn.execute("ALTER TABLE sessions DROP COLUMN created_source")
+ writer._conn.commit()
+ writer.close()
+ ro = SessionDB(db_path=path, read_only=True)
+ try:
+ assert SurfaceLabelReader(ro).session_count(source="cli") == 1
+ columns = {row[1] for row in ro._conn.execute("PRAGMA table_info(sessions)")}
+ assert "created_source" not in columns
+ finally:
+ ro.close()