Skip to content

The agent that grows with you

fix: goal cards repaint when a tool changes the goal mid-turn (CLI, TUI, Desktop)

Tekniumb2bd13c0a929
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index 32779095d93..ada900e97c3 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -856,6 +856,13 @@ 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)
@@ -872,6 +879,8 @@ class GatewayTurnProgressMixin:
# Task state is application data, not tool chrome: the full snapshot, as the TUI gateway emits it.
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()
if self._ctx._native_slack_task_cards:
self.native_tool_complete_callback(call_id, tool_name, args, result)
diff --git a/gateway/session_authority.py b/gateway/session_authority.py
index 7c2216852e7..8e82a226da6 100644
--- a/gateway/session_authority.py
+++ b/gateway/session_authority.py
@@ -83,6 +83,9 @@ class LiveSession:
# The background-review guard of a cold ``/refine`` (gateway/session_refine.py): its side agent is
# per call, so the run token lives here; a second /refine joins it and the next turn cancels it.
review: SimpleNamespace = field(default_factory=SimpleNamespace)
+ # Revision of the last ``session.control.update`` (gateway/session_control_actions.publish): a tool
+ # completion republishes only when a tool actually moved the goal/loop/heartbeat state.
+ control_revision: str = ""
def __post_init__(self):
self.controls = PendingControls(self.event_stream)
diff --git a/gateway/session_control_actions.py b/gateway/session_control_actions.py
index 1a27557ee23..5fdf5536af0 100644
--- a/gateway/session_control_actions.py
+++ b/gateway/session_control_actions.py
@@ -72,13 +72,14 @@ async def _subgoal(connection, ref, params, action, args):
return {'type': 'exec', 'output': output}
-def publish(authority, session_id, *, only_if_present=False):
+def publish(authority, session_id, *, only_if_present=False, only_if_changed=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).
+ Desktop, Ink and the classic CLI 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, a tool that changed it mid-turn.
+ ``only_if_present`` skips a session with no automation state (a plain turn's event stream stays
+ unchanged); ``only_if_changed`` also skips one whose snapshot matches the last one published.
"""
live = authority.sessions.get(session_id) if authority is not None else None
if live is None:
@@ -90,8 +91,10 @@ def publish(authority, session_id, *, only_if_present=False):
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')
+ if (only_if_present and not snapshot['revision']) or (only_if_changed and snapshot['revision'] == live.control_revision):
+ return
+ live.control_revision = snapshot['revision']
+ live.event_stream.publish(session_id, {'control': snapshot}, event_type='session.control.update')
async def control(connection, ref, params):
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index 2119c21dadc..f1b552c2306 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -733,6 +733,7 @@ class CLIAgentSetupMixin:
# ``cli._active_agent_ref`` None forever — so memory shutdown never ran on /exit (#49287).
import cli as _cli
_cli._active_agent_ref = self.agent
+ self.agent.control_update_callback = self._mark_automation_stale
# Seed the agent's once-per-lifecycle auto_load cache with the bytes the preload
# thread rendered, so the shared prompt path never re-reads config or skill files.
_auto_result = getattr(self, "_auto_load_skills_result", None)
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.py
index 8e8c7e0418a..b3050c24b38 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -528,6 +528,11 @@ class CLILoopsMixin:
return self._session_bound_manager(
attr, label, (lambda: lambda sid: remote(sid, connection)) if gateway else local)
+ def _mark_automation_stale(self) -> None:
+ """Agent thread: the gateway published this session's goal/loop state mid-turn (a tool moved it).
+ The dock re-reads the mirrored managers on its next spinner-thread poll (``cli_session_dock``)."""
+ self._automation_stale = True
+
def _get_goal_manager(self):
"""GoalManager bound to the current session_id (see ``_session_bound_manager``)."""
def max_turns():
diff --git a/hermes_cli/cli_session_dock.py b/hermes_cli/cli_session_dock.py
index b5538e6d5c2..268db5a60ac 100644
--- a/hermes_cli/cli_session_dock.py
+++ b/hermes_cli/cli_session_dock.py
@@ -14,6 +14,18 @@ import time
QUEUE_ROWS = 3
+def sync_automation(cli) -> None:
+ """Re-read the goal/loop managers' mirrored state once after the gateway flagged it changed mid-turn
+ (``_mark_automation_stale``): one ``state`` round trip per change, none while nothing moves."""
+ if not getattr(cli, "_automation_stale", False):
+ return
+ cli._automation_stale = False
+ for attr in ("_goal_manager", "_loop_manager"):
+ mgr = getattr(cli, attr, None)
+ if mgr is not None and mgr.session_id == getattr(cli, "session_id", None):
+ mgr.refresh()
+
+
def goal_line(cli) -> str:
"""``GoalManager.status_line()`` for an active or paused goal, else ``''``.
diff --git a/hermes_cli/cli_subagent_monitor.py b/hermes_cli/cli_subagent_monitor.py
index 18126e89fef..bc2dabe3893 100644
--- a/hermes_cli/cli_subagent_monitor.py
+++ b/hermes_cli/cli_subagent_monitor.py
@@ -80,6 +80,7 @@ class SubagentMonitor:
row['key'] = row['subagent_id']
row.pop('running_seconds', None)
processes = procs.process_rows(now)
+ session_rows.sync_automation(self.cli)
goal = session_rows.goal_line(self.cli)
loop_badge, loop, loop_prompt = session_rows.loop_row(self.cli, now)
queued = session_rows.queued_prompts(self.cli)
diff --git a/hermes_cli/gateway_agent.py b/hermes_cli/gateway_agent.py
index 1565322a535..e1b89b88067 100644
--- a/hermes_cli/gateway_agent.py
+++ b/hermes_cli/gateway_agent.py
@@ -137,6 +137,9 @@ class GatewayAgent:
# (``request.cancel``: another viewer answered, the turn ended); called off the agent thread.
self.modal_withdraw_callback = modal_withdraw_callback
self._open_request = None # (request id, method) of the server request a modal is answering
+ # Set by the CLI after construction: a ``session.control.update`` mid-turn (a tool moved the goal
+ # or loop) marks its mirrored managers stale; the dock re-reads them off this thread.
+ self.control_update_callback = None
self.suppress_status_output = False
self._print_fn = None
# Inert private attributes main's CLI writes (CALLMAP §3.2).
@@ -946,6 +949,10 @@ class GatewayAgent:
if isinstance(payload.get("todos"), list):
self._todo_store.items = list(payload["todos"])
+ def _on_control_update(self, payload, stream_callback, starts):
+ if self.control_update_callback is not None:
+ self.control_update_callback()
+
def _on_thinking(self, payload, stream_callback, starts):
if self.thinking_callback is not None:
self.thinking_callback(payload.get("text") or "")
@@ -1304,6 +1311,7 @@ _HANDLERS = {
"tool.start": GatewayAgent._on_tool_start,
"tool.complete": GatewayAgent._on_tool_complete,
"todo.updated": GatewayAgent._on_todo,
+ "session.control.update": GatewayAgent._on_control_update,
"thinking.delta": GatewayAgent._on_thinking,
"reasoning.delta": GatewayAgent._on_reasoning,
"reasoning.available": GatewayAgent._on_reasoning_available,
diff --git a/hermes_cli/goals.py b/hermes_cli/goals.py
index c00618e36bf..96ee695e28d 100644
--- a/hermes_cli/goals.py
+++ b/hermes_cli/goals.py
@@ -1099,6 +1099,10 @@ class GoalManager:
self.default_max_turns = int(default_max_turns or DEFAULT_MAX_TURNS)
self._state: Optional[GoalState] = load_goal(session_id)
+ def refresh(self) -> None:
+ """Re-read state from the DB (another writer, e.g. a tool, moved it)."""
+ self._state = load_goal(self.session_id)
+
# --- introspection ------------------------------------------------
@property
diff --git a/tests/gateway/test_local_viewer_events_turn.py b/tests/gateway/test_local_viewer_events_turn.py
index 0543b0015b8..1334e183ea9 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -33,6 +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
return turn
diff --git a/tests/gateway/test_session_viewer_automation.py b/tests/gateway/test_session_viewer_automation.py
index 17dd71909f0..542be62f8ea 100644
--- a/tests/gateway/test_session_viewer_automation.py
+++ b/tests/gateway/test_session_viewer_automation.py
@@ -145,3 +145,21 @@ async def test_a_read_that_clears_a_goal_barrier_repaints_the_other_viewers(owne
await owner.call(kind, call)
assert len(updates) == 1 and 'wait_barrier' not in updates[0]['control']['goal']
assert updates[0]['control']['loop']['deferred_by_goal'] is True
+
+
+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
+ from hermes_cli.goals import GoalManager
+ 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)
+ 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)
+ assert [u['control']['goal']['subgoals'] for u in updates] == [['tests pass']]
diff --git a/tests/hermes_cli/test_session_dock.py b/tests/hermes_cli/test_session_dock.py
index abea3fdc838..ddfbdb0b503 100644
--- a/tests/hermes_cli/test_session_dock.py
+++ b/tests/hermes_cli/test_session_dock.py
@@ -133,3 +133,26 @@ def test_dock_loop_row_counts_down_to_the_next_wakeup(hermes_home):
assert dock.refresh(now=due) and dock.loop == "⏸ loop paused · user-paused · 1 run · check the deploy"
mgr.clear()
assert dock.refresh(now=due) and not dock.has_rows
+
+
+def test_dock_repaints_a_goal_a_tool_changed_mid_turn(hermes_home):
+ """A plugin tool adds criteria to the goal mid-turn: the gateway's ``session.control.update`` frame
+ marks the CLI's mirrored manager stale and the dock's next poll re-reads it (once), not at turn end."""
+ from hermes_cli.cli_loops_mixin import CLILoopsMixin
+ from hermes_cli.cli_subagent_monitor import SubagentMonitor
+ from hermes_cli.gateway_agent import _HANDLERS
+ from hermes_cli.goals import GoalManager
+
+ mgr = GoalManager(session_id="sid-a")
+ mgr.set("ship the dock feature")
+ cli = SimpleNamespace(agent=None, session_id="sid-a", _goal_manager=mgr, _pending_input=queue.Queue())
+ dock = SubagentMonitor(cli)
+ dock.refresh()
+ GoalManager(session_id="sid-a").add_subgoal("tests pass") # the tool's own writer
+ dock.refresh()
+ assert "subgoal" not in dock.dock_text(columns=80, rows=40)
+
+ agent = SimpleNamespace(control_update_callback=lambda: CLILoopsMixin._mark_automation_stale(cli))
+ _HANDLERS["session.control.update"](agent, {"control": {}}, None, {})
+ assert dock.refresh() and "1 subgoal" in dock.dock_text(columns=80, rows=40).splitlines()[0]
+ assert cli._automation_stale is False
diff --git a/tui_gateway/methods_session_control.py b/tui_gateway/methods_session_control.py
index 4f9160a886d..3cff6f80c71 100644
--- a/tui_gateway/methods_session_control.py
+++ b/tui_gateway/methods_session_control.py
@@ -214,18 +214,22 @@ def _goal_blocks_loop_tick(session_key: str) -> bool:
_SESSION_CONTROL_SLASHES = frozenset({"goal", "heartbeat", "loop", "subgoal"})
-def _publish_session_control_snapshot(sid: str, session: dict | None, *, only_if_present: bool = False) -> None:
+def _publish_session_control_snapshot(sid: str, session: dict | None, *, only_if_present: bool = False,
+ only_if_changed: bool = False) -> None:
"""Best-effort ``session.control.update`` for one live session. Also called after the post-turn hooks,
because the goal judge and loop tick evaluation mutate persisted state AFTER ``message.complete`` — a
client refresh keyed on that event reads the pre-judge turn count. ``only_if_present`` keeps the
- post-turn event stream of a session with no automation state byte-identical to today's."""
+ post-turn event stream of a session with no automation state byte-identical to today's;
+ ``only_if_changed`` (every tool completion) also skips a snapshot equal to the last one published."""
if not session or not (session_key := str(session.get("session_key") or "")):
return
try:
with _session_profile_runtime_scope(session):
control = _snapshot_control(session_key)
- if only_if_present and not control["revision"]:
+ if (only_if_present and not control["revision"]) or (
+ only_if_changed and control["revision"] == session.get("control_revision", "")):
return
+ session["control_revision"] = control["revision"]
_emit("session.control.update", sid, {"control": control})
except Exception:
logger.debug("session.control.update publish failed for %s", sid, exc_info=True)
diff --git a/tui_gateway/tool_progress.py b/tui_gateway/tool_progress.py
index 6396e162c53..b0b545de12a 100644
--- a/tui_gateway/tool_progress.py
+++ b/tui_gateway/tool_progress.py
@@ -364,6 +364,10 @@ def _on_tool_complete(sid: str, tool_call_id: str, name: str, args: dict, result
# every client reconcile without parsing tool args.
if todo_state is not None:
_emit("todo.updated", sid, todo_state)
+ # A tool (a plugin adding goal criteria, parking the goal) can move automation state mid-turn: repaint
+ # the cards now, not at turn end. Revision-gated, so an ordinary tool emits nothing.
+ if session is not None:
+ _publish_session_control_snapshot(sid, session, only_if_changed=True)
# ── _on_tool_progress dispatch: each handler takes (sid, name, preview, kw) ─────────────────────
diff --git a/ui-tui/src/__tests__/goalBar.test.tsx b/ui-tui/src/__tests__/goalBar.test.tsx
index 259278e4663..155b840c7e3 100644
--- a/ui-tui/src/__tests__/goalBar.test.tsx
+++ b/ui-tui/src/__tests__/goalBar.test.tsx
@@ -46,6 +46,14 @@ it('shows a standing goal (active, parked, paused) and hides it once done or cle
detail: 'budget · 3/20 turns',
label: 'goal paused'
})
+ expect(
+ goalLine(
+ goal({
+ gates: [{ attempts: 0, command: 'pytest', max_retries: 2, timeout_seconds: 60 }],
+ subgoals: ['tests pass', 'docs updated']
+ })
+ )
+ ).toMatchObject({ detail: '3/20 turns · 2 subgoals · 1 gate' })
expect(goalLine(goal({ status: 'done' }))).toBeNull()
expect(goalLine(null)).toBeNull()
diff --git a/ui-tui/src/app/goalStatus.ts b/ui-tui/src/app/goalStatus.ts
index cb284152760..6dfe76bc08f 100644
--- a/ui-tui/src/app/goalStatus.ts
+++ b/ui-tui/src/app/goalStatus.ts
@@ -27,14 +27,20 @@ export interface GoalLine {
const clock = (epochSeconds: number) =>
new Date(epochSeconds * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
-/** `⊙ goal · 3/20 turns · <title>` for an active goal, `⏳ goal parked` / `⏸ goal paused` with the
+const count = (n: number, noun: string) => (n ? `${n} ${noun}${n === 1 ? '' : 's'}` : '')
+
+/** `⊙ goal · 3/20 turns · 2 subgoals · <title>` for an active goal, `⏳ goal parked` / `⏸ goal paused` with the
* reason while held, `null` once it is done or cleared (the transcript carries the verdict). */
export function goalLine(goal: GoalSnapshot | null): GoalLine | null {
if (!goal || (goal.status !== 'active' && goal.status !== 'paused')) {
return null
}
- const turns = `${goal.turns_used}/${goal.max_turns} turns`
+ // Subgoals and gates as the CLI dock counts them: a tool adding criteria mid-turn shows up here.
+ const turns = [`${goal.turns_used}/${goal.max_turns} turns`, count(goal.subgoals.length, 'subgoal'), count(goal.gates.length, 'gate')]
+ .filter(Boolean)
+ .join(' · ')
+
const barrier = goal.status === 'active' ? goal.wait_barrier : null
if (barrier) {
diff --git a/website/docs/user-guide/tui.md b/website/docs/user-guide/tui.md
index ad695665481..dacedcbb8e0 100644
--- a/website/docs/user-guide/tui.md
+++ b/website/docs/user-guide/tui.md
@@ -105,7 +105,7 @@ Keybindings match the [Classic CLI](cli.md#keybindings) exactly. The only behavi
On macOS, `F7` means the physical F7 function key. MacBook keyboards may use that row for system controls instead; hold **Fn** (the **globe** key on newer keyboards) while pressing **F7**, or enable **Use F1, F2, etc. keys as standard function keys** in **System Settings → Keyboard → Keyboard Shortcuts → Function Keys**. If the terminal still does not forward it, use the equivalent **Ctrl+R** binding below.
- **`Ctrl+T`** expands the automatic live-work dock (subagents, plus a **Processes** block for `terminal(background=true)` spawns) into the full-height `/agents` roster. Select a worker and press **Enter** (or **`t`**) for its live transcript, **`d`** for rich details, **`e`** to steer, or **`x`** to stop it. The dock fits its row count to terminal height and preserves your composer draft. See [Monitoring subagents](./features/delegation.md#monitoring-running-subagents-agents).
-- A standing **`/goal`** gets its own row above the live dock (`⊙ goal · 3/20 turns · …`, or `⏳ goal parked` / `⏸ goal paused` with the reason); it leaves once the goal is done or cleared. Queued follow-ups are listed above it.
+- A standing **`/goal`** gets its own row above the live dock (`⊙ goal · 3/20 turns · 2 subgoals · …`, or `⏳ goal parked` / `⏸ goal paused` with the reason); it repaints as soon as anything changes the goal, a tool mid-turn included, and leaves once the goal is done or cleared. Queued follow-ups are listed above it.
- **`Ctrl+R`** toggles the live dock between its default preview and one summary line. **`F7`** remains an optional alias where the terminal sends function keys through. This does not open the monitor or move composer focus; the choice lasts for this TUI process without changing config.
- **Mouse drag** highlights text with a uniform selection background.
- **`Cmd+V` / `Ctrl+V`** first tries normal text paste, then falls back to OSC52/native clipboard reads, and finally image attach when the clipboard or pasted payload resolves to an image.