Skip to content

The agent that grows with you

fix(gateway): the session authority answers session.active_list from its own live turns

unsupportedpastelsc3ecea58a874
diff --git a/gateway/session_active_list.py b/gateway/session_active_list.py
new file mode 100644
index 00000000000..5ca3abc0f38
--- /dev/null
+++ b/gateway/session_active_list.py
@@ -0,0 +1,53 @@
+"""``session.active_list`` on the session authority: the live state of the turns it owns.
+
+Desktop's silent-turn check (``session-states.ts`` ``onEventSilence``) and its sidebar poll read
+this verb. Unregistered here, the WS fell back to the legacy sidecar's handler, which lists only
+the sidecar's own ``_sessions`` and never an authority-owned session: a foreground tool quiet for
+45 s read as a reaped turn, and Desktop painted "Hermes ended this turn without a reply" over a
+turn that was still running. Rows keep ``server._session_live_item``'s shape; ``id`` and
+``session_key`` are both the session id, as ``session.resume`` reports them.
+"""
+from __future__ import annotations
+
+from gateway.session_contract import SessionRef
+from hermes_state_runtime import RuntimeStoreError
+
+
+def _status(live, handle, pending) -> str:
+ if handle.execution_state == 'running':
+ prompts = live.controls.snapshot(handle.ref.session_id, handle.execution_generation)
+ return 'waiting' if prompts else 'working'
+ # Admitted, not yet claimed by the drain: the turn exists, its agent has not started.
+ return 'starting' if any(row['status'] == 'queued' for row in pending) else 'idle'
+
+
+async def active_list(connection, ref, params):
+ if set(params) - {'profile', 'current_session_id'}:
+ raise RuntimeStoreError('invalid_params')
+ if 'session:read' not in connection.actor.capabilities:
+ raise RuntimeStoreError('permission_denied')
+ from gateway.session_local_close import closed_and_unviewed
+ from hermes_state_sessions import INTERNAL_LISTING_SOURCES
+ authority = connection.authority
+ current = str(params.get('current_session_id') or '')
+ rows = []
+ for sid, live in tuple(authority.sessions.items()):
+ candidate = SessionRef(connection.actor.profile_id, sid)
+ try:
+ handle = await authority.resolve(connection.actor, candidate)
+ except RuntimeStoreError as exc:
+ if exc.reason not in {'permission_denied', 'profile_mismatch', 'not_found'}:
+ raise
+ continue
+ row = authority.db.get_session(sid) or {}
+ # The same population as the live ``session.list`` feed, hidden chats included: a hidden
+ # chat open in a pane still needs its turn's liveness.
+ if row.get('source') in INTERNAL_LISTING_SOURCES or closed_and_unviewed(authority, sid, handle):
+ continue
+ started = float(row.get('started_at') or 0)
+ rows.append({'current': sid == current, 'id': sid, 'session_key': sid,
+ 'last_active': float(row.get('ended_at') or started), 'started_at': started,
+ 'message_count': int(row.get('message_count') or 0),
+ 'model': str(row.get('model') or ''), 'preview': '', 'title': row.get('title') or '',
+ 'status': _status(live, handle, authority._pending_rows(candidate))})
+ return {'sessions': rows}
diff --git a/gateway/session_controls.py b/gateway/session_controls.py
index 8d1c46013f8..8d6949c1dfd 100644
--- a/gateway/session_controls.py
+++ b/gateway/session_controls.py
@@ -124,6 +124,8 @@ class AuthorityConnection:
handlers['session.prune'] = partial(prune, self)
from gateway.session_usage import stats
handlers['session.stats'] = partial(stats, self)
+ from gateway.session_active_list import active_list
+ handlers['session.active_list'] = partial(active_list, self)
from gateway.session_viewer_automation import automation
handlers['session.automation'] = partial(automation, self)
return handlers
diff --git a/tests/gateway/test_authority_active_list.py b/tests/gateway/test_authority_active_list.py
new file mode 100644
index 00000000000..064a9cac26b
--- /dev/null
+++ b/tests/gateway/test_authority_active_list.py
@@ -0,0 +1,70 @@
+"""``session.active_list`` is answered by the session authority from its own live turns.
+
+Desktop's silent-turn check (``session-states.ts`` ``onEventSilence``) asks this verb whether a
+turn that went 45 s without an event is still running. The authority never registered it, so the
+WS fell back to the legacy sidecar's handler, whose ``_sessions`` never holds an authority-owned
+session: a foreground tool quiet for 45 s read as a reaped turn, and Desktop painted "Hermes ended
+this turn without a reply" over a turn that was still running.
+"""
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+import pytest_asyncio
+
+
+@pytest_asyncio.fixture
+async def owner(tmp_path, monkeypatch):
+ from gateway.config import GatewayConfig, Platform
+ from gateway.session import SessionSource, SessionStore
+ from gateway.session_authority import LiveSession, initialize_session_authority
+ from gateway.session_controls import AuthorityConnection
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ started, release = asyncio.Event(), asyncio.Event()
+
+ async def answer(event):
+ # A long foreground tool: the turn emits nothing until it returns.
+ started.set()
+ await release.wait()
+ return event.text
+
+ runner = SimpleNamespace(_session_db=store._db, session_store=store, _draining=False,
+ _handle_message=answer, _adapter_for_source=lambda source: None)
+ authority = await initialize_session_authority(runner, profile_id='live', instance_id='owner')
+ store._db.create_session('chat', source='telegram')
+ authority.sessions['chat'] = LiveSession(SessionSource(platform=Platform.TELEGRAM, chat_id='chat'), 'chat')
+ connection = AuthorityConnection(authority, object(), {'user_id': 'viewer'})
+
+ async def active(**params):
+ reply = await connection.dispatch({'id': 1, 'method': 'session.active_list', 'params': params})
+ assert 'result' in reply, reply
+ return {row['id']: row for row in reply['result']['sessions']}
+
+ async def submit(text):
+ from gateway.session_contract import SessionRef, Submission
+ await authority.submit(connection.actor, Submission(text, SessionRef('live', 'chat'), {'text': text}, 'queue'))
+ await asyncio.wait_for(started.wait(), 5)
+
+ yield SimpleNamespace(authority=authority, active=active, submit=submit, release=release)
+ release.set()
+
+
+async def test_a_running_turn_reads_working_until_it_settles(owner):
+ assert (await owner.active())['chat']['status'] == 'idle'
+ await owner.submit('hi')
+ row = (await owner.active(current_session_id='chat'))['chat']
+ assert (row['status'], row['session_key'], row['current']) == ('working', 'chat', True), row
+ owner.release.set()
+ await owner.authority.sessions['chat'].task
+ assert (await owner.active())['chat']['status'] == 'idle'
+
+
+async def test_a_turn_blocked_on_a_prompt_reads_waiting(owner, monkeypatch):
+ await owner.submit('hi')
+ controls = owner.authority.sessions['chat'].controls
+ monkeypatch.setattr(controls, 'snapshot', lambda session_id, generation: ({'kind': 'approval'},))
+ assert (await owner.active())['chat']['status'] == 'waiting'