The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: session picker lifecycle status + delete
Teknium933ef6947055
diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex cea74357d5d..5ea7c0dcec9 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -1156,21 +1156,75 @@ def _confirm_startup_expensive_model_override(args) -> None:raise SystemExit(1)-def _session_browse_picker(sessions: list) -> Optional[str]:+def _session_status_tag(status: Optional[str]) -> str:+ """Short fixed-width tag for a session lifecycle status."""+ return {+ "complete": "done",+ "interrupted": "intr",+ "error": "err",+ "empty": "empty",+ }.get(status or "", "-")+++def _annotate_session_statuses(sessions: list, session_db) -> None:+ """Attach a ``_status`` key to each session row (best-effort, cheap).++ Uses ``SessionDB.session_lifecycle_statuses`` — one indexed last-message+ lookup per listed session, never a transcript scan. On any failure the+ rows simply stay untagged and the picker renders '-' for status.+ """+ if session_db is None or not sessions:+ return+ try:+ statuses = session_db.session_lifecycle_statuses(+ [s.get("id") for s in sessions]+ )+ except Exception:+ return+ for s in sessions:+ s["_status"] = statuses.get(s.get("id"), "")+++def _session_browse_picker(sessions: list, session_db=None) -> Optional[str]:"""Interactive curses-based session browser with live search filtering.+ Shows lifecycle status (done / intr / err / empty) and message count per+ session when *session_db* is provided. With a live *session_db*, pressing+ ``d`` on a row (while the search filter is empty) prompts y/n and deletes+ the session via ``SessionDB.delete_session``.+Returns the selected session ID, or None if cancelled."""if not sessions:print("No sessions found.")return None+ _annotate_session_statuses(sessions, session_db)++ def _delete_session(session_id: str) -> bool:+ if session_db is None:+ return False+ try:+ sessions_dir = get_hermes_home() / "sessions"+ except Exception:+ sessions_dir = None+ try:+ return bool(+ session_db.delete_session(session_id, sessions_dir=sessions_dir)+ )+ except Exception:+ return False+# Try curses-based picker firsttry:import cursesresult_holder = [None]+ # Layout: [arrow 3] [title/preview flexible] [status 5] [msgs 5]+ # [active 12] [src 6] [id 18]+ _FIXED_COLS = 3 + 5 + 2 + 5 + 2 + 12 + 6 + 18 + 6+def _format_row(s, max_x):"""Format a session row for display."""title = (s.get("title") or "").strip()@@ -1178,11 +1232,11 @@ def _session_browse_picker(sessions: list) -> Optional[str]:source = s.get("source", "")[:6]last_active = _relative_time(s.get("last_active"))sid = s["id"][:18]+ status = _session_status_tag(s.get("_status"))+ msgs = s.get("message_count")+ msgs_str = str(msgs) if isinstance(msgs, int) else "-"- # Adaptive column widths based on terminal width- # Layout: [arrow 3] [title/preview flexible] [active 12] [src 6] [id 18]- fixed_cols = 3 + 12 + 6 + 18 + 6 # arrow + active + src + id + padding- name_width = max(20, max_x - fixed_cols)+ name_width = max(20, max_x - _FIXED_COLS)if title:name = title[:name_width]@@ -1191,7 +1245,10 @@ def _session_browse_picker(sessions: list) -> Optional[str]:else:name = sid- return f"{name:<{name_width}} {last_active:<10} {source:<5} {sid}"+ return (+ f"{name:<{name_width}} {status:<5} {msgs_str:>5} "+ f"{last_active:<10} {source:<5} {sid}"+ )def _match(s, query):"""Check if a session matches the search query (case-insensitive)."""@@ -1212,12 +1269,25 @@ def _session_browse_picker(sessions: list) -> Optional[str]:curses.init_pair(2, curses.COLOR_YELLOW, -1) # headercurses.init_pair(3, curses.COLOR_CYAN, -1) # searchcurses.init_pair(4, 8 if curses.COLORS > 8 else curses.COLOR_WHITE, -1) # dim+ curses.init_pair(5, curses.COLOR_RED, -1) # error/deletecursor = 0scroll_offset = 0search_text = ""+ confirm_delete = None # session dict pending y/n confirmation+ flash = "" # one-frame notice (e.g. "deleted <title>")filtered = list(sessions)+ def _status_attr(status):+ if not curses.has_colors():+ return curses.A_NORMAL+ return {+ "complete": curses.color_pair(1),+ "interrupted": curses.color_pair(2),+ "error": curses.color_pair(5),+ "empty": curses.color_pair(4),+ }.get(status or "", curses.A_NORMAL)+while True:stdscr.clear()max_y, max_x = stdscr.getmaxyx()@@ -1238,7 +1308,10 @@ def _session_browse_picker(sessions: list) -> Optional[str]:if curses.has_colors():header_attr |= curses.color_pair(3)else:- header = " Browse sessions — ↑↓ navigate Enter select Type to filter Esc quit"+ header = (+ " Browse sessions — ↑↓ navigate Enter select"+ " Type to filter Esc quit"+ )header_attr = curses.A_BOLDif curses.has_colors():header_attr |= curses.color_pair(2)@@ -1248,9 +1321,11 @@ def _session_browse_picker(sessions: list) -> Optional[str]:pass# Column header line- fixed_cols = 3 + 12 + 6 + 18 + 6- name_width = max(20, max_x - fixed_cols)- col_header = f" {'Title / Preview':<{name_width}} {'Active':<10} {'Src':<5} {'ID'}"+ name_width = max(20, max_x - _FIXED_COLS)+ col_header = (+ f" {'Title / Preview':<{name_width}} {'Stat':<5} "+ f"{'Msgs':>5} {'Active':<10} {'Src':<5} {'ID'}"+ )try:dim_attr = (curses.color_pair(4) if curses.has_colors() else curses.A_DIM@@ -1298,31 +1373,76 @@ def _session_browse_picker(sessions: list) -> Optional[str]:attr |= curses.color_pair(1)try:stdscr.addnstr(y, 0, row, max_x - 1, attr)+ if i != cursor:+ # Recolor the status tag column in place.+ status = s.get("_status")+ tag = _session_status_tag(status)+ tag_x = 3 + max(20, (max_x - 3) - _FIXED_COLS) + 2+ if tag_x + 5 < max_x - 1:+ stdscr.addnstr(+ y, tag_x, f"{tag:<5}", 5, _status_attr(status)+ )except curses.error:pass# Footerfooter_y = max_y - 1- if filtered:- footer = f" {cursor + 1}/{len(filtered)} sessions"- if len(filtered) < len(sessions):- footer += f" (filtered from {len(sessions)})"+ footer_attr = (+ curses.color_pair(4) if curses.has_colors() else curses.A_DIM+ )+ if confirm_delete is not None:+ label = (+ (confirm_delete.get("title") or "").strip()+ or (confirm_delete.get("preview") or "").strip()+ or confirm_delete["id"]+ )+ if len(label) > 40:+ label = label[:37] + "..."+ footer = f" Delete session '{label}'? [y/N]"+ footer_attr = curses.A_BOLD+ if curses.has_colors():+ footer_attr |= curses.color_pair(5)+ elif flash:+ footer = f" {flash}"+ flash = ""else:- footer = f" 0/{len(sessions)} sessions"+ if filtered:+ footer = f" {cursor + 1}/{len(filtered)} sessions"+ if len(filtered) < len(sessions):+ footer += f" (filtered from {len(sessions)})"+ else:+ footer = f" 0/{len(sessions)} sessions"+ if session_db is not None and not search_text:+ footer += " d delete"try:- stdscr.addnstr(- footer_y,- 0,- footer,- max_x - 1,- curses.color_pair(4) if curses.has_colors() else curses.A_DIM,- )+ stdscr.addnstr(footer_y, 0, footer, max_x - 1, footer_attr)except curses.error:passstdscr.refresh()key = stdscr.getch()+ if confirm_delete is not None:+ # y/n confirmation mode — only an explicit 'y' deletes.+ target = confirm_delete+ confirm_delete = None+ if key in {ord("y"), ord("Y")}:+ if _delete_session(target["id"]):+ sessions[:] = [+ s for s in sessions if s["id"] != target["id"]+ ]+ filtered = (+ [s for s in sessions if _match(s, search_text)]+ if search_text+ else list(sessions)+ )+ flash = "Deleted."+ if not sessions:+ return+ else:+ flash = "Delete failed."+ continue+if key in {curses.KEY_UP,}:if filtered:cursor = (cursor - 1) % len(filtered)@@ -1354,6 +1474,15 @@ def _session_browse_picker(sessions: list) -> Optional[str]:scroll_offset = 0elif key == ord("q") and not search_text:return+ elif (+ key == ord("d")+ and not search_text+ and session_db is not None+ and filtered+ ):+ # 'd' only acts as delete when the filter is empty —+ # while a search is active it types into the query below.+ confirm_delete = filtered[cursor]elif 32 <= key <= 126:# Printable character → add to search filtersearch_text += chr(key)@@ -1367,7 +1496,8 @@ def _session_browse_picker(sessions: list) -> Optional[str]:except Exception:pass- # Fallback: numbered list (Windows without curses, etc.)+ # Fallback: numbered list (Windows without curses, etc.). Shows the same+ # status/message-count columns but has no delete support.print("\n Browse sessions (enter number to resume, q to cancel)\n")for i, s in enumerate(sessions):title = (s.get("title") or "").strip()@@ -1377,7 +1507,13 @@ def _session_browse_picker(sessions: list) -> Optional[str]:label = label[:47] + "..."last_active = _relative_time(s.get("last_active"))src = s.get("source", "")[:6]- print(f" {i + 1:>3}. {label:<50} {last_active:<10} {src}")+ status = _session_status_tag(s.get("_status"))+ msgs = s.get("message_count")+ msgs_str = str(msgs) if isinstance(msgs, int) else "-"+ print(+ f" {i + 1:>3}. {label:<50} {status:<5} {msgs_str:>5} "+ f"{last_active:<10} {src}"+ )while True:try:diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.pyindex 25a4d9ec3cd..2cb35793d51 100644--- a/hermes_cli/sessions_cmd.py+++ b/hermes_cli/sessions_cmd.py@@ -39,8 +39,8 @@ def _relative_time(ts):return _m()._relative_time(ts)-def _session_browse_picker(sessions):- return _m()._session_browse_picker(sessions)+def _session_browse_picker(sessions, session_db=None):+ return _m()._session_browse_picker(sessions, session_db=session_db)def _size_delta_label(saved_mb):@@ -1076,12 +1076,17 @@ def cmd_sessions(args, sessions_parser=None):sessions = db.list_sessions_rich(source=source, exclude_sources=_browse_exclude, limit=limit)- db.close()if not sessions:+ db.close()print("No sessions found.")return- selected_id = _session_browse_picker(sessions)+ # Keep the DB open: the picker uses it for lifecycle status tags and+ # the 'd' delete-with-confirmation action.+ try:+ selected_id = _session_browse_picker(sessions, session_db=db)+ finally:+ db.close()if not selected_id:print("Cancelled.")returndiff --git a/hermes_state.py b/hermes_state.pyindex d229bfcb1b9..1f3c92d681b 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -3021,6 +3021,48 @@ def count_db_holders(db_path: Path) -> Optional[int]:return None+# Lifecycle statuses surfaced by session pickers. Classification looks ONLY at+# a session's final message row — role, whether it carries tool_calls, and its+# finish_reason — so it stays O(1) per session (see+# SessionDB.session_lifecycle_statuses).+SESSION_STATUS_COMPLETE = "complete"+SESSION_STATUS_INTERRUPTED = "interrupted"+SESSION_STATUS_ERROR = "error"+SESSION_STATUS_EMPTY = "empty"++# finish_reason values that mark the turn as having ended in a provider or+# agent error (vs. a normal 'stop'/'length'/'tool_calls' completion).+_ERROR_FINISH_REASONS = frozenset({"error", "agent_error", "content_filter"})+++def classify_session_status(+ role: Optional[str],+ has_tool_calls: bool,+ finish_reason: Optional[str],+) -> str:+ """Classify a session's lifecycle from the shape of its final message.++ - assistant with a normal finish → ``complete``+ - assistant that still has pending tool_calls (no tool result row ever+ followed, or it would be the last row instead) → ``interrupted``+ - user or tool as the last row → ``interrupted`` (the agent never got to+ answer / never consumed the tool result)+ - an error finish_reason on the last row → ``error``+ - anything unrecognized → ``complete`` (benign default; pickers must not+ alarm on unknown shapes)+ """+ if (finish_reason or "").strip().lower() in _ERROR_FINISH_REASONS:+ return SESSION_STATUS_ERROR+ r = (role or "").strip().lower()+ if r == "assistant":+ # The last row being an assistant message WITH tool_calls means the+ # matching tool result never landed — an interrupted tool turn.+ return SESSION_STATUS_INTERRUPTED if has_tool_calls else SESSION_STATUS_COMPLETE+ if r in {"user", "tool"}:+ return SESSION_STATUS_INTERRUPTED+ return SESSION_STATUS_COMPLETE++class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin):"""SQLite-backed session storage with FTS5 search.@@ -8773,6 +8815,53 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)return sessions+ def session_lifecycle_statuses(+ self, session_ids: List[str]+ ) -> Dict[str, str]:+ """Classify each session's lifecycle state from its LAST message row.++ Returns ``{session_id: status}`` where status is one of:++ - ``'complete'`` — last message is a normal assistant reply+ - ``'interrupted'`` — last message is a user turn, a pending assistant+ tool call (no tool result followed), or a tool result the assistant+ never responded to+ - ``'error'`` — last message carries an error finish_reason+ - ``'empty'`` — session has no messages++ Cost-bounded by design: one query that resolves each listed session's+ newest message id via ``MAX(id)`` (an index seek on+ ``idx_messages_session_id``) and joins back for that single row's+ role/tool_calls/finish_reason. Never scans transcripts, so it stays+ cheap on large databases regardless of total message volume.+ """+ ids = [sid for sid in (session_ids or []) if sid]+ if not ids:+ return {}+ statuses: Dict[str, str] = {sid: "empty" for sid in ids}+ placeholders = ",".join("?" for _ in ids)+ query = f"""+ SELECT m.session_id, m.role,+ m.tool_calls IS NOT NULL AS has_tool_calls,+ m.finish_reason+ FROM messages m+ JOIN (+ SELECT session_id, MAX(id) AS max_id+ FROM messages+ WHERE session_id IN ({placeholders})+ GROUP BY session_id+ ) latest ON m.id = latest.max_id+ """+ with self._read_ctx() as conn:+ rows = conn.execute(query, ids).fetchall()+ for row in rows:+ statuses[row["session_id"]] = classify_session_status(+ role=row["role"],+ has_tool_calls=bool(row["has_tool_calls"]),+ finish_reason=row["finish_reason"],+ )+ return statuses+# =========================================================================# Message storage# =========================================================================diff --git a/tests/hermes_state/test_session_lifecycle_status.py b/tests/hermes_state/test_session_lifecycle_status.pynew file mode 100644index 00000000000..9223dfa3518--- /dev/null+++ b/tests/hermes_state/test_session_lifecycle_status.py@@ -0,0 +1,188 @@+"""Lifecycle status classification for session pickers.++Covers ``classify_session_status`` (pure last-message shape → status) and+``SessionDB.session_lifecycle_statuses`` (batched last-message lookup), plus+the delete wiring the picker's 'd' key relies on.+"""++import pytest++from hermes_state import (+ SESSION_STATUS_COMPLETE,+ SESSION_STATUS_EMPTY,+ SESSION_STATUS_ERROR,+ SESSION_STATUS_INTERRUPTED,+ SessionDB,+ classify_session_status,+)+++def db(tmp_path):+ database = SessionDB(tmp_path / "state.db")+ try:+ yield database+ finally:+ database.close()+++# ---------------------------------------------------------------------------+# Pure classifier+# ---------------------------------------------------------------------------++ "role,has_tool_calls,finish_reason,expected",+ [+ ("assistant", False, "stop", SESSION_STATUS_COMPLETE),+ ("assistant", False, None, SESSION_STATUS_COMPLETE),+ ("assistant", False, "length", SESSION_STATUS_COMPLETE),+ ("assistant", True, "tool_calls", SESSION_STATUS_INTERRUPTED),+ ("user", False, None, SESSION_STATUS_INTERRUPTED),+ ("tool", False, None, SESSION_STATUS_INTERRUPTED),+ ("assistant", False, "error", SESSION_STATUS_ERROR),+ ("assistant", True, "error", SESSION_STATUS_ERROR),+ ("user", False, "agent_error", SESSION_STATUS_ERROR),+ ("system", False, None, SESSION_STATUS_COMPLETE),+ (None, False, None, SESSION_STATUS_COMPLETE),+ ],+)+def test_classify_session_status(role, has_tool_calls, finish_reason, expected):+ assert classify_session_status(role, has_tool_calls, finish_reason) == expected+++# ---------------------------------------------------------------------------+# DB-backed batch classification+# ---------------------------------------------------------------------------++def test_session_lifecycle_statuses_shapes(db):+ # complete: normal user → assistant exchange+ db.create_session("s_complete", source="cli")+ db.append_message("s_complete", "user", "hi")+ db.append_message("s_complete", "assistant", "hello", finish_reason="stop")++ # interrupted: user asked, no reply landed+ db.create_session("s_user_tail", source="cli")+ db.append_message("s_user_tail", "user", "are you there?")++ # interrupted: assistant fired tool calls, no tool result followed+ db.create_session("s_pending_tool", source="cli")+ db.append_message("s_pending_tool", "user", "run it")+ db.append_message(+ "s_pending_tool",+ "assistant",+ None,+ tool_calls=[{"id": "c1", "function": {"name": "terminal", "arguments": "{}"}}],+ finish_reason="tool_calls",+ )++ # complete: full tool round-trip then final assistant reply+ db.create_session("s_tool_roundtrip", source="cli")+ db.append_message("s_tool_roundtrip", "user", "run it")+ db.append_message(+ "s_tool_roundtrip",+ "assistant",+ None,+ tool_calls=[{"id": "c1", "function": {"name": "terminal", "arguments": "{}"}}],+ finish_reason="tool_calls",+ )+ db.append_message("s_tool_roundtrip", "tool", "ok", tool_call_id="c1")+ db.append_message("s_tool_roundtrip", "assistant", "done", finish_reason="stop")++ # interrupted: tool result present but assistant never consumed it+ db.create_session("s_tool_tail", source="cli")+ db.append_message("s_tool_tail", "user", "run it")+ db.append_message(+ "s_tool_tail",+ "assistant",+ None,+ tool_calls=[{"id": "c2", "function": {"name": "terminal", "arguments": "{}"}}],+ finish_reason="tool_calls",+ )+ db.append_message("s_tool_tail", "tool", "ok", tool_call_id="c2")++ # error: last message carries an error finish_reason+ db.create_session("s_error", source="cli")+ db.append_message("s_error", "user", "hi")+ db.append_message("s_error", "assistant", "boom", finish_reason="error")++ # empty: session row exists, zero messages+ db.create_session("s_empty", source="cli")++ statuses = db.session_lifecycle_statuses(+ [+ "s_complete",+ "s_user_tail",+ "s_pending_tool",+ "s_tool_roundtrip",+ "s_tool_tail",+ "s_error",+ "s_empty",+ ]+ )+ assert statuses == {+ "s_complete": SESSION_STATUS_COMPLETE,+ "s_user_tail": SESSION_STATUS_INTERRUPTED,+ "s_pending_tool": SESSION_STATUS_INTERRUPTED,+ "s_tool_roundtrip": SESSION_STATUS_COMPLETE,+ "s_tool_tail": SESSION_STATUS_INTERRUPTED,+ "s_error": SESSION_STATUS_ERROR,+ "s_empty": SESSION_STATUS_EMPTY,+ }+++def test_session_lifecycle_statuses_empty_input(db):+ assert db.session_lifecycle_statuses([]) == {}+ assert db.session_lifecycle_statuses([None, ""]) == {}+++def test_session_lifecycle_statuses_unknown_id(db):+ # Unknown ids classify as 'empty' (no messages), never raise.+ assert db.session_lifecycle_statuses(["nope"]) == {+ "nope": SESSION_STATUS_EMPTY+ }+++# ---------------------------------------------------------------------------+# Picker helpers (status annotation + delete wiring)+# ---------------------------------------------------------------------------++def test_annotate_session_statuses(db):+ from hermes_cli.main import _annotate_session_statuses, _session_status_tag++ db.create_session("s1", source="cli")+ db.append_message("s1", "user", "hi")+ db.append_message("s1", "assistant", "hello", finish_reason="stop")+ db.create_session("s2", source="cli")+ db.append_message("s2", "user", "hi")++ rows = [{"id": "s1"}, {"id": "s2"}]+ _annotate_session_statuses(rows, db)+ assert rows[0]["_status"] == SESSION_STATUS_COMPLETE+ assert rows[1]["_status"] == SESSION_STATUS_INTERRUPTED++ # No db → rows untouched, tag falls back to '-'+ bare = [{"id": "s1"}]+ _annotate_session_statuses(bare, None)+ assert "_status" not in bare[0]+ assert _session_status_tag(bare[0].get("_status")) == "-"++ # Tag mapping+ assert _session_status_tag(SESSION_STATUS_COMPLETE) == "done"+ assert _session_status_tag(SESSION_STATUS_INTERRUPTED) == "intr"+ assert _session_status_tag(SESSION_STATUS_ERROR) == "err"+ assert _session_status_tag(SESSION_STATUS_EMPTY) == "empty"+++def test_delete_session_removes_session_and_messages(db, tmp_path):+ db.create_session("doomed", source="cli")+ db.append_message("doomed", "user", "hi")+ db.append_message("doomed", "assistant", "hello", finish_reason="stop")++ assert db.delete_session("doomed", sessions_dir=tmp_path / "sessions") is True+ assert db.get_session("doomed") is None+ remaining = db._conn.execute(+ "SELECT COUNT(*) FROM messages WHERE session_id = ?", ("doomed",)+ ).fetchone()[0]+ assert remaining == 0+ # Deleting again reports False (not found)+ assert db.delete_session("doomed") is Falsediff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex d2e7b091313..18acbc934a7 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1467,7 +1467,7 @@ Subcommands:| Subcommand | Description ||------------|-------------|| `list` | List recent sessions. |-| `browse` | Interactive session picker with search and resume. |+| `browse` | Interactive session picker with search and resume. Each row shows a lifecycle status tag (`done` / `intr` / `err` / `empty`, derived from the session's final message) and its message count. Press `d` on a highlighted row (while the search filter is empty) to delete that session after a y/N confirmation; while a filter is active, `d` types into the search instead. || `export <output> [--session-id ID]` | Export sessions to JSONL. || `delete <session-id>` | Delete one session. || `prune` | Delete sessions matching filters: time bounds `--older-than`/`--newer-than`/`--before`/`--after` (durations like `5h`/`2d`, bare days, or ISO timestamps); attributes `--source`, `--title`, `--model`, `--provider`, `--branch`, `--end-reason`, `--user`, `--chat-id`, `--chat-type`, `--cwd`; numeric bounds `--min/--max-messages`, `--min/--max-tokens`, `--min/--max-cost`, `--min/--max-tool-calls`; plus `--include-archived`, `--dry-run`, `--yes`. Default: older than 90 days. |