Skip to content

The agent that grows with you

fix(tui): preserve queued image ownership

fyzanshaikd50858584c69
diff --git a/tests/test_tui_gateway_queue_on_busy.py b/tests/test_tui_gateway_queue_on_busy.py
index a2acfb51fd0..e6780e29764 100644
--- a/tests/test_tui_gateway_queue_on_busy.py
+++ b/tests/test_tui_gateway_queue_on_busy.py
@@ -39,6 +39,19 @@ def test_enqueue_pins_text_and_transport():
assert session["queued_prompt"] == {"text": "hello", "transport": "ws-1"}
+def test_enqueue_preserves_order_after_an_image_turn():
+ session = _session()
+ server._enqueue_prompt(session, "B", "ws-1")
+ server._enqueue_prompt(session, "C", "ws-1", image_paths=["/tmp/c.png"])
+ server._enqueue_prompt(session, "D", "ws-1")
+
+ assert session["queued_prompt"] == {"text": "B", "transport": "ws-1"}
+ assert session["queued_prompts"] == [
+ {"text": "C", "transport": "ws-1", "image_paths": ["/tmp/c.png"]},
+ {"text": "D", "transport": "ws-1"},
+ ]
+
+
# ── _handle_busy_submit (policy) ───────────────────────────────────────────
@@ -150,13 +163,92 @@ def test_busy_interrupt_mode_queues_multimodal_payload_instead_of_redirect(monke
assert session["queued_prompt"]["text"] == rich
+def test_busy_submit_claims_attached_image_for_queued_turn(monkeypatch):
+ """A pasted image belongs to its submitted prompt, not ambient session state."""
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")
+ redirected = []
+ interrupted = threading.Event()
+ agent = types.SimpleNamespace(
+ _supports_active_turn_redirect=True,
+ redirect=lambda text: redirected.append(text) or True,
+ interrupt=interrupted.set,
+ )
+ session = _session(agent=agent, running=True, attached_images=["/tmp/b.png"])
+ server._sessions["sid"] = session
+ try:
+ response = server._methods["prompt.submit"](
+ "r1", {"session_id": "sid", "text": "is this B?"}
+ )
+ finally:
+ server._sessions.pop("sid", None)
+
+ assert response["result"]["status"] == "queued"
+ assert redirected == []
+ assert not interrupted.wait(0.1)
+ assert session["attached_images"] == []
+ assert session["queued_prompt"] == {
+ "text": "is this B?",
+ "image_paths": ["/tmp/b.png"],
+ "transport": None,
+ }
+
+
+def test_busy_image_prompts_keep_b_and_c_attachments_in_submission_order(monkeypatch):
+ """A later paste must not replace the image already claimed by B."""
+ monkeypatch.setattr(server, "_load_busy_input_mode", lambda: "interrupt")
+ monkeypatch.setattr(
+ server,
+ "_run_prompt_submit",
+ lambda rid, sid, _session, text, **kwargs: dispatched.append((rid, sid, text, kwargs)),
+ )
+ agent = types.SimpleNamespace(
+ _supports_active_turn_redirect=True,
+ redirect=lambda _text: (_ for _ in ()).throw(AssertionError("images must queue")),
+ interrupt=lambda: None,
+ )
+ session = _session(agent=agent, running=True, attached_images=["/tmp/b.png"])
+ dispatched = []
+ server._sessions["sid"] = session
+ try:
+ server._methods["prompt.submit"]("b", {"session_id": "sid", "text": "B"})
+ session["attached_images"] = ["/tmp/c.png"]
+ server._methods["prompt.submit"]("c", {"session_id": "sid", "text": "C"})
+
+ assert session["queued_prompt"]["image_paths"] == ["/tmp/b.png"]
+ assert session["queued_prompts"] == [
+ {"text": "C", "image_paths": ["/tmp/c.png"], "transport": None}
+ ]
+
+ session["running"] = False
+ assert server._drain_queued_prompt("drain-b", "sid", session) is True
+ session["running"] = False
+ assert server._drain_queued_prompt("drain-c", "sid", session) is True
+ finally:
+ server._sessions.pop("sid", None)
+
+ assert dispatched == [
+ (
+ "drain-b",
+ "sid",
+ "B",
+ {"image_paths": ["/tmp/b.png"], "queued_prompt_generation": 0},
+ ),
+ (
+ "drain-c",
+ "sid",
+ "C",
+ {"image_paths": ["/tmp/c.png"], "queued_prompt_generation": 0},
+ ),
+ ]
+
+
# ── _drain_queued_prompt ───────────────────────────────────────────────────
def test_drain_fires_queued_prompt_and_claims_running(monkeypatch):
fired = {}
monkeypatch.setattr(
server, "_run_prompt_submit",
- lambda rid, sid, session, text: fired.update(rid=rid, sid=sid, text=text),
+ lambda rid, sid, session, text, **kwargs: fired.update(rid=rid, sid=sid, text=text),
)
session = _session(queued_prompt={"text": "go", "transport": "ws-9"})
@@ -167,6 +259,30 @@ def test_drain_fires_queued_prompt_and_claims_running(monkeypatch):
assert session["transport"] == "ws-9"
+def test_drain_compute_host_forwards_queued_image_paths(monkeypatch):
+ captured = {}
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda _session: True)
+ monkeypatch.setattr(
+ server,
+ "_submit_prompt_to_compute_host",
+ lambda rid, sid, session, text, **kwargs: captured.update(
+ rid=rid, sid=sid, text=text, image_paths=kwargs.get("image_paths")
+ )
+ or {"result": {"status": "started"}},
+ )
+ session = _session(
+ queued_prompt={"text": "inspect", "image_paths": ["/tmp/b.png"], "transport": "ws-9"}
+ )
+
+ assert server._drain_queued_prompt("r1", "sid", session) is True
+ assert captured == {
+ "rid": "r1",
+ "sid": "sid",
+ "text": "inspect",
+ "image_paths": ["/tmp/b.png"],
+ }
+
+
@@ -182,3 +298,64 @@ def test_drain_releases_running_on_dispatch_failure(monkeypatch):
assert session["running"] is False
+def test_drain_does_not_dispatch_a_prompt_cancelled_after_claim(monkeypatch):
+ session = _session(queued_prompt={"text": "B", "transport": None})
+ monkeypatch.setattr(
+ server,
+ "_session_uses_compute_host",
+ lambda _session: session.__setitem__("_queued_prompt_generation", 1) or False,
+ )
+ monkeypatch.setattr(
+ server,
+ "_run_prompt_submit",
+ lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("must not dispatch")),
+ )
+
+ assert server._drain_queued_prompt("r1", "sid", session) is True
+ assert session["running"] is False
+
+
+def test_drain_does_not_clear_stop_after_its_final_generation_check(monkeypatch):
+ class _Agent:
+ clear_calls = 0
+
+ def clear_interrupt(self):
+ self.clear_calls += 1
+
+ agent = _Agent()
+ session = _session(agent=agent, queued_prompt={"text": "B", "transport": None})
+ original_run = server._run_prompt_submit
+
+ def stop_before_run(*args, **kwargs):
+ session["_queued_prompt_generation"] = 1
+ return original_run(*args, **kwargs)
+
+ monkeypatch.setattr(server, "_session_uses_compute_host", lambda _session: False)
+ monkeypatch.setattr(server, "_run_prompt_submit", stop_before_run)
+
+ assert server._drain_queued_prompt("r1", "sid", session) is True
+ assert agent.clear_calls == 0
+ assert session["running"] is False
+
+
+def test_drain_continues_with_later_queued_prompt_after_dispatch_failure(monkeypatch):
+ calls = []
+
+ def _run(_rid, _sid, session, text, **_kwargs):
+ calls.append(text)
+ if text == "broken":
+ raise RuntimeError("dispatch failed")
+ session["running"] = False
+
+ monkeypatch.setattr(server, "_run_prompt_submit", _run)
+ session = _session(
+ queued_prompt={"text": "broken", "transport": None},
+ queued_prompts=[{"text": "next", "image_paths": ["/tmp/next.png"], "transport": None}],
+ )
+
+ assert server._drain_queued_prompt("r1", "sid", session) is True
+ assert calls == ["broken", "next"]
+ assert session["queued_prompt"] is None
+ assert session.get("queued_prompts") is None
+
+
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index 3e4ce0ddb11..02408174835 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -271,6 +271,22 @@ def test_prompt_submit_dispatches_to_compute_host_when_turn_isolation_enabled(mo
server._sessions.pop("iso-sid", None)
+def test_compute_host_explicit_images_do_not_clear_later_attachment(monkeypatch):
+ class _Supervisor:
+ def submit_turn(self, _frame, *, on_complete=None):
+ session["attached_images"].append("/tmp/c.png")
+
+ session = _session(attached_images=[])
+ monkeypatch.setattr(server, "_get_compute_host_supervisor", lambda _cfg=None: _Supervisor())
+
+ response = server._submit_prompt_to_compute_host(
+ "r1", "sid", session, "B", image_paths=["/tmp/b.png"]
+ )
+
+ assert response["result"]["status"] == "streaming"
+ assert session["attached_images"] == ["/tmp/c.png"]
+
+
def test_prompt_submit_fails_open_inline_when_compute_host_dispatch_breaks(monkeypatch):
class _BrokenSupervisor:
def submit_turn(self, frame, *, on_complete=None):
@@ -9121,6 +9137,7 @@ def test_interrupt_drops_queued_prompt_for_session():
),
running=True,
queued_prompt={"text": "next prompt", "transport": None},
+ queued_prompts=[{"text": "later prompt", "image_paths": ["/tmp/later.png"], "transport": None}],
_run_thread=_LiveThread(),
)
server._sessions["sid"] = session
@@ -9133,6 +9150,7 @@ def test_interrupt_drops_queued_prompt_for_session():
assert resp.get("result"), f"got error: {resp.get('error')}"
assert calls["interrupted"] is True
assert session.get("queued_prompt") is None
+ assert session.get("queued_prompts") is None
finally:
server._sessions.pop("sid", None)
diff --git a/tui_gateway/compute_host.py b/tui_gateway/compute_host.py
index d1c46dd9c20..83aaf740b92 100644
--- a/tui_gateway/compute_host.py
+++ b/tui_gateway/compute_host.py
@@ -281,6 +281,8 @@ class ComputeHost:
with session.get("history_lock", threading.Lock()):
session["_turn_cancel_requested"] = True
session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
self.emit({"type": "interrupt.ack", "sid": sid, "request_id": frame.get("request_id"), "applied": True, "applied_ns": now_ns()})
except Exception as exc:
self.emit({"type": "interrupt.ack", "sid": sid, "request_id": frame.get("request_id"), "applied": False, "message": str(exc)})
@@ -355,6 +357,22 @@ class ComputeHost:
session = self._ensure_server_session(server, frame)
with session["history_lock"]:
+ queued_prompt_generation = frame.get("queued_prompt_generation")
+ if (
+ queued_prompt_generation is not None
+ and int(session.get("_queued_prompt_generation", 0))
+ != int(queued_prompt_generation)
+ ):
+ self.emit(
+ {
+ "type": "turn.end",
+ "sid": sid,
+ "request_id": request_id,
+ "interrupted": True,
+ "ended_ns": now_ns(),
+ }
+ )
+ return
if session.get("running"):
self.emit({"type": "turn.error", "sid": sid, "request_id": request_id, "message": "session busy"})
return
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index 68210a4c8a3..44ef31ca82d 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -2721,6 +2721,8 @@ def _(rid, params: dict) -> dict:
with session["history_lock"]:
session["_turn_cancel_requested"] = True
session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
_clear_pending(sid)
try:
from tools.approval import resolve_gateway_approval
@@ -2742,11 +2744,13 @@ def _(rid, params: dict) -> dict:
run_thread = session.get("_run_thread")
run_thread_alive = run_thread is not None and run_thread.is_alive()
should_interrupt = bool(session.get("running"))
- if should_interrupt and hasattr(session["agent"], "interrupt"):
- session["agent"].interrupt()
with session["history_lock"]:
session["_turn_cancel_requested"] = True
session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
+ if should_interrupt and hasattr(session["agent"], "interrupt"):
+ session["agent"].interrupt()
if not run_thread_alive:
with session["history_lock"]:
if session.get("running"):
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index d049c7556d1..a6074592b97 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1490,11 +1490,22 @@ def _get_compute_host_supervisor(cfg: dict | None = None):
return _compute_host_supervisor
-def _compute_host_turn_frame(rid: str, sid: str, session: dict, text: Any) -> dict:
+def _compute_host_turn_frame(
+ rid: str,
+ sid: str,
+ session: dict,
+ text: Any,
+ image_paths: list[str] | None = None,
+ queued_prompt_generation: int | None = None,
+) -> dict:
with session["history_lock"]:
history = list(session.get("history", []))
history_version = int(session.get("history_version", 0))
- attached_images = list(session.get("attached_images", []))
+ attached_images = (
+ list(image_paths)
+ if image_paths is not None
+ else list(session.get("attached_images", []))
+ )
return {
"type": "turn.start",
"sid": sid,
@@ -1511,6 +1522,7 @@ def _compute_host_turn_frame(rid: str, sid: str, session: dict, text: Any) -> di
"service_tier_override": session.get("create_service_tier_override"),
"source": _session_source(session),
"attached_images": attached_images,
+ "queued_prompt_generation": queued_prompt_generation,
}
@@ -1581,9 +1593,23 @@ def _on_compute_host_turn_done(rid: str, sid: str, session: dict, frame: dict) -
_drain_queued_prompt(rid, sid, session)
-def _submit_prompt_to_compute_host(rid: str, sid: str, session: dict, text: Any) -> dict:
+def _submit_prompt_to_compute_host(
+ rid: str,
+ sid: str,
+ session: dict,
+ text: Any,
+ image_paths: list[str] | None = None,
+ queued_prompt_generation: int | None = None,
+) -> dict:
cfg = _load_dashboard_process_isolation_config()
- frame = _compute_host_turn_frame(rid, sid, session, text)
+ frame = _compute_host_turn_frame(
+ rid,
+ sid,
+ session,
+ text,
+ image_paths=image_paths,
+ queued_prompt_generation=queued_prompt_generation,
+ )
def _complete(done: dict) -> None:
# submit_turn reports a synchronous pipe failure through the callback
@@ -1600,7 +1626,8 @@ def _submit_prompt_to_compute_host(rid: str, sid: str, session: dict, text: Any)
return _err(rid, 5019, f"compute-host dispatch failed: {exc}")
with session["history_lock"]:
session["_compute_host_active"] = True
- session["attached_images"] = []
+ if image_paths is None:
+ session["attached_images"] = []
return _ok(rid, {"status": "streaming", "turn_isolation": True})
@@ -5914,6 +5941,9 @@ def _reset_session_agent(sid: str, session: dict) -> dict:
session["agent"] = new_agent
session["config_model_seen"] = _config_model_target()
session["attached_images"] = []
+ session["queued_prompt"] = None
+ session.pop("queued_prompts", None)
+ session["_queued_prompt_generation"] = int(session.get("_queued_prompt_generation", 0)) + 1
session["edit_snapshots"] = {}
session["image_counter"] = 0
session["running"] = False
@@ -7095,24 +7125,41 @@ def _maybe_schedule_auto_continue(sid: str, session: dict, session_key: str) ->
return {"attempt": attempt, "interrupted_at": marker["started_at"]}
-def _enqueue_prompt(session: dict, text: Any, transport: Any) -> None:
+def _enqueue_prompt(
+ session: dict,
+ text: Any,
+ transport: Any,
+ image_paths: list[str] | None = None,
+) -> None:
"""Stash a message to run as the very next turn once the live one ends.
- Used when a prompt arrives mid-turn (see ``_handle_busy_submit``). A single
- slot is kept; a second arrival is merged (lossless, mirroring the
- consecutive-user merge in ``repair_message_sequence``) so nothing the user
- typed is dropped. ``transport`` is pinned so the drained turn streams back to
- the client that sent it even if the session transport is rebound meanwhile.
+ Used when a prompt arrives mid-turn (see ``_handle_busy_submit``). Text-only
+ arrivals share a slot and merge losslessly (mirroring the consecutive-user
+ merge in ``repair_message_sequence``). Image-bearing submissions stay as
+ separate envelopes, so their attachment ownership and chronology survive.
+ ``transport`` is pinned so the drained turn streams back to the client that
+ sent it even if the session transport is rebound meanwhile.
"""
+ image_paths = list(image_paths or [])
+ queued = {"text": text, "transport": transport}
+ if image_paths:
+ queued["image_paths"] = image_paths
existing = session.get("queued_prompt")
if (
existing
and isinstance(existing.get("text"), str)
and isinstance(text, str)
+ and not existing.get("image_paths")
+ and not image_paths
+ and not session.get("queued_prompts")
):
prev = existing["text"]
- text = f"{prev}\n\n{text}" if prev and text else (prev or text)
- session["queued_prompt"] = {"text": text, "transport": transport}
+ existing["text"] = f"{prev}\n\n{text}" if prev and text else (prev or text)
+ return
+ if existing:
+ session.setdefault("queued_prompts", []).append(queued)
+ return
+ session["queued_prompt"] = queued
def _interrupt_busy_session(sid: str, session: dict, agent: Any) -> None:
@@ -7179,7 +7226,15 @@ def _handle_busy_submit(
# The turn ended between prompt.submit's first busy check and this
# helper. Let the caller retry and claim the now-idle session.
return None
- text_only = _is_text_only_busy_payload(text)
+ with session["history_lock"]:
+ if not session.get("running"):
+ return None
+ image_paths = list(session.get("attached_images", []))
+ if image_paths:
+ # Claim at submission time. A later paste must not be consumed by
+ # this prompt after the active turn finally yields.
+ session["attached_images"] = []
+ text_only = not image_paths and _is_text_only_busy_payload(text)
plain_text = _coerce_message_text(text).strip() if text_only else ""
if mode == "steer" and text_only and plain_text and agent is not None and hasattr(agent, "steer"):
try:
@@ -7213,11 +7268,15 @@ def _handle_busy_submit(
# can wait behind the very operation it is trying to cancel.
with session["history_lock"]:
if not session.get("running"):
+ if image_paths:
+ session["attached_images"] = image_paths + list(session.get("attached_images", []))
return None
- _enqueue_prompt(session, text, transport)
+ _enqueue_prompt(session, text, transport, image_paths=image_paths)
session["last_active"] = time.time()
- if mode != "queue":
+ # Attachments need a separate model invocation. Queue them without
+ # cancelling the active turn so the user gets both results in order.
+ if mode != "queue" and not image_paths:
_interrupt_busy_session(sid, session, agent)
return _ok(rid, {"status": "queued"})
@@ -7233,21 +7292,60 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
queued = session.get("queued_prompt")
if not queued or session.get("running"):
return False
- session["queued_prompt"] = None
+ queue_generation = int(session.get("_queued_prompt_generation", 0))
+ queued_prompts = session.get("queued_prompts") or []
+ session["queued_prompt"] = queued_prompts.pop(0) if queued_prompts else None
+ if not queued_prompts:
+ session.pop("queued_prompts", None)
session["running"] = True
if queued.get("transport") is not None:
session["transport"] = queued["transport"]
+ use_compute_host = _session_uses_compute_host(session)
+ with session["history_lock"]:
+ if int(session.get("_queued_prompt_generation", 0)) != queue_generation:
+ session["running"] = False
+ return True
+ dispatch_failed = False
try:
- if _session_uses_compute_host(session):
- resp = _submit_prompt_to_compute_host(rid, sid, session, queued["text"])
+ if use_compute_host:
+ if queued.get("image_paths"):
+ resp = _submit_prompt_to_compute_host(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ image_paths=queued["image_paths"],
+ queued_prompt_generation=queue_generation,
+ )
+ else:
+ resp = _submit_prompt_to_compute_host(
+ rid, sid, session, queued["text"], queued_prompt_generation=queue_generation
+ )
if resp.get("error"):
message = str(((resp.get("error") or {}).get("message")) or "queued prompt failed")
with session["history_lock"]:
session["running"] = False
_clear_inflight_turn(session)
_emit("error", sid, {"message": message})
+ dispatch_failed = True
else:
- _run_prompt_submit(rid, sid, session, queued["text"])
+ if queued.get("image_paths"):
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ image_paths=queued["image_paths"],
+ queued_prompt_generation=queue_generation,
+ )
+ else:
+ _run_prompt_submit(
+ rid,
+ sid,
+ session,
+ queued["text"],
+ queued_prompt_generation=queue_generation,
+ )
except Exception as exc:
print(
f"[tui_gateway] queued prompt dispatch failed: "
@@ -7256,6 +7354,14 @@ def _drain_queued_prompt(rid, sid: str, session: dict) -> bool:
)
with session["history_lock"]:
session["running"] = False
+ dispatch_failed = True
+ if dispatch_failed:
+ with session["history_lock"]:
+ drain_next = bool(session.get("queued_prompt")) and not session.get(
+ "_turn_cancel_requested"
+ )
+ if drain_next:
+ _drain_queued_prompt(rid, sid, session)
return True
@@ -9029,25 +9135,41 @@ def _start_notification_poller(sid: str, session: dict) -> threading.Event:
def _run_prompt_submit(
- rid, sid: str, session: dict, text: Any, *, display_kind: str | None = None,
+ rid,
+ sid: str,
+ session: dict,
+ text: Any,
+ *,
+ display_kind: str | None = None,
display_metadata: dict | None = None,
+ image_paths: list[str] | None = None,
+ queued_prompt_generation: int | None = None,
) -> None:
with session["history_lock"]:
+ if (
+ queued_prompt_generation is not None
+ and int(session.get("_queued_prompt_generation", 0)) != queued_prompt_generation
+ ):
+ session["running"] = False
+ return
history = list(session["history"])
history_version = int(session.get("history_version", 0))
- images = list(session.get("attached_images", []))
- session["attached_images"] = []
+ if image_paths is None:
+ images = list(session.get("attached_images", []))
+ session["attached_images"] = []
+ else:
+ images = list(image_paths)
inflight = session.get("inflight_turn")
# A retained failed turn (see _fail_inflight_turn) is a stale leftover
# by the time a new turn starts — replace it, never append onto it.
if not isinstance(inflight, dict) or inflight.get("status") == "error":
_start_inflight_turn(session, text)
- agent = session["agent"]
- if hasattr(agent, "clear_interrupt"):
- try:
- agent.clear_interrupt()
- except Exception:
- pass
+ agent = session["agent"]
+ if hasattr(agent, "clear_interrupt"):
+ try:
+ agent.clear_interrupt()
+ except Exception:
+ pass
_emit("message.start", sid)
def run():