The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(tui_gateway): reopen a finalized row before the isolated compute-host dispatch too (#85303 review)
Brooklyn Nicholsondfdf602642be
diff --git a/tests/tui_gateway/test_resume_readonly_mount.py b/tests/tui_gateway/test_resume_readonly_mount.pyindex 939400dc906..611967dd6ab 100644--- a/tests/tui_gateway/test_resume_readonly_mount.py+++ b/tests/tui_gateway/test_resume_readonly_mount.py@@ -3,7 +3,11 @@ hydration / the lazy watch path must NOT clear ``ended_at``/``end_reason`` — ofirst real turn (prompt.submit) reopens the row, so DB-derived liveness cannot re-lighta finished session just because someone opened it."""+import io+import jsonimport threading+import time+import typesimport pytest@@ -11,6 +15,20 @@ from hermes_state import SessionDBfrom tui_gateway import server+def _frames(out: io.StringIO) -> list[dict]:+ return [json.loads(line) for line in out.getvalue().splitlines() if line.strip()]+++def _wait_for(out: io.StringIO, predicate, timeout: float = 10.0) -> dict:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ for frame in _frames(out):+ if predicate(frame):+ return frame+ time.sleep(0.01)+ raise AssertionError(f"timed out; saw={_frames(out)}")++def _finalized_db(tmp_path, *, ended_reason="agent_close"):home = tmp_path / "home"home.mkdir(exist_ok=True)@@ -34,7 +52,7 @@ def _mount(monkeypatch, db, home, tmp_path, *, defer_history=False):monkeypatch.setattr(server, "_schedule_session_cap_enforcement", lambda: None)monkeypatch.setattr(server, "_maybe_schedule_auto_continue", lambda *args: None)monkeypatch.setattr(server, "_start_agent_build", lambda *args: built.set())- monkeypatch.setattr(server, "_emit", lambda kind, sid, payload: events.append((kind, payload)))+ monkeypatch.setattr(server, "_emit", lambda kind, sid, payload=None: events.append((kind, payload)))return events, built@@ -110,3 +128,82 @@ def test_reopen_if_finalized_leaves_live_rows_untouched(tmp_path):row = db.get_session("live")assert row["ended_at"] is None and row["end_reason"] is Nonedb.close()+++def test_isolated_dispatch_reopens_a_finalized_row(tmp_path, monkeypatch):+ """The compute-host seam: prompt.submit returns BEFORE its persist on an isolated turn+ (the child process runs the turn), so the reopen must live on the dispatch path every+ turn crosses, not in the skipped persist. A finalized row a lazy mount is about to send+ through must be reopened before the child writes into it."""+ from tui_gateway import server++ db, home = _finalized_db(tmp_path)+ events, built = _mount(monkeypatch, db, home, tmp_path)+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda session, cfg=None: True)+ monkeypatch.setattr(server, "_load_dashboard_process_isolation_config", lambda: {"turn_isolation": True})+ dispatched = {}+ monkeypatch.setattr(server, "_submit_prompt_to_compute_host",+ lambda rid, sid, session, text, **kw: dispatched.update(sid=sid, text=text)+ or {"result": {"status": "streaming", "turn_isolation": True}})+ monkeypatch.setattr(server, "_handle_busy_submit", lambda *a, **k: None)+ sid = None+ try:+ # Mount first (read-only): the submit then routes through the mounted session record.+ mounted = server.handle_request({"id": "resume", "method": "session.resume", "params": {+ "session_id": "finalized", "source": "desktop", "lazy": True}})+ assert mounted is not None and "error" not in mounted, mounted+ sid = mounted["result"]["session_id"]+ session = server._sessions[sid]+ session["agent"] = types.SimpleNamespace(session_id="finalized", clear_interrupt=lambda: None)+ session["agent_ready"] = threading.Event()+ response = server.handle_request({"id": "submit", "method": "prompt.submit", "params": {+ "session_id": sid, "text": "one more thing"}})+ assert response is not None and "error" not in response, response+ assert dispatched.get("text") == "one more thing"+ row = db.get_session("finalized")+ assert row["ended_at"] is None, (+ "an isolated (compute-host) dispatch is a real turn: the finalized row must be "+ "reopened even though prompt.submit returns before its own persist (#85303)")+ finally:+ if sid is not None:+ server._sessions.pop(sid, None)+ db.close()+++def test_compute_host_child_turn_reopens_a_finalized_row(tmp_path, monkeypatch):+ """The child-process half: the compute host builds its own session record and runs+ ``_run_prompt_submit`` directly, so the reopen at the dispatch seam fires there too —+ the turn's transcript is written into a live row even though the child never saw+ prompt.submit."""+ from tui_gateway import server+ from tui_gateway.compute_host import ComputeHost++ db, home = _finalized_db(tmp_path)+ events, built = _mount(monkeypatch, db, home, tmp_path)+ # The child-side session record: built from a turn.start frame, agent already attached.+ agent = types.SimpleNamespace(session_id="finalized", clear_interrupt=lambda: None)+ session = {+ "agent": agent, "session_key": "finalized", "history": [], "history_lock": threading.Lock(),+ "history_version": 0, "running": False, "attached_images": [], "image_counter": 0,+ "cols": 80, "slash_worker": None, "show_reasoning": False, "tool_progress_mode": "all",+ "inflight_turn": None, "created_at": time.time(), "last_active": time.time(),+ }+ server._sessions["child-sid"] = session+ # Cut the turn right after admission (the reopen runs BEFORE admission).+ import tui_gateway.prompt_turn as prompt_turn+ monkeypatch.setattr(server, "_prepare_turn_input", lambda *a, **k: None, raising=False)+ monkeypatch.setattr(prompt_turn, "_prepare_turn_input", lambda *a, **k: None, raising=False)+ out = io.StringIO()+ host = ComputeHost(stdout=out, heartbeat_secs=0)+ try:+ host.handle_frame({"type": "turn.start", "sid": "child-sid", "request_id": "t",+ "text": "hello", "session_key": "finalized", "source": "desktop"})+ _wait_for(out, lambda f: f["type"] == "turn.end", timeout=10.0)+ row = db.get_session("finalized")+ assert row["ended_at"] is None, (+ "a turn run by the compute-host child is a real turn: the finalized row must be "+ "reopened before the child's transcript writes land (#85303)")+ finally:+ server._sessions.pop("child-sid", None)+ host.close()+ db.close()diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 4f5dd16a8af..b4d8686fb09 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -782,6 +782,19 @@ def _(rid, params: dict) -> dict:if turn_author:logger.debug("isolated compute turns carry no author yet; the turn from %s runs unattributed",turn_author.get("id"))+ # The isolated dispatch returns BELOW before the inline persist, so the reopen+ # cannot live only in _persist_session_row_for_submit: the turn is already+ # admitted here (running, in flight, active-slot lease claimed, truncation+ # applied inline), and the child's transcript writes must land in a live row+ # (#85303 review: the early return made _reopen_if_finalized unreachable on+ # this path). Best-effort like the helper: a failed read never blocks the send.+ try:+ with _session_db(session) as db:+ if db is not None:+ _reopen_if_finalized(db, str(session.get("session_key") or ""))+ except Exception:+ logger.debug("finalized-session reopen before isolated dispatch failed for %s",+ sid, exc_info=True)isolated_response = _submit_prompt_to_compute_host(rid, sid, session, text, display_kind=display_kind, display_metadata=display_metadata)if not isolated_response.get("error"):diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.pyindex 6152dd0c9f6..acd10860e8c 100644--- a/tui_gateway/prompt_turn.py+++ b/tui_gateway/prompt_turn.py@@ -1120,6 +1120,17 @@ def _run_prompt_submit(logger.warning("prompt dispatch: session store unavailable for %s — this turn may not persist",session.get("session_key") or sid)+ else:+ # The first real turn reopens a finalized row (#85303): resume/mount is read-only, so+ # the row's ended_at is cleared HERE — at the one seam every dispatch crosses, not in+ # prompt.submit's persist. The isolated compute-host dispatch returns from prompt.submit+ # before that persist (the child process runs the turn), so a reopen placed there never+ # fires for isolated turns; here it covers inline and isolated dispatch equally, plus+ # the synthesized turns that bypass prompt.submit entirely. Best-effort, like the+ # reopen helper itself: a failed read never blocks the turn.+ with _session_db(session) as db:+ if db is not None:+ _reopen_if_finalized(db, str(session.get("session_key") or ""))admitted = _admit_prompt_turn(sid, session, text, image_paths, queued_prompt_generation, display_kind, display_metadata)if admitted is None: