Skip to content

The agent that grows with you

feat(gateway): local-viewer tool.complete carries inline_diff; the todo tool publishes todo.updated

Teknium259ce3e59e74
diff --git a/gateway/local_viewer_events.py b/gateway/local_viewer_events.py
index de18b94ccbb..303b2541e26 100644
--- a/gateway/local_viewer_events.py
+++ b/gateway/local_viewer_events.py
@@ -81,11 +81,55 @@ def restore(agent, previous: dict | None) -> None:
setattr(agent, name, value)
-def note_tool_start(turn, call_id) -> None:
- """Monotonic start time of one call, for ``tool.complete.duration_s``."""
- turn.__dict__.setdefault("_local_tool_starts", {})[str(call_id or "")] = time.monotonic()
-
-
-def complete_fields(turn, call_id) -> dict:
- started = turn.__dict__.setdefault("_local_tool_starts", {}).pop(str(call_id or ""), None)
- return {"duration_s": (time.monotonic() - started) if started is not None else None}
+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
+ writes, so the gateway owns the snapshot the classic CLI used to take in process."""
+ key = str(call_id or "")
+ turn.__dict__.setdefault("_local_tool_starts", {})[key] = time.monotonic()
+ if tool_name is None:
+ return
+ try:
+ from agent.display import capture_local_edit_snapshot
+ snapshot = capture_local_edit_snapshot(tool_name, args if isinstance(args, dict) else {},
+ task_id=turn._ctx.session_id)
+ except Exception:
+ snapshot = None
+ if snapshot is not None:
+ turn.__dict__.setdefault("_local_edit_snapshots", {})[key] = snapshot
+
+
+def complete_fields(turn, call_id, tool_name=None, args=None, result=None) -> dict:
+ """``duration_s``, ``inline_diff`` (the rendered edit diff main's CLI printed after a write,
+ ``None`` when there is none) and, for the todo tool, the full ``todos`` snapshot."""
+ key = str(call_id or "")
+ started = turn.__dict__.setdefault("_local_tool_starts", {}).pop(key, None)
+ fields = {"duration_s": (time.monotonic() - started) if started is not None else None}
+ if tool_name is None:
+ return fields
+ snapshot = turn.__dict__.setdefault("_local_edit_snapshots", {}).pop(key, None)
+ rendered: list[str] = []
+ try:
+ from agent.display import render_edit_diff_with_delta
+ render_edit_diff_with_delta(tool_name, result, function_args=args if isinstance(args, dict) else {},
+ snapshot=snapshot, print_fn=rendered.append)
+ except Exception:
+ rendered = []
+ fields["inline_diff"] = "\n".join(rendered) if rendered else None
+ todo = todo_state(tool_name, result)
+ if todo is not None:
+ fields.update(todo)
+ return fields
+
+
+def todo_state(tool_name, result) -> dict | None:
+ """The client-safe ``{todos, revision}`` snapshot a todo tool's result carries, else None."""
+ from tools.todo_tool import is_todo_tool_name
+ if not is_todo_tool_name(tool_name):
+ return None
+ import json
+ from tui_gateway.tool_progress import _normalize_todo_state
+ try:
+ return _normalize_todo_state(json.loads(result) if isinstance(result, str) else result)
+ except (TypeError, ValueError):
+ return None
diff --git a/gateway/run_turn_progress.py b/gateway/run_turn_progress.py
index e66a5e17211..97f2f47c84a 100644
--- a/gateway/run_turn_progress.py
+++ b/gateway/run_turn_progress.py
@@ -826,7 +826,7 @@ class GatewayTurnProgressMixin:
"""Compose the voice ack + native task-card start consumers."""
if local_viewer_turn(self):
from gateway import local_viewer_events
- local_viewer_events.note_tool_start(self, call_id)
+ local_viewer_events.note_tool_start(self, call_id, tool_name, args)
self._publish_execution("tool.start", _tool_lifecycle_payload(call_id, tool_name, args))
self._publish_api_tool("tool.start", call_id, tool_name, args)
if self._ctx._voice_ack_guild[0] is not None:
@@ -844,8 +844,11 @@ class GatewayTurnProgressMixin:
payload = _tool_complete_payload(call_id, tool_name, args, result, is_error=is_error, verbose=verbose)
if local_viewer_turn(self):
from gateway import local_viewer_events
- payload.update(local_viewer_events.complete_fields(self, call_id))
+ payload.update(local_viewer_events.complete_fields(self, call_id, tool_name, args, result))
self._publish_execution("tool.complete", payload)
+ if local_viewer_turn(self) and isinstance(payload.get("todos"), list):
+ # 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 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 9e443204084..6ff450de3d4 100644
--- a/tests/gateway/test_local_viewer_events_turn.py
+++ b/tests/gateway/test_local_viewer_events_turn.py
@@ -184,3 +184,45 @@ async def test_show_reasoning_is_a_session_scoped_config_key(tmp_path, monkeypat
assert bad['error']['message'] == 'invalid_params', bad
finally:
await connection.close()
+
+
+def test_a_local_write_ships_its_inline_diff_snapshotted_before_the_tool_ran(tmp_path):
+ published = []
+ turn = _turn(Platform.LOCAL, published)
+ target = tmp_path / 'notes.txt'
+ target.write_text('alpha\nbeta\n')
+ args = {'path': str(target), 'content': 'alpha\ngamma\n'}
+ turn.combined_tool_start_callback('w1', 'write_file', args)
+ target.write_text(args['content']) # the tool writes after the start callback
+ turn.combined_tool_complete_callback('w1', 'write_file', args, '{"bytes_written": 12}')
+ complete = next(payload for kind, payload in published if kind == 'tool.complete')
+ diff = complete['inline_diff']
+ assert isinstance(diff, str) and '-beta' in diff and '+gamma' in diff, diff
+ from tui_gateway.contracts.registry import EVENTS
+ EVENTS['tool.complete'].payload.model_validate({k: complete[k] for k in ('tool_id', 'name', 'duration_s', 'inline_diff')})
+
+
+def test_the_todo_tool_publishes_the_full_snapshot():
+ import json
+ published = []
+ turn = _turn(Platform.LOCAL, published)
+ todos = [{'id': '1', 'content': 'ship', 'status': 'in_progress'}]
+ turn.combined_tool_start_callback('t1', 'todo', {'todos': todos})
+ turn.combined_tool_complete_callback('t1', 'todo', {'todos': todos}, json.dumps({'todos': todos, 'revision': 3}))
+ kinds = [kind for kind, _ in published]
+ assert kinds == ['tool.start', 'tool.complete', 'todo.updated']
+ assert published[-1][1] == {'todos': todos, 'revision': 3}
+ assert published[1][1]['inline_diff'] is None and published[1][1]['todos'] == todos
+ from tui_gateway.contracts.registry import EVENTS
+ EVENTS['todo.updated'].payload.model_validate(published[-1][1])
+
+
+def test_messaging_tool_events_carry_no_diff_or_todo_frame():
+ import json
+ published = []
+ turn = _turn(Platform.TELEGRAM, published)
+ todos = [{'id': '1', 'content': 'ship', 'status': 'pending'}]
+ turn.combined_tool_start_callback('t1', 'todo', {'todos': todos})
+ turn.combined_tool_complete_callback('t1', 'todo', {'todos': todos}, json.dumps({'todos': todos, 'revision': 1}))
+ assert [kind for kind, _ in published] == ['tool.start', 'tool.complete']
+ assert 'inline_diff' not in published[1][1] and 'todos' not in published[1][1]