Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(agentic-ide): harden busy-pane delivery after review

rubenluetke10-beep9a52f9da9f26
diff --git a/jarvis/agentic_ide/agent_transcript.py b/jarvis/agentic_ide/agent_transcript.py
index 2b0fa4534a..9c3baaef5c 100644
--- a/jarvis/agentic_ide/agent_transcript.py
+++ b/jarvis/agentic_ide/agent_transcript.py
@@ -678,6 +678,8 @@ class _EventLog:
#: A finished thought waits for the NEXT record's timestamp, which is
#: the only place its duration can be read from.
self._thought: tuple[str, str, int] | None = None
+ # The event a message typed mid-turn became, until anything follows it.
+ self._queued_event: dict[str, Any] | None = None
# ----------------------------------------------------------------- core
def _emit(self, kind: str, payload: dict[str, Any], ts: int) -> None:
@@ -743,13 +745,14 @@ class _EventLog:
self.turn_id = None
# -------------------------------------------------------------- records
- def user(self, text: str, ts: int) -> None:
+ def user(self, text: str, ts: int, *, queued: bool = False) -> None:
body = _clip(text)
if not body:
return
if (
- self.events
- and self.events[-1]["kind"] == "user_message"
+ not queued
+ and self.events
+ and self.events[-1] is self._queued_event
and self.events[-1]["payload"].get("text") == body
):
# The record of a message typed mid-turn, followed by the CLI
@@ -757,6 +760,7 @@ class _EventLog:
return
self.close_turn(ts)
self._emit("user_message", {"text": body}, ts)
+ self._queued_event = self.events[-1] if queued else None
def thinking(self, text: str, message_id: str, ts: int) -> None:
self._ensure_turn(ts)
@@ -986,6 +990,7 @@ def _claude_events(session_id: str, home: Path | None, live: bool) -> list[dict[
log.user(
_spoken(str(queued.get("prompt") or "")),
_ts_ms(row.get("timestamp") or queued.get("timestamp")) or log.last_ms,
+ queued=True,
)
continue
if kind not in ("user", "assistant"):
diff --git a/jarvis/agentic_ide/delegation_wait.py b/jarvis/agentic_ide/delegation_wait.py
index edd8342c24..6b0714a623 100644
--- a/jarvis/agentic_ide/delegation_wait.py
+++ b/jarvis/agentic_ide/delegation_wait.py
@@ -41,17 +41,24 @@ def _read(term: Any, identity: tuple) -> dict[str, Any] | None:
)
or []
)
+ expected = " ".join(
+ agent_transcript._clip(agent_transcript._spoken(term.last_prompt)).split()
+ )
+ since = int(float(identity[1] or 0) * 1000)
+ # The newest record of THIS submission. A note typed into the running turn
+ # after it is part of the same work, not a reason to stop waiting.
start = next(
- (i for i in range(len(events) - 1, -1, -1) if events[i]["kind"] == "user_message"), None
+ (
+ i
+ for i in range(len(events) - 1, -1, -1)
+ if events[i]["kind"] == "user_message"
+ and int(events[i].get("ts_ms") or 0) >= since
+ and " ".join(events[i]["payload"].get("text", "").split()) == expected
+ ),
+ None,
)
if start is None:
return None
- user = events[start]
- expected = agent_transcript._clip(agent_transcript._spoken(term.last_prompt))
- if int(user.get("ts_ms") or 0) < int(float(identity[1] or 0) * 1000) or " ".join(
- user["payload"].get("text", "").split()
- ) != " ".join(expected.split()):
- return None
own = events[start + 1 :]
calls = {e["payload"].get("call_id"): e["payload"] for e in own if e["kind"] == "tool_call"}
for event in own:
diff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.py
index ccc11d84e4..42e9e82bb0 100644
--- a/jarvis/agentic_ide/orchestration.py
+++ b/jarvis/agentic_ide/orchestration.py
@@ -261,6 +261,8 @@ class WorkspaceOrchestrator:
# free. A "queued" receipt with no task here was left by an earlier
# run of the app and was never typed.
self._queued: dict[str, asyncio.Task] = {}
+ # receipt_id -> its pane, in the order the messages were queued.
+ self._queued_for: dict[str, str] = {}
# Announces new panes to the open UI; set by the runtime that owns a bus.
self.publish: Callable[[Any], Awaitable[Any]] | None = None
@@ -1364,6 +1366,7 @@ class WorkspaceOrchestrator:
The returned event releases the queue once that receipt is filed.
"""
armed = asyncio.Event()
+ self._queued_for[receipt_id] = delivery["target"]["terminal_id"]
self._queued[receipt_id] = asyncio.create_task(
self._drain(receipt_id, delivery, time.monotonic() + _QUEUE_TTL_S, armed),
name=f"workspace-queue:{receipt_id}",
@@ -1386,30 +1389,58 @@ class WorkspaceOrchestrator:
async def _drain(
self, receipt_id: str, delivery: dict[str, Any], deadline: float, armed: asyncio.Event,
) -> None:
- """Deliver one queued message once its pane is free, then file the receipt."""
+ """Deliver one queued message once its pane is free, then file the receipt.
+
+ Messages queued for one pane go out in the order they were queued: only
+ the oldest one still waiting may type. A cancel that lands while an
+ attempt is typing files ``uncertain``, never "nothing was typed".
+ """
target = delivery["target"]
result: dict[str, Any] | None = None
+ delivering = False
+ problem = ""
try:
await armed.wait()
while time.monotonic() < deadline:
await asyncio.sleep(_QUEUE_POLL_S + random.uniform(0.0, 1.0)) # noqa: S311
- found = self.registry.find_terminal(target["terminal_id"], target["workspace_id"])
- # A cheap fresh check first: an attempt resolves and copies
- # images, which is wasted on a pane that is still working.
- if found is not None and await self.registry.turn_in_progress(found[1]):
+ if self._queued_ahead(receipt_id, target["terminal_id"]):
+ continue
+ try:
+ found = self.registry.find_terminal(
+ target["terminal_id"], target["workspace_id"]
+ )
+ # A cheap fresh check first: an attempt resolves and copies
+ # images, which is wasted on a pane that is still working.
+ if found is not None and await self.registry.turn_in_progress(found[1]):
+ continue
+ except Exception as exc: # noqa: BLE001 - a failed look is retried, never fatal
+ from loguru import logger
+
+ problem = f"{type(exc).__name__}: {exc}"
+ logger.warning("Queued delivery could not read its pane: {}", problem)
continue
+ delivering = True
outcome = await self._deliver(delivery, when_busy="refuse")
+ delivering = False
if outcome.get("busy"):
continue # Someone else's prompt got there first.
result = outcome
break
except asyncio.CancelledError:
- result = {
- "status": "expired", "success": False, "target": target,
- "input_written": False,
- "reason": "The app stopped before the queued message was delivered; "
- "nothing was typed.",
- }
+ result = (
+ {
+ "status": "uncertain", "success": False, "target": target,
+ "reason": "The app stopped while the queued message was being typed. "
+ "Inspect the session; do not resend automatically.",
+ }
+ if delivering
+ else {
+ "status": "expired", "success": False, "target": target,
+ "input_written": False,
+ "reason": "The app stopped before the queued message was delivered; "
+ "nothing was typed.",
+ }
+ )
raise
finally:
if result is None:
@@ -1417,7 +1448,8 @@ class WorkspaceOrchestrator:
"status": "expired", "success": False, "target": target,
"input_written": False,
"reason": f"The turn did not end within {_QUEUE_TTL_S // 60} minutes; "
- "the queued message was not typed.",
+ "the queued message was not typed."
+ + (f" Last error reading the pane: {problem}" if problem else ""),
}
result = {**result, "request_id": delivery["request_id"], "queued": True}
try:
@@ -1429,6 +1461,16 @@ class WorkspaceOrchestrator:
logger.warning("Queued delivery receipt was not saved: {}", exc)
self._queued.pop(receipt_id, None)
+ self._queued_for.pop(receipt_id, None)
+
+ def _queued_ahead(self, receipt_id: str, terminal_id: str) -> bool:
+ """Is an older message still waiting for the same pane?"""
+ for queued, pane in self._queued_for.items():
+ if queued == receipt_id:
+ return False
+ if pane == terminal_id:
+ return True
+ return False
_orchestrators: dict[int, WorkspaceOrchestrator] = {}
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index a2b2dfbadc..83bfad7596 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -6741,13 +6741,17 @@ class Registry:
mid_turn = False
if require_idle:
busy = await self.turn_in_progress(term)
- if busy == "working" and when_busy == "interrupt":
- busy = await self._interrupt_turn(owner, term)
- if busy == "working":
+ if busy in ("working", "starting") and when_busy == "interrupt":
+ busy, pressed = await self._interrupt_turn(owner, term)
+ if busy in ("working", "starting"):
raise AgentBusyError(
f"Stop was pressed, but {term.name} had not ended its turn after "
- f"{INTERRUPT_SETTLE_S:.0f} s; nothing was typed.",
- interrupted=True,
+ f"{INTERRUPT_SETTLE_S:.0f} s; nothing was typed."
+ if pressed
+ else f"{term.name} was still starting its turn after "
+ f"{INTERRUPT_SETTLE_S:.0f} s, so Stop was not pressed; "
+ "nothing was typed.",
+ interrupted=pressed,
)
if busy in ("failed", "exited"):
raise SessionError(
@@ -6809,31 +6813,38 @@ class Registry:
return activity
# An interrupted turn ("stopped") sits at its prompt like a finished
# one; only a pane that is still starting with a task already handed
- # over waits — it is about to work.
+ # over waits — it is about to work, but no turn is proven yet.
if has_submission and activity not in ("waiting", "stopped"):
- return "working"
+ return "starting"
return ""
- async def _interrupt_turn(self, owner: Session, term: Terminal) -> str:
- """Press Stop once and wait for the turn to end; the busy word left, if any.
+ async def _interrupt_turn(self, owner: Session, term: Terminal) -> tuple[str, bool]:
+ """Press Stop once and wait for the turn to end.
- Re-read right before the key: a turn that ended meanwhile is not
- stopped again, because Escape at an idle prompt opens some CLIs'
- history views. One key, never a kill — the process and its
- conversation stay, and an unsaved edit in the step in flight is the
- CLI's own Stop semantics.
+ Returns the busy word left (if any) and whether Stop was pressed.
+
+ Stop is pressed only on a PROVEN turn ("working"): Escape at an idle
+ prompt opens some CLIs' history views or clears a draft, so a pane
+ that is merely starting is watched until it works or settles, and a
+ turn that ended meanwhile is not stopped again. One key, never a kill —
+ the process and its conversation stay, and an unsaved edit in the step
+ in flight is the CLI's own Stop semantics.
"""
+ deadline = time.monotonic() + INTERRUPT_SETTLE_S
busy = await self.turn_in_progress(term)
+ while busy == "starting" and time.monotonic() < deadline:
+ await asyncio.sleep(_INTERRUPT_POLL_S)
+ busy = await self.turn_in_progress(term)
if busy != "working":
- return busy
+ return busy, False
if not self.write("pane:" + term.history_id, _INTERRUPT_KEY, owner.id):
raise SessionError(f"{term.name} is not running; nothing was sent.")
logger.info("Agentic IDE: pressed Stop on {} to deliver a correction", term.name)
deadline = time.monotonic() + INTERRUPT_SETTLE_S
- while busy == "working" and time.monotonic() < deadline:
+ while busy in ("working", "starting") and time.monotonic() < deadline:
await asyncio.sleep(_INTERRUPT_POLL_S)
busy = await self.turn_in_progress(term)
- return busy
+ return busy, True
@staticmethod
def input_token(term: Terminal) -> str:
diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.py
index a65e19f3b2..0082922706 100644
--- a/tests/contract/test_workspace_orchestration.py
+++ b/tests/contract/test_workspace_orchestration.py
@@ -769,3 +769,53 @@ def test_tool_schema_offers_while_busy_and_shows_it_for_approval():
described = tool.describe_args({"action": "send", "prompt": "x", "while_busy": "interrupt"})
assert described["while_busy"] == "interrupt"
assert "while_busy" not in tool.describe_args({"action": "send", "prompt": "x"})
+
+
+async def test_a_stop_while_the_queue_is_typing_is_uncertain_never_retyped(rig, fast_queue):
+ args, held = await busy_send(rig, while_busy="queue")
+ typing = asyncio.Event()
+ finish = asyncio.Event()
+ plain_run = rig[2].run
+
+ async def slow_run(call):
+ if call["action"] == "send" and not rig[2].refused:
+ typing.set()
+ await finish.wait() # the app stops while this write is in flight
+ return await plain_run(call)
+
+ rig[2].run = slow_run
+ rig[2].refused = False
+ await asyncio.wait_for(typing.wait(), 2)
+ for task in list(rig[0]._queued.values()):
+ task.cancel()
+ await until(lambda: not rig[0]._queued)
+ again = await rig[0].run(args)
+ assert again["status"] == "uncertain"
+ assert rig[2].typed == [] # the cancelled write never completed, and no retry typed
+
+
+async def test_a_failed_look_at_the_pane_is_retried_not_dropped(rig, fast_queue, monkeypatch):
+ args, held = await busy_send(rig, while_busy="queue")
+ looks = []
+
+ async def flaky(term):
+ looks.append(term)
+ if len(looks) == 1:
+ raise OSError("transcript locked")
+ return ""
+
+ monkeypatch.setattr(rig[1], "turn_in_progress", flaky)
+ rig[2].refused = False
+ await until(lambda: not rig[0]._queued)
+ assert len(looks) >= 2
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_messages_queued_for_one_pane_arrive_in_order(rig, fast_queue):
+ first, held = await busy_send(rig, while_busy="queue")
+ second = {**first, "request_id": uuid4().hex, "prompt": "And keep the tests green"}
+ assert (await rig[0].run(second))["status"] == "queued"
+ rig[2].refused = False
+ await until(lambda: not rig[0]._queued)
+ assert rig[2].typed == [first["prompt"], second["prompt"]]
diff --git a/tests/unit/agentic_ide/test_agent_transcript_events.py b/tests/unit/agentic_ide/test_agent_transcript_events.py
index 9f66df620b..4590ce9992 100644
--- a/tests/unit/agentic_ide/test_agent_transcript_events.py
+++ b/tests/unit/agentic_ide/test_agent_transcript_events.py
@@ -368,6 +368,16 @@ class TestClaudeEvents:
users = [ev["payload"]["text"] for ev in events if ev["kind"] == "user_message"]
assert users == ["Review the folder editor", "Only review the save flow"]
+ def test_a_message_said_twice_by_the_person_stays_twice(self, tmp_path: Path) -> None:
+ # Only the CLI's own resubmission of a mid-turn message is folded.
+ _claude_session(tmp_path, "abc", [_user("continue", 0), _user("continue", 1)])
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ assert events is not None
+ assert [ev["payload"]["text"] for ev in events if ev["kind"] == "user_message"] == [
+ "continue",
+ "continue",
+ ]
+
def test_no_file_is_none_not_an_error(self, tmp_path: Path) -> None:
assert agent_transcript.read_events("claude", "nope", home=tmp_path) is None
assert agent_transcript.read_events("shell", "abc", home=tmp_path) is None
diff --git a/tests/unit/agentic_ide/test_delegation_wait.py b/tests/unit/agentic_ide/test_delegation_wait.py
index 6b5f5da4d6..46ce669c6a 100644
--- a/tests/unit/agentic_ide/test_delegation_wait.py
+++ b/tests/unit/agentic_ide/test_delegation_wait.py
@@ -164,3 +164,33 @@ def test_coding_question_is_returned_as_input_needed(recorded):
),
)
assert delegation_wait._read(term, (1, 100))["status"] == "needs_input"
+
+
+def _claude_steered_turn(term, write):
+ term.agent = "claude"
+ write(
+ {"type": "user", "timestamp": stamp(101), "message": {"content": "Fix the bug"}},
+ {"type": "assistant", "timestamp": stamp(102), "message": {
+ "content": [{"type": "tool_use", "id": "c1", "name": "Read", "input": {}}]}},
+ {"type": "attachment", "timestamp": stamp(103), "attachment": {
+ "type": "queued_command", "prompt": "Only the save flow",
+ "commandMode": "prompt", "origin": {"kind": "human"}}},
+ {"type": "assistant", "timestamp": stamp(104), "message": {
+ "content": [{"type": "text", "text": "Report"}], "stop_reason": "end_turn"}},
+ )
+
+
+def test_a_note_typed_into_the_running_turn_does_not_orphan_the_job(recorded):
+ # The note is part of the same work: the job still completes with its report.
+ term, write = recorded
+ _claude_steered_turn(term, write)
+ result = delegation_wait._read(term, (1, 100))
+ assert result["status"] == "completed" and result["report"] == "Report"
+
+
+def test_a_steered_correction_completes_with_the_turn_it_joined(recorded):
+ term, write = recorded
+ term.last_prompt, term.last_submit_at = "Only the save flow", 102.5
+ _claude_steered_turn(term, write)
+ result = delegation_wait._read(term, (1, 102.5))
+ assert result["status"] == "completed" and result["report"] == "Report"
diff --git a/tests/unit/agentic_ide/test_send_gate.py b/tests/unit/agentic_ide/test_send_gate.py
index fd5563cdcf..69131b03ff 100644
--- a/tests/unit/agentic_ide/test_send_gate.py
+++ b/tests/unit/agentic_ide/test_send_gate.py
@@ -330,3 +330,34 @@ async def test_unknown_busy_delivery_is_refused(pane):
with pytest.raises(SessionError, match="Unknown busy delivery"):
await correct(registry, workspace, term, "kill")
assert sent == []
+
+
+async def test_interrupt_never_presses_stop_on_a_pane_that_is_only_starting(pane, monkeypatch):
+ # No turn is proven yet: Escape there could clear a draft or open history.
+ registry, workspace, term, record, sent = pane
+ monkeypatch.setattr(session_module, "_INTERRUPT_POLL_S", 0.01)
+ readings = iter(["starting", "starting", "starting", ""])
+
+ async def reading(_term):
+ return next(readings, "")
+
+ monkeypatch.setattr(registry, "turn_in_progress", reading)
+ pressed = keys_pressed(registry, monkeypatch)
+ await correct(registry, workspace, term, "interrupt")
+ assert pressed == [] and sent == ["Narrow the review to the save flow"]
+
+
+async def test_interrupt_on_a_pane_that_never_starts_working_presses_nothing(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ monkeypatch.setattr(session_module, "_INTERRUPT_POLL_S", 0.01)
+ monkeypatch.setattr(session_module, "INTERRUPT_SETTLE_S", 0.05)
+
+ async def reading(_term):
+ return "starting"
+
+ monkeypatch.setattr(registry, "turn_in_progress", reading)
+ pressed = keys_pressed(registry, monkeypatch)
+ with pytest.raises(AgentBusyError, match="Stop was not pressed") as refused:
+ await correct(registry, workspace, term, "interrupt")
+ assert refused.value.interrupted is False
+ assert pressed == [] and sent == []