The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui): record why an orphaned build left the session without an agent
kshitijk4poorcb6ab42257a6
diff --git a/tests/tui_gateway/test_none_agent_turn_guard.py b/tests/tui_gateway/test_none_agent_turn_guard.pyindex 7ac3ab51c7e..14bb573dff8 100644--- a/tests/tui_gateway/test_none_agent_turn_guard.py+++ b/tests/tui_gateway/test_none_agent_turn_guard.py@@ -96,3 +96,32 @@ def test_replaced_record_build_records_reason_and_leaves_agent_unset(monkeypatchassert session["agent"] is Noneassert session["agent_ready"].is_set()assert session["agent_error"] == AGENT_BUILD_ABANDONED+++def test_build_finishing_after_close_records_reason_and_closes_orphan(monkeypatch, tmp_path):+ """A build that finishes after ``session.close`` popped its record closes the late agent and+ records why nothing attached, exactly like the replaced-before-attach exit (#49852)."""+ import tui_gateway.entry as entry++ monkeypatch.setattr(server.threading, "Thread", _InlineThread)+ monkeypatch.setattr(entry, "ensure_mcp_discovery_started", lambda: None)+ closed: list[str] = []+ sid = "closed-mid-build"++ def _make_agent_then_close(_sid, _key, **_kwargs):+ with server._sessions_lock: # session.close lands while the agent is being constructed+ server._sessions.pop(sid, None)+ return types.SimpleNamespace(close=lambda: closed.append("closed"))++ monkeypatch.setattr(server, "_make_agent", _make_agent_then_close)+ session = _session(None, agent_ready=threading.Event(), cwd=str(tmp_path), profile_home=None)+ server._sessions[sid] = session+ try:+ server._start_agent_build(sid, session)+ finally:+ server._sessions.pop(sid, None)++ assert closed == ["closed"]+ assert session["agent"] is None+ assert session["agent_ready"].is_set()+ assert session["agent_error"] == AGENT_BUILD_ABANDONEDdiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex bae5019d4e9..a6868375706 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1185,6 +1185,9 @@ def _start_agent_build(sid: str, session: dict) -> None:# an agent that did not exist yet. Release the orphan immediately and do not keep wiring# workers/callbacks for a dead session (#49852).if not _attach_built_agent(sid, current, agent):+ # Same contract as the replaced-before-attach exit above: a turn admitted against+ # this record must refuse with the real reason rather than a generic missing agent.+ current["agent_error"] = AGENT_BUILD_ABANDONEDwith contextlib.suppress(Exception):if hasattr(agent, "close"):agent.close()