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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(agentic-ide): let an ordered pane delivery survive the caller's hangup
rubenluetke10-beep892d330ede04
diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.pyindex 3a83172d9a..2fdd42f77c 100644--- a/jarvis/agentic_ide/fanout.py+++ b/jarvis/agentic_ide/fanout.py@@ -183,6 +183,83 @@ async def _finish_prompt_attachments_shielded(raise+#: Fan-outs whose caller was cancelled mid-delivery (voice hangup, dropped+#: HTTP client). The strong reference is what keeps a detached fan-out alive+#: until every pane has its verdict; the done-callback below is what makes+#: that verdict diagnosable from the log once nobody is left to speak it+#: (AP-30: a swallowed outcome reads as "the feature does nothing").+_DETACHED_DELIVERIES: set[asyncio.Future[Any]] = set()+++def _finish_detached(work: asyncio.Future[Any], names: tuple[str, ...]) -> None:+ """Log how a detached fan-out ended — its caller can no longer report it."""+ _DETACHED_DELIVERIES.discard(work)+ if work.cancelled():+ log.warning(+ "Agentic IDE fan-out (detached): delivery for %s was cancelled "+ "before it could finish — those panes received nothing",+ ", ".join(names),+ )+ return+ exc = work.exception()+ if exc is not None:+ log.warning(+ "Agentic IDE fan-out (detached): delivery for %s failed: %r",+ ", ".join(names),+ exc,+ )+ return+ for name, result in zip(names, work.result(), strict=False):+ if isinstance(result, Delivery):+ log.info(+ "Agentic IDE fan-out (detached): %s → %s",+ result.terminal,+ "delivered" if result.delivered else (result.reason_code or "failed"),+ )+ else:+ log.warning(+ "Agentic IDE fan-out (detached): %s failed unexpectedly: %r",+ name,+ result,+ )+++def note_detached_delivery(work: asyncio.Future[Any], *, describe: str) -> None:+ """Keep a caller-cancelled delivery alive and log how it ends.++ For delivery paths OUTSIDE this module's fan-out (the single-pane REST+ prompt route) that need the same survival property: the caller re-raises+ its cancellation, the work keeps the strong reference it needs to finish,+ and its outcome lands in the log because nobody is left to speak it+ (AP-30).+ """+ _DETACHED_DELIVERIES.add(work)++ def _done(task: asyncio.Future[Any]) -> None:+ _DETACHED_DELIVERIES.discard(task)+ if task.cancelled():+ log.warning(+ "Agentic IDE (detached): %s was cancelled before it finished — "+ "nothing was typed",+ describe,+ )+ return+ exc = task.exception()+ if exc is not None:+ log.warning("Agentic IDE (detached): %s failed: %r", describe, exc)+ return+ log.info(+ "Agentic IDE (detached): %s finished after its caller went away",+ describe,+ )++ work.add_done_callback(_done)+ log.warning(+ "Agentic IDE: caller cancelled mid-delivery — finishing %s detached",+ describe,+ )++async def _default_compose(utterance: str, **kwargs: Any) -> Any:from .prompt_composer import compose as compose_prompt@@ -231,6 +308,11 @@ async def deliver(Never raises for a single pane. A pane that is missing, not running, whoseprompt could not be written, or whose PTY write failed comes back as anundelivered ``Delivery`` carrying the reason.++ Survives its caller. Once the fleet is composing, cancelling this call —+ a voice hangup, a disconnected client — re-raises for the caller but lets+ the briefs finish detached: hanging up ends the conversation, not the+ order the user already gave. The detached outcome is logged per pane."""wanted = _unique(terminals)if not wanted:@@ -389,9 +471,32 @@ async def deliver(# return_exceptions is deliberate belt-and-braces: `one` already contains# every failure it can foresee, and an unforeseen one must still not cancel# the siblings mid-write.- results = await asyncio.gather(- *(one(name) for name in wanted), return_exceptions=True+ work = asyncio.ensure_future(+ asyncio.gather(*(one(name) for name in wanted), return_exceptions=True))+ try:+ results = await asyncio.shield(work)+ except asyncio.CancelledError:+ if work.cancelled():+ raise+ # The CALLER died mid-delivery — a voice hangup, a disconnected HTTP+ # client — not the fleet. The order was accepted before the composer+ # started, and cancelling here is how "prompt T1 …" ended as a pane+ # that never received anything while the user believed it had (live+ # 2026-08-06 18:49/18:52: both turns were cancelled inside a 15-20 s+ # subscription-CLI composition and nothing was ever typed). Hanging up+ # ends the CONVERSATION — the spoken verdict is dropped — but the+ # briefs still land; the receipt (`last_prompt_at`) stays the proof.+ _DETACHED_DELIVERIES.add(work)+ work.add_done_callback(+ lambda task, names=tuple(wanted): _finish_detached(task, names)+ )+ log.warning(+ "Agentic IDE fan-out: caller cancelled mid-delivery — finishing "+ "the briefs for %s detached",+ ", ".join(wanted),+ )+ raisedeliveries: list[Delivery] = []for name, result in zip(wanted, results, strict=True):if isinstance(result, Delivery):diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex f5dc5d46e8..eced08b311 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -2917,110 +2917,135 @@ async def terminal_prompt(request: Request, name: str, req: PromptRequest) -> distatus_code=404, detail=_unknown_terminal_detail(registry, name))- text = req.prompt- composed_by = "raw"- files: list[str] = []- attachments = [- drop_analysis.DropAnalysis.from_dict(a.model_dump()) for a in req.attachments- ]- if req.compose:- from jarvis.agentic_ide.prompt_composer import compose as compose_prompt-- # The pane decides which workspace composes the prompt. Composition- # reads the codebase to attach `@file` references, and taking those- # from the front workspace while sending to a pane in another one would- # point the agent at files that are not in its tree.- session, term_for_compose = found- result = await compose_prompt(- req.prompt,- session=session,- terminal_name=term_for_compose.name,- agent_display=AGENT_DISPLAY.get(term_for_compose.agent, term_for_compose.agent),- attachments=attachments,- )- text, composed_by, files = result.text, result.composed_by, result.files- if not text:- raise HTTPException(status_code=422, detail="The prompt was empty after composition.")- elif attachments:- # Attachments without composition still have to reach the agent. Silently- # dropping them would be the worst reading of this request: the caller- # said "here is what the user dropped" and the agent would receive a- # sentence about a screenshot nobody described. The deterministic- # renderer is the same one the no-provider path uses.- from jarvis.agentic_ide import prompt_blueprint-- text = sanitize_prompt(- prompt_blueprint.render_fallback(text, [], attachments), keep_newlines=True- )[:MAX_PROMPT_CHARS]- composed_by = "fallback"+ async def _compose_and_send() -> dict:+ text = req.prompt+ composed_by = "raw"+ files: list[str] = []+ attachments = [+ drop_analysis.DropAnalysis.from_dict(a.model_dump())+ for a in req.attachments+ ]+ if req.compose:+ from jarvis.agentic_ide.prompt_composer import compose as compose_prompt++ # The pane decides which workspace composes the prompt. Composition+ # reads the codebase to attach `@file` references, and taking those+ # from the front workspace while sending to a pane in another one would+ # point the agent at files that are not in its tree.+ session, term_for_compose = found+ result = await compose_prompt(+ req.prompt,+ session=session,+ terminal_name=term_for_compose.name,+ agent_display=AGENT_DISPLAY.get(+ term_for_compose.agent, term_for_compose.agent+ ),+ attachments=attachments,+ )+ text, composed_by, files = result.text, result.composed_by, result.files+ if not text:+ raise HTTPException(+ status_code=422, detail="The prompt was empty after composition."+ )+ elif attachments:+ # Attachments without composition still have to reach the agent. Silently+ # dropping them would be the worst reading of this request: the caller+ # said "here is what the user dropped" and the agent would receive a+ # sentence about a screenshot nobody described. The deterministic+ # renderer is the same one the no-provider path uses.+ from jarvis.agentic_ide import prompt_blueprint++ text = sanitize_prompt(+ prompt_blueprint.render_fallback(text, [], attachments),+ keep_newlines=True,+ )[:MAX_PROMPT_CHARS]+ composed_by = "fallback"++ if req.dry_run:+ return {+ "ok": True,+ "terminal": name,+ "sent": "",+ "composed": text,+ "composed_by": composed_by,+ "files": files,+ "attachments": [a.to_dict() for a in attachments],+ "dry_run": True,+ }- if req.dry_run:+ try:+ term = await registry.send_prompt(name, text)+ except SessionError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++ # Say out loud that a prompt went in.+ #+ # Until now the ONLY sign was the agent echoing it back down that pane's own+ # terminal socket — one path, with no second opinion anywhere in the app. So+ # whenever that path was interrupted (a viewer that had lost its pane, a+ # window that was not looking, a socket in the middle of a slow reconnect)+ # the user was told the prompt had been sent and watched a screen where+ # nothing whatsoever happened, which reads as "it did nothing" (reported+ # 2026-07-28). This event is independent of the pane: it arrives on the app+ # socket every client already holds.+ bus = getattr(request.app.state, "bus", None)+ if bus is not None:+ try:+ await bus.publish(+ prompt_sent_event(found[0], term, source_layer="agentic_ide_routes")+ )+ except Exception as exc: # noqa: BLE001 - notification is not the work+ log.debug("AgenticIdePromptSent publish failed: %s", exc)++ # `submitted` is the honest part of this answer, and it has THREE states:+ # True the agent accepted the prompt and started, False the text is provably+ # still in its input box, null the pane never visibly took it and no claim+ # can be made either way. Collapsing null into False used to report "the+ # text is sitting in its input box" about a pane where it demonstrably was+ # not — a confident answer nobody had. A caller that reports "sent to Mika"+ # on anything but True is lying to the user.return {"ok": True,- "terminal": name,- "sent": "",- "composed": text,+ "terminal": term.name,+ "agent": AGENT_DISPLAY.get(term.agent, term.agent),+ "sent": term.last_prompt,"composed_by": composed_by,"files": files,- "attachments": [a.to_dict() for a in attachments],- "dry_run": True,+ "prompts_sent": term.prompts_sent,+ "submitted": term.submitted,+ "detail": (+ ""+ if term.submitted is True+ else (+ f"{term.name} did not accept the prompt — the text is sitting in "+ "its input box. Tell the user, and let them press Enter there."+ )+ if term.submitted is False+ else (+ f"{term.name} never showed the prompt arriving, so it may have "+ "started or may have missed it entirely. Tell the user to check "+ "that pane."+ )+ ),}+ # The delivery must survive its caller. This is the route a spoken "prompt+ # T1 …" executes through, and composition holds it for up to+ # COMPOSE_TIMEOUT_S — a voice hangup (or a dropped client) used to cancel+ # the handler mid-compose, so nothing was ever typed while the user+ # believed the pane was working (live 2026-08-06 18:52). A dry run has no+ # side effect worth protecting, and skipping the extra task keeps it cheap.+ if req.dry_run:+ return await _compose_and_send()+ work = asyncio.ensure_future(_compose_and_send())try:- term = await registry.send_prompt(name, text)- except SessionError as exc:- raise HTTPException(status_code=409, detail=str(exc)) from exc+ return await asyncio.shield(work)+ except asyncio.CancelledError:+ if not work.cancelled():+ from jarvis.agentic_ide.fanout import note_detached_delivery- # Say out loud that a prompt went in.- #- # Until now the ONLY sign was the agent echoing it back down that pane's own- # terminal socket — one path, with no second opinion anywhere in the app. So- # whenever that path was interrupted (a viewer that had lost its pane, a- # window that was not looking, a socket in the middle of a slow reconnect)- # the user was told the prompt had been sent and watched a screen where- # nothing whatsoever happened, which reads as "it did nothing" (reported- # 2026-07-28). This event is independent of the pane: it arrives on the app- # socket every client already holds.- bus = getattr(request.app.state, "bus", None)- if bus is not None:- try:- await bus.publish(- prompt_sent_event(found[0], term, source_layer="agentic_ide_routes")- )- except Exception as exc: # noqa: BLE001 - notification is not the work- log.debug("AgenticIdePromptSent publish failed: %s", exc)-- # `submitted` is the honest part of this answer, and it has THREE states:- # True the agent accepted the prompt and started, False the text is provably- # still in its input box, null the pane never visibly took it and no claim- # can be made either way. Collapsing null into False used to report "the- # text is sitting in its input box" about a pane where it demonstrably was- # not — a confident answer nobody had. A caller that reports "sent to Mika"- # on anything but True is lying to the user.- return {- "ok": True,- "terminal": term.name,- "agent": AGENT_DISPLAY.get(term.agent, term.agent),- "sent": term.last_prompt,- "composed_by": composed_by,- "files": files,- "prompts_sent": term.prompts_sent,- "submitted": term.submitted,- "detail": (- ""- if term.submitted is True- else (- f"{term.name} did not accept the prompt — the text is sitting in "- "its input box. Tell the user, and let them press Enter there."- )- if term.submitted is False- else (- f"{term.name} never showed the prompt arriving, so it may have "- "started or may have missed it entirely. Tell the user to check "- "that pane."- )- ),- }+ note_detached_delivery(work, describe=f"the prompt for {name}")+ raise# --------------------------------------------------------------------------- #diff --git a/tests/unit/agentic_ide/test_fanout.py b/tests/unit/agentic_ide/test_fanout.pyindex a167fcf784..10f1b23618 100644--- a/tests/unit/agentic_ide/test_fanout.py+++ b/tests/unit/agentic_ide/test_fanout.py@@ -236,20 +236,51 @@ async def test_overlapping_deliveries_reserve_batches_by_identity() -> None:assert term.pending_prompt_attachment_batches == []-async def test_cancelled_delivery_releases_its_attachment_reservation() -> None:+def _pending_detached() -> asyncio.Future:+ """The one still-running fan-out a cancelled caller left behind.++ Filters on ``done()`` because the module registry may briefly hold settled+ futures from earlier fan-outs — the discard runs in a done-callback, one+ loop tick after completion.+ """+ pending = [w for w in fanout._DETACHED_DELIVERIES if not w.done()]+ assert len(pending) == 1+ return pending[0]+++async def _settle_detached() -> None:+ """Wait for every detached fan-out of THIS loop to finish."""+ pending = [w for w in fanout._DETACHED_DELIVERIES if not w.done()]+ if pending:+ await asyncio.wait(pending, timeout=5.0)+++async def test_a_hangup_mid_compose_still_briefs_the_pane() -> None:+ """Cancelling the CALLER detaches the delivery instead of killing it.++ The live 2026-08-06 failure: "prompt terminal T1 …" reached the composer,+ the composer's writer needed 15-20 s, the user hung up at 13 s, and the+ cancellation killed the delivery mid-compose — nothing was ever typed while+ the user believed T1 was working. Hanging up ends the conversation, not the+ order: the brief must still land, and its receipt must still be written.+ """session = _session("Iris")attachment = SimpleNamespace(name="layout.png")term = session.terminals[0]- batch = PendingPromptAttachmentBatch(- "batch-a", (attachment,), ("layout.png",)- )+ batch = PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))term.pending_prompt_attachment_batches.append(batch)composing = asyncio.Event()+ release = asyncio.Event()+ sent: dict[str, str] = {}async def compose(_utterance: str, **_kwargs) -> ComposedPrompt:composing.set()- await asyncio.Event().wait()- return ComposedPrompt(text="unreachable")+ await release.wait()+ return ComposedPrompt(text="the finished brief")++ async def send(name: str, text: str) -> SimpleNamespace:+ sent[name] = text+ return SimpleNamespace(submitted=True)task = asyncio.create_task(fanout.deliver(@@ -258,6 +289,7 @@ async def test_cancelled_delivery_releases_its_attachment_reservation() -> None:utterance="fix the layout",include_pending_attachments=True,compose=compose,+ send=send,))await composing.wait()@@ -265,47 +297,57 @@ async def test_cancelled_delivery_releases_its_attachment_reservation() -> None:with pytest.raises(asyncio.CancelledError):await task- assert term.pending_prompt_attachment_batches == [batch]+ # The caller is gone; the composition is still running detached.+ work = _pending_detached()+ assert sent == {}+ release.set()+ await work++ assert sent == {"Iris": "the finished brief"}+ assert term.pending_prompt_attachment_batches == []assert term.pending_prompt_attachment_reservations == set()-async def test_cancellation_while_waiting_for_gate_never_reserves_a_batch() -> None:- session = _session("Iris", "Bruno")- first_started = asyncio.Event()- never_release = asyncio.Event()- for index, term in enumerate(session.terminals):- attachment = SimpleNamespace(name=f"layout-{index}.png")- term.pending_prompt_attachment_batches.append(- PendingPromptAttachmentBatch(- f"batch-{index}", (attachment,), (attachment.name,)- )- )+async def test_a_cancelled_detached_delivery_releases_its_reservation() -> None:+ """Killing the detached WORK itself (loop shutdown) must not leak a batch.- async def compose(_utterance: str, **kwargs) -> ComposedPrompt:- if kwargs["terminal_name"] == "Iris":- first_started.set()- await never_release.wait()- return ComposedPrompt(text="brief")+ The caller-cancel path above finishes the brief; this is the other exit —+ the process is going down and the detached fan-out is cancelled for real.+ The staged attachment then stays claimable for the next spoken prompt.+ """+ session = _session("Iris")+ attachment = SimpleNamespace(name="layout.png")+ term = session.terminals[0]+ batch = PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))+ term.pending_prompt_attachment_batches.append(batch)+ composing = asyncio.Event()++ async def compose(_utterance: str, **_kwargs) -> ComposedPrompt:+ composing.set()+ await asyncio.Event().wait()+ return ComposedPrompt(text="unreachable")task = asyncio.create_task(fanout.deliver(session=session,- terminals=["Iris", "Bruno"],- utterance="brief both panes",+ terminals=["Iris"],+ utterance="fix the layout",include_pending_attachments=True,compose=compose,- limit=1,))- await first_started.wait()+ await composing.wait()task.cancel()with pytest.raises(asyncio.CancelledError):await task- assert all(- term.pending_prompt_attachment_reservations == set()- for term in session.terminals- )+ work = _pending_detached()+ work.cancel()+ with pytest.raises(asyncio.CancelledError):+ await work++ assert term.pending_prompt_attachment_batches == [batch]+ assert term.pending_prompt_attachment_reservations == set()async def test_cancellation_during_commit_still_consumes_a_sent_batch() -> None:@@ -342,6 +384,9 @@ async def test_cancellation_during_commit_still_consumes_a_sent_batch() -> None:with pytest.raises(asyncio.CancelledError):await task+ # The commit finishes inside the detached fan-out, not the dead caller.+ await _settle_detached()+assert term.pending_prompt_attachment_batches == []assert term.pending_prompt_attachment_reservations == set()