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): hanging up ends a pane's brief, and the wait is visible

rubenluetke10-beep99b1a6a4c600
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 122f962fc1..65626d465f 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -9319,3 +9319,104 @@ from a command. Guards accumulated along one path eventually cover the case
they were each built for and, between them, the case nobody wrote a guard for.
The fix is not a fourth heuristic but an explicit ordering of the ones already
there, cheapest and most certain first.
+
+## BUG-136: a spoken brief for a pane outlives the call that ordered it — the confirmation is spoken before the prompt exists, and hanging up does not stop it (HIGH, FIXED 2026-08-13)
+
+**Symptoms (maintainer report).** "The terminals are prompted before they
+actually are prompted." Jarvis says the pane has been prompted, nothing in the
+app indicates work is running — no thinking state, no status line — so it reads
+as a failure, and roughly twenty seconds later the pane really is prompted.
+Second half of the same report: hanging up does not end it. The order keeps
+running in the background and types into the pane after the call is over.
+
+**Forensics (live log, 2026-08-13 11:19-11:21).** One spoken order to T5
+produced four deliveries and three contradictory spoken accounts:
+
+| time | what happened |
+| --- | --- |
+| 11:19:33 | turn 1 dispatched; the composer's writer (`claude-cli`) starts |
+| 11:19:42 | a repeat turn is answered with the honest progress line |
+| 11:19:43 | **user hangs up** (hotkey); two delegates "retained for exactly-once delivery" |
+| 11:20:03 | T5 is typed into — 20 s after the hangup, inside the NEXT call |
+| 11:20:10 | T5 is typed into again (turn 2's own composition) |
+| 11:20:12 | "I have prompted T5 to do a deep dive …" — **2.0 s after dispatch** |
+| 11:20:17 / 11:20:21 | the same sentence announced twice more, the last one after the second hangup |
+| 11:20:26 | that order's fan-out finally reports `could not send to T5` → "I could not reach T5, so nothing is running." |
+
+**Root.** Three separate causes, one shape: **the delivery outlives the turn
+that ordered it, and nothing downstream knows.**
+
+1. **Structural.** Composing a brief is 16-30 s by deliberate design (quality
+ over latency, maintainer decision 2026-07-25; `COMPOSE_TIMEOUT_S` is 90 s,
+ `HEDGE_AFTER_S` 30 s), while a delegated voice turn is force-answered after
+ 20 s (`tool_use_loop` deadline). A spoken pane order therefore CANNOT finish
+ inside its own turn: the verdict always arrives as an out-of-band
+ announcement, which can land in a later call, after a hangup, or out of order
+ against a second delivery of the same order.
+2. **The claim.** On a turn where no delivery was dispatched at all (a VAD
+ fragment — "when you speak with him you can't"), the router brain narrated
+ the PENDING order as finished. Every workspace fact in front of it said a
+ prompt had been sent to that pane (`prompts_sent`, `last prompt sent: "…"`)
+ and nothing said the current brief was still being written. The prompt rule
+ forbidding the claim was already there and was ignored — prompt compliance is
+ not a correctness boundary (BUG-047 class rule).
+3. **Invisibility.** Both signals that would have shown the work existed —
+ the composer's `STAGE_*` beats (`AgenticIdeComposeProgress`) and
+ `AgenticIdePromptSent` — were published ONLY by the REST route behind the
+ typed prompt bar. The spoken path passed no sink and published no delivery
+ event, so a voice-driven brief was invisible in every window until the agent
+ echoed it back. The frontend has rendered both for weeks
+ (`useWebSocket.ts`, `AgenticGrid.tsx`).
+4. **Hangup.** `fanout.deliver` deliberately detached on caller cancellation and
+ `RealtimeVoiceSession.end` transfers unfinished delegates to process scope,
+ both fixes for the opposite failure (2026-08-06: a hangup mid-composition
+ typed nothing while the user believed it had). Together they made a hangup a
+ no-op for an order already in flight.
+
+**Fix.**
+
+- `jarvis/agentic_ide/fanout.py`: `deliver(..., on_progress=, on_delivered=,
+ cancel_on_hangup=)`. `cancel_spoken_deliveries()` aborts every spoken fan-out
+ still being written; the detach stays the rule for REST/CLI callers, where a
+ lost client is a lost READER, not a withdrawn order. `in_flight_briefs()`
+ exposes the per-pane ledger.
+- `jarvis/realtime/session.py`: `_abandon_spoken_workspace_briefs()` runs in
+ `end()` for every reason except the two handovers (`desktop_fallback`,
+ `realtime_fallback`, where the same call continues in the pipeline).
+ `_run_delegate` re-raises the cancellation, so an abandoned brief speaks
+ nothing at all. `jarvis/speech/pipeline.py` does the same at the one
+ engine-agnostic session end, for the classic engine.
+- `jarvis/brain/manager.py`: `_agentic_ide_delivery_signals()` publishes the
+ composer's beats and `AgenticIdePromptSent` from the spoken path — the same
+ events, so no client changes.
+- `jarvis/agentic_ide/context.py`: a pane with a brief in flight is stated as
+ `A BRIEF IS STILL BEING WRITTEN … nothing has reached T5 yet`, with the rule
+ that the counted prompts are OLD ones.
+
+Safe to abandon precisely for THIS kind of work: the PTY write is the last step
+of a fan-out, so an abandoned brief leaves no text in the input box, no receipt
+and no started agent — unlike a sent mail or a spawned mission, which is why
+everything else is still retained.
+
+**Guards:** `tests/unit/agentic_ide/test_fanout.py`
+(`test_a_hangup_abandons_a_spoken_brief`,
+`test_a_spoken_delivery_narrates_and_reports_its_arrival`,
+`test_an_injected_composer_needs_no_progress_keyword`, and the renamed
+`test_a_cancelled_reader_still_briefs_the_pane` which pins the REST contract),
+`tests/unit/realtime/test_session.py`
+(`test_hangup_abandons_a_coding_brief_that_is_still_being_written`,
+`test_a_handover_keeps_the_coding_brief_alive`, alongside the unchanged
+`test_session_end_names_the_delegated_request_it_retains`), and
+`tests/unit/agentic_ide/test_context.py`
+(`test_a_brief_being_written_is_stated_as_not_arrived`).
+
+**Lesson.** A quality decision that makes one step slower than the turn that
+runs it changes the honesty contract of everything downstream, and that
+consequence is invisible at the site of the decision. Two survival rules were
+added for the same 20-30 s window from opposite directions — "finish the brief
+after the caller dies" and "retain the delegate after the socket closes" — and
+each was right about the incident it fixed. What neither could know is who the
+reader is: a dropped HTTP client has lost the answer, while a person who hangs
+up has withdrawn the request. The same cancellation means different things to
+different callers, so survival has to be the CALLER's declaration, never the
+work's default.
diff --git a/jarvis/agentic_ide/context.py b/jarvis/agentic_ide/context.py
index 16f3aea519..bdb92085d3 100644
--- a/jarvis/agentic_ide/context.py
+++ b/jarvis/agentic_ide/context.py
@@ -77,6 +77,10 @@ _HEADER = (
"terminal later. If the work did not go out, say plainly that it did not and "
"why — an honest \"I could not reach that terminal\" is always better than a "
"confident sentence that turns out to be false.\n"
+ "- A pane listed below as STILL BEING WRITTEN has received NOTHING yet. The "
+ "prompt writer takes 10-30 seconds, and the earlier prompts counted for that "
+ "pane are OLD ones, not this one. Say the work is still going out — never "
+ "that it arrived, and never that the agent has started.\n"
"- Brainstorming, architecture, and 'what should we do next' are answered "
"inline, against this codebase, and you may propose which terminal should "
"take which part.\n"
@@ -88,9 +92,22 @@ _HEADER = (
)
-def _terminal_block(term, tail_lines: int = _LINES_PER_TERMINAL) -> list[str]: # noqa: ANN001 - Terminal, avoid import cycle
+def _terminal_block( # noqa: ANN001 - Terminal, avoid import cycle
+ term,
+ tail_lines: int = _LINES_PER_TERMINAL,
+ *,
+ writing_for_s: float | None = None,
+) -> list[str]:
status = term.status
bits = [f"{term.name} ({term.display_name}) — {status}"]
+ if writing_for_s is not None:
+ # Stated before the receipt count on purpose: the counted prompts are
+ # what the model turned into "I have prompted T5" while this one was
+ # still being written (live 2026-08-13 11:20:12).
+ bits.append(
+ f"A BRIEF IS STILL BEING WRITTEN for it ({int(writing_for_s)}s so "
+ f"far) — nothing has reached {term.name} yet"
+ )
if status == "live" and term.last_output_at:
idle = max(0, int(time.time() - term.last_output_at))
bits.append(f"last output {idle}s ago")
@@ -139,9 +156,23 @@ def focus_context_block(max_chars: int = _MAX_CHARS) -> str:
if len(session.terminals) < _CROWDED_AT
else _LINES_PER_TERMINAL_CROWDED
)
+ # Which panes have a brief ON THE WAY. The one workspace fact that
+ # exists nowhere else: a pane with a 20 s composition running looks
+ # exactly like an idle pane that was prompted an hour ago, and the model
+ # answered from the older receipt.
+ try:
+ from .fanout import in_flight_briefs
+
+ writing = dict(in_flight_briefs(session))
+ except Exception: # noqa: BLE001 - a missing fact never costs the block
+ writing = {}
parts.append(f"Terminals in this workspace ({len(session.terminals)}):")
for term in session.terminals:
- parts.extend(_terminal_block(term, tail_lines))
+ parts.extend(
+ _terminal_block(
+ term, tail_lines, writing_for_s=writing.get(term.name)
+ )
+ )
else:
parts.append("No terminals are open in this workspace yet.")
diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.py
index 66db1c8ddc..5b629b91c0 100644
--- a/jarvis/agentic_ide/fanout.py
+++ b/jarvis/agentic_ide/fanout.py
@@ -356,6 +356,77 @@ def note_detached_delivery(work: asyncio.Future[Any], *, describe: str) -> None:
)
+#: Spoken fan-outs a hangup must be able to abort. A brief ordered by voice
+#: belongs to the conversation that ordered it: ending the call ends the order
+#: (maintainer decision 2026-08-13). This narrows the 2026-08-06 detach rule to
+#: the REST/CLI callers it was written for — a dropped HTTP client is a lost
+#: READER, not a withdrawn instruction — because on the spoken path the detach
+#: produced the opposite failure: the user hung up, the workspace stayed silent
+#: for another 20-30 s, and a pane they had stopped waiting for was typed into
+#: (live 2026-08-13 11:19:43 hangup → 11:20:03 delivery).
+#:
+#: A registry rather than "cancel the caller": since the realtime session
+#: transfers unfinished delegate work to process scope on hangup ("retaining it
+#: for exactly-once delivery"), the caller no longer dies when the call ends, so
+#: nothing downstream ever learned the conversation was over. Teardown cancels
+#: these futures explicitly instead.
+_SPOKEN_DELIVERIES: set[asyncio.Future[Any]] = set()
+
+
+def cancel_spoken_deliveries(*, reason: str = "the call ended") -> int:
+ """Abort every spoken fan-out still being written; return how many stopped.
+
+ Called from voice-session teardown. Nothing has reached a pane at that
+ point — the PTY write is the LAST step of ``deliver`` — so an aborted brief
+ leaves the workspace exactly as it was: no text in the input box, no
+ receipt (``last_prompt_at``), nothing for the user to discover later.
+
+ Idempotent, never raises, and a no-op when no brief is in flight.
+ """
+ live = [work for work in tuple(_SPOKEN_DELIVERIES) if not work.done()]
+ for work in live:
+ work.cancel()
+ if live:
+ log.info(
+ "Agentic IDE fan-out: %s — abandoned %d brief(s) still being "
+ "written; nothing was typed",
+ reason,
+ len(live),
+ )
+ return len(live)
+
+
+#: Panes whose brief is being written RIGHT NOW: ``(workspace_id, pane)`` →
+#: ``time.monotonic()`` when it started. A counter rather than a flag, because
+#: one pane can legitimately be in two fan-outs at once.
+#:
+#: Read by the turn context (``agentic_ide.context``) so the model answering a
+#: turn is told the one fact it cannot see anywhere else: a brief is on its way
+#: and NOTHING has reached that pane yet. Without it, the only workspace
+#: evidence in front of the model was the receipt of EARLIER prompts, and it
+#: duly narrated the pending one as finished — live 2026-08-13 11:20:12, "I have
+#: prompted T5 …" spoken 2 s after dispatch, 14 s before that brief's writer had
+#: even started, for a delivery that then failed outright.
+_IN_FLIGHT: dict[tuple[str, str], list[float]] = {}
+
+
+def in_flight_briefs(session: Any, *, now: float | None = None) -> tuple[tuple[str, float], ...]:
+ """Panes of ``session`` with a brief being written, and its age in seconds.
+
+ In-memory read of a dict, so it is free on the voice hot path (AP-9).
+ """
+ workspace_id = str(getattr(session, "id", "") or "")
+ if not workspace_id:
+ return ()
+ moment = time.monotonic() if now is None else now
+ out = [
+ (pane, max(0.0, moment - min(starts)))
+ for (wid, pane), starts in _IN_FLIGHT.items()
+ if wid == workspace_id and starts
+ ]
+ return tuple(sorted(out, key=lambda item: item[0]))
+
+
async def _default_compose(utterance: str, **kwargs: Any) -> Any:
from .prompt_composer import compose as compose_prompt
@@ -380,6 +451,9 @@ async def deliver(
send: Callable[[str, str], Awaitable[Any]] | None = None,
limit: int = DEFAULT_CONCURRENCY,
include_pending_attachments: bool = False,
+ on_progress: Callable[[Any], None] | None = None,
+ on_delivered: Callable[[Any], Awaitable[None]] | None = None,
+ cancel_on_hangup: bool = False,
) -> FanOutResult:
"""Compose and deliver a prompt for each of ``terminals``.
@@ -401,14 +475,26 @@ async def deliver(
delivery path. Manual REST/CLI fan-out must not steal a drop that was
explicitly staged for the next spoken prompt.
+ ``on_progress`` receives the composer's ``ComposeNotice`` beats for every
+ pane, so a caller that is not the REST route can put the 10-30 s of writing
+ on a screen too. ``on_delivered`` is awaited with the pane's ``Terminal``
+ right after its prompt went in, which is how a caller announces the ARRIVAL
+ without having to wait for the slowest sibling.
+
Never raises for a single pane. A pane that is missing, not running, whose
prompt could not be written, or whose PTY write failed comes back as an
undelivered ``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.
+ Survives its caller by default: cancelling this call re-raises for the
+ caller but lets the briefs finish detached, because a REST client that
+ disconnects has lost the ANSWER, not withdrawn the order. ``deliver`` is a
+ long-running effect and a reader is not its owner.
+
+ ``cancel_on_hangup=True`` reverses that for the spoken path: the fan-out is
+ registered with :func:`cancel_spoken_deliveries` and abandoned the moment
+ the call ends. Hanging up ends the order — the user stopped waiting, and a
+ pane typed into half a minute later is work they no longer asked for
+ (maintainer decision 2026-08-13). Nothing is typed on that exit.
"""
wanted = _unique(terminals)
if not wanted:
@@ -429,8 +515,30 @@ async def deliver(
Announced here rather than after the gather: with a fleet composing at
once, collecting every line until the slowest pane finishes turns
per-pane progress back into the silence it exists to remove.
+
+ Marked in-flight per PANE, not per fan-out: with five panes composing
+ at once, a ledger cleared only at the end would still be claiming
+ "nothing has reached T1" minutes after T1 was typed into.
"""
- delivery = await _one(name)
+ found = session.find(name) if session is not None else None
+ key = (
+ str(getattr(session, "id", "") or ""),
+ str(getattr(found, "name", "") or name),
+ )
+ started = time.monotonic()
+ if key[0]:
+ _IN_FLIGHT.setdefault(key, []).append(started)
+ try:
+ delivery = await _one(name)
+ finally:
+ starts = _IN_FLIGHT.get(key)
+ if starts is not None:
+ if started in starts:
+ starts.remove(started)
+ else: # pragma: no cover - defensive, clocks are monotonic
+ starts.pop()
+ if not starts:
+ _IN_FLIGHT.pop(key, None)
try:
from .prompt_composer import announce_delivery
@@ -489,6 +597,10 @@ async def deliver(
try:
from .session import AGENT_DISPLAY
+ # Passed only when there IS a sink: the composer defaults to its
+ # own stdout notice, and injected test/CLI composers are free to
+ # take no such keyword at all.
+ progress_kw = {} if on_progress is None else {"on_progress": on_progress}
composed = await compose_fn(
utterance,
session=session,
@@ -497,6 +609,7 @@ async def deliver(
instruction=own_instruction,
conversation=tuple(conversation or ()),
attachments=pending_attachments,
+ **progress_kw,
)
except asyncio.CancelledError:
await _finish_prompt_attachments_shielded(term, pending_batches, consume=False)
@@ -544,6 +657,16 @@ async def deliver(
await _finish_prompt_attachments_shielded(term, pending_batches, consume=True)
+ if on_delivered is not None:
+ try:
+ await on_delivered(term)
+ except Exception: # noqa: BLE001 - a notification never costs a delivery
+ log.debug(
+ "Agentic IDE fan-out: could not announce the send for %s",
+ term.name,
+ exc_info=True,
+ )
+
# The sender reports whether the agent actually STARTED. A sender that
# says nothing leaves it None (unknown) rather than claiming success —
# the readback then stays silent about it instead of overstating.
@@ -562,19 +685,41 @@ async def deliver(
work = asyncio.ensure_future(
asyncio.gather(*(one(name) for name in wanted), return_exceptions=True)
)
+ if cancel_on_hangup:
+ _SPOKEN_DELIVERIES.add(work)
+ work.add_done_callback(_SPOKEN_DELIVERIES.discard)
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
+ if cancel_on_hangup:
+ # The spoken caller is gone (teardown cancelled the retained
+ # delegate task, a turn was abandoned). The order goes with the
+ # conversation instead of typing into panes nobody is waiting on.
+ # The strong reference and the callback stay for the unwind only:
+ # the attachment reservations settle inside it, and the honest
+ # "those panes received nothing" line lands in the log (AP-30).
+ _DETACHED_DELIVERIES.add(work)
+ work.add_done_callback(
+ lambda task, names=tuple(wanted): _finish_detached(task, names)
+ )
+ work.cancel()
+ log.info(
+ "Agentic IDE fan-out: the spoken caller went away — abandoning "
+ "the brief(s) for %s; nothing was typed",
+ ", ".join(wanted),
+ )
+ raise
+ # The CALLER died mid-delivery — a disconnected HTTP client, a cancelled
+ # CLI — 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.
+ # subscription-CLI composition and nothing was ever typed). Losing the
+ # reader drops the verdict, not the order; the briefs still land and the
+ # receipt (`last_prompt_at`) stays the proof. The SPOKEN path takes the
+ # branch above instead — there the reader is the person who ordered it.
_DETACHED_DELIVERIES.add(work)
work.add_done_callback(lambda task, names=tuple(wanted): _finish_detached(task, names))
log.warning(
@@ -616,7 +761,9 @@ __all__ = [
"Delivery",
"FanOutResult",
"RecentFanOut",
+ "cancel_spoken_deliveries",
"deliver",
"find_duplicate_fanout",
+ "in_flight_briefs",
"record_fanout",
]
diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.py
index 81763ad13a..056bbfafab 100644
--- a/jarvis/brain/manager.py
+++ b/jarvis/brain/manager.py
@@ -6431,6 +6431,72 @@ class BrainManager:
log.debug("Agentic IDE: conversation context unavailable", exc_info=True)
return ()
+ def _agentic_ide_delivery_signals(
+ self, session: Any
+ ) -> tuple[Callable[[Any], None] | None, Callable[[Any], Awaitable[None]] | None]:
+ """Put a SPOKEN delivery on screen: the writing beats, then the arrival.
+
+ Writing a brief is 10-30 s of quality-tier model work, and nothing on
+ screen said so when the order arrived by voice. Both signals existed
+ already — the composer's ``STAGE_*`` beats and ``AgenticIdePromptSent``
+ — but only the typed prompt bar's REST route published them, so a spoken
+ "T5, look at the transcript" left the whole app looking untouched until
+ the agent itself echoed the text half a minute later. Reported
+ 2026-08-13: the bar showed no thinking state, "so you think it did not
+ work" — and then the pane was prompted 20 s later.
+
+ Deliberately the SAME events, not a spoken line: the clients already
+ render them (the pane's live status line, the delivery toast), and a
+ sentence spoken before the work is done is a claim a downstream model
+ re-tenses into "I have prompted T5" — the failure this whole path is
+ built to avoid.
+
+ Returns ``(None, None)`` without a bus. A publish that fails costs the
+ line, never the brief.
+ """
+ bus = self._bus
+ if bus is None:
+ return None, None
+ from jarvis.agentic_ide.session import prompt_sent_event
+ from jarvis.core.events import AgenticIdeComposeProgress
+
+ session_id = str(getattr(session, "id", "") or "")
+
+ def _beat(notice: Any) -> None:
+ from jarvis.agentic_ide.prompt_composer import print_notice
+
+ # Keep the stdout/log line a headless install watches, exactly as
+ # the REST route does — the socket beat is an addition to it.
+ print_notice(notice)
+ try:
+ loop = asyncio.get_running_loop()
+ except RuntimeError: # pragma: no cover - no loop, no clients
+ return
+ task = loop.create_task(
+ bus.publish(
+ AgenticIdeComposeProgress(
+ session_id=session_id,
+ terminal=str(getattr(notice, "terminal", "") or ""),
+ stage=str(getattr(notice, "stage", "") or ""),
+ message=str(getattr(notice, "message", "") or ""),
+ kind=str(getattr(notice, "kind", "") or ""),
+ source_layer="brain.agentic_ide_prompt",
+ )
+ )
+ )
+ # Fire-and-forget: a beat that cannot be delivered must never cost
+ # the brief, nor a warning about an unobserved task at teardown.
+ task.add_done_callback(lambda done: done.cancelled() or done.exception())
+
+ async def _delivered(term: Any) -> None:
+ await bus.publish(
+ prompt_sent_event(
+ session, term, source_layer="brain.agentic_ide_prompt"
+ )
+ )
+
+ return _beat, _delivered
+
async def _deliver_agentic_ide_prompt(
self,
*,
@@ -6467,6 +6533,7 @@ class BrainManager:
# A delivery that did not happen is a fact worth saying out loud, so
# every exit below carries one; ``deliver`` itself never raises for a
# single pane, so reaching these means the whole fan-out fell over.
+ on_progress, on_delivered = self._agentic_ide_delivery_signals(session)
try:
result = await ide_fanout.deliver(
session=session,
@@ -6476,6 +6543,10 @@ class BrainManager:
assignments=assignments,
conversation=self._agentic_ide_conversation(utterance),
include_pending_attachments=consume_pending_voice_attachments,
+ on_progress=on_progress,
+ on_delivered=on_delivered,
+ # Hanging up ends the order (maintainer decision 2026-08-13).
+ cancel_on_hangup=True,
)
except Exception: # noqa: BLE001 - never crash the turn over a pane
log.warning("Agentic IDE fast-path failed", exc_info=True)
diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.py
index 610c3216bf..ee74a19cdd 100644
--- a/jarvis/realtime/session.py
+++ b/jarvis/realtime/session.py
@@ -63,6 +63,7 @@ from jarvis.realtime.scrub_gate import ScrubHoldGate
from jarvis.sessions.constants import (
HANGUP_CLIENT_STOP,
HANGUP_DESKTOP_FALLBACK,
+ HANGUP_REALTIME_FALLBACK,
HANGUP_VOICE_PATTERN,
SPOKEN_KIND_PROGRESS,
SPOKEN_KIND_REPLY,
@@ -630,6 +631,11 @@ _LATE_DELEGATE_POLL_S = 0.15
# before process-scope retention. Real action work remains untouched after
# this tiny teardown-only grace and is transferred below.
_DELEGATE_END_SETTLE_S = 0.1
+# Session ends that HAND THE CALL OVER instead of finishing it: the same
+# conversation continues in the classic pipeline under the same session id, so
+# an order the user gave is still live and must not be abandoned with the
+# transport. Every other reason is the call being over.
+_HANDOVER_END_REASONS = frozenset({HANGUP_DESKTOP_FALLBACK, HANGUP_REALTIME_FALLBACK})
# Strong references for delegated work whose realtime transport has already
# gone away. The task itself retains the session-local delivery ledger and
# publishes the final result through AnnouncementRequested; a module-level
@@ -9242,6 +9248,48 @@ class RealtimeVoiceSession:
close_clean=not (self._close_timed_out or self._failed.is_set()),
)
+ def _abandon_spoken_workspace_briefs(self, reason: str) -> None:
+ """Drop every coding-agent brief still being written for this call.
+
+ The one exception to the retention rule below, and the maintainer's
+ decision of 2026-08-13: hanging up ends the ORDER for a workspace pane,
+ not just the conversation. Live that day — hangup at 11:19:43, the brief
+ landed in T5 at 11:20:03 — the user had stopped waiting twenty seconds
+ before a pane they were watching started working on something they no
+ longer expected, and a second announcement about it was spoken into an
+ idle room.
+
+ Safe precisely for THIS kind of work and no other: the PTY write is the
+ last step of a fan-out, so an abandoned brief leaves no text in the
+ input box, no receipt and no half-run agent — unlike a mail that was
+ already sent or a mission that already spawned, which is why everything
+ else is still transferred to process scope instead.
+
+ Nothing is spoken about it: ``_run_delegate`` re-raises the
+ cancellation, so the turn publishes no result at all. The abandoned
+ panes are named in the log by the fan-out itself.
+ """
+ try:
+ from jarvis.agentic_ide.fanout import cancel_spoken_deliveries
+
+ stopped = cancel_spoken_deliveries(
+ reason=f"the call ended ({reason or 'unknown'})"
+ )
+ except Exception: # noqa: BLE001 - optional surface, never break teardown
+ log.debug(
+ "realtime[%s] could not abandon workspace briefs",
+ self.session_id,
+ exc_info=True,
+ )
+ return
+ if stopped:
+ log.info(
+ "realtime[%s] hangup abandoned %d coding-agent brief(s) that "
+ "were still being written",
+ self.session_id,
+ stopped,
+ )
+
async def end(self, *, reason: str = "") -> None:
if self._ended:
return
@@ -9262,6 +9310,8 @@ class RealtimeVoiceSession:
if self._end_call_timer is not None and not self._end_call_timer.done():
self._end_call_timer.cancel()
self._end_call_timer = None
+ if reason not in _HANDOVER_END_REASONS:
+ self._abandon_spoken_workspace_briefs(reason)
if self._delegate_tasks:
await asyncio.wait(
tuple(self._delegate_tasks),
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index ae0b43fe0d..1b5ef3b4ae 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -7575,6 +7575,23 @@ class SpeechPipeline:
win.clear()
except Exception: # noqa: BLE001 — teardown must never crash
log.debug("Clarify/continuation teardown failed", exc_info=True)
+ # Hanging up ends a coding-agent brief that is still being
+ # written, the same way it does on the realtime engine (see
+ # ``RealtimeVoiceSession._abandon_spoken_workspace_briefs``):
+ # composing takes 10-30 s, and a pane typed into after the user
+ # stopped waiting is work they no longer asked for. Idempotent —
+ # a realtime call that already dropped its briefs leaves none
+ # here. Skipped on an engine reconnect: that session re-arms and
+ # the order the user gave is still live.
+ if not reopen_after_engine_change:
+ try:
+ from jarvis.agentic_ide.fanout import cancel_spoken_deliveries
+
+ cancel_spoken_deliveries(
+ reason=f"the call ended ({hangup_reason or 'unknown'})"
+ )
+ except Exception: # noqa: BLE001 — teardown must never crash
+ log.debug("Workspace brief teardown failed", exc_info=True)
await self._publish_event(
VoiceSessionEnded(
source_layer="speech.pipeline",
diff --git a/tests/unit/agentic_ide/test_context.py b/tests/unit/agentic_ide/test_context.py
index 983e90245d..e8f87a1874 100644
--- a/tests/unit/agentic_ide/test_context.py
+++ b/tests/unit/agentic_ide/test_context.py
@@ -98,6 +98,62 @@ async def test_block_is_capped(
assert len(focus_context_block(max_chars=800)) <= 800
+async def test_a_brief_being_written_is_stated_as_not_arrived(
+ wired: tuple[Registry, FakePtyManager], tmp_path: Path
+) -> None:
+ """The one workspace fact that lived nowhere: a brief is ON THE WAY.
+
+ Live 2026-08-13 11:20:12 — "I have prompted T5 to do a deep dive …" was
+ spoken 2 s after dispatch, 14 s before that brief's writer had even started,
+ for a delivery that then failed. Everything the model could see said a
+ prompt HAD been sent to that pane (the receipt count, the last prompt text);
+ nothing said the current one was still being written.
+ """
+ import asyncio
+
+ from jarvis.agentic_ide import fanout
+
+ registry, _ = wired
+ await registry.start(str(tmp_path), [{"agent": "claude"}])
+ registry.set_focus_mode(True)
+ # A pane is only written into once it is live with a PTY.
+ await registry.attach("T1", 80, 24, _noop, _noop_exit)
+ session = registry.session
+ assert session is not None
+
+ composing = asyncio.Event()
+
+ async def compose(_utterance: str, **_kwargs):
+ composing.set()
+ await asyncio.Event().wait()
+
+ task = asyncio.create_task(
+ fanout.deliver(
+ session=session,
+ terminals=["T1"],
+ utterance="analyse the run",
+ compose=compose,
+ send=lambda _n, _t: asyncio.sleep(0),
+ cancel_on_hangup=True,
+ )
+ )
+ # Bounded: a pane that never reaches the composer must fail the test, not
+ # hang the suite.
+ await asyncio.wait_for(composing.wait(), timeout=5.0)
+
+ block = focus_context_block()
+ assert "STILL BEING WRITTEN" in block
+ assert "nothing has reached T1 yet" in block
+
+ fanout.cancel_spoken_deliveries()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ # …and the pane's marker disappears again once no brief is in flight, so a
+ # later turn is not told it is waiting for something that was abandoned.
+ # (The rule in the header stays, of course — it is not a pane line.)
+ assert "nothing has reached T1 yet" not in focus_context_block()
+
+
async def test_turning_focus_off_removes_the_block_again(
wired: tuple[Registry, FakePtyManager], tmp_path: Path
) -> None:
diff --git a/tests/unit/agentic_ide/test_fanout.py b/tests/unit/agentic_ide/test_fanout.py
index d621d78ac5..357943b43a 100644
--- a/tests/unit/agentic_ide/test_fanout.py
+++ b/tests/unit/agentic_ide/test_fanout.py
@@ -254,14 +254,19 @@ async def _settle_detached() -> None:
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.
+async def test_a_cancelled_reader_still_briefs_the_pane() -> None:
+ """Cancelling a REST/CLI 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.
+ the composer's writer needed 15-20 s, the caller was cancelled at 13 s, and
+ that killed the delivery mid-compose — nothing was ever typed while the user
+ believed T1 was working. A client that goes away has lost the ANSWER, not
+ withdrawn the order: the brief must still land, and its receipt must still
+ be written.
+
+ The SPOKEN path is the deliberate exception (``cancel_on_hangup``) — see
+ ``test_a_hangup_abandons_a_spoken_brief``: there the caller IS the person who
+ gave the order.
"""
session = _session("Iris")
attachment = SimpleNamespace(name="layout.png")
@@ -390,6 +395,121 @@ async def test_cancellation_during_commit_still_consumes_a_sent_batch() -> None:
assert term.pending_prompt_attachment_reservations == set()
+async def test_a_hangup_abandons_a_spoken_brief() -> None:
+ """Hanging up ends the ORDER for a pane, not just the conversation.
+
+ Maintainer decision 2026-08-13, from the session that produced it: the user
+ hung up at 11:19:43 and T5 was typed into at 11:20:03 — twenty seconds after
+ they had stopped waiting, on a screen they were watching, followed by a
+ verdict spoken into an empty room. Composition is the whole 20-30 s window,
+ and the PTY write is its LAST step, so abandoning it leaves the pane exactly
+ as it was: no text, no receipt, nothing to discover later.
+ """
+ session = _session("Iris")
+ term = session.terminals[0]
+ attachment = SimpleNamespace(name="layout.png")
+ batch = PendingPromptAttachmentBatch("batch-a", (attachment,), ("layout.png",))
+ term.pending_prompt_attachment_batches.append(batch)
+ composing = asyncio.Event()
+ sent: dict[str, str] = {}
+
+ async def compose(_utterance: str, **_kwargs) -> ComposedPrompt:
+ composing.set()
+ await asyncio.Event().wait() # the writer is still thinking
+ return ComposedPrompt(text="unreachable")
+
+ async def send(name: str, text: str) -> SimpleNamespace:
+ sent[name] = text
+ return SimpleNamespace(submitted=True)
+
+ task = asyncio.create_task(
+ fanout.deliver(
+ session=session,
+ terminals=["Iris"],
+ utterance="fix the layout",
+ include_pending_attachments=True,
+ compose=compose,
+ send=send,
+ cancel_on_hangup=True,
+ )
+ )
+ await composing.wait()
+
+ assert fanout.cancel_spoken_deliveries(reason="the call ended (hotkey)") == 1
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+ # Nothing typed, no brief left running, and the staged drop stays claimable
+ # for the next spoken prompt rather than being consumed by a dead order.
+ assert sent == {}
+ assert [w for w in fanout._SPOKEN_DELIVERIES if not w.done()] == []
+ assert term.pending_prompt_attachment_batches == [batch]
+ assert term.pending_prompt_attachment_reservations == set()
+ # Idempotent: teardown may run through both the realtime session and the
+ # pipeline for the same call.
+ assert fanout.cancel_spoken_deliveries() == 0
+
+
+async def test_a_spoken_delivery_narrates_and_reports_its_arrival() -> None:
+ """The spoken path gets the same two UI signals the typed prompt bar has.
+
+ Until 2026-08-13 both were wired to the REST route only, so speaking to a
+ pane left the app looking untouched for the 10-30 s a brief takes to write —
+ "the bar didn't indicate any thinking, so you think it didn't work".
+ """
+ beats: list[str] = []
+ arrived: list[str] = []
+
+ async def compose(utterance: str, **kwargs) -> ComposedPrompt:
+ kwargs["on_progress"](
+ SimpleNamespace(
+ stage="drafting", message="writing for Iris", terminal="Iris", kind=""
+ )
+ )
+ return ComposedPrompt(text=utterance)
+
+ async def send(name: str, _text: str) -> SimpleNamespace:
+ return SimpleNamespace(name=name, submitted=True)
+
+ async def on_delivered(term) -> None: # noqa: ANN001 - the fake Terminal
+ arrived.append(term.name)
+
+ result = await fanout.deliver(
+ session=_session("Iris"),
+ terminals=["Iris"],
+ utterance="analyse the run",
+ compose=compose,
+ send=send,
+ on_progress=lambda notice: beats.append(notice.stage),
+ on_delivered=on_delivered,
+ )
+
+ assert beats == ["drafting"]
+ assert arrived == ["Iris"]
+ assert result.all_delivered is True
+
+
+async def test_an_injected_composer_needs_no_progress_keyword() -> None:
+ """No sink, no keyword: the composer's own stdout notice stays the default."""
+ seen: list[str] = []
+
+ async def compose(utterance: str, **kwargs) -> ComposedPrompt:
+ seen.append(",".join(sorted(kwargs)))
+ return ComposedPrompt(text=utterance)
+
+ async def send(name: str, _text: str) -> SimpleNamespace:
+ return SimpleNamespace(name=name, submitted=True)
+
+ await fanout.deliver(
+ session=_session("Iris"),
+ terminals=["Iris"],
+ utterance="analyse the run",
+ compose=compose,
+ send=send,
+ )
+ assert "on_progress" not in seen[0]
+
+
async def test_prompts_are_composed_concurrently() -> None:
"""Composed one after another, eight panes cannot fit in a voice turn."""
rec = Recorder()
diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.py
index 848e777f6f..b1f4d25a5b 100644
--- a/tests/unit/realtime/test_session.py
+++ b/tests/unit/realtime/test_session.py
@@ -6061,6 +6061,49 @@ async def test_session_end_names_the_delegated_request_it_retains(caplog):
) == 1
+async def test_hangup_abandons_a_coding_brief_that_is_still_being_written(
+ monkeypatch,
+):
+ """The ONE piece of delegated work a hangup drops instead of retaining.
+
+ Maintainer decision 2026-08-13: hanging up ends the order for a workspace
+ pane. Composing a brief takes 10-30 s and the PTY write is its last step, so
+ abandoning it leaves the pane untouched — unlike a sent mail or a spawned
+ mission, which is why the retention above stays the rule for everything else.
+ """
+ from jarvis.agentic_ide import fanout as ide_fanout
+
+ reasons: list[str] = []
+ monkeypatch.setattr(
+ ide_fanout,
+ "cancel_spoken_deliveries",
+ lambda *, reason="": reasons.append(reason) or 1,
+ )
+
+ sess = _session(FakeProvider([]))
+ await sess.end(reason="hotkey")
+
+ assert len(reasons) == 1
+ assert "hotkey" in reasons[0]
+
+
+async def test_a_handover_keeps_the_coding_brief_alive(monkeypatch):
+ """desktop_fallback is not a hangup: the same call continues elsewhere."""
+ from jarvis.agentic_ide import fanout as ide_fanout
+
+ called: list[str] = []
+ monkeypatch.setattr(
+ ide_fanout,
+ "cancel_spoken_deliveries",
+ lambda *, reason="": called.append(reason) or 0,
+ )
+
+ sess = _session(FakeProvider([]))
+ await sess.end(reason="desktop_fallback")
+
+ assert called == []
+
+
# ---------------------------------------------------------------------------
# BUG-071: in-place transport rebuild after a mid-call provider death
# ---------------------------------------------------------------------------