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): let a user's correction reach a coding agent that is in a turn

rubenluetke10-beepcae1d4ac791b
diff --git a/docs/igentic-workspaces.md b/docs/igentic-workspaces.md
index 2c2aef00cb..53d1714c37 100644
--- a/docs/igentic-workspaces.md
+++ b/docs/igentic-workspaces.md
@@ -71,6 +71,31 @@ neither voice reconnection nor a new tool-call ID replays that request. Receipts
include the immutable target and execution trace. Requests to a closed, moved,
archived or non-coding session fail without falling back to another terminal.
+### Agents that are in a turn
+
+A plain `send` never reaches into running work: a session in a turn returns
+`not_accepted` with `busy: true`, types nothing, and lists how the message could
+still get there. Only a correction the user directs at that running work uses
+`while_busy`:
+
+- `steer` types it into the running turn. Only for a CLI whose own mid-turn
+ input reaches that turn (`WorkspaceAgent.steers_mid_turn`: Claude Code, GLM,
+ Codex). Nothing is stopped. Other CLIs refuse it before typing.
+- `interrupt` presses Stop once (Escape), waits up to 15 s for the turn to end,
+ then types the correction at the prompt. The process, conversation and files
+ stay. A turn that has not ended by then is handed to the queue.
+- `queue` holds the message in the app and types it once the turn ends, for up
+ to 30 minutes. Its receipt reads `queued` until then and becomes the delivery
+ result. An app restart before delivery leaves nothing typed; the receipt then
+ reads `expired`.
+
+None of them types into an open question or permission prompt; that is
+`respond`. A busy refusal, an expired queue or any other receipt that proves
+nothing was typed may be retried with the same `request_id` and prompt (also
+with a different `while_busy`); an accepted, queued or uncertain receipt is
+returned instead of a second delivery. Claude Code records a mid-turn message as
+a human `queued_command`; `context` shows it as a user message.
+
## Boundaries and verification
This is a T3 shared contract change. No new OS adapter, credential or model
diff --git a/jarvis/agentic_ide/agent_transcript.py b/jarvis/agentic_ide/agent_transcript.py
index aa340b00fb..2b0fa4534a 100644
--- a/jarvis/agentic_ide/agent_transcript.py
+++ b/jarvis/agentic_ide/agent_transcript.py
@@ -747,6 +747,14 @@ class _EventLog:
body = _clip(text)
if not body:
return
+ if (
+ self.events
+ and self.events[-1]["kind"] == "user_message"
+ and self.events[-1]["payload"].get("text") == body
+ ):
+ # The record of a message typed mid-turn, followed by the CLI
+ # submitting that same message as the next prompt: one message.
+ return
self.close_turn(ts)
self._emit("user_message", {"text": body}, ts)
@@ -963,6 +971,23 @@ def _claude_events(session_id: str, home: Path | None, live: bool) -> list[dict[
if kind == "system" and row.get("subtype") == "turn_duration":
log.close_turn(_ts_ms(row.get("timestamp")) or log.last_ms)
continue
+ if kind == "attachment":
+ # A message the person typed while a turn ran: the CLI records it
+ # here and hands it to the model at its next step (mid-turn
+ # steering). Notices queued by the CLI itself carry another origin.
+ queued = row.get("attachment")
+ if (
+ isinstance(queued, dict)
+ and queued.get("type") == "queued_command"
+ and isinstance(queued.get("origin"), dict)
+ and queued["origin"].get("kind") == "human"
+ and queued.get("commandMode", "prompt") == "prompt"
+ ):
+ log.user(
+ _spoken(str(queued.get("prompt") or "")),
+ _ts_ms(row.get("timestamp") or queued.get("timestamp")) or log.last_ms,
+ )
+ continue
if kind not in ("user", "assistant"):
continue
message = row.get("message")
diff --git a/jarvis/agentic_ide/control.py b/jarvis/agentic_ide/control.py
index 4dd023f636..5a76c9666b 100644
--- a/jarvis/agentic_ide/control.py
+++ b/jarvis/agentic_ide/control.py
@@ -182,6 +182,7 @@ class CodingSessionControl:
expected_input=str(args.get("input_token") or "") if action == "respond" else "",
allow_question=action == "respond" and args.get("response_mode") == "dialog",
followup=current_delegation_origin.get(),
+ when_busy=str(args.get("when_busy") or "refuse") if action == "send" else "refuse",
)
return {
**self._state(owner, term),
@@ -191,6 +192,11 @@ class CodingSessionControl:
else "uncertain",
"input_written": True,
"completed": False,
+ **(
+ {"mid_turn": True,
+ "note": "Typed into the running turn; the agent takes it at its next step."}
+ if term.last_send_mid_turn else {}
+ ),
"images": image_receipts,
"retry": "Do not resend automatically. Read context and inspect delivery first.",
}
diff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.py
index e19b1da87f..ccc11d84e4 100644
--- a/jarvis/agentic_ide/orchestration.py
+++ b/jarvis/agentic_ide/orchestration.py
@@ -11,6 +11,7 @@ import asyncio
import hashlib
import inspect
import json
+import random
import re
import threading
import time
@@ -23,9 +24,11 @@ from jarvis.live.state import LiveLedger
from .session import (
MAX_PANES_PER_REQUEST,
+ AgentBusyError,
Registry,
SessionError,
accepts_prompts,
+ steers_mid_turn,
terminals_added_event,
)
from .workspace_catalog import project_graph
@@ -58,7 +61,14 @@ _WORKSPACE_ACTIONS = frozenset({"open_workspace", "restore", "show"})
# How many times one request may be re-attempted after receipts proving that
# nothing was typed (the pane was busy, closed, or not a coding pane).
_REFUSED_ATTEMPTS = 20
-_PRE_WRITE_REFUSALS = frozenset({"not_accepted", "stale_target", "unavailable"})
+_PRE_WRITE_REFUSALS = frozenset({"not_accepted", "stale_target", "unavailable", "expired"})
+# What a send does with a pane that is in a turn. Only "refuse" is automatic;
+# the others carry the user's own correction to the running work.
+_WHILE_BUSY = ("refuse", "steer", "interrupt", "queue")
+# A queued message waits this long for the turn to end, re-checking the pane
+# every few seconds (jittered: several queues never poll in lockstep).
+_QUEUE_TTL_S = 30 * 60
+_QUEUE_POLL_S = 3.0
# The keys a person presses in a pane besides typing: menus, dialogs, the
# permission-mode cycle (Shift+Tab) and Stop (Escape). Nothing else is sendable.
_KEY_SEQUENCES = {
@@ -247,6 +257,10 @@ class WorkspaceOrchestrator:
# name or ID), never for a first-idle pick or a CLI-kind match.
self._named: set[str] = set()
self._issued_lock = threading.Lock()
+ # receipt_id -> the task holding a queued message until its pane is
+ # 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] = {}
# Announces new panes to the open UI; set by the runtime that owns a bus.
self.publish: Callable[[Any], Awaitable[Any]] | None = None
@@ -1155,12 +1169,19 @@ class WorkspaceOrchestrator:
return await self.workspace_action(args, trace_id=trace_id)
if action not in {"send", "context"}:
raise ValueError("Unknown workspace orchestration action.")
+ while_busy = str(args.get("while_busy") or "refuse").strip().casefold()
+ if while_busy not in _WHILE_BUSY:
+ raise ValueError(f"while_busy must be one of {', '.join(_WHILE_BUSY)}.")
+ if while_busy != "refuse" and action != "send":
+ raise ValueError("while_busy belongs to send only.")
target, request_id = self._reconcile(args, action)
project_id, workspace_id, terminal_id = (target[key] for key in _TARGET_KEYS)
if not project_id or not workspace_id or not terminal_id.startswith("pane:"):
raise ValueError(
"Resolve a target first; project_id, workspace_id and terminal_id are required."
)
+ prompt = ""
+ receipt_id = request_id
if action == "send":
prompt = str(args.get("prompt") or "").strip()
if not prompt:
@@ -1172,6 +1193,8 @@ class WorkspaceOrchestrator:
seed = f"{terminal_id}\n{prompt}\n{refs}\n{int(time.time() // _RETRY_WINDOW_S)}"
request_id = hashlib.sha256(seed.encode("utf-8")).hexdigest()[:32]
self._mark_sent(request_id, _assignment(args))
+ # The assignment, never the delivery mode: resending a refused
+ # request with while_busy is the same instruction, not a new one.
claimed = {**target, "prompt": prompt, "image_refs": refs,
**({"image_scope": image_scope} if refs else {})}
# A receipt proving nothing was typed (busy, closed, not a coding
@@ -1185,81 +1208,227 @@ class WorkspaceOrchestrator:
self.ledger.claim, "workspace-orchestration", receipt_id, "send",
claimed, 0, deduplicate_unconfirmed=True,
)
+ if (
+ previous is not None
+ and previous.get("status") == "queued"
+ and receipt_id not in self._queued
+ ):
+ # Queued by an earlier run of the app, which stopped before
+ # the turn ended: nothing was typed, so the slot is free.
+ previous = {
+ **previous, "status": "expired", "success": False,
+ "input_written": False,
+ "reason": "The app stopped before the queued message was delivered; "
+ "nothing was typed.",
+ }
+ await asyncio.to_thread(
+ self.ledger.finish, "workspace-orchestration", receipt_id, previous
+ )
if previous is None or not _never_delivered(previous):
break
if previous is not None:
return {"target": target, "request_id": request_id, **previous}
+ delivery = {
+ "action": action, "target": target, "prompt": prompt, "refs": refs,
+ "image_scope": image_scope, "trace_id": trace_id, "request_id": request_id,
+ "limit": args.get("limit", 30),
+ }
+ result = await self._deliver(
+ delivery, when_busy="refuse" if while_busy == "queue" else while_busy,
+ )
+ armed: asyncio.Event | None = None
+ if action == "send" and result.get("busy") and (
+ while_busy == "queue" or result.get("interrupted")
+ ):
+ # Stop was pressed, or the user asked to wait: the message is held
+ # until the turn ends, under this same receipt.
+ result, armed = self._queue(
+ receipt_id, delivery, interrupted=bool(result.get("interrupted")),
+ )
+ try:
+ if action == "send":
+ result["request_id"] = request_id
+ await asyncio.to_thread(
+ self.ledger.finish, "workspace-orchestration", receipt_id, result
+ )
+ finally:
+ if armed is not None:
+ # Only now may the queue type it: its outcome must replace the
+ # "queued" receipt, never be overwritten by it.
+ armed.set()
+ return result
+
+ async def _deliver(self, delivery: dict[str, Any], *, when_busy: str) -> dict[str, Any]:
+ """One attempt at a send or context read on the resolved pane."""
+ action, target = delivery["action"], delivery["target"]
+ workspace_id, terminal_id = target["workspace_id"], target["terminal_id"]
owner = self.registry.get(workspace_id)
found = self.registry.find_terminal(terminal_id, workspace_id) if owner else None
- result: dict[str, Any]
- if owner is None or owner.project_id != project_id or found is None or found[1].archived:
- result = {
+ if (
+ owner is None
+ or owner.project_id != target["project_id"]
+ or found is None
+ or found[1].archived
+ ):
+ return {
"status": "stale_target",
"target": target,
"reason": "The resolved coding session is no longer in that project/workspace.",
}
- elif not accepts_prompts(found[1].agent):
- result = {
+ if not accepts_prompts(found[1].agent):
+ return {
"status": "unavailable",
"target": target,
"reason": "This session does not accept coding tasks.",
}
- else:
- # The low-level gateway enforces idle/asking state and refuses exited
- # agents. It never falls through to a shell or a different pane.
- try:
- delivery = await self.sessions.run(
- {
- "action": action,
- "workspace_id": workspace_id,
- "terminal_id": terminal_id,
- **(
- {"prompt": prompt, "image_refs": refs, "_image_scope": image_scope}
- if action == "send"
- else {"limit": args.get("limit", 30)}
- ),
- }
- )
- result = {
- **delivery,
- "status": delivery.get("delivery", delivery.get("status", "observed")),
- "target": target,
- "trace_id": trace_id,
- "request_id": request_id,
+ # The low-level gateway enforces idle/asking state and refuses exited
+ # agents. It never falls through to a shell or a different pane.
+ try:
+ reply = await self.sessions.run(
+ {
+ "action": action,
+ "workspace_id": workspace_id,
+ "terminal_id": terminal_id,
+ **(
+ {"prompt": delivery["prompt"], "image_refs": delivery["refs"],
+ "_image_scope": delivery["image_scope"], "when_busy": when_busy}
+ if action == "send"
+ else {"limit": delivery["limit"]}
+ ),
}
- except SessionError as exc:
- # The coding-session adapter documents SessionError as a
- # pre-write refusal; post-write uncertainty is a receipt.
+ )
+ return {
+ **reply,
+ "status": reply.get("delivery", reply.get("status", "observed")),
+ "target": target,
+ "trace_id": delivery["trace_id"],
+ "request_id": delivery["request_id"],
+ }
+ except AgentBusyError as exc:
+ # Pre-write, like every SessionError, and the one refusal the
+ # caller can answer with another delivery the USER chose.
+ can_steer = steers_mid_turn(found[1].agent)
+ return {
+ "status": "not_accepted",
+ "target": target,
+ "reason": str(exc),
+ "completed": False,
+ "input_written": False,
+ "busy": True,
+ **({"interrupted": True} if exc.interrupted else {}),
+ "while_busy_options": {"steer": can_steer, "interrupt": True, "queue": True},
+ "next": (
+ "The agent is in a turn. Only when the USER is correcting or redirecting "
+ "this running work, resend this request with "
+ + ("while_busy='steer' (reaches the running turn; nothing stops) or "
+ if can_steer else "")
+ + "while_busy='interrupt' (stops the turn, keeps the session, then "
+ "delivers). while_busy='queue' delivers it when the turn ends. A new or "
+ "unrelated task waits, goes to another agent, or is the user's call."
+ ),
+ }
+ except SessionError as exc:
+ # The coding-session adapter documents SessionError as a
+ # pre-write refusal; post-write uncertainty is a receipt.
+ return {
+ "status": "not_accepted",
+ "target": target,
+ "reason": str(exc),
+ "completed": False,
+ }
+ except Exception as exc:
+ # Preserve uncertainty: an adapter can fail after the write.
+ # The durable claim remains, preventing an automatic replay.
+ from loguru import logger
+
+ logger.warning("Workspace action {} failed: {}", action, type(exc).__name__)
+ if action != "send":
+ raise
+ return {
+ "status": "uncertain",
+ "target": target,
+ "request_id": delivery["request_id"],
+ "reason": (
+ "Delivery could not be confirmed. Inspect the session; "
+ "do not resend automatically."
+ ),
+ }
+
+ def _queue(
+ self, receipt_id: str, delivery: dict[str, Any], *, interrupted: bool,
+ ) -> tuple[dict[str, Any], asyncio.Event]:
+ """Hold a message until its pane ends the turn, then type it there.
+
+ Registered before the caller files the "queued" receipt, so a retry in
+ between never takes it for one an earlier run of the app left behind.
+ The returned event releases the queue once that receipt is filed.
+ """
+ armed = asyncio.Event()
+ self._queued[receipt_id] = asyncio.create_task(
+ self._drain(receipt_id, delivery, time.monotonic() + _QUEUE_TTL_S, armed),
+ name=f"workspace-queue:{receipt_id}",
+ )
+ return {
+ "status": "queued",
+ "target": delivery["target"],
+ "input_written": False,
+ "completed": False,
+ **({"interrupted": True} if interrupted else {}),
+ "reason": (
+ ("Stop was pressed but the turn had not ended yet. " if interrupted else "")
+ + "The app holds the message and types it at the agent's prompt as soon as "
+ f"its turn ends (for up to {_QUEUE_TTL_S // 60} minutes). This request_id "
+ "then reads the delivery result. Do not resend; an app restart before "
+ "delivery drops it unsent (reported as expired)."
+ ),
+ }, armed
+
+ 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."""
+ target = delivery["target"]
+ result: dict[str, Any] | None = None
+ 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]):
+ continue
+ outcome = await self._deliver(delivery, when_busy="refuse")
+ 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.",
+ }
+ raise
+ finally:
+ if result is None:
result = {
- "status": "not_accepted",
- "target": target,
- "reason": str(exc),
- "completed": False,
+ "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.",
}
- except Exception as exc:
- # Preserve uncertainty: an adapter can fail after the write.
- # The durable claim remains, preventing an automatic replay.
+ result = {**result, "request_id": delivery["request_id"], "queued": True}
+ try:
+ # Synchronous on purpose: this also runs while the loop is
+ # cancelling the task, where no thread hop can be awaited.
+ self.ledger.finish("workspace-orchestration", receipt_id, result)
+ except Exception as exc: # noqa: BLE001 - a lost receipt is logged, never raised
from loguru import logger
- logger.warning("Workspace action {} failed: {}", action, type(exc).__name__)
- if action == "send":
- result = {
- "status": "uncertain",
- "target": target,
- "request_id": request_id,
- "reason": (
- "Delivery could not be confirmed. Inspect the session; "
- "do not resend automatically."
- ),
- }
- else:
- raise
- if action == "send":
- result["request_id"] = request_id
- await asyncio.to_thread(
- self.ledger.finish, "workspace-orchestration", receipt_id, result
- )
- return result
+ logger.warning("Queued delivery receipt was not saved: {}", exc)
+ self._queued.pop(receipt_id, None)
_orchestrators: dict[int, WorkspaceOrchestrator] = {}
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index ccac285a61..a2b2dfbadc 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -217,6 +217,22 @@ def accepts_prompts(agent: str) -> bool:
return spec is not None and spec.is_coding_agent and spec.accepts_typed_prompts
+def steers_mid_turn(agent: str) -> bool:
+ """Does a line submitted while this agent works reach its running turn?"""
+ spec = workspace_agents.get_agent(agent)
+ return accepts_prompts(agent) and spec is not None and spec.steers_mid_turn
+
+
+#: How a delivery treats a pane that is in a turn (``Registry.send_prompt``).
+WHEN_BUSY = ("refuse", "steer", "interrupt")
+#: How long an interrupt-and-resume waits for the turn to end after Stop.
+INTERRUPT_SETTLE_S = 15.0
+_INTERRUPT_POLL_S = 0.5
+#: Stop for a running turn: the key every coding CLI's own hint names
+#: ("esc to interrupt"). Ctrl+C is not used: pressed twice it quits some CLIs.
+_INTERRUPT_KEY = "\x1b"
+
+
def _unavailable(agent: str) -> str:
"""Why this pane cannot open, said in the terms of what it would have run.
@@ -1154,6 +1170,9 @@ class Terminal:
last_submit_at: float | None = None
# Did the last prompt actually leave the input line? None = none sent yet.
submitted: bool | None = None
+ # Was the last prompt Jarvis sent typed into a RUNNING turn (native
+ # steering) rather than at an idle prompt? Read by the delivery receipt.
+ last_send_mid_turn: bool = False
# A hand-pressed Enter on an injected prompt is being checked against the
# screen. Kept explicit so another Enter stays on the verified path rather
# than being mistaken for a brand-new manual instruction.
@@ -1936,6 +1955,22 @@ class SessionNotReady(SessionError):
"""
+class AgentBusyError(SessionError):
+ """The pane is in a turn and the caller did not choose how to reach it.
+
+ Raised BEFORE any text is typed, like every ``SessionError`` (an interrupt
+ may have pressed Stop, which ``interrupted`` reports). Its own type
+ because "busy" is the one refusal a caller can act on with a different
+ delivery (steer, interrupt-and-resume or a queue), while every other
+ refusal means the pane cannot be typed into at all. ``interrupted`` is
+ True when Stop was pressed and the turn had not ended in time.
+ """
+
+ def __init__(self, message: str, *, interrupted: bool = False) -> None:
+ super().__init__(message)
+ self.interrupted = interrupted
+
+
class PlacementError(SessionError):
"""A pane could not be set up on (or brought back from) a computer.
@@ -6666,12 +6701,29 @@ class Registry:
allow_question: bool = False,
followup: dict[str, str] | None = None,
expected_location: tuple[str, str, str] | None = None,
+ when_busy: str = "refuse",
) -> Terminal:
"""Serialize deliveries and pin the pane before the first await.
Explicit Jarvis voice requests retain a result receipt. Direct pane input
and work supervised by another agent keep their existing reporting owner.
+
+ ``require_idle`` gates on a pane in a turn, and ``when_busy`` says what
+ a busy pane gets. ``refuse`` (the default) raises ``AgentBusyError`` —
+ an ordinary message never reaches into running work. The other two are
+ for a correction the USER directed at that work:
+
+ * ``steer`` types it into the running turn, on a CLI whose own mid-turn
+ input reaches that turn (``steers_mid_turn``). Nothing is stopped.
+ * ``interrupt`` presses Stop, waits for the turn to end, then types it
+ at the prompt. The process, its conversation and its files stay; only
+ the step in flight is cut short, as the pane's own Stop does.
+
+ Neither types into an open question or permission prompt, which would
+ answer it.
"""
+ if when_busy not in WHEN_BUSY:
+ raise SessionError(f"Unknown busy delivery {when_busy!r}; nothing was sent.")
found = self.find_terminal(wanted, workspace_id)
if found is None:
raise self._unknown_terminal(wanted)
@@ -6686,24 +6738,36 @@ class Registry:
or self.input_token(term) != expected_input
):
raise SessionError("The input request changed; nothing was sent.")
+ mid_turn = False
if require_idle:
- # Judge on fresh lifecycle evidence, never the sweep's stamp.
- from .activity import send_reading
- from .task_state import probe
-
- await probe(term)
- activity = send_reading(term)
- has_submission = (
- term.last_submit_at is not None
- and term.submit_generation == term.process_generation
- )
- # 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.
- if activity in ("working", "asking", "failed", "exited") or (
- has_submission and activity not in ("waiting", "stopped")
- ):
- raise SessionError("The selected coding agent is busy; nothing was sent.")
+ busy = await self.turn_in_progress(term)
+ if busy == "working" and when_busy == "interrupt":
+ busy = await self._interrupt_turn(owner, term)
+ if busy == "working":
+ 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,
+ )
+ if busy in ("failed", "exited"):
+ raise SessionError(
+ f"{term.name} is not running ({busy}); nothing was sent."
+ )
+ if busy == "asking" and when_busy != "refuse":
+ raise SessionError(
+ f"{term.name} is asking a question; answer it with respond "
+ "(the correction can be the answer). Nothing was sent."
+ )
+ if busy and when_busy == "steer":
+ if not steers_mid_turn(term.agent):
+ raise AgentBusyError(
+ f"{agent_display(term.agent)} does not take a message in the middle "
+ "of a turn; nothing was sent. Interrupt it first or queue the "
+ "message for when the turn ends."
+ )
+ mid_turn = True
+ elif busy:
+ raise AgentBusyError("The selected coding agent is busy; nothing was sent.")
pending = None
if followup is not None and followup.get("reply_surface") in {"voice", "chat"}:
from .followthrough import prepare
@@ -6720,11 +6784,57 @@ class Registry:
pending_result=pending,
expected_location=expected_location,
)
+ result.last_send_mid_turn = mid_turn
from .delegation_wait import track_submission
track_submission(self, owner, result)
return result
+ @staticmethod
+ async def turn_in_progress(term: Terminal) -> str:
+ """What keeps ``term`` from taking a prompt now, or "" when nothing does.
+
+ Judged on fresh lifecycle evidence, never the sweep's stamp.
+ """
+ from .activity import send_reading
+ from .task_state import probe
+
+ await probe(term)
+ activity = send_reading(term)
+ has_submission = (
+ term.last_submit_at is not None
+ and term.submit_generation == term.process_generation
+ )
+ if activity in ("working", "asking", "failed", "exited"):
+ 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.
+ if has_submission and activity not in ("waiting", "stopped"):
+ return "working"
+ 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.
+
+ 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.
+ """
+ busy = await self.turn_in_progress(term)
+ if busy != "working":
+ return busy
+ 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:
+ await asyncio.sleep(_INTERRUPT_POLL_S)
+ busy = await self.turn_in_progress(term)
+ return busy
+
@staticmethod
def input_token(term: Terminal) -> str:
"""Bind a textual reply to the current process and visible input request."""
diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.py
index 1f85c68bf9..3ab1774c46 100644
--- a/jarvis/brain/workspace_tool.py
+++ b/jarvis/brain/workspace_tool.py
@@ -76,12 +76,18 @@ class WorkspaceOrchestrationTool:
"repairs a mistyped request ID only when the target agrees); reuse it for "
"retries. Explicit background targets never switch the visible workspace. "
"Accepted means delivered, not completed; uncertain delivery must not be retried. "
+ "A send to an agent in a turn is refused as busy (nothing typed) unless while_busy "
+ "says otherwise. Set while_busy only for the USER's own correction or redirect of "
+ "the work that agent is doing now: steer types it into the running turn (CLIs that "
+ "support it), interrupt stops the turn and then delivers it (the session and its "
+ "context stay), queue delivers it once the turn ends. Retry a busy refusal with the "
+ "same request_id and prompt. Never use while_busy for an ordinary or unrelated task. "
"The result returns asynchronously to this conversation; keep talking to the user "
"instead of waiting or polling in a loop. "
"Creation receipts own their new panes: never send recovery or correction prompts "
"to existing panes, and never recreate after uncertain startup or delivery. "
- "After a proven pre-write refusal, resolve the SAME pane for a fresh request_id "
- "before a new attempt. "
+ "After a proven pre-write refusal (nothing typed), retry the SAME pane with the "
+ "same request_id and prompt. "
"Use context with the same IDs to inspect recorded results. No prompt rewriting is needed. "
"A prompt for create, open_workspace or send is a work order the agent carries "
"out, never a read-only request unless the user asked for one (see prompt). "
@@ -148,6 +154,15 @@ class WorkspaceOrchestrationTool:
"type": "string",
"description": "request_id from resolve; keep it unchanged on retries.",
},
+ "while_busy": {
+ "type": "string",
+ "enum": ["refuse", "steer", "interrupt", "queue"],
+ "description": (
+ "send: what happens when the agent is in a turn. refuse (default) sends "
+ "nothing. steer/interrupt/queue only for the user's explicit correction "
+ "of that running work."
+ ),
+ },
"limit": {"type": "integer", "minimum": 1, "maximum": 100},
"cli": {
"type": "string",
@@ -217,6 +232,11 @@ class WorkspaceOrchestrationTool:
else ""
),
"task": str(args.get("prompt") or "")[:240],
+ **(
+ {"while_busy": str(args["while_busy"])}
+ if args.get("while_busy") not in (None, "", "refuse")
+ else {}
+ ),
}
async def execute(self, args: dict, ctx: ExecutionContext) -> ToolResult:
diff --git a/jarvis/workspace/agents.py b/jarvis/workspace/agents.py
index d4c359a7d3..2bb3784b77 100644
--- a/jarvis/workspace/agents.py
+++ b/jarvis/workspace/agents.py
@@ -301,6 +301,11 @@ class WorkspaceAgent:
#: already covers the near-universal "esc to interrupt" wording; an entry
#: names only its own peculiarity.
busy_fragments: tuple[str, ...] = ()
+ #: True when a line submitted WHILE a turn runs reaches that running turn:
+ #: the CLI's own mid-turn steering. False means nothing is known about
+ #: typing into a busy pane of it, so a correction must stop the turn first
+ #: or wait for it to end (:meth:`jarvis.agentic_ide.session.Registry.send_prompt`).
+ steers_mid_turn: bool = False
#: The per-project instructions file this CLI reads (CLAUDE.md, AGENTS.md).
instruction_filename: str = ""
@@ -765,6 +770,10 @@ _AGENTS: dict[str, WorkspaceAgent] = {
# launch-and-prompt path, so waiting for its input line to appear would
# only slow down behaviour that already works.
needs_input_line_wait=False,
+ # Measured (2.1.x): a message submitted mid-turn is recorded as a
+ # human ``queued_command`` and handed to the model at its next step,
+ # inside the running turn.
+ steers_mid_turn=True,
instruction_filename="CLAUDE.md",
# Its footer row ("<folder> 🌿 <branch> <model> (1M context)") carries
# plenty of letters, so without these the deterministic recap of a busy
@@ -815,6 +824,10 @@ _AGENTS: dict[str, WorkspaceAgent] = {
input_markers=("›", "»"),
requires_visible_input_cursor=True,
asks_colours_after_input_line=True,
+ # Checked on 0.160: Enter while a task runs sends into the active turn
+ # (Tab would queue it instead); review and compact turns refuse a
+ # steer and keep the text in the composer, which the send reports.
+ steers_mid_turn=True,
# Two simultaneous resumes against Codex's shared SQLite/runtime store
# were measured beyond 90 s while one resume initialized substantially
# faster. Serialize only this shared-store boot phase. Claude and every
@@ -952,6 +965,7 @@ _AGENTS: dict[str, WorkspaceAgent] = {
resume_adapter="claude",
file_reference="at",
needs_input_line_wait=False,
+ steers_mid_turn=True,
instruction_filename="CLAUDE.md",
# Resolved fresh on every spawn AND every resume — see the docstring.
spawn_env_factory=glm_spawn_env,
diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.py
index 2f072d2518..a65e19f3b2 100644
--- a/tests/contract/test_workspace_orchestration.py
+++ b/tests/contract/test_workspace_orchestration.py
@@ -9,10 +9,15 @@ from uuid import uuid4
import pytest
-from jarvis.agentic_ide import library, resume_store
+from jarvis.agentic_ide import library, orchestration, resume_store
from jarvis.agentic_ide.folders import probe_project
from jarvis.agentic_ide.orchestration import WorkspaceOrchestrator
-from jarvis.agentic_ide.session import Registry, Session, SessionError, Terminal
+from jarvis.agentic_ide.session import (
+ AgentBusyError,
+ Registry,
+ Session,
+ Terminal,
+)
from jarvis.brain.tool_gateway import BrainSupervisorToolGateway
from jarvis.brain.workspace_tool import WorkspaceOrchestrationTool
from jarvis.core.protocols import ExecutionContext, SupervisorToolRequest
@@ -22,21 +27,39 @@ from tests.fakes.fake_pty_manager import FakePtyManager
class Sessions:
+ """The coding-session gateway; ``refused`` is a pane in a running turn."""
+
def __init__(self):
self.calls = []
self.fail = False
self.refused = False
+ self.steerable = True # the CLI takes input mid-turn
+ self.settles = True # Stop ends the turn in time
+ self.typed = [] # every prompt that actually reached the pane
async def run(self, args):
self.calls.append(args)
await asyncio.sleep(0)
+ mid_turn = False
if self.refused:
- raise SessionError("The selected coding agent is busy; nothing was sent.")
+ mode = args.get("when_busy", "refuse") if args["action"] == "send" else "refuse"
+ if mode == "steer" and self.steerable:
+ mid_turn = True
+ elif mode == "interrupt" and self.settles:
+ self.refused = False
+ else:
+ raise AgentBusyError(
+ "The selected coding agent is busy; nothing was sent.",
+ interrupted=mode == "interrupt",
+ )
if self.fail:
raise RuntimeError("transport interrupted after possible write")
if args["action"] in {"input", "observe"}:
return {"input_token": "token-1", "response_mode": "dialog", "screen_excerpt": "?"}
- return {"delivery": "accepted", "submitted": True, "completed": False}
+ if args["action"] == "send":
+ self.typed.append(args["prompt"])
+ return {"delivery": "accepted", "submitted": True, "completed": False,
+ **({"mid_turn": True} if mid_turn else {})}
@pytest.fixture
@@ -584,3 +607,165 @@ def test_pane_reads_are_safe_and_every_new_action_validates(rig):
for action in ("respond", "keys", "interrupt", "close", "open_workspace", "restore", "show"):
jsonschema.validate({"action": action}, tool.schema)
assert tool.risk_tier_for_args({"action": action}) == "monitor"
+
+
+# --- Reaching an agent that is in a turn ---------------------------------------
+#
+# Live 2026-10-07: a scope correction sent to a working Claude pane came back
+# not_accepted ("The selected coding agent is busy; nothing was sent."), with
+# no way to deliver it. A busy refusal now says how the USER's correction can
+# reach the turn, and a resend of the same request delivers it exactly once.
+
+
+def fast_queue(monkeypatch):
+ monkeypatch.setattr(orchestration, "_QUEUE_POLL_S", 0.01)
+ monkeypatch.setattr(orchestration.random, "uniform", lambda *_: 0.0)
+
+
+async def until(predicate, timeout_s: float = 2.0) -> None:
+ deadline = time.monotonic() + timeout_s
+ while not predicate():
+ assert time.monotonic() < deadline, "condition never became true"
+ await asyncio.sleep(0.01)
+
+
+async def busy_send(rig, **extra):
+ resolved = await target(rig)
+ rig[2].refused = True
+ args = {"action": "send", **resolved, "request_id": uuid4().hex,
+ "prompt": "Narrow the review to the save flow", **extra}
+ return args, await rig[0].run(args)
+
+
+async def test_ordinary_send_to_a_busy_agent_types_nothing_and_says_how(rig):
+ args, refused = await busy_send(rig)
+ assert refused["status"] == "not_accepted" and refused["busy"] is True
+ assert refused["input_written"] is False
+ assert refused["while_busy_options"] == {"steer": True, "interrupt": True, "queue": True}
+ assert "while_busy='steer'" in refused["next"]
+ assert rig[2].calls[-1]["when_busy"] == "refuse"
+ assert rig[2].typed == []
+
+
+async def test_busy_refusal_then_steer_delivers_the_correction_exactly_once(rig):
+ args, refused = await busy_send(rig)
+ assert refused["status"] == "not_accepted"
+ steered = await rig[0].run({**args, "while_busy": "steer"})
+ assert steered["status"] == "accepted" and steered["mid_turn"] is True
+ assert steered["request_id"] == refused["request_id"]
+ assert rig[2].typed == [args["prompt"]]
+ # Any retry of the request reads its receipt, whatever mode it names.
+ for mode in ("steer", "interrupt", "queue", "refuse"):
+ again = await rig[0].run({**args, "while_busy": mode})
+ assert again["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_steer_on_a_cli_without_mid_turn_input_is_refused_with_options(rig):
+ rig[2].steerable = False
+ args, refused = await busy_send(rig, while_busy="steer")
+ assert refused["status"] == "not_accepted" and refused["busy"] is True
+ assert rig[2].typed == []
+
+
+async def test_interrupt_stops_the_turn_and_delivers_once(rig):
+ args, delivered = await busy_send(rig, while_busy="interrupt")
+ assert delivered["status"] == "accepted"
+ assert rig[2].calls[-1]["when_busy"] == "interrupt"
+ assert rig[2].typed == [args["prompt"]]
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_interrupt_that_does_not_settle_is_queued_then_delivered_once(rig, fast_queue):
+ rig[2].settles = False
+ args, held = await busy_send(rig, while_busy="interrupt")
+ assert held["status"] == "queued" and held["interrupted"] is True
+ assert held["input_written"] is False and rig[2].typed == []
+ # The turn ends on its own; the queue types the correction at the prompt.
+ rig[2].refused = False
+ await until(lambda: rig[2].typed)
+ await until(lambda: not rig[0]._queued)
+ receipt = await rig[0].run(args)
+ assert receipt["status"] == "accepted" and receipt["queued"] is True
+ assert rig[2].typed == [args["prompt"]]
+ # The queue never presses Stop again: only the first attempt interrupted.
+ assert [c.get("when_busy") for c in rig[2].calls].count("interrupt") == 1
+
+
+async def test_queue_holds_the_message_until_the_turn_ends(rig, fast_queue):
+ args, held = await busy_send(rig, while_busy="queue")
+ assert held["status"] == "queued" and "interrupted" not in held
+ assert all(c["when_busy"] == "refuse" for c in rig[2].calls)
+ # While it waits, a retry reads the queued receipt and sends nothing.
+ await asyncio.sleep(0.05)
+ assert (await rig[0].run(args))["status"] == "queued"
+ assert rig[2].typed == []
+ rig[2].refused = False
+ await until(lambda: not rig[0]._queued)
+ assert rig[2].typed == [args["prompt"]]
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_queue_that_never_frees_expires_unsent_and_can_be_retried(
+ rig, fast_queue, monkeypatch,
+):
+ monkeypatch.setattr(orchestration, "_QUEUE_TTL_S", 0.05)
+ args, held = await busy_send(rig, while_busy="queue")
+ assert held["status"] == "queued"
+ await until(lambda: not rig[0]._queued)
+ retried = await rig[0].run({**args, "while_busy": "refuse"})
+ # The expired receipt proved nothing was typed, so this retry was a fresh
+ # attempt, refused again because the pane is still busy.
+ assert retried["status"] == "not_accepted" and retried["busy"] is True
+ rig[2].refused = False
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_a_queue_left_by_an_earlier_app_run_is_expired_not_trusted(rig, fast_queue):
+ args, held = await busy_send(rig, while_busy="queue")
+ assert held["status"] == "queued"
+ # The app stops: its queue task ends without typing. A new orchestrator over
+ # the same receipt store has no task holding that message.
+ for task in list(rig[0]._queued.values()):
+ task.cancel()
+ await until(lambda: not rig[0]._queued)
+ restarted = WorkspaceOrchestrator(rig[1], rig[2], rig[0].ledger)
+ rig[2].refused = False
+ assert (await restarted.run(args))["status"] == "accepted"
+ assert (await restarted.run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_a_receipt_still_marked_queued_without_its_task_is_not_trusted(rig, fast_queue):
+ args, held = await busy_send(rig, while_busy="queue")
+ receipt_id = next(iter(rig[0]._queued))
+ # A hard stop: the task vanished without filing its final receipt.
+ rig[0]._queued.pop(receipt_id).cancel()
+ await asyncio.sleep(0.05)
+ rig[0].ledger.finish("workspace-orchestration", receipt_id, held)
+ rig[2].refused = False
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert rig[2].typed == [args["prompt"]]
+
+
+async def test_unknown_or_misplaced_while_busy_is_rejected(rig):
+ resolved = await target(rig)
+ with pytest.raises(ValueError, match="while_busy must be one of"):
+ await rig[0].run({"action": "send", **resolved, "prompt": "x", "while_busy": "kill"})
+ with pytest.raises(ValueError, match="belongs to send"):
+ await rig[0].run({"action": "context", **resolved, "while_busy": "steer"})
+ assert rig[2].calls == []
+
+
+def test_tool_schema_offers_while_busy_and_shows_it_for_approval():
+ tool = WorkspaceOrchestrationTool(gateway=None)
+ assert tool.schema["properties"]["while_busy"]["enum"] == [
+ "refuse", "steer", "interrupt", "queue",
+ ]
+ 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"})
diff --git a/tests/unit/agentic_ide/test_agent_transcript_events.py b/tests/unit/agentic_ide/test_agent_transcript_events.py
index c176198a8a..9f66df620b 100644
--- a/tests/unit/agentic_ide/test_agent_transcript_events.py
+++ b/tests/unit/agentic_ide/test_agent_transcript_events.py
@@ -292,6 +292,82 @@ class TestClaudeEvents:
whole = list(agent_transcript._rows(path))
assert [row["uuid"] for row in whole] == [f"u-{n}" for n in range(5)]
+ def test_a_message_typed_mid_turn_shows_where_the_agent_took_it(self, tmp_path: Path) -> None:
+ """A correction steered into a running turn is on record, once.
+
+ Claude Code writes a message typed while it works as a human
+ ``queued_command`` attachment and hands it to the model at its next
+ step; there is no user row for it. Without reading it, a delivered
+ correction was invisible to everyone checking that it arrived. A
+ notice the CLI queues itself is not a person speaking.
+ """
+ queued = {
+ "type": "attachment",
+ "timestamp": _at(3),
+ "attachment": {
+ "type": "queued_command",
+ "prompt": "Only review the save flow",
+ "commandMode": "prompt",
+ "origin": {"kind": "human"},
+ },
+ }
+ notice = {
+ "type": "attachment",
+ "timestamp": _at(4),
+ "attachment": {
+ "type": "queued_command",
+ "prompt": "<task-notification>done</task-notification>",
+ "origin": {"kind": "task-notification"},
+ },
+ }
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("Review the folder editor", 0),
+ _assistant({"type": "tool_use", "id": "c1", "name": "Read", "input": {}}, 1),
+ _tool_result("c1", "...", 2),
+ queued,
+ notice,
+ _assistant({"type": "text", "text": "Narrowed to saving."}, 5, mid="m2"),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ assert events is not None
+ users = [ev["payload"]["text"] for ev in events if ev["kind"] == "user_message"]
+ assert users == ["Review the folder editor", "Only review the save flow"]
+ after = events[[ev["kind"] for ev in events].index("user_message", 1) + 1 :]
+ assert [ev["payload"]["text"] for ev in after if ev["kind"] == "assistant_text"] == [
+ "Narrowed to saving."
+ ]
+ assert after[-1]["kind"] == "turn_finished"
+
+ def test_a_queued_message_the_cli_then_submits_is_one_message(self, tmp_path: Path) -> None:
+ _claude_session(
+ tmp_path,
+ "abc",
+ [
+ _user("Review the folder editor", 0),
+ _assistant({"type": "text", "text": "Done."}, 1),
+ {
+ "type": "attachment",
+ "timestamp": _at(2),
+ "attachment": {
+ "type": "queued_command",
+ "prompt": "Only review the save flow",
+ "commandMode": "prompt",
+ "origin": {"kind": "human"},
+ },
+ },
+ _user("Only review the save flow", 3),
+ _assistant({"type": "text", "text": "Narrowed."}, 4, mid="m2"),
+ ],
+ )
+ events = agent_transcript.read_events("claude", "abc", home=tmp_path, live=False)
+ assert events is not None
+ 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_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_send_gate.py b/tests/unit/agentic_ide/test_send_gate.py
index 6a9f5de2e0..fd5563cdcf 100644
--- a/tests/unit/agentic_ide/test_send_gate.py
+++ b/tests/unit/agentic_ide/test_send_gate.py
@@ -16,7 +16,14 @@ from uuid import uuid4
import pytest
from jarvis.agentic_ide import activity, delegation_wait, task_state
-from jarvis.agentic_ide.session import Registry, Session, SessionError, Terminal
+from jarvis.agentic_ide import session as session_module
+from jarvis.agentic_ide.session import (
+ AgentBusyError,
+ Registry,
+ Session,
+ SessionError,
+ Terminal,
+)
from tests.fakes.fake_pty_manager import FakePtyManager
@@ -176,3 +183,150 @@ async def test_fresh_submission_is_busy_before_its_record_appears(pane):
with pytest.raises(SessionError, match="busy"):
await send(registry, workspace, term)
assert sent == []
+
+
+# --- A correction the user directs at a running turn ---------------------------
+#
+# Live 2026-10-07: a scope correction to a Claude pane that was still working
+# came back "The selected coding agent is busy; nothing was sent." Every send
+# demanded an idle pane, so a correction could never reach running work.
+
+
+def working(record, now: float) -> None:
+ write(record, user(now - 299), assistant(now - 5, stop="tool_use"))
+
+
+def keys_pressed(registry, monkeypatch, *, on_stop=None) -> list[str]:
+ pressed: list[str] = []
+
+ def press(key, data, workspace_id=None):
+ pressed.append(data)
+ if on_stop is not None and data == "\x1b":
+ on_stop()
+ return True
+
+ monkeypatch.setattr(registry, "write", press)
+ return pressed
+
+
+async def correct(registry, workspace, term, when_busy: str):
+ return await registry.send_prompt(
+ "pane:" + term.history_id, "Narrow the review to the save flow",
+ workspace_id=workspace.id, require_idle=True, when_busy=when_busy,
+ )
+
+
+async def test_an_ordinary_send_never_reaches_into_a_running_turn(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ pressed = keys_pressed(registry, monkeypatch)
+ now = time.time()
+ submitted(term, now - 300)
+ working(record, now)
+ with pytest.raises(AgentBusyError) as refused:
+ await send(registry, workspace, term)
+ assert not refused.value.interrupted
+ assert sent == [] and pressed == []
+
+
+async def test_steer_types_into_a_running_claude_turn_without_stopping_it(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ pressed = keys_pressed(registry, monkeypatch)
+ now = time.time()
+ submitted(term, now - 300)
+ working(record, now)
+ result = await correct(registry, workspace, term, "steer")
+ assert sent == ["Narrow the review to the save flow"]
+ assert pressed == []
+ assert result.last_send_mid_turn is True
+
+
+async def test_steer_reaches_a_busy_codex_pane(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ term.agent = "codex"
+ term.resume = None # no readable record: the fresh submit itself proves the turn
+ pressed = keys_pressed(registry, monkeypatch)
+ submitted(term, time.time() - 1)
+ result = await correct(registry, workspace, term, "steer")
+ assert sent == ["Narrow the review to the save flow"] and pressed == []
+ assert result.last_send_mid_turn is True
+
+
+async def test_steer_at_an_idle_prompt_is_an_ordinary_send(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ submitted(term, now - 1200)
+ write(record, user(now - 1199), assistant(now - 60), *footer(now - 60))
+ result = await correct(registry, workspace, term, "steer")
+ assert sent == ["Narrow the review to the save flow"]
+ assert result.last_send_mid_turn is False
+
+
+async def test_steer_is_refused_where_the_cli_has_no_mid_turn_input(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ term.agent = "cursor"
+ term.resume = None
+ pressed = keys_pressed(registry, monkeypatch)
+ submitted(term, time.time() - 1)
+ with pytest.raises(AgentBusyError, match="Interrupt it first or queue"):
+ await correct(registry, workspace, term, "steer")
+ assert sent == [] and pressed == []
+
+
[email protected]("when_busy", ["steer", "interrupt"])
+async def test_a_correction_never_answers_an_open_question(pane, monkeypatch, when_busy):
+ registry, workspace, term, record, sent = pane
+ pressed = keys_pressed(registry, monkeypatch)
+ now = time.time()
+ submitted(term, now - 300)
+ write(record, user(now - 299), {"timestamp": at(now - 5), "type": "assistant",
+ "message": {"role": "assistant", "content": [
+ {"type": "tool_use", "name": "AskUserQuestion"}]}})
+ with pytest.raises(SessionError, match="respond") as refused:
+ await correct(registry, workspace, term, when_busy)
+ assert not isinstance(refused.value, AgentBusyError)
+ assert sent == [] and pressed == []
+
+
+async def test_interrupt_stops_the_turn_once_then_delivers(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ monkeypatch.setattr(session_module, "_INTERRUPT_POLL_S", 0.01)
+ now = time.time()
+ submitted(term, now - 300)
+ working(record, now)
+ pressed = keys_pressed(registry, monkeypatch, on_stop=lambda: write(
+ record, user(time.time(), "[Request interrupted by user for tool use]")))
+ result = await correct(registry, workspace, term, "interrupt")
+ assert pressed == ["\x1b"]
+ assert sent == ["Narrow the review to the save flow"]
+ assert result.last_send_mid_turn is False
+
+
+async def test_interrupt_of_a_finished_turn_presses_nothing(pane, monkeypatch):
+ registry, workspace, term, record, sent = pane
+ pressed = keys_pressed(registry, monkeypatch)
+ now = time.time()
+ submitted(term, now - 1200)
+ write(record, user(now - 1199), assistant(now - 60), *footer(now - 60))
+ await correct(registry, workspace, term, "interrupt")
+ assert pressed == [] and sent == ["Narrow the review to the save flow"]
+
+
+async def test_interrupt_that_does_not_settle_types_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)
+ pressed = keys_pressed(registry, monkeypatch)
+ now = time.time()
+ submitted(term, now - 300)
+ working(record, now)
+ with pytest.raises(AgentBusyError) as refused:
+ await correct(registry, workspace, term, "interrupt")
+ assert refused.value.interrupted is True
+ assert pressed == ["\x1b"] and sent == []
+
+
+async def test_unknown_busy_delivery_is_refused(pane):
+ registry, workspace, term, record, sent = pane
+ with pytest.raises(SessionError, match="Unknown busy delivery"):
+ await correct(registry, workspace, term, "kill")
+ assert sent == []