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): stop stale busy refusals and let mixed requests reach named panes

rubenluetke10-beep5d4a1c69bbd2
diff --git a/jarvis/agentic_ide/activity.py b/jarvis/agentic_ide/activity.py
index 44d10978fc..5ad079f960 100644
--- a/jarvis/agentic_ide/activity.py
+++ b/jarvis/agentic_ide/activity.py
@@ -451,6 +451,25 @@ def observed(term: Any, *, now: float | None = None) -> Reading:
return reading
+def send_reading(term: Any, *, now: float | None = None) -> Activity | Literal[""]:
+ """May a new instruction be typed into ``term`` right now?
+
+ For the delivery gate, after the caller refreshed lifecycle evidence
+ (``task_state.probe``): never the sweep's stamp, which can be seconds old
+ or left behind by a sweep that stalled. ``unknown`` means no record proves
+ a running turn AND the screen is not moving, which is a pane sitting at its
+ prompt: an Enter that started no task, a CLI without a readable record, or
+ a remote pane. Refusing it left finished agents "busy" until their next
+ turn (live 2026-10-07: an idle Claude pane refused an approved brief). The
+ submit grace still covers the seconds before a fresh turn shows.
+ """
+ moment = time.time() if now is None else now
+ word = read_activity(term, now=moment)
+ if word == "unknown":
+ word = "waiting"
+ return _submit_graced(term, Reading(word, 0.0), moment).activity
+
+
def has_work_behind_it(term: Any) -> bool:
"""Is this pane's stillness a FINISHED job, or an untouched terminal?
@@ -519,6 +538,7 @@ __all__ = [
"observed",
"read_activity",
"screen_digest",
+ "send_reading",
"shows_question",
"stamp",
"visible_rows",
diff --git a/jarvis/agentic_ide/orchestration.py b/jarvis/agentic_ide/orchestration.py
index 24051d1936..e19b1da87f 100644
--- a/jarvis/agentic_ide/orchestration.py
+++ b/jarvis/agentic_ide/orchestration.py
@@ -55,6 +55,10 @@ _TARGET_KEYS = ("project_id", "workspace_id", "terminal_id")
_RETRY_WINDOW_S = 120
_PANE_ACTIONS = frozenset({"observe", "respond", "keys", "interrupt", "close"})
_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"})
# 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 = {
@@ -194,6 +198,20 @@ def _is_request_id(value: str) -> bool:
return True
+def _never_delivered(receipt: dict) -> bool:
+ """Does this send receipt prove that nothing reached the pane?
+
+ Only the pre-write refusals qualify (the session adapter raises
+ ``SessionError`` before typing anything). An unconfirmed write, a ledger
+ collision or an accepted send is never retried.
+ """
+ return (
+ receipt.get("status") in _PRE_WRITE_REFUSALS
+ and not receipt.get("input_written")
+ and not receipt.get("submitted")
+ )
+
+
def _assignment(args: dict) -> str:
"""The brief AND its chosen images identify a retry."""
return json.dumps([str(args.get("prompt") or "").strip(), args.get("image_refs", [])])
@@ -225,6 +243,9 @@ class WorkspaceOrchestrator:
self._ledger_compatible = False
# request_id -> (target IDs, issued at, prompt sent under it or "")
self._issued: dict[str, tuple[dict[str, str], float, str]] = {}
+ # request_ids minted for a pane the caller NAMED (call-sign, custom
+ # name or ID), never for a first-idle pick or a CLI-kind match.
+ self._named: set[str] = set()
self._issued_lock = threading.Lock()
# Announces new panes to the open UI; set by the runtime that owns a bus.
self.publish: Callable[[Any], Awaitable[Any]] | None = None
@@ -328,6 +349,7 @@ class WorkspaceOrchestrator:
return picked
project, workspace = picked
agents = [a for a in workspace["agents"] if a["accepts_tasks"]]
+ named = []
if agent_ref:
named = _best(agent_ref, agents, lambda a: ((a["id"],), (a["name"],)))
by_cli = [a for a in agents if _matches(agent_ref, a["agent"])]
@@ -369,7 +391,7 @@ class WorkspaceOrchestrator:
"workspace_id": workspace["id"],
"terminal_id": agent["id"],
}
- request_id = self._issue(target)
+ request_id = self._issue(target, named=bool(named))
return {
"status": "resolved",
"request_id": request_id,
@@ -382,14 +404,17 @@ class WorkspaceOrchestrator:
"selection": "explicit_agent" if agent_ref else "first_idle_agent",
}
- def _issue(self, target: dict[str, str]) -> str:
+ def _issue(self, target: dict[str, str], *, named: bool = False) -> str:
"""Mint a request_id for ``target`` and remember it for id repair."""
request_id = uuid4().hex
with self._issued_lock:
now = time.monotonic()
for stale in [k for k, (_, at, _) in self._issued.items() if now - at > _RESOLVE_TTL_S]:
del self._issued[stale]
+ self._named.discard(stale)
self._issued[request_id] = (target, now, "")
+ if named:
+ self._named.add(request_id)
return request_id
async def create(self, args: dict[str, Any], *, trace_id: str = "") -> dict[str, Any]:
@@ -1003,6 +1028,68 @@ class WorkspaceOrchestrator:
target, _, _ = self._issued[request_id]
self._issued[request_id] = (target, time.monotonic(), prompt)
+ async def _gate_existing(
+ self, action: str, args: dict[str, Any], creation: dict[str, Any] | None,
+ ) -> dict[str, Any] | None:
+ """Existing-pane work inside a request that asks for NEW panes.
+
+ Returns the final reply, or ``None`` when the call may proceed. Only a
+ pane the caller NAMED qualifies — its call-sign, custom name or ID via
+ resolve. A first-idle pick, a CLI-kind match ("the Claude Code agent")
+ or a bare terminal_id is how a new task used to land on an old pane, so
+ those stay refused, as do restore/show and this request's own brief.
+ """
+ refusal: dict[str, Any] = {
+ "status": "new_agent_required", "success": False,
+ "reason": "This request asks for NEW panes: use create (or open_workspace for a "
+ "new workspace). An existing agent is addressed only by its name "
+ "(resolve with agent=<its call-sign or name>); never an idle pick, a CLI "
+ "kind, this request's new task, or a correction to other agents.",
+ "creation": creation,
+ }
+ agent_ref = str(args.get("agent") or "").strip()
+ if action == "resolve":
+ graph = await asyncio.to_thread(self.graph)
+ if agent_ref:
+ resolved = self.resolve(args, graph)
+ if resolved.get("status") != "resolved" or resolved["request_id"] in self._named:
+ return resolved
+ with self._issued_lock:
+ self._issued.pop(resolved["request_id"], None)
+ # The IDs a following create needs, without minting a pane target.
+ picked = self._workspace(args, graph, "")
+ if isinstance(picked, tuple):
+ project, workspace = picked
+ refusal |= {
+ "project_id": project["id"], "project": project["name"],
+ "workspace_id": workspace["id"], "workspace": workspace["name"],
+ }
+ return refusal
+ if action not in {"send", *_PANE_ACTIONS}:
+ return refusal
+ if action != "send" and agent_ref and not str(args.get("terminal_id") or "").strip():
+ resolved = self.resolve(args, await asyncio.to_thread(self.graph))
+ if resolved.get("status") != "resolved":
+ return resolved
+ return None if resolved["request_id"] in self._named else refusal
+ _, match = self._reconcile(args, action)
+ if match not in self._named:
+ return refusal
+ if action == "send":
+ assignment = _assignment(args)
+ with self._issued_lock:
+ briefs = {
+ self._issued[a["request_id"]][2]
+ for a in (creation or {}).get("agents", [])
+ if a.get("request_id") in self._issued
+ }
+ if assignment in briefs:
+ # The new panes' brief must not also reach an old pane.
+ return {**refusal, "status": "delivery_already_owned",
+ "reason": "This task already went to the panes this request created. "
+ "Observe those IDs; do not hand it to another agent."}
+ return None
+
async def run(self, args: dict[str, Any], *, trace_id: str = "") -> dict[str, Any]:
if not self._ledger_compatible:
return {
@@ -1025,22 +1112,19 @@ class WorkspaceOrchestrator:
# open_workspace always starts a NEW workspace with NEW panes, so it is
# a creation like create (live 2026-10-07: a new-agent workspace request
# was refused as pane reuse and nothing opened).
- if (args.get("_requires_new") or creation) and action not in {
+ created = {a["terminal_id"] for a in (creation or {}).get("agents", [])}
+ to_created = action == "send" and str(args.get("terminal_id") or "") in created
+ if (args.get("_requires_new") or creation) and not to_created and action not in {
"inspect", "create", "open_workspace", "context", "observe",
}:
- allowed = {
- a["terminal_id"] for a in (creation or {}).get("agents", [])
- }
- # A NEW request cannot borrow an idle pane or repair existing tasks.
- # Only an exact ID from this request's creation may be addressed.
- if action != "send" or str(args.get("terminal_id") or "") not in allowed:
- return {
- "status": "new_agent_required", "success": False,
- "reason": "This request requires NEW panes. Use create (or open_workspace "
- "for a new workspace); do not resolve, reuse or send "
- "correction prompts to existing agents.",
- "creation": creation,
- }
+ # A NEW request cannot borrow an idle pane for its new task, but it
+ # may also carry independent work for an agent the user NAMED
+ # (live 2026-10-07: "first update the PR #430 session, then start a
+ # new bug-fix session" refused the update as pane reuse).
+ gated = await self._gate_existing(action, args, creation)
+ if gated is not None:
+ return gated
+ if creation and to_created:
# create(prompt=...) already owns delivery, including uncertainty.
if creation and (creation.get("deliveries") or creation.get("status") == "uncertain"):
return {
@@ -1088,16 +1172,21 @@ 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))
- previous = await asyncio.to_thread(
- self.ledger.claim,
- "workspace-orchestration",
- request_id,
- "send",
- {**target, "prompt": prompt, "image_refs": refs,
- **({"image_scope": image_scope} if refs else {})},
- 0,
- deduplicate_unconfirmed=True,
- )
+ 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
+ # pane) does not spend the request: retrying the same assignment
+ # takes the next attempt slot. Anything else, including an
+ # unconfirmed write, stays the answer (live 2026-10-07: an approved
+ # brief refused as "busy" could never be retried once idle).
+ for attempt in range(_REFUSED_ATTEMPTS):
+ receipt_id = request_id if not attempt else f"{request_id}~{attempt}"
+ previous = await asyncio.to_thread(
+ self.ledger.claim, "workspace-orchestration", receipt_id, "send",
+ claimed, 0, deduplicate_unconfirmed=True,
+ )
+ if previous is None or not _never_delivered(previous):
+ break
if previous is not None:
return {"target": target, "request_id": request_id, **previous}
owner = self.registry.get(workspace_id)
@@ -1168,7 +1257,7 @@ class WorkspaceOrchestrator:
if action == "send":
result["request_id"] = request_id
await asyncio.to_thread(
- self.ledger.finish, "workspace-orchestration", request_id, result
+ self.ledger.finish, "workspace-orchestration", receipt_id, result
)
return result
diff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.py
index a6b7ac42e7..ccac285a61 100644
--- a/jarvis/agentic_ide/session.py
+++ b/jarvis/agentic_ide/session.py
@@ -6687,13 +6687,21 @@ class Registry:
):
raise SessionError("The input request changed; nothing was sent.")
if require_idle:
- activity = term.reading().activity
+ # 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 != "waiting"
+ has_submission and activity not in ("waiting", "stopped")
):
raise SessionError("The selected coding agent is busy; nothing was sent.")
pending = None
diff --git a/jarvis/agentic_ide/task_state.py b/jarvis/agentic_ide/task_state.py
index a8c66fb024..ac8c83bf41 100644
--- a/jarvis/agentic_ide/task_state.py
+++ b/jarvis/agentic_ide/task_state.py
@@ -82,6 +82,11 @@ def transition(agent: str, row: dict) -> tuple[str, float] | None:
if kind not in {"user", "assistant"} or not isinstance(message, dict):
return None
content = message.get("content")
+ if kind == "user" and row.get("queueTranscriptOnly"):
+ # Claude Code records a queued notice (e.g. "background command did
+ # not finish before the previous session ended") without starting a
+ # turn. Reading it as work left an idle pane "working" for good.
+ return None
if kind == "user":
texts = [content] if isinstance(content, str) else [
b.get("text", "") for b in content or [] if isinstance(b, dict)
@@ -132,7 +137,7 @@ def _read(key: tuple, now: float) -> Evidence:
for raw in handle:
try:
row = json.loads(raw)
- except (ValueError, UnicodeDecodeError): # The writer may still be completing its final JSON line.
+ except (ValueError, UnicodeDecodeError):
result = Evidence(checked_at=now)
continue # The writer may not have completed its last JSON line.
if not isinstance(row, dict):
diff --git a/tests/contract/test_workspace_dispatch_isolation.py b/tests/contract/test_workspace_dispatch_isolation.py
index c325f171e6..e2e2268113 100644
--- a/tests/contract/test_workspace_dispatch_isolation.py
+++ b/tests/contract/test_workspace_dispatch_isolation.py
@@ -463,3 +463,131 @@ async def test_new_request_still_cannot_reopen_or_show_existing_workspaces(rig,
{"action": action, "workspace": "Personal Jarvis"}, context(OPEN_TEXT)
)
assert result.output["status"] == "new_agent_required"
+
+
+MIXED_TEXT = (
+ "First send the approved brief to Alex in Personal Jarvis, then start a new Codex "
+ "session to fix audio mute."
+)
+
+
+def named_pane(rig, workspace="Personal Jarvis"):
+ owner = next(w for w in rig[1].sessions if w.name == workspace)
+ return owner, owner.terminals[0]
+
+
+ "create_first", [False, True], ids=["update-then-create", "create-then-update"]
+)
+async def test_mixed_request_updates_the_named_pane_and_creates_a_new_one(
+ rig, runnable, create_first
+):
+ # Live 2026-10-07: "first update the PR #430 session, then create a new
+ # bug-fix session" refused the update (and a retry) as pane reuse.
+ orchestrator, registry, sessions = rig
+ tool = WorkspaceOrchestrationTool(orchestrator)
+ assert dispatch_context(MIXED_TEXT, {}, "turn")["_requires_new"]
+ owner, old = named_pane(rig)
+ old_id = "pane:" + old.history_id
+
+ async def update():
+ resolved = await tool.execute(
+ {"action": "resolve", "workspace": "Personal Jarvis", "agent": "Alex"},
+ context(MIXED_TEXT),
+ )
+ assert resolved.output["status"] == "resolved", resolved.output
+ assert resolved.output["target"]["terminal_id"] == old_id
+ sent = await tool.execute(
+ {"action": "send", **{k: resolved.output["target"][k] for k in (
+ "project_id", "workspace_id", "terminal_id")},
+ "request_id": resolved.output["request_id"], "prompt": "Apply the approved plan"},
+ context(MIXED_TEXT),
+ )
+ assert sent.success, sent.output
+ return sent
+
+ async def create():
+ made = await tool.execute(create_args(), context(MIXED_TEXT))
+ assert made.success, made.output
+ return made.output["agents"][0]["terminal_id"]
+
+ if create_first:
+ new_id = await create()
+ await update()
+ else:
+ await update()
+ new_id = await create()
+ assert new_id != old_id
+ assert sorted(c["terminal_id"] for c in sessions.calls) == sorted([old_id, new_id])
+ briefs = {c["terminal_id"]: c["prompt"] for c in sessions.calls}
+ assert briefs == {old_id: "Apply the approved plan", new_id: "Fix output mute"}
+
+
[email protected]("agent", ["", "Codex", "codex"])
+async def test_new_request_never_picks_an_idle_or_cli_kind_pane(rig, agent):
+ tool = WorkspaceOrchestrationTool(rig[0])
+ args = {"action": "resolve", "workspace": "Personal Jarvis"}
+ if agent:
+ args["agent"] = agent
+ result = await tool.execute(args, context(MIXED_TEXT))
+ assert result.output["status"] == "new_agent_required"
+ # The refusal still hands over the IDs a following create needs.
+ owner, _ = named_pane(rig)
+ assert result.output["workspace_id"] == owner.id
+ assert result.output["project_id"] == owner.project_id
+ assert not rig[2].calls
+
+
+async def test_new_panes_brief_cannot_also_go_to_a_named_old_pane(rig, runnable):
+ tool = WorkspaceOrchestrationTool(rig[0])
+ made = await tool.execute(create_args(), context(MIXED_TEXT))
+ assert made.success
+ resolved = await tool.execute(
+ {"action": "resolve", "workspace": "Personal Jarvis", "agent": "Alex"},
+ context(MIXED_TEXT),
+ )
+ duplicate = await tool.execute(
+ {"action": "send", **{k: resolved.output["target"][k] for k in (
+ "project_id", "workspace_id", "terminal_id")},
+ "request_id": resolved.output["request_id"], "prompt": "Fix output mute"},
+ context(MIXED_TEXT),
+ )
+ assert duplicate.output["status"] == "delivery_already_owned"
+ assert [c["terminal_id"] for c in rig[2].calls] == [made.output["agents"][0]["terminal_id"]]
+
+
+async def test_named_update_refused_as_busy_retries_with_the_same_request_id(rig, runnable):
+ tool = WorkspaceOrchestrationTool(rig[0])
+ resolved = await tool.execute(
+ {"action": "resolve", "workspace": "Personal Jarvis", "agent": "Alex"},
+ context(MIXED_TEXT),
+ )
+ args = {"action": "send", **{k: resolved.output["target"][k] for k in (
+ "project_id", "workspace_id", "terminal_id")},
+ "request_id": resolved.output["request_id"], "prompt": "Apply the approved plan"}
+ rig[2].refused = True
+ busy = await tool.execute(args, context(MIXED_TEXT))
+ assert busy.output["status"] == "not_accepted"
+ rig[2].refused = False
+ # Proven non-delivery: the same request may go once the pane is idle.
+ retry = await tool.execute(args, context(MIXED_TEXT))
+ assert retry.success and retry.output["status"] == "accepted"
+ assert (await tool.execute(args, context(MIXED_TEXT))).output["status"] == "accepted"
+ assert len(rig[2].calls) == 2
+
+
+async def test_named_pane_actions_stay_available_in_a_new_request(rig):
+ tool = WorkspaceOrchestrationTool(rig[0])
+ owner, old = named_pane(rig)
+ blind = await tool.execute(
+ {"action": "interrupt", "workspace_id": owner.id,
+ "terminal_id": "pane:" + old.history_id},
+ context(MIXED_TEXT),
+ )
+ assert blind.output["status"] == "new_agent_required"
+ pressed = await tool.execute(
+ {"action": "interrupt", "workspace": "Personal Jarvis", "agent": "Alex"},
+ context(MIXED_TEXT),
+ )
+ assert pressed.output["status"] != "new_agent_required"
+ assert pressed.output["target"]["terminal_id"] == "pane:" + old.history_id
diff --git a/tests/contract/test_workspace_orchestration.py b/tests/contract/test_workspace_orchestration.py
index 4843c8522d..2f072d2518 100644
--- a/tests/contract/test_workspace_orchestration.py
+++ b/tests/contract/test_workspace_orchestration.py
@@ -255,13 +255,39 @@ def test_send_runs_without_a_spoken_question_and_reads_remain_safe(rig):
async def test_prewrite_refusal_is_recorded_without_claiming_uncertainty(rig):
+ # Live 2026-10-07: an approved brief refused as "busy" kept echoing that
+ # receipt for its request_id after the pane was idle; nothing ever went.
resolved = await target(rig)
rig[2].refused = True
args = {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}
first = await rig[0].run(args)
assert first["status"] == "not_accepted"
- assert await rig[0].run(args) == first
- assert len(rig[2].calls) == 1
+ again = await rig[0].run(args)
+ assert again["status"] == "not_accepted"
+ assert again["request_id"] == first["request_id"]
+ assert len(rig[2].calls) == 2
+ rig[2].refused = False
+ delivered = await rig[0].run(args)
+ assert delivered["status"] == "accepted"
+ assert delivered["request_id"] == first["request_id"]
+ # Once typed, the same request is a receipt read, never a second write.
+ assert (await rig[0].run(args))["status"] == "accepted"
+ assert len(rig[2].calls) == 3
+ # A refused request ID still cannot carry a different assignment.
+ assert (await rig[0].run({**args, "prompt": "Correction"}))["success"] is False
+ assert len(rig[2].calls) == 3
+
+
+async def test_retry_after_uncertain_write_is_never_retyped(rig):
+ resolved = await target(rig)
+ args = {"action": "send", **resolved, "request_id": uuid4().hex, "prompt": "Task"}
+ rig[2].refused = True
+ assert (await rig[0].run(args))["status"] == "not_accepted"
+ rig[2].refused, rig[2].fail = False, True
+ assert (await rig[0].run(args))["status"] == "uncertain"
+ rig[2].fail = False
+ assert (await rig[0].run(args))["status"] == "uncertain"
+ assert len(rig[2].calls) == 2
async def test_later_same_task_has_an_app_minted_distinct_request(rig):
diff --git a/tests/unit/agentic_ide/test_send_gate.py b/tests/unit/agentic_ide/test_send_gate.py
new file mode 100644
index 0000000000..6a9f5de2e0
--- /dev/null
+++ b/tests/unit/agentic_ide/test_send_gate.py
@@ -0,0 +1,178 @@
+"""The delivery gate judges a pane on fresh lifecycle evidence, not a stale stamp.
+
+Live 2026-10-07: an idle Claude pane that had finished its turn (recap shown,
+empty input) refused an approved brief as "busy", and a pane whose transcript
+ended in a queued notice that never started a turn read "working" for an hour.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import UTC, datetime
+from types import SimpleNamespace
+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 tests.fakes.fake_pty_manager import FakePtyManager
+
+
[email protected](autouse=True)
+def clean_evidence():
+ task_state.reset()
+ yield
+ task_state.reset()
+
+
+def at(moment: float) -> str:
+ return datetime.fromtimestamp(moment, UTC).isoformat()
+
+
+def user(moment: float, text: str = "Analyse PR #430", **extra) -> dict:
+ return {"timestamp": at(moment), "type": "user",
+ "message": {"role": "user", "content": text}, **extra}
+
+
+def assistant(moment: float, stop: str = "end_turn") -> dict:
+ return {"timestamp": at(moment), "type": "assistant",
+ "message": {"role": "assistant", "stop_reason": stop,
+ "content": [{"type": "text", "text": "Done."}]}}
+
+
+def footer(moment: float) -> list[dict]:
+ return [
+ {"timestamp": at(moment), "type": "system", "subtype": "stop_hook_summary"},
+ {"timestamp": at(moment), "type": "system", "subtype": "turn_duration"},
+ {"timestamp": at(moment + 180), "type": "system", "subtype": "away_summary"},
+ ]
+
+
+def notice(moment: float) -> dict:
+ """The row Claude Code writes for a queued notice that starts no turn."""
+ return user(
+ moment,
+ "<task-notification>\n<status>stopped</status>\n<summary>Background shell "
+ "command didn't finish before the previous session ended</summary>\n"
+ "</task-notification>",
+ origin={"kind": "task-notification"}, promptSource="system",
+ queueTranscriptOnly=True,
+ )
+
+
+def pane(tmp_path, monkeypatch):
+ record = tmp_path / "session.jsonl"
+ record.write_text("", encoding="utf-8")
+ monkeypatch.setattr(task_state.agent_transcript, "_claude_file", lambda *_: record)
+ registry = Registry(pty_manager=FakePtyManager())
+ term = Terminal("t1", "T1", "claude", "Claude Code", 0, status="live")
+ term.pty_id = "pty-1"
+ term.resume = SimpleNamespace(id="session")
+ workspace = Session(
+ id=uuid4().hex, folder=str(tmp_path), name="pull requests", profile=None,
+ terminals=[term], created_at=1, project_id="project",
+ )
+ registry._sessions[workspace.id] = workspace
+ sent: list[str] = []
+
+ async def deliver(identity, text, **_):
+ sent.append(text)
+ return term
+
+ monkeypatch.setattr(registry, "_send_prompt_locked", deliver)
+ monkeypatch.setattr(delegation_wait, "track_submission", lambda *_: None)
+ return registry, workspace, term, record, sent
+
+
+def write(record, *rows):
+ with record.open("a", encoding="utf-8") as handle:
+ for row in rows:
+ handle.write(json.dumps(row) + "\n")
+
+
+def submitted(term, moment: float) -> None:
+ term.last_submit_at = moment
+ term.submit_generation = term.process_generation
+
+
+async def send(registry, workspace, term):
+ await registry.send_prompt(
+ "pane:" + term.history_id, "Updated brief", workspace_id=workspace.id,
+ require_idle=True,
+ )
+
+
+async def test_finished_turn_is_sendable_despite_a_stale_working_stamp(pane):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ submitted(term, now - 1200)
+ write(record, user(now - 1199), assistant(now - 60), *footer(now - 60))
+ # The sweep's last word, from while the turn ran, is still "fresh".
+ activity.stamp(term, "working", now=now)
+ await send(registry, workspace, term)
+ assert sent == ["Updated brief"]
+
+
+async def test_enter_that_started_no_turn_does_not_make_the_pane_busy(pane):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ write(record, user(now - 1200), assistant(now - 600), *footer(now - 600))
+ # An empty Enter / slash command after the turn: a submit with no record.
+ submitted(term, now - 120)
+ await task_state.probe(term)
+ assert activity.read_activity(term) == "unknown" # the badge stays honest
+ activity.stamp(term, "unknown", now=now)
+ await send(registry, workspace, term)
+ assert sent == ["Updated brief"]
+
+
+async def test_queued_notice_does_not_keep_a_finished_pane_working(pane):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ submitted(term, now - 3600)
+ write(record, user(now - 3599), assistant(now - 3000), *footer(now - 3000),
+ notice(now - 1800))
+ await task_state.probe(term)
+ assert activity.read_activity(term) == "waiting"
+ await send(registry, workspace, term)
+ assert sent == ["Updated brief"]
+
+
+async def test_an_interrupted_turn_accepts_the_next_instruction(pane):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ submitted(term, now - 300)
+ write(record, user(now - 299), user(now - 200, "[Request interrupted by user]"))
+ await send(registry, workspace, term)
+ assert sent == ["Updated brief"]
+
+
[email protected]("last", ["tool_use", "question"])
+async def test_a_running_turn_or_open_question_still_refuses(pane, last):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ submitted(term, now - 300)
+ write(record, user(now - 299))
+ if last == "tool_use":
+ write(record, assistant(now - 5, stop="tool_use"))
+ else:
+ write(record, {"timestamp": at(now - 5), "type": "assistant",
+ "message": {"role": "assistant", "content": [
+ {"type": "tool_use", "name": "AskUserQuestion"}]}})
+ activity.stamp(term, "waiting", now=now) # even a stamp saying otherwise
+ with pytest.raises(SessionError, match="busy"):
+ await send(registry, workspace, term)
+ assert sent == []
+
+
+async def test_fresh_submission_is_busy_before_its_record_appears(pane):
+ registry, workspace, term, record, sent = pane
+ now = time.time()
+ write(record, user(now - 600), assistant(now - 500), *footer(now - 500))
+ submitted(term, now - 1) # just sent; the CLI has not written its row yet
+ with pytest.raises(SessionError, match="busy"):
+ await send(registry, workspace, term)
+ assert sent == []
diff --git a/tests/unit/agentic_ide/test_task_state.py b/tests/unit/agentic_ide/test_task_state.py
index f66ce05e64..8dc0cc90a5 100644
--- a/tests/unit/agentic_ide/test_task_state.py
+++ b/tests/unit/agentic_ide/test_task_state.py
@@ -147,6 +147,9 @@ async def test_unchanged_file_is_not_parsed_again(pane, monkeypatch):
({"type": "assistant", "message": {"content": [
{"type": "tool_use", "name": "AskUserQuestion"}]}}, "asking"),
({"type": "user", "message": {"content": "[Request interrupted by user]"}}, "stopped"),
+ ({"type": "user", "message": {"content": "<task-notification>"}}, "working"),
+ ({"type": "user", "queueTranscriptOnly": True,
+ "message": {"content": "<task-notification>"}}, None),
({"type": "system", "subtype": "turn_duration"}, "completed"),
({"type": "assistant", "isSidechain": True,
"message": {"stop_reason": "end_turn"}}, None),