Skip to content

The agent that grows with you

fix: tool-completion goal republish runs on the gateway loop; legacy gate sees every publish

Tekniumc4104b15842e
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index 3fd85e0a9db..de6bec9a747 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -167,6 +167,19 @@ def restore(agent, previous: dict | None) -> None:
setattr(agent, name, value)
+def publish_control_if_changed(turn) -> None:
+ """Agent thread, after each tool: a tool (a plugin adding goal criteria, parking the goal) can move
+ automation state mid-turn, so viewers' cards repaint now instead of at turn end. The snapshot is read,
+ compared and published on the gateway loop, in order with the slash commands' publishes (a snapshot
+ read here could land after a newer one); revision-gated, so other tools publish nothing."""
+ from gateway.session_control_actions import publish
+ authority, canonical_id, _generation = turn._approval_owner
+
+ async def republish():
+ publish(authority, canonical_id, only_if_changed=True)
+ turn._schedule(republish(), "session.control.update after a tool")
+
+
def note_tool_start(turn, call_id, tool_name=None, args=None) -> None:
"""Monotonic start time of one call (``tool.complete.duration_s``) and, for a write-capable
tool, the before-state of its local files: the agent fires the start callback BEFORE the tool
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index ada900e97c3..6200c3367ae 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -856,13 +856,6 @@ class GatewayTurnProgressMixin:
if self._ctx._native_slack_task_cards:
self.native_tool_start_callback(call_id, tool_name, args)
- def _publish_control_if_changed(self):
- """A tool (a plugin adding goal criteria, parking the goal) can move automation state mid-turn:
- viewers' cards repaint now instead of at turn end. Revision-gated, so other tools publish nothing."""
- from gateway.session_control_actions import publish
- authority, canonical_id, _generation = self._approval_owner
- publish(authority, canonical_id, only_if_changed=True)
-
def combined_tool_complete_callback(self, call_id, tool_name, args, result):
from agent.display import _detect_tool_failure
is_error, _ = _detect_tool_failure(tool_name, result)
@@ -880,7 +873,8 @@ class GatewayTurnProgressMixin:
self._publish_execution("todo.updated", {"todos": payload["todos"], "revision": payload.get("revision", 0)})
self._publish_api_tool("tool.complete", call_id, tool_name, args, result)
if local_viewer_turn(self):
- self._publish_control_if_changed()
+ from gateway import local_viewer_events
+ local_viewer_events.publish_control_if_changed(self)
if self._ctx._native_slack_task_cards:
self.native_tool_complete_callback(call_id, tool_name, args, result)
diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.py
index 1334e183ea9..c27c309a893 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -33,7 +33,7 @@ def _turn(platform, published, *, live=None):
turn._approval_owner = (authority, 's', 1)
turn._publish_execution = lambda kind, payload: published.append((kind, payload)) or True
turn._publish_api_tool = lambda *a, **k: None
- turn._publish_control_if_changed = lambda: None
+ turn._schedule = lambda coro, _message: coro.close() # the session.control.update hop to the gateway loop
return turn
diff --git a/tests/gateway/test_session_viewer_automation.py b/tests/gateway/test_session_viewer_automation.py
index 542be62f8ea..42f4e11fa9f 100644
--- a/tests/gateway/test_session_viewer_automation.py
+++ b/tests/gateway/test_session_viewer_automation.py
@@ -149,17 +149,27 @@ async def test_a_read_that_clears_a_goal_barrier_repaints_the_other_viewers(owne
@pytest.mark.asyncio
async def test_a_tool_that_moves_the_goal_mid_turn_repaints_the_viewers_once(owner):
- """A plugin tool writes goal criteria mid-turn; the tool-completion republish
- (``run_turn_progress`` → ``publish(only_if_changed=True)``) sends the new snapshot, other tools nothing."""
- from gateway.session_control_actions import publish
+ """A plugin tool writes goal criteria mid-turn: the turn's tool-completion callback republishes the new
+ snapshot once, and a tool that changed nothing publishes nothing."""
+ import asyncio
+ from gateway.config import Platform
from hermes_cli.goals import GoalManager
+ from tests.gateway.test_local_viewer_events_turn import _turn
await owner.call('goal', 'set', 'ship it')
updates = []
owner.authority.sessions[owner.ref.session_id].event_stream.observers.add(
lambda frame: frame['params']['type'] == 'session.control.update' and updates.append(frame['params']['payload']))
- publish(owner.authority, owner.ref.session_id, only_if_changed=True)
+ turn = _turn(Platform.LOCAL, [])
+ turn._approval_owner = (owner.authority, owner.ref.session_id, 1)
+ turn._schedule = lambda coro, _message: asyncio.ensure_future(coro)
+
+ async def tool_completes(write=None):
+ if write:
+ GoalManager(session_id=owner.target).add_subgoal(write) # the plugin tool's own write
+ turn.combined_tool_complete_callback('call', 'probe', {}, 'ok')
+ await asyncio.sleep(0)
+ await tool_completes()
assert updates == []
- GoalManager(session_id=owner.target).add_subgoal('tests pass')
- publish(owner.authority, owner.ref.session_id, only_if_changed=True)
- publish(owner.authority, owner.ref.session_id, only_if_changed=True)
+ await tool_completes('tests pass')
+ await tool_completes()
assert [u['control']['goal']['subgoals'] for u in updates] == [['tests pass']]
diff --git a/tui_gateway/methods_session_control.py b/tui_gateway/methods_session_control.py
index 3cff6f80c71..3c90342b21c 100644
--- a/tui_gateway/methods_session_control.py
+++ b/tui_gateway/methods_session_control.py
@@ -299,12 +299,10 @@ def _(rid, params: dict) -> dict:
logger.debug("session.control snapshot after %s failed: %s", action, exc, exc_info=True)
return _err(rid, 5031, f"session.control snapshot failed: {exc}")
- # command.dispatch already published the update for goal/loop actions; manager actions publish here.
+ # command.dispatch already published the update for goal/loop actions; manager actions publish here,
+ # through the one publisher that records the revision the tool-completion gate compares against.
if action not in _ACTION_COMMAND_MAP:
- try:
- _emit("session.control.update", params.get("session_id") or "", {"control": control})
- except Exception as exc:
- logger.debug("session.control.update emit failed (best-effort): %s", exc, exc_info=True)
+ _publish_session_control_snapshot(params.get("session_id") or "", session)
return _ok(rid, {"control": control, "dispatch": _dispatch_envelope(action_result)})