Skip to content

The agent that grows with you

fix(gateway): viewers get session.control.update when /goal, /loop or /heartbeat state moves

Teknium874d1485abc6
diff --git a/gateway/run_goals.py b/gateway/run_goals.py
index 3494968a66f..72208ae5b21 100644
--- a/gateway/run_goals.py
+++ b/gateway/run_goals.py
@@ -369,6 +369,16 @@ class GatewayGoalsMixin:
await hook(session_entry=session_entry, source=source, final_response=final_text)
except Exception as exc:
logger.debug("%s hook failed: %s", label, exc)
+ self._publish_local_control(source, only_if_present=True)
+
+ def _publish_local_control(self, source: Any, *, only_if_present: bool = False) -> None:
+ """A local (Desktop/Ink) session's goal or loop state just moved here: repaint its viewers' cards,
+ whose loop countdown runs off the snapshot's ``next_due_at``."""
+ if getattr(source, "platform", None) != Platform.LOCAL:
+ return
+ from gateway.session_authorities import active_authority
+ from gateway.session_control_actions import publish
+ publish(active_authority(self), source.chat_id, only_if_present=only_if_present)
@staticmethod
def _final_text_for_post_turn_hooks(agent_result, event=None) -> str:
@@ -491,6 +501,8 @@ class GatewayGoalsMixin:
logger.warning("loop wakeup injection failed for %s: %s", sid, exc)
with suppress(Exception):
mgr.abandon_tick()
+ # Viewers swap the countdown for "running now" (or re-anchor it after a slash tick settled).
+ self._publish_local_control(source)
async def _loop_wakeup_watcher(self, interval: float = 15.0) -> None:
"""Fire due /loop wakeups for idle gateway sessions: a coarse ticker scans persisted loops
diff --git a/gateway/session_commands.py b/gateway/session_commands.py
index 0b9f6babdfd..164ebaa7a8f 100644
--- a/gateway/session_commands.py
+++ b/gateway/session_commands.py
@@ -38,6 +38,8 @@ _APPROVAL_COMMANDS = frozenset({'approve', 'deny'})
# Reports with no messaging handler: the classic CLI's own text, built by the owner for this
# session (gateway/session_info_reads.py).
_INFO_READS = frozenset({'toolsets', 'platforms'})
+# Commands that move the session's goal/loop/heartbeat state: every viewer's cards repaint after them.
+_AUTOMATION_COMMANDS = frozenset({'goal', 'subgoal', 'loop', 'heartbeat'})
# Kanban verbs that only read the board. ``create`` would also subscribe the LOCAL chat to
# messaging notifications, and every other verb mutates the board.
@@ -284,6 +286,9 @@ async def execute_command(connection, ref, params, *, dispatch=False):
handle = authority._handle(ref)
live.controls.snapshot(ref.session_id, handle.execution_generation
if handle.execution_state == 'running' else None)
+ if canonical in _AUTOMATION_COMMANDS:
+ from gateway.session_control_actions import publish
+ publish(authority, ref.session_id)
prompt = prompt if prompt is not None else sink.prompt
if prompt:
# The client submits the turn with its own durable input id; the gateway never does.
diff --git a/gateway/session_control_actions.py b/gateway/session_control_actions.py
index 6d8a0e813e4..9053978a00d 100644
--- a/gateway/session_control_actions.py
+++ b/gateway/session_control_actions.py
@@ -5,8 +5,12 @@ answered -32601. Each action is the typed slash command the button stands for, r
``execute_command`` (the gateway's own /goal /loop /heartbeat /subgoal handlers, with their
capability, local-source, admission and busy rules), answered with the owner's control snapshot.
"""
+import logging
+
from hermes_state_runtime import RuntimeStoreError
+logger = logging.getLogger(__name__)
+
_ACTION_COMMANDS = {
'goal.pause': ('goal', 'pause'), 'goal.resume': ('goal', 'resume'),
'goal.clear': ('goal', 'clear'), 'goal.unwait': ('goal', 'unwait'),
@@ -63,6 +67,28 @@ async def _add_subgoal(connection, ref, params, text):
return {'type': 'exec', 'output': err or t('gateway.subgoal.added', index=index, text=added)}
+def publish(authority, session_id, *, only_if_present=False):
+ """Push one live session's control snapshot to every viewer as ``session.control.update``.
+
+ Desktop and Ink paint the goal/loop/heartbeat cards from this event and run the loop countdown off
+ its ``next_due_at``, so every place that moves that state on the owner publishes: the slash
+ commands, a fired or settled loop wakeup, a judged turn. ``only_if_present`` skips a session with
+ no automation state (a plain turn's event stream stays unchanged).
+ """
+ live = authority.sessions.get(session_id) if authority is not None else None
+ if live is None:
+ return
+ from gateway.session_ancillary import control_snapshot
+ from gateway.session_contract import SessionRef
+ try:
+ snapshot = control_snapshot(authority, SessionRef(authority.profile_id, session_id))
+ except RuntimeStoreError: # unreadable row: the change itself already landed; the next publish repaints
+ logger.debug('session.control.update skipped for %s', session_id, exc_info=True)
+ return
+ if not only_if_present or snapshot['revision']:
+ live.event_stream.publish(session_id, {'control': snapshot}, event_type='session.control.update')
+
+
async def control(connection, ref, params):
if set(params) - {'session_id', 'profile', 'action', 'args'} or not ref.session_id:
raise RuntimeStoreError('invalid_params')
@@ -74,14 +100,14 @@ async def control(connection, ref, params):
if ref.session_id not in connection.authority.sessions:
raise RuntimeStoreError('not_found')
scope = {key: params[key] for key in ('session_id', 'profile') if key in params}
+ # Other viewers (another Desktop window, Ink) repaint their cards from session.control.update, not the
+ # reply: execute_command publishes it for the automation commands, the subgoal add here.
if arg is None:
result = await _add_subgoal(connection, ref, scope, args['text'].strip())
+ publish(connection.authority, ref.session_id)
else:
from gateway.session_commands import execute_command
result = await execute_command(connection, ref, {**scope, 'name': name, 'arg': arg}, dispatch=True)
from gateway.session_ancillary import read
snapshot = await read(connection, ref, scope, kind='control')
- # Other viewers (another Desktop window, Ink) repaint their cards from this event, not the reply.
- connection.authority.sessions[ref.session_id].event_stream.publish(
- ref.session_id, snapshot, event_type='session.control.update')
return {**snapshot, 'dispatch': {key: result.get(key) for key in _ENVELOPE}}
diff --git a/tests/gateway/fixtures/tui_desktop_routes_peer.py b/tests/gateway/fixtures/tui_desktop_routes_peer.py
index e85d90c2c42..e81ecca0cea 100644
--- a/tests/gateway/fixtures/tui_desktop_routes_peer.py
+++ b/tests/gateway/fixtures/tui_desktop_routes_peer.py
@@ -102,15 +102,19 @@ async def _control(authority, ws, reader, sid, marker, receipt):
params = {'action': action, **({'args': args} if args else {})}
return await rpc(ws, 'session.control', session_id=sid, **params)
- for command in ('goal ship the owned fixture', 'loop every 10m CHECK_LOOP', 'heartbeat every 10m PING_HEARTBEAT'):
+ updates = []
+ authority.sessions[sid].event_stream.observers.add(
+ lambda frame: frame['params']['type'] == 'session.control.update' and updates.append(frame['params']))
+ for command, kind in (('goal ship the owned fixture', 'goal'), ('loop every 10m CHECK_LOOP', 'loop'),
+ ('heartbeat every 10m PING_HEARTBEAT', 'heartbeat')):
typed = await rpc(ws, 'slash.exec', session_id=sid, command=command)
assert 'result' in typed, (command, typed)
+ # A typed command repaints every viewer's cards too (Ink has no other refresh path).
+ assert updates and updates.pop()['payload']['control'][kind]['status'] == 'active', (command, updates)
denied = await _call(reader, 'session.control', session_id=sid, action='goal.pause')
assert _error(denied) == 'permission_denied', denied
# Every other viewer of the session: what its card repaints from.
- updates = []
- authority.sessions[sid].event_stream.observers.add(
- lambda frame: frame['params']['type'] == 'session.control.update' and updates.append(frame['params']))
+ updates.clear()
for action, check in [
('goal.pause', lambda c: c['goal']['status'] == 'paused'),
('goal.resume', lambda c: c['goal']['status'] == 'active'),