Skip to content

The agent that grows with you

fix(gateway): run session-end lifecycle on the owner when the last viewer closes

unsupportedpastels017aab5bcb15
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index bd25116f75b..22ff351d8b3 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -103,6 +103,9 @@ class SessionAuthority:
self.retired = False
self._classic_evict_at = {} # route -> last leaked/reaped-slot eviction check (monotonic)
self.executing = {} # session id -> generation whose execution is in progress (publish fence)
+ # session id -> end_reason of a last-viewer close still waiting for an idle FIFO
+ # (gateway/session_viewer_close); a viewer attaching again cancels it.
+ self.pending_closes = {}
def authorize(self, actor, ref, capability):
"""Every handler calls this first, so a later ``self.sessions[ref.session_id]`` is
@@ -216,6 +219,7 @@ class SessionAuthority:
subscription = next((key for key, member in live.subscribers.items()
if member == actor), None) or uuid.uuid4().hex
live.subscribers[subscription] = actor
+ self.pending_closes.pop(ref.session_id, None)
transport = self.events.get(actor.transport_id)
if transport is not None:
live.event_stream.fanout.attach(transport)
@@ -248,13 +252,15 @@ class SessionAuthority:
if not live.subscribers:
from gateway.session_local_mcp import release_editor_mcp
await asyncio.to_thread(release_editor_mcp, self, [session_id])
- from gateway.session_acp_lifecycle import (
- end_idle_acp_session, end_idle_viewer_session, reopen_if_reattached)
+ if end_reason:
+ from gateway.session_viewer_close import close_viewer_session
+ await close_viewer_session(self, session_id, end_reason)
+ return
+ from gateway.session_acp_lifecycle import end_idle_acp_session, reopen_if_reattached
from gateway.session_runtime_workers import tracked_write
# A viewer that attached while the close was off the loop reopens it.
- close = (partial(end_idle_viewer_session, self, session_id, end_reason) if end_reason
- else partial(end_idle_acp_session, self, session_id))
- await tracked_write(self, close, then=partial(reopen_if_reattached, self, session_id))
+ await tracked_write(self, partial(end_idle_acp_session, self, session_id),
+ then=partial(reopen_if_reattached, self, session_id))
return
raise RuntimeStoreError('not_found')
@@ -935,6 +941,10 @@ class SessionAuthority:
# ``rescan`` on this still-live drain, which must claim it rather than exit.
from gateway.session_runtime_workers import tracked_write
await tracked_write(self, partial(end_idle_acp_session, self, ref.session_id))
+ if live.rescan:
+ continue
+ from gateway.session_viewer_close import settle_viewer_close
+ await settle_viewer_close(self, ref.session_id) # a close that arrived mid-turn
if live.rescan:
continue
return
diff --git a/gateway/session_viewer_close.py b/gateway/session_viewer_close.py
new file mode 100644
index 00000000000..8133cc62552
--- /dev/null
+++ b/gateway/session_viewer_close.py
@@ -0,0 +1,80 @@
+"""The last viewer closing a session ends it on the owner, lifecycle included (#134889 LC-1/LC-2/LC-6).
+
+Main's classic CLI and TUI ran the end of a conversation in their own process: ``end_session``,
+the memory providers' ``on_session_end`` extraction and plugin ``on_session_finalize`` (which also
+closes the Relay conversation scope). Under the gateway those clients are viewers: the agent, its
+memory manager and the Relay scope live in the owner, so ``session.detach {end_reason}`` from the
+last viewer is where the owner runs them. A close that lands while a turn is still queued or running
+is remembered and completed when the FIFO goes idle, so exiting mid-turn still ends the row.
+"""
+import asyncio
+import logging
+from functools import partial
+
+from hermes_state_local import local_receipt
+from hermes_state_runtime import RuntimeStoreError
+
+logger = logging.getLogger(__name__)
+
+_BUSY_SQL = ("SELECT 1 FROM session_admissions WHERE target_session_id=? AND status IN ('queued','started','unknown') "
+ "UNION ALL SELECT 1 FROM worker_executions WHERE session_id IN (?,?) "
+ "AND status IN ('registered','running','unknown') LIMIT 1")
+
+
+def _physical_target(authority, session_id):
+ try:
+ return local_receipt(authority.db, session_id)['entry']['session_id']
+ except (RuntimeStoreError, KeyError, TypeError):
+ return authority.db.get_compression_tip(session_id) or session_id
+
+
+def _busy(authority, session_id, target):
+ with authority.db._read_ctx() as conn:
+ return conn.execute(_BUSY_SQL, (session_id, session_id, target)).fetchone() is not None
+
+
+async def close_viewer_session(authority, session_id, reason):
+ """``session.detach {end_reason}`` left *session_id* without viewers: close it now, or once idle."""
+ authority.pending_closes[session_id] = reason
+ await settle_viewer_close(authority, session_id)
+
+
+async def settle_viewer_close(authority, session_id):
+ """Complete a pending viewer close once *session_id* has no viewer and an idle FIFO: stamp the
+ row with the viewer's reason, commit the cached agent's memory and fire ``on_session_finalize``.
+ The drain calls this at every idle point; a viewer attaching meanwhile cancels the close."""
+ reason = authority.pending_closes.get(session_id)
+ live = authority.sessions.get(session_id)
+ if reason is None or live is None or live.subscribers:
+ authority.pending_closes.pop(session_id, None)
+ return
+ from gateway.session_acp_lifecycle import end_idle_viewer_session, reopen_if_reattached
+ from gateway.session_runtime_workers import tracked_write
+ await tracked_write(authority, partial(end_idle_viewer_session, authority, session_id, reason),
+ then=partial(reopen_if_reattached, authority, session_id))
+ target = _physical_target(authority, session_id)
+ if live.subscribers or authority.pending_closes.get(session_id) != reason:
+ return
+ if await asyncio.to_thread(_busy, authority, session_id, target):
+ return # the drain's next idle point completes it
+ authority.pending_closes.pop(session_id, None)
+ await _run_close_lifecycle(authority, live, target, reason)
+
+
+async def _run_close_lifecycle(authority, live, target, reason):
+ """What main's client ran at exit and ``/new``, in the process that owns the session: the
+ memory providers' end-of-session commit (the cached agent is evicted at a boundary, as a
+ gateway ``/new`` does) and the finalize hooks under the owning profile's scope."""
+ runner = authority.runner
+ evict = getattr(runner, '_evict_cached_agent_at_boundary', None)
+ if evict is not None:
+ evict(live.route)
+ finalize = getattr(runner, '_finalize_session_off_loop', None)
+ if finalize is None:
+ return
+ row = await asyncio.to_thread(authority.db.get_session, target)
+ platform = (row or {}).get('source') or (live.source.platform.value if live.source else '')
+ messages = await finalize(session_id=target, platform=platform, reason=reason, session_key=live.route)
+ if messages:
+ # No viewer is left to show them (session.detach carries no messages yet).
+ logger.info('Session-end plugin message(s) for %s dropped: no viewer', target)
diff --git a/hermes_cli/cli_session_mixin.py b/hermes_cli/cli_session_mixin.py
index 49b18c441d1..7888dc3aba5 100644
--- a/hermes_cli/cli_session_mixin.py
+++ b/hermes_cli/cli_session_mixin.py
@@ -491,7 +491,9 @@ class CLISessionMixin:
# rotation) so /new never blocks on the LLM-bound call.
_boundary_snapshot = self._launch_session_boundary_memory_flush(
list(self.conversation_history), session_id=old_session_id)
- self._notify_session_boundary("on_session_finalize")
+ from hermes_cli.cli_shutdown import _gateway_owns_session_end
+ if not _gateway_owns_session_end(self.agent): # the gateway finalizes at end_session below
+ self._notify_session_boundary("on_session_finalize")
if self._session_db and old_session_id:
# /new can arrive mid-turn before _flush_messages_to_session_db() ran — flush
diff --git a/hermes_cli/cli_shutdown.py b/hermes_cli/cli_shutdown.py
index 724a7aba9d9..d8ed31451ba 100644
--- a/hermes_cli/cli_shutdown.py
+++ b/hermes_cli/cli_shutdown.py
@@ -156,7 +156,16 @@ _CLEANUP_STEPS = (
)
+def _gateway_owns_session_end(agent) -> bool:
+ """A gateway-backed session ends in the gateway: the viewer's ``end_session`` (``session.detach
+ {end_reason}``) makes the owner run finalize and the memory commit (gateway/session_viewer_close)."""
+ from hermes_cli.gateway_agent import GatewayAgent
+ return isinstance(agent, GatewayAgent)
+
+
def _should_emit_cleanup_session_finalize(session_id: str | None) -> bool:
+ if _gateway_owns_session_end(_cli()._active_agent_ref):
+ return False
# A handed-off session is owned by the gateway process — never finalize it here.
# The CLI must not finalize it on exit — that sets end_reason on a row the gateway reopened and is
# actively writing to, causing the handoff leg to vanish from session history (#88234).
diff --git a/hermes_cli/cli_tui_runtime_mixin.py b/hermes_cli/cli_tui_runtime_mixin.py
index f73a7c95400..e7254aaefb6 100644
--- a/hermes_cli/cli_tui_runtime_mixin.py
+++ b/hermes_cli/cli_tui_runtime_mixin.py
@@ -526,8 +526,10 @@ class CLITuiRuntimeMixin:
_cprint(f" {_DIM}{t('cli.tui.session_delete_missing', session_id=_escape(_sid))}{_RST}")
except (Exception, KeyboardInterrupt) as e:
logger.debug("Could not delete session on exit: %s", e)
- # run_conversation() fires on_session_end on normal completion; only fire here mid-turn.
- if self.agent and self._agent_running:
+ # run_conversation() fires on_session_end on normal completion; only fire here mid-turn. A gateway
+ # turn fires it in the gateway when the interrupted turn finalizes.
+ from hermes_cli.cli_shutdown import _gateway_owns_session_end
+ if self.agent and self._agent_running and not _gateway_owns_session_end(self.agent):
_invoke_interrupted_session_end(self.agent, self.agent.session_id, "shutdown")
_run_cleanup()
self._print_exit_summary()
diff --git a/tests/gateway/test_viewer_close_lifecycle.py b/tests/gateway/test_viewer_close_lifecycle.py
new file mode 100644
index 00000000000..2a6a77c28f9
--- /dev/null
+++ b/tests/gateway/test_viewer_close_lifecycle.py
@@ -0,0 +1,103 @@
+"""The owner runs a session's end-of-conversation lifecycle when its last viewer closes it.
+
+Regression for #134889 LC-1/LC-2/LC-6. Main's classic CLI and TUI ran the memory providers'
+``on_session_end`` commit and plugin ``on_session_finalize`` (which closes the Relay scope) in their own
+process at exit and ``/new``. Under the gateway the client is a viewer with no memory manager, so
+nothing ran until idle eviction; and a close sent while a turn was live left ``ended_at`` unset for good.
+"""
+from types import SimpleNamespace
+
+import pytest
+
+from tests.waiting import async_wait_until
+
+
+async def _owner(tmp_path, monkeypatch):
+ from gateway import run
+ from gateway.config import GatewayConfig
+ from gateway.session import SessionStore
+ from gateway.session_authority import initialize_session_authority
+
+ monkeypatch.setenv('HERMES_HOME', str(tmp_path))
+ monkeypatch.setattr(run, '_load_gateway_config', lambda: {'platform_toolsets': {'cli': []}})
+ store = SessionStore(tmp_path / 'sessions', GatewayConfig())
+ calls = []
+
+ async def finalize(**kwargs):
+ calls.append(('finalize', kwargs))
+ return []
+
+ runner = SimpleNamespace(session_store=store, _session_db=store._db, adapters={}, _draining=False,
+ _cached_agent_for=lambda route: None,
+ _evict_cached_agent_at_boundary=lambda key: calls.append(('commit', key)),
+ _finalize_session_off_loop=finalize)
+ runner._adapter_for_source = lambda source: runner.adapters.get(source.platform)
+ authority = await initialize_session_authority(runner, profile_id=str(tmp_path), instance_id='owner')
+ return store._db, authority, calls
+
+
+def _viewer(authority, tmp_path):
+ from gateway.session_controls import AuthorityConnection
+ return AuthorityConnection(authority, SimpleNamespace(write=lambda frame: None), {
+ 'provider': 'local', 'user_id': 'native', 'profile_id': str(tmp_path), 'instance_id': 'owner'})
+
+
+async def _call(conn, method, **params):
+ reply = await conn.dispatch({'id': 1, 'method': method, 'params': params})
+ assert 'result' in reply, reply
+ return reply['result']
+
+
+async def _open(db, authority, tmp_path):
+ db.create_session('chat', source='cli', model='fake-model', cwd=str(tmp_path))
+ db.append_message('chat', 'user', 'q')
+ db.append_message('chat', 'assistant', 'a')
+ viewer = _viewer(authority, tmp_path)
+ resumed = await _call(viewer, 'session.resume', session_id='chat')
+ db.reopen_session('chat')
+ return viewer, resumed['subscription_id']
+
+
+async def test_last_viewer_close_commits_memory_and_finalizes_on_the_owner(tmp_path, monkeypatch):
+ db, authority, calls = await _owner(tmp_path, monkeypatch)
+ viewer, subscription = await _open(db, authority, tmp_path)
+ other = _viewer(authority, tmp_path)
+ second = await _call(other, 'session.resume', session_id='chat')
+ route = authority.sessions['chat'].route
+
+ # Another viewer still has the conversation open: nothing ends.
+ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription, end_reason='new_session')
+ assert calls == []
+ # A plain detach (a viewer leaving, not closing) never ends it either.
+ await _call(other, 'session.detach', session_id='chat', subscription_id=second['subscription_id'])
+ assert calls == [] and db.get_session('chat')['end_reason'] is None
+
+ again = await _call(other, 'session.resume', session_id='chat')
+ await _call(other, 'session.detach', session_id='chat', subscription_id=again['subscription_id'],
+ end_reason='cli_close')
+ assert db.get_session('chat')['end_reason'] == 'cli_close'
+ assert calls == [('commit', route), ('finalize', {
+ 'session_id': 'chat', 'platform': 'cli', 'reason': 'cli_close', 'session_key': route})]
+
+
+async def test_close_while_a_turn_is_queued_completes_when_the_fifo_goes_idle(tmp_path, monkeypatch):
+ from gateway.session_contract import SessionRef
+ from hermes_state_runtime import admit_session_input, cancel_session_input
+
+ db, authority, calls = await _owner(tmp_path, monkeypatch)
+ viewer, subscription = await _open(db, authority, tmp_path)
+ row = admit_session_input(db, epoch=authority.epoch, principal_id='native', session_id='chat',
+ request_id='r1', payload={'text': 'still running'})
+
+ await _call(viewer, 'session.detach', session_id='chat', subscription_id=subscription, end_reason='cli_close')
+ assert db.get_session('chat')['ended_at'] is None and calls == []
+
+ # The turn ends (here: cancelled) and the drain reaches its idle point.
+ cancel_session_input(db, epoch=authority.epoch, admission_id=row['admission_id'])
+ authority._schedule(SessionRef(authority.profile_id, 'chat'))
+ await async_wait_until(lambda: len(calls) == 2)
+ assert db.get_session('chat')['end_reason'] == 'cli_close'
+ assert [name for name, _ in calls] == ['commit', 'finalize']
+
diff --git a/tests/hermes_cli/test_gateway_session_end_ownership.py b/tests/hermes_cli/test_gateway_session_end_ownership.py
new file mode 100644
index 00000000000..f5420348d75
--- /dev/null
+++ b/tests/hermes_cli/test_gateway_session_end_ownership.py
@@ -0,0 +1,55 @@
+"""A gateway-backed classic CLI leaves the end of its session to the gateway.
+
+Regression for #134889 LC-2. The CLI's ``end_session`` (exit, ``/new``) detaches with an ``end_reason``
+and the gateway, which owns the agent, the memory manager and the Relay scope, runs
+``on_session_finalize`` (tests/gateway/test_viewer_close_lifecycle.py). Firing it in the CLI process as
+well finalized every session twice, once in a process that holds none of that state; and the CLI's
+mid-turn ``on_session_end`` duplicated the one the gateway's interrupted turn fires.
+"""
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from hermes_cli.gateway_agent import GatewayAgent
+
+
+def cli_mod():
+ import cli as cli_mod
+ cli_mod._cleanup_done = False
+ cli_mod._single_query_finalize_attempted_session_ids.clear()
+ cli_mod._handed_off_session_ids.clear()
+ yield cli_mod
+ cli_mod._active_agent_ref = None
+ cli_mod._cleanup_done = False
+
+
+def _gateway_agent(session_id):
+ return GatewayAgent(connection=MagicMock(), session_id=session_id)
+
+
+@patch("hermes_cli.lifecycle.finalize_session")
+def test_exit_cleanup_does_not_finalize_a_gateway_session(mock_finalize, cli_mod):
+ cli_mod._active_agent_ref = _gateway_agent("gw-session")
+ cli_mod._run_cleanup()
+ mock_finalize.assert_not_called()
+
+
+@patch("hermes_cli.lifecycle.invoke_hook")
+@patch("hermes_cli.lifecycle.finalize_session")
+def test_new_does_not_finalize_a_gateway_session_in_the_cli(mock_finalize, mock_invoke_hook, cli_mod):
+ cli = cli_mod.HermesCLI()
+ cli.agent = _gateway_agent("gw-session")
+ cli.new_session(silent=True)
+ mock_finalize.assert_not_called()
+
+
+@patch("hermes_cli.lifecycle.invoke_hook")
+def test_exit_mid_turn_leaves_on_session_end_to_the_gateway_turn(mock_invoke_hook, cli_mod):
+ cli = cli_mod.HermesCLI()
+ cli.agent = _gateway_agent("gw-session")
+ cli._agent_running = True
+ cli._session_db = None
+ with patch.object(cli_mod, "_run_cleanup"), patch.object(cli, "_print_exit_summary"):
+ cli._tui_shutdown()
+ assert not [c for c in mock_invoke_hook.call_args_list if c.args == ("on_session_end",)]