The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): one lock around read-compare-emit so a tool's older goal snapshot can't land after a user change
Tekniume5619a7344ee
diff --git a/tests/tui_gateway/test_session_control.py b/tests/tui_gateway/test_session_control.pyindex 27ae37c6c8f..fd69b4a7d9c 100644--- a/tests/tui_gateway/test_session_control.py+++ b/tests/tui_gateway/test_session_control.py@@ -390,6 +390,37 @@ class TestUpdatePublication:updates = [e for e in emitted if e[0] == "session.control.update"]assert updates == [("session.control.update", sid, {"control": response["result"]["control"]})]+ def test_a_tool_completion_racing_a_user_change_never_publishes_the_older_snapshot(self, server, session, monkeypatch):+ """The tool-completion republish runs on the agent thread: if it read the goal just before the user+ added a criterion, that older snapshot must not be emitted after the user's (Ink/Desktop keep the last)."""+ sid, key, entry = session+ _save_goal(key)+ server._publish_session_control_snapshot(sid, entry)+ emitted = self._capture(server, monkeypatch)+ read, release, real_snapshot = threading.Event(), threading.Event(), server._snapshot_control++ def snapshot_then_stall(session_key): # scheduling only: the tool thread stalls after its read+ control = real_snapshot(session_key)+ if threading.current_thread().name == "tool":+ read.set()+ release.wait(5)+ return control+ monkeypatch.setattr(server, "_snapshot_control", snapshot_then_stall)+ tool = threading.Thread(name="tool", target=server._on_tool_complete,+ args=(sid, "call", "terminal", {"command": "true"}, '{"exit_code": 0}'))+ tool.start()+ assert read.wait(5)+ user = threading.Thread(target=_call, args=(server, "session.control"),+ kwargs={"session_id": sid, "action": "subgoal.add", "args": {"text": "newer criterion"}})+ user.start()+ user.join(0.5)+ release.set()+ tool.join(5)+ user.join(5)+ updates = [payload["control"]["goal"]["subgoals"] for event, _sid, payload in emitted+ if event == "session.control.update"]+ assert updates[-1] == ["newer criterion"]+@pytest.mark.parametrize("name,arg", [("goal", "pause"), ("loop", "pause")])def test_typed_slash_via_command_dispatch_publishes_the_new_state(self, server, session, monkeypatch, name, arg):"""/goal and /loop never reach the slash worker (``_PENDING_INPUT_COMMANDS``) — the built-in path mustdiff --git a/tui_gateway/methods_session_control.py b/tui_gateway/methods_session_control.pyindex 3c90342b21c..8f6a76aebae 100644--- a/tui_gateway/methods_session_control.py+++ b/tui_gateway/methods_session_control.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport hashlibimport jsonimport logging+import threadingimport timefrom .method_ctx import HandlerRegistry, bind_module@@ -214,6 +215,12 @@ def _goal_blocks_loop_tick(session_key: str) -> bool:_SESSION_CONTROL_SLASHES = frozenset({"goal", "heartbeat", "loop", "subgoal"})+# Tool completions publish from the agent thread while control actions and slash commands publish from+# RPC threads: the snapshot read, the revision compare and the emit happen as one step, so an update read+# before a user's change can never be emitted after it.+_PUBLISH_LOCK = threading.Lock()++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,@@ -224,13 +231,14 @@ def _publish_session_control_snapshot(sid: str, session: dict | None, *, only_ifif not session or not (session_key := str(session.get("session_key") or "")):returntry:- with _session_profile_runtime_scope(session):- control = _snapshot_control(session_key)- 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})+ with _PUBLISH_LOCK:+ with _session_profile_runtime_scope(session):+ control = _snapshot_control(session_key)+ 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)