Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
322 changes: 283 additions & 39 deletions hermes_cli/web_server.py

Large diffs are not rendered by default.

83 changes: 75 additions & 8 deletions hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -1159,6 +1159,44 @@ def get_compression_tip(self, session_id: str) -> Optional[str]:
current = row["id"]
return current

@staticmethod
def _resumable_session_predicate(alias: str = "s") -> str:
"""SQL predicate for logical sessions that can resume to messages.

Compression roots may have ``message_count = 0`` while their live
continuation child holds the messages. Treat those roots as resumable
too so list/count callers don't hide valid compressed conversations.
"""
return f"""
(
EXISTS (
SELECT 1 FROM messages m
WHERE m.session_id = {alias}.id
LIMIT 1
)
OR EXISTS (
WITH RECURSIVE compression_chain(id) AS (
SELECT child.id
FROM sessions child
WHERE child.parent_session_id = {alias}.id
AND {alias}.end_reason = 'compression'
AND child.started_at >= COALESCE({alias}.ended_at, {alias}.started_at)
UNION ALL
SELECT child.id
FROM compression_chain cc
JOIN sessions parent ON parent.id = cc.id
JOIN sessions child ON child.parent_session_id = parent.id
WHERE parent.end_reason = 'compression'
AND child.started_at >= COALESCE(parent.ended_at, parent.started_at)
)
SELECT 1
FROM compression_chain cc
JOIN messages m ON m.session_id = cc.id
LIMIT 1
)
)
"""

def list_sessions_rich(
self,
source: str = None,
Expand All @@ -1168,6 +1206,7 @@ def list_sessions_rich(
include_children: bool = False,
project_compression_tips: bool = True,
order_by_last_active: bool = False,
resumable_only: bool = False,
) -> List[Dict[str, Any]]:
"""List sessions with preview (first user message) and last active timestamp.

Expand Down Expand Up @@ -1220,6 +1259,8 @@ def list_sessions_rich(
placeholders = ",".join("?" for _ in exclude_sources)
where_clauses.append(f"s.source NOT IN ({placeholders})")
params.extend(exclude_sources)
if resumable_only:
where_clauses.append(self._resumable_session_predicate("s"))

where_sql = f"WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
if order_by_last_active:
Expand Down Expand Up @@ -2415,15 +2456,41 @@ def search_sessions(
# Utility
# =========================================================================

def session_count(self, source: str = None) -> int:
"""Count sessions, optionally filtered by source."""
def session_count(
self,
source: str = None,
exclude_sources: List[str] = None,
resumable_only: bool = False,
include_children: bool = True,
) -> int:
"""Count sessions, optionally using the same coarse filters as listings."""
where_clauses = []
params = []

if not include_children:
where_clauses.append(
"(s.parent_session_id IS NULL"
" OR EXISTS (SELECT 1 FROM sessions p"
" WHERE p.id = s.parent_session_id"
" AND p.end_reason = 'branched'"
" AND s.started_at >= p.ended_at))"
)
if source:
where_clauses.append("s.source = ?")
params.append(source)
if exclude_sources:
placeholders = ",".join("?" for _ in exclude_sources)
where_clauses.append(f"s.source NOT IN ({placeholders})")
params.extend(exclude_sources)
if resumable_only:
where_clauses.append(self._resumable_session_predicate("s"))

where_sql = f" WHERE {' AND '.join(where_clauses)}" if where_clauses else ""
with self._lock:
if source:
cursor = self._conn.execute(
"SELECT COUNT(*) FROM sessions WHERE source = ?", (source,)
)
else:
cursor = self._conn.execute("SELECT COUNT(*) FROM sessions")
cursor = self._conn.execute(
f"SELECT COUNT(*) FROM sessions s{where_sql}",
params,
)
return cursor.fetchone()[0]

def message_count(self, session_id: str = None) -> int:
Expand Down
208 changes: 208 additions & 0 deletions tests/hermes_cli/test_web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,128 @@ def test_get_status(self):
assert "hermes_home" in data
assert "active_sessions" in data

def test_get_sessions_defaults_hide_cron_and_empty_sessions(self):
from hermes_state import SessionDB

db = SessionDB()
try:
db.create_session(
session_id="visible-cli",
source="cli",
model="test-model",
)
db.set_session_title("visible-cli", "Visible CLI")
db.append_message("visible-cli", role="user", content="hello dashboard")
db.end_session("visible-cli", "test")

db.create_session(
session_id="cron-with-message",
source="cron",
model="test-model",
)
db.set_session_title("cron-with-message", "Cron Should Hide")
db.append_message("cron-with-message", role="user", content="cron output")
db.end_session("cron-with-message", "test")

db.create_session(
session_id="empty-cli",
source="cli",
model="test-model",
)
db.set_session_title("empty-cli", "Empty Should Hide")
db.end_session("empty-cli", "test")
finally:
db.close()

resp = self.client.get("/api/sessions?limit=20&offset=0")

assert resp.status_code == 200
data = resp.json()
ids = [s["id"] for s in data["sessions"]]

assert ids == ["visible-cli"]
assert data["total"] == 1
assert data["limit"] == 20
assert data["offset"] == 0

session = data["sessions"][0]
assert session["source"] == "cli"
assert session["message_count"] == 1
assert session["title"] == "Visible CLI"

def test_get_most_recent_session_filters_internal_and_empty_rows(self):
from hermes_state import SessionDB

db = SessionDB()
try:
db.create_session(
session_id="older-cli",
source="cli",
model="test-model",
)
db.append_message("older-cli", role="user", content="older user work")
db.end_session("older-cli", "test")

db.create_session(
session_id="newer-cron",
source="cron",
model="test-model",
)
db.append_message("newer-cron", role="user", content="cron output")
db.end_session("newer-cron", "test")

db.create_session(
session_id="newer-empty-cli",
source="cli",
model="test-model",
)
db.end_session("newer-empty-cli", "test")

db.create_session(
session_id="latest-cli",
source="cli",
model="test-model",
)
db.append_message("latest-cli", role="user", content="latest user work")
db.end_session("latest-cli", "test")
finally:
db.close()

resp = self.client.get("/api/sessions/most-recent")

assert resp.status_code == 200
data = resp.json()
assert data["session_id"] == "latest-cli"
assert data["source"] == "cli"
assert data["title"] == ""

def test_get_most_recent_session_returns_null_without_resumable_rows(self):
from hermes_state import SessionDB

db = SessionDB()
try:
db.create_session(
session_id="cron-only",
source="cron",
model="test-model",
)
db.append_message("cron-only", role="user", content="cron output")
db.end_session("cron-only", "test")

db.create_session(
session_id="empty-cli-only",
source="cli",
model="test-model",
)
db.end_session("empty-cli-only", "test")
finally:
db.close()

resp = self.client.get("/api/sessions/most-recent")

assert resp.status_code == 200
assert resp.json() == {"session_id": None}

def test_get_status_filters_unconfigured_gateway_platforms(self, monkeypatch):
import gateway.config as gateway_config
import hermes_cli.web_server as web_server
Expand Down Expand Up @@ -2082,6 +2204,13 @@ def _setup(self, monkeypatch, _isolate_hermes_home):
monkeypatch.setattr(ws, "_DASHBOARD_EMBEDDED_CHAT_ENABLED", True)
self.token = ws._SESSION_TOKEN
self.client = TestClient(ws.app)
yield
for session in list(getattr(ws, "_dashboard_pty_sessions", {}).values()):
try:
session.bridge.close()
except Exception:
pass
getattr(ws, "_dashboard_pty_sessions", {}).clear()

def _url(self, token: str | None = None, **params: str) -> str:
tok = token if token is not None else self.token
Expand Down Expand Up @@ -2296,6 +2425,85 @@ def fake_resolve(resume=None, sidecar_url=None):
assert "channel=abc-123" in url
assert "token=" in url

def test_attach_failure_detaches_dead_websocket(self, monkeypatch):
"""A client drop during buffered replay must not leave session.ws stuck.

The next reconnect relies on session.ws being clear; otherwise the PTY
session can sit attached to a dead socket until a later writer failure.
"""
class FakeBridge:
def close(self):
pass

session = self.ws_module._DashboardPtySession(FakeBridge())

async def fake_get_session(**_kwargs):
return session

async def fake_attach(sess, ws):
sess.ws = ws
raise RuntimeError("client dropped during replay")

monkeypatch.setattr(
self.ws_module, "_get_dashboard_pty_session", fake_get_session
)
monkeypatch.setattr(
self.ws_module, "_attach_dashboard_pty_session", fake_attach
)

with self.client.websocket_connect(self._url(channel="attach-fail")) as conn:
msg = conn.receive_text()

assert "Chat connection failed" in msg
assert session.ws is None

def test_channel_disconnect_keeps_pty_alive_for_reconnect(self, monkeypatch):
import time

class FakeBridge:
def __init__(self):
self.closed = 0
self.writes: list[bytes] = []
self.resizes: list[tuple[int, int]] = []

def read(self, timeout):
time.sleep(min(float(timeout or 0), 0.01))
return b""

def write(self, raw):
self.writes.append(raw)

def resize(self, cols, rows):
self.resizes.append((cols, rows))

def close(self):
self.closed += 1

fake = FakeBridge()
spawns: list[FakeBridge] = []
monkeypatch.setattr(
self.ws_module,
"_resolve_chat_argv",
lambda resume=None, sidecar_url=None: (["/bin/cat"], None, None),
)
monkeypatch.setattr(
self.ws_module.PtyBridge,
"spawn",
classmethod(lambda cls, *a, **k: spawns.append(fake) or fake),
)

with self.client.websocket_connect(self._url(channel="persist-test")) as conn:
conn.send_bytes(b"first\n")

time.sleep(0.05)
assert fake.closed == 0

with self.client.websocket_connect(self._url(channel="persist-test")) as conn:
conn.send_bytes(b"second\n")

assert len(spawns) == 1
assert fake.writes == [b"first\n", b"second\n"]

def test_pub_broadcasts_to_events_subscribers(self, monkeypatch):
"""Frame written to /api/pub is rebroadcast verbatim to every
/api/events subscriber on the same channel."""
Expand Down
49 changes: 49 additions & 0 deletions tests/test_hermes_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -2348,6 +2348,55 @@ def test_list_surfaces_tip_for_compressed_root(self, db):
assert tip_row["ended_at"] is None # tip is still live
assert tip_row["end_reason"] is None

def test_resumable_only_includes_empty_compression_root_with_message_tip(self, db):
"""A compressed root can have zero own messages while its continuation
has the usable transcript; resumable-only views must keep that logical
conversation visible.
"""
import time as _time

t0 = _time.time() - 3600
db.create_session("empty-root", "cli")
db._conn.execute(
"UPDATE sessions SET started_at=?, ended_at=?, end_reason=? WHERE id=?",
(t0, t0 + 100, "compression", "empty-root"),
)
db.create_session("message-tip", "cli", parent_session_id="empty-root")
db._conn.execute(
"UPDATE sessions SET started_at=? WHERE id=?", (t0 + 101, "message-tip")
)
db.append_message("message-tip", "user", "resume me")
db._conn.commit()

sessions = db.list_sessions_rich(
source="cli", exclude_sources=["tool", "cron"], resumable_only=True
)

assert [s["id"] for s in sessions] == ["message-tip"]
assert sessions[0]["_lineage_root_id"] == "empty-root"
assert db.session_count(
source="cli",
exclude_sources=["tool", "cron"],
resumable_only=True,
include_children=False,
) == 1

def test_resumable_only_does_not_count_empty_orphan_compression_root(self, db):
import time as _time

t0 = _time.time() - 3600
db.create_session("empty-root", "cli")
db._conn.execute(
"UPDATE sessions SET started_at=?, ended_at=?, end_reason=? WHERE id=?",
(t0, t0 + 100, "compression", "empty-root"),
)
db._conn.commit()

assert db.list_sessions_rich(source="cli", resumable_only=True) == []
assert db.session_count(
source="cli", resumable_only=True, include_children=False
) == 0

def test_list_without_projection_returns_raw_root(self, db):
"""project_compression_tips=False returns the raw parent-NULL root
rows — useful for admin/debug UIs.
Expand Down
Loading