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
feat(voice): return delegated results without interrupting conversation (#279)
Ruben Lütke1ccf92568202
diff --git a/docs/agent-society/MASTERPLAN.md b/docs/agent-society/MASTERPLAN.mdindex 3226901cbe..2f1521dbb4 100644--- a/docs/agent-society/MASTERPLAN.md+++ b/docs/agent-society/MASTERPLAN.md@@ -32,7 +32,8 @@ carries the team card (roster + hands, byte-stable, current on the next turn aftwrite), the router's decision table has a DELEGATE way ahead of `spawn_worker`, the realtimesession gets a names directive and the turn planner a `SOCIETY` reason, `delegate_to_agent`picks the fitting agent when no name is given, and a lead-assigned result comes back as a-spoken completion plus a notice in the front-page chat (`agent-definition.md` §3.5). **M3+notice in its originating chat and, for voice requests, a batched update at a conversational+pause (`agent-definition.md` §3.5). **M3world** is the maintainer's parallel track. Open in M4: rooms live under the scheduler, thecurator.diff --git a/docs/agent-society/agent-definition.md b/docs/agent-society/agent-definition.mdindex cda3d3e50a..5d21c83885 100644--- a/docs/agent-society/agent-definition.md+++ b/docs/agent-society/agent-definition.md@@ -313,8 +313,11 @@ Gmail agent stood on the island. The team card (`jarvis/society/lead_card.py`) iname the roster does not know, "email agent") the lead picks the agent whose focus fits thetask (`SocietyRuntime.pick_agent`, `derive_focus` over the task text) or says that nobodyfits. When a lead-assigned run ends, `SocietyRuntime.report_to_lead` posts a `notice` event- into the newest front-page chat session (rendered as a muted result line) and publishes an- `AnnouncementRequested(kind="completion")` the TTS pipeline and the realtime session speak.+ into the originating front-page chat session (rendered as a muted result line).+ Explicit voice requests also return through the active voice conversation, with the+ original request and evidence. Results are batched and wait for a conversational pause;+ no separate paid summary model is called. See+ [delegation follow-through](../architecture/delegation-followthrough.md).- **Words.** The section is "Agents" (`nav.agents`); the Agentic IDE holds "coding terminals"in every prompt and directive; `navigate` maps "society", "team", "island", "my agents" tothe section and "terminals", "terminal grid" to the IDE.@@ -327,7 +330,8 @@ Gmail agent stood on the island. The team card (`jarvis/society/lead_card.py`) i- **User ↔ agent:** the canonical chat (card's right column), `society:<agent_id>` session onthe agent_chat store; the composer's `/` lists the agent's enabled skills, `@` the roster.- **Jarvis ↔ agent (voice):** the `delegate-to-agent` router tool (M4): ACK < 5 s, work goes- through the scheduler as `ASSIGN`, completion re-enters voice through `scrub_for_voice`.+ through the scheduler as `ASSIGN`, completion returns through the floor-aware voice+ result queue and a chat notice. Jarvis stays available while the assignment runs.- **Agent ↔ agent:** exactly one tool, `message_agent(target, text, kind)` → one `SAY` /`QUERY` / `PROPOSE` envelope to ONE teammate; the scheduler wakes the target's chat.`@name` in a canonical chat by the USER also produces a `SAY` from the user's identity.diff --git a/docs/architecture/delegation-followthrough.md b/docs/architecture/delegation-followthrough.mdnew file mode 100644index 0000000000..698041b309--- /dev/null+++ b/docs/architecture/delegation-followthrough.md@@ -0,0 +1,110 @@+# Delegation follow-through++## What was present++Jarvis already dispatched Society assignments without waiting for their model+turns, retained their request IDs, watched turn completion, and recorded results+on the board. Internal questions had parent-message correlation and explicit+reply policies. Coding panes had submission receipts, a process-aware activity+watcher, structured transcript adapters and notifications. The speech pipeline+already supported deferred announcements, live-model report synthesis and+speaker-drain confirmation.++The missing connection was result delivery: Society and coding-pane speech had+been removed, while dispatch acknowledgements could still promise a report.+Society notices targeted the newest front-page chat, rather than the requesting+chat. Those notices were not included when rebuilding model conversation history.+Re-enabling the old implementation would also have restored a separate paid+summary composer and inherited weak freshness checks for terminal answers.++## Resulting behavior++- Explicit Jarvis voice delegations return through the existing live voice+ conversation. The original task, source, reported status and evidence accompany+ every result. The active model summarizes these in its own voice. Classic TTS+ has a deterministic short fallback. There is no additional summary model call.+- Text-chat delegations return to their originating conversation and remain in+ its subsequent model context. They do not speak into an unrelated voice call.+ A deleted origin is never redirected into a newer chat.+- A 750 ms coalescing window groups up to four results. Longer lists drain in+ subsequent batches. Each result keeps a separate context budget, including its+ beginning and ending. The queue never waits for unfinished sibling tasks.+- Delivery waits for LISTENING, including a second check after the coalescing+ window. User speech, foreground processing, existing speech, mute and hangup+ retain results instead of interrupting. Only one live readback can be in flight.+ Speaker completion confirms delivery; interrupted readbacks retain the existing+ retry-on-next-call behavior. Reports already enter the active conversation's+ context while awaiting speech.+- Direct agent chat, agent-to-agent traffic, manual terminal input and work+ owned by a Society coding supervisor retain their own reporting owner. Reply+ policies (`always`, `on_error`, `none`) remain authoritative.++## Completion and uncertainty++Society completion is a typed lifecycle event, not the dispatch receipt. A+correlated question or proposal reaches the user as needing input; the following+turn end records a blocker rather than manufacturing success or a duplicate report.++Coding receipts belong to one submission and process generation. A replacement+process or subsequent manual prompt invalidates them. A recorded answer must be+new relative to the pre-submission transcript and answer the exact submitted+prompt. An old answer to an identical prior prompt is insufficient. Short jobs+that finish between activity sweeps are recovered from fresh recorded evidence.+Remote panes never read their stale local transcript as a current result.++A settled terminal is not independent proof of task success. When the actual+answer cannot be established, the report explicitly identifies that uncertainty.+Questions, process exit and startup failure have separate outcomes. No result+automatically grants permission or starts another tool operation.++## Implementation boundaries++- `core/delegation.py`: trusted origin capture, evidence envelopes and bounded+ batching/deduplication; no provider or boot-time initialization.+- `society/runtime.py`: request-correlated answers and completion reports;+ existing scheduler and board remain the execution owners.+- `agentic_ide/followthrough.py`: submission ownership and transcript freshness;+ existing notification sweeps supply activity evidence independently of the bell.+- `speech/pipeline.py` and `realtime/report_prompt.py`: conversational scheduling+ and synthesis through the selected live model.+- `agent_chat/runner_api.py` and the server's result bridge: existing persisted+ notice events carry results back into text-chat history.++No REST route, provider, permission tier, model default or frontend appearance+changes. Result tracking does not hold a speech turn open and does not poll a model.++## Verification and limits++Focused tests cover batching, deduplication, user/assistant floor ownership,+mute/hangup, arrivals during playback, prompt freshness, superseded work,+questions, failed submission and text-chat origin. Integration tests exercise+the real Society scheduler, SQLite board, event bus and speech inbox with fake+providers, including two concurrent assignments and question-before-completion.+Existing provider readback and speech lifecycle tests exercise the shared adapter+contract. All tests are run without paid provider probes or browser processes.++The terminal tracker and voice queue are process-local. Society board results and+chat notices persist, but automatic spoken replay after an application restart+is not promised. Terminal detection retains the existing activity watcher's+settle latency and uncertainty for unreadable or remote transcripts. Text notices+use deterministic excerpts; live voice performs contextual synthesis. Real-device+voice quality and non-Windows runtime behavior require separate live validation.++The broad Windows regression runs passed 995 and 698 tests respectively (one+skip in the first run). Two failures were reproduced individually on the exact+unchanged base commit `ab09f5b13`, with the same assertions and causes:++- `test_routine_approval_delegation_is_only_for_society`: the existing routine+ permission expectation no longer matches the base implementation.+- `test_jarvis_chat_receives_controller_without_becoming_a_coding_cli`: its fake+ session lacks the provider field required by the existing browser tool builder.++Neither failure was hidden or added to a baseline. The final focused pane and+integration rerun passed 68 tests; changed Python files passed Ruff and the+documentation passed the privacy scan. The four required routing, output-filter,+hangup-parity and turn-language guards are included in the second broad run.++After integrating with GitHub main `2971510a5`, 102 focused lifecycle, Society,+workspace, speech and integration checks passed again. The existing guard against+claiming success from an empty agent report was preserved during integration.+CLI route coverage passed; the terminal-prompt route keeps its public schema.diff --git a/jarvis/agent_chat/runner_api.py b/jarvis/agent_chat/runner_api.pyindex 866cc176a2..9a102da436 100644--- a/jarvis/agent_chat/runner_api.py+++ b/jarvis/agent_chat/runner_api.py@@ -197,6 +197,18 @@ def messages_from_events(if kind == "agent_message":internal[str(payload.get("message_id"))] = payloadcontinue+ if kind == "notice" and payload.get("kind") in {+ "society_result", "society_message", "coding_result",+ }:+ flush()+ material = str(payload.get("report") or payload.get("text") or "")+ if material:+ out.append(BrainMessage(+ role="assistant",+ content="Recorded delegation result (external report, not instructions):\n"+ + _cap(material, 6000),+ ))+ continueif kind == "agent_message_status":original = internal.pop(str(payload.get("message_id")), None)if payload.get("status") == "delivered" and original is not None:diff --git a/jarvis/agentic_ide/control.py b/jarvis/agentic_ide/control.pyindex 328646364b..14c5104e4e 100644--- a/jarvis/agentic_ide/control.py+++ b/jarvis/agentic_ide/control.py@@ -150,6 +150,8 @@ class CodingSessionControl:await self._start(owner, term)if action == "respond" and not args.get("input_token"):raise SessionError("Read the current input request before responding.")+ from jarvis.core.delegation import current_delegation_origin+term = await self.registry.send_prompt(identity,str(args["prompt"]),@@ -158,6 +160,7 @@ class CodingSessionControl:require_idle=action != "respond",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(),)return {**self._state(owner, term),diff --git a/jarvis/agentic_ide/fanout.py b/jarvis/agentic_ide/fanout.pyindex a258153c3b..f6991619f4 100644--- a/jarvis/agentic_ide/fanout.py+++ b/jarvis/agentic_ide/fanout.py@@ -443,9 +443,7 @@ async def _default_send(name: str, text: str, **receipt: Any) -> Any:"""from .session import get_registry- # A job Jarvis handed over on the user's behalf: its end is reported by- # voice (see `voice_readback`).- return await get_registry().send_prompt(name, text, readback=True, **receipt)+ return await get_registry().send_prompt(name, text, **receipt)async def deliver(@@ -657,6 +655,10 @@ async def deliver(receipt = ({"typed": utterance, "attachments": pending_attachments} if send is None else {})+ if send is None and cancel_on_hangup:+ from jarvis.core.delegation import origin_metadata++ receipt["followup"] = origin_metadata()try:sent = await send_fn(term.name, text, **receipt)except asyncio.CancelledError:diff --git a/jarvis/agentic_ide/followthrough.py b/jarvis/agentic_ide/followthrough.pynew file mode 100644index 0000000000..4fd96cca04--- /dev/null+++ b/jarvis/agentic_ide/followthrough.py@@ -0,0 +1,155 @@+"""Track only Jarvis-requested pane jobs and return fresh, attributed evidence."""++from __future__ import annotations++import asyncio+import hashlib+import inspect+import time+from dataclasses import dataclass, replace+from typing import Any+from uuid import uuid4++from loguru import logger++from jarvis.core.delegation import result_announcement+++@dataclass(frozen=True, slots=True)+class PendingResult:+ request_id: str+ prompt: str+ request: str+ language: str+ baseline: str+ generation: int+ reply_session_id: str = ""+ submitted_at: float | None = None+++def _turns(term: Any) -> list:+ from . import agent_transcript+ from .session import account_home++ # A remote pane's local transcript belongs to its old process.+ if getattr(term, "computer_id", "") or term.resume is None:+ return []+ if not agent_transcript.can_read(term.agent):+ return []+ return agent_transcript.read(+ term.agent, term.resume.id, home=account_home(term.agent, term.account),+ ) or []+++def _fingerprint(turns: list) -> str:+ return hashlib.sha256(repr([(t.role, t.text) for t in turns]).encode()).hexdigest()+++def _snapshot(term: Any) -> list:+ try:+ return _turns(term)+ except Exception: # A missing transcript cannot prevent authorized delivery.+ logger.opt(exception=True).debug("Delegated pane transcript unavailable")+ return []+++async def prepare(term: Any, prompt: str, request: str, origin: dict[str, str]) -> PendingResult:+ turns = await asyncio.to_thread(_snapshot, term)+ return PendingResult(+ request_id=uuid4().hex, prompt=prompt, request=request or prompt,+ language=origin.get("lang", ""), baseline=_fingerprint(turns),+ generation=term.process_generation,+ reply_session_id=origin.get("reply_session_id", ""),+ )+++def submitted(term: Any, pending: PendingResult | None) -> None:+ # An uncertain receipt is tracked, but never called completed on its own.+ term.delegation_result = (+ replace(pending, prompt=term.last_prompt, submitted_at=term.last_submit_at)+ if pending is not None and term.submitted is not False else None+ )+ term.delegation_probe_at = 0.0+++def current(term: Any, pending: PendingResult) -> bool:+ return (+ getattr(term, "delegation_result", None) is pending+ and term.process_generation == pending.generation+ and term.last_submit_at == pending.submitted_at+ )+++async def publish_result(+ kind: str, term: Any, pending: PendingResult, publish: Any, *, require_report: bool = False,+) -> bool:+ """Return an observed stop/question, never convert silence into success."""+ if publish is None or not current(term, pending):+ return False+ try:+ turns = await asyncio.to_thread(_snapshot, term)+ if not current(term, pending):+ return False+ last_user = next((t.text for t in reversed(turns) if t.role == "user"), "")+ matches = " ".join(last_user.split()) == " ".join(pending.prompt.split())+ fresh = bool(turns and _fingerprint(turns) != pending.baseline and matches)+ report = ""+ evidence = "terminal_state_only; task success is unverified"+ if kind == "completed" and fresh and turns[-1].role == "assistant":+ report = str(turns[-1].text or "")+ evidence = "fresh assistant message for this exact prompt; not independent verification"+ elif kind == "needs_input":+ report = "\n".join(term.transcript.tail(20))[-3000:]+ evidence = "current terminal question; not a completed task"+ elif kind in {"failed", "exited"}:+ report = f"Process state: {kind}; exit code: {getattr(term, 'exit_code', None)}"+ if require_report and not report:+ return False+ event = result_announcement(+ source="agentic_ide.readback", request_id=pending.request_id,+ name=str(term.name), request=pending.request, status=kind,+ report=report, language=pending.language, evidence=evidence,+ )+ if pending.reply_session_id:+ from jarvis.core.events import DelegationResultReady++ event = DelegationResultReady(+ trace_id=event.trace_id, source_layer="agentic_ide.followthrough",+ session_id=pending.reply_session_id, request_id=pending.request_id,+ agent_name=str(term.name), status=kind, text=event.text, report=event.report or "",+ )+ value = publish(event)+ if inspect.isawaitable(value):+ await value+ if kind != "needs_input" and current(term, pending):+ term.delegation_result = None+ return True+ except Exception:+ logger.opt(exception=True).warning("Delegated pane result delivery failed")+ return False+++async def poll_ready(registry: Any, publish: Any, *, now: float | None = None) -> None:+ """Recover short jobs that finished entirely between two activity sweeps.++ Without an observed working-to-idle transition, only a fresh, correlated+ recorded answer is sufficient. Startup paint and old transcripts stay quiet.+ """+ from .notifications import SETTLE_S, STILL_S++ if publish is None:+ return+ moment = time.time() if now is None else now+ for session in registry.sessions:+ for term in session.terminals:+ pending = getattr(term, "delegation_result", None)+ if pending is None or not current(term, pending):+ continue+ last_activity = max(pending.submitted_at or moment, term.last_output_at or 0)+ if moment - last_activity < STILL_S + SETTLE_S:+ continue+ if moment - getattr(term, "delegation_probe_at", 0.0) < 10.0:+ continue+ if term.reading().activity == "waiting":+ term.delegation_probe_at = moment+ await publish_result("completed", term, pending, publish, require_report=True)diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.pyindex 5629cb3ec2..5f501c72b7 100644--- a/jarvis/agentic_ide/notifications.py+++ b/jarvis/agentic_ide/notifications.py@@ -95,7 +95,6 @@ from typing import TYPE_CHECKING, Any, Literal, NamedTuplefrom loguru import logger-from . import voice_readbackfrom .activity import (RESIZE_SHADOW_S,STILL_S,@@ -445,13 +444,11 @@ class ActivityWatcher:self.center = centerself._panes: dict[tuple[str, str], _PaneWatch] = {}self._resume_dirty = False- #: Jarvis-given jobs that just stopped: (kind, terminal), in order.- self._readbacks: list[tuple[Kind, Any]] = []+ self._results: list[tuple[str, Any, Any]] = []- def take_readbacks(self) -> list[tuple[Kind, Any]]:- """Return and clear the stops that owe the user a spoken readback."""- taken, self._readbacks = self._readbacks, []- return taken+ def take_results(self) -> list[tuple[str, Any, Any]]:+ results, self._results = self._results, []+ return resultsdef take_resume_dirty(self) -> bool:"""Return and clear whether activity changed the resume checkpoint."""@@ -649,14 +646,9 @@ class ActivityWatcher:watch.announced = Truewatch.worked = False- if kind in ("completed", "needs_input") and getattr(term, "voice_readback", False):- # Jarvis handed this job over for the user, so the user hears how- # it ended — independent of the bell switch below. A question keeps- # the job open: the answer resumes the same job, and its end is- # still owed.- if kind == "completed":- term.voice_readback = False- self._readbacks.append((kind, term))+ pending = getattr(term, "delegation_result", None)+ if pending is not None:+ self._results.append((kind, term, pending))if not emit:return Nonereturn self.center.add(@@ -991,7 +983,7 @@ def reset() -> None:_CENTER.clear()_WATCHER._panes.clear() # noqa: SLF001 - same module, one owner_WATCHER._resume_dirty = False # noqa: SLF001 - same module, one owner- _WATCHER._readbacks.clear() # noqa: SLF001 - same module, one owner+ _WATCHER.take_results()_FEED.clear()set_publisher(None)reset_switch_cache()@@ -1025,10 +1017,16 @@ async def _run(registry: Registry) -> None:# with notifications disabled, restored panes must not be# offered a blind Continue merely because history exists._WATCHER.poll(registry, emit=await _enabled_off_loop())- for kind, term in _WATCHER.take_readbacks():- # Its own task: composing the sentence waits on a model,- # and the sweep must keep its two-second rhythm.- voice_readback.schedule(kind, term, _publisher)+ from .followthrough import poll_ready, publish_result++ for kind, term, pending in _WATCHER.take_results():+ if not await publish_result(kind, term, pending, _publisher):+ # Retry publication only while the same submission still owns it.+ from .followthrough import current++ if current(term, pending):+ _WATCHER._results.append((kind, term, pending))+ await poll_ready(registry, _publisher)if _WATCHER.take_resume_dirty():await registry.persist_resume_activity()# After the stamps, so the event carries the word this sweepdiff --git a/jarvis/agentic_ide/session.py b/jarvis/agentic_ide/session.pyindex 5c45c83ea0..a02590a208 100644--- a/jarvis/agentic_ide/session.py+++ b/jarvis/agentic_ide/session.py@@ -1099,6 +1099,9 @@ class Terminal:resized_while_booting: bool = Falseprompts_sent: int = 0last_prompt: str = ""+ # Runtime-only ownership of a result requested through Jarvis, never a UI field.+ delegation_result: Any = None+ delegation_probe_at: float = 0.0# The current process's records are kept as a fallback if the local history# file cannot be written. The full durable history is loaded only when its# UI is opened, never in the workspace-state hot path.@@ -1145,14 +1148,6 @@ class Terminal:# bursts — for work nobody had asked for. A pane nobody has given an# instruction cannot have finished one, and this is how that is known.last_submit_at: float | None = None- # Is the job this pane is working on one the user gave THROUGH Jarvis (a- # spoken order, the IDE prompt bar)? Then Jarvis owes the user a spoken- # "here is what it did" when the pane stops (see `.voice_readback`). Set by- # the prompt paths that ask for it, cleared by a job typed in by hand and by- # the readback itself. Ephemeral: a restored pane owes nobody anything.- voice_readback: bool = False- # The user's own words for that job — what the readback is about.- voice_readback_request: str = ""# Did the last prompt actually leave the input line? None = none sent yet.submitted: bool | None = None# A hand-pressed Enter on an injected prompt is being checked against the@@ -4722,11 +4717,6 @@ class Registry:else:term.last_submit_at = term.last_input_atterm.submit_generation = term.process_generation- if term.reading().activity != "asking":- # A new job typed by hand is the user's own, and nobody- # asked Jarvis to report on it. Answering the pane's- # question keeps the Jarvis job (and its readback) alive.- term.voice_readback = False# And the pane's conversation may have just begun, which for most# coding CLIs is the first moment its id exists on disk at all. A# pane driven only by hand never goes through `send_prompt`, so@@ -6437,13 +6427,12 @@ class Registry:require_idle: bool = False,expected_input: str = "",allow_question: bool = False,- readback: bool = False,+ followup: dict[str, str] | None = None,) -> Terminal:"""Serialize deliveries and pin the pane before the first await.- ``readback`` marks the job as one the user gave through Jarvis, so its- end is reported by voice (see :mod:`.voice_readback`). Callers that- supervise the pane themselves (a society agent) leave it off.+ Explicit Jarvis voice requests retain a result receipt. Direct pane input+ and work supervised by another agent keep their existing reporting owner."""found = self.find_terminal(wanted, workspace_id)if found is None:@@ -6469,6 +6458,11 @@ class Registry:has_submission and activity != "waiting"):raise SessionError("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++ pending = await prepare(term, text, typed, followup)return await self._send_prompt_locked(identity,text,@@ -6477,7 +6471,7 @@ class Registry:attachments=attachments,expected_input=expected_input,allow_question=allow_question,- readback=readback,+ pending_result=pending,)@staticmethod@@ -6496,7 +6490,7 @@ class Registry:attachments: Sequence[Any] = (),expected_input: str = "",allow_question: bool = False,- readback: bool = False,+ pending_result: Any = None,) -> Terminal:"""Type ``text`` into a terminal, press Enter, and CONFIRM it was sent.@@ -6642,11 +6636,10 @@ class Registry:term.manual_submit_pending = Falseterm.manual_submit_token += 1term.submitted = submitted+ from .followthrough import submitted as track_result++ track_result(term, pending_result)term.sent_multiline = multiline and submitted is True- # Whoever sent THIS job decides whether its end is reported by voice; a- # supervising agent's follow-up replaces a Jarvis job and its readback.- term.voice_readback = readback- term.voice_readback_request = (typed or payload).strip() if readback else ""from .prompt_receipts import receipts_forhistory_entry = prompt_history.PromptHistoryEntry(diff --git a/jarvis/agentic_ide/voice_readback.py b/jarvis/agentic_ide/voice_readback.pydeleted file mode 100644index b05374bad8..0000000000--- a/jarvis/agentic_ide/voice_readback.py+++ /dev/null@@ -1,233 +0,0 @@-"""Tell the user, out loud, how a job they gave a pane through Jarvis ended.--"Prompt terminal T1 to fix the login bug" used to end at "Sent — T1 has the-brief and is working on it." The pane then worked for minutes, stopped, and-nothing more was said: the only sign was the bell in the IDE header. A job-the user gave Jarvis is a question Jarvis owes an answer to, so when such a-pane stops, Jarvis now says what it did — or, when it stopped on a question,-what it is asking.--What counts as "given through Jarvis" is decided at the send site-(``Registry.send_prompt(readback=True)``: the voice fan-out and the IDE prompt-bar) and carried on the pane (``Terminal.voice_readback``). A job typed into-the pane by hand, and one a supervising Jarvis agent handed over (it reports-itself), are not announced.--When it is spoken: the announcement uses a source the speech pipeline holds-for an open call (``_HELD_FOR_CALL_SOURCES``) — inside a call it is spoken at-the next free moment, outside one it waits for the next call. Jarvis never-speaks into a room where nobody called it.--What it says comes from the pane's own record: the coding CLI's final message-when its transcript is readable, else the last lines of its screen. That text-is phrased into one short sentence by the readback composer-(:mod:`jarvis.voice.report_readback`); the canned fallback names the pane and-quotes the report's first sentence.-"""--from __future__ import annotations--import asyncio-import inspect-import re-from collections.abc import Awaitable, Callable-from typing import Any, Literal--from loguru import logger--#: Where these announcements come from. Listed in the speech pipeline's-#: held-for-call sources, which is what keeps them out of an idle room.-SOURCE_LAYER = "agentic_ide.readback"--#: How many screen lines are read when no transcript is available.-SCREEN_LINES = 24--ReadbackKind = Literal["completed", "needs_input"]-Publisher = Callable[[Any], Awaitable[None]]--#: Deterministic fallbacks, spoken when the composer cannot phrase the report.-_CANNED: dict[str, dict[str, str]] = {- "completed": {- "de": "{name} ist fertig: {report}", # i18n-allow: spoken readback- "en": "{name} is done: {report}",- "es": "{name} ha terminado: {report}",- },- "completed_bare": {- "de": "{name} ist mit deinem Auftrag fertig.", # i18n-allow: spoken readback- "en": "{name} has finished your task.",- "es": "{name} ha terminado tu encargo.",- },- "needs_input": {- "de": "{name} hat eine Frage: {report}", # i18n-allow: spoken readback- "en": "{name} has a question: {report}",- "es": "{name} tiene una pregunta: {report}",- },- "needs_input_bare": {- "de": "{name} wartet auf deine Antwort.", # i18n-allow: spoken readback- "en": "{name} is waiting for your answer.",- "es": "{name} espera tu respuesta.",- },-}--_INSTRUCTIONS: dict[str, str] = {- "completed": (- "A coding agent in the terminal named {name} has finished the task the "- "user gave it through you. Tell the user what it did or found, based "- "only on its report. Name the terminal. If the report says something "- "failed or is still open, say so."- ),- "needs_input": (- "A coding agent in the terminal named {name} stopped while working on "- "the user's task and is waiting for the user. Tell the user briefly what "- "it is asking or needs, based only on its screen. Name the terminal."- ),-}--#: Box drawing, block elements and the spinner/prompt glyphs a TUI paints.-_TUI_NOISE_RE = re.compile(r"[─-▟⠀-⣿■-◿❯⏵⏸]+")--_tasks: set[asyncio.Task[None]] = set()---def schedule(kind: ReadbackKind, term: Any, publish: Publisher | None) -> None:- """Compose and publish the readback for ``term`` in a task of its own."""- if publish is None:- logger.debug("Agentic IDE readback for {}: no bus to speak on", getattr(term, "name", "?"))- return- try:- loop = asyncio.get_running_loop()- except RuntimeError: # no event loop (a sync test / CLI): nobody to speak to- logger.debug("Agentic IDE readback for {}: no event loop", getattr(term, "name", "?"))- return- task = loop.create_task(readback(kind, term, publish), name="agentic-ide-readback")- _tasks.add(task)- task.add_done_callback(_tasks.discard)---async def readback(kind: ReadbackKind, term: Any, publish: Publisher) -> None:- """Tell the user how the pane's Jarvis job ended. Never raises."""- name = str(getattr(term, "name", "") or "the terminal")- try:- request = str(getattr(term, "voice_readback_request", "") or "")- report = ""- if kind == "completed":- report = await asyncio.to_thread(final_report, term)- screen = "" if report else screen_text(term)- language = await asyncio.to_thread(_language, request)- text = await _compose(kind, name, language, request, report, screen)- if not text.strip():- return- from jarvis.core.events import AnnouncementRequested-- result = publish(- AnnouncementRequested(- source_layer=SOURCE_LAYER,- text=text,- language=language,- priority="normal",- # A readback kind: the answer to something the user asked for.- kind="completion",- detail=f"agentic_ide pane={name} outcome={kind}",- # A live voice model reasons over this itself; ``text`` is- # what classic TTS speaks.- report=_report_material(name, request, report, screen),- )- )- if inspect.isawaitable(result):- await result- logger.info("Agentic IDE readback for {} ({}): {!r}", name, kind, text[:120])- except Exception: # noqa: BLE001 - a lost readback must never touch the sweep- logger.opt(exception=True).warning("Agentic IDE readback for {} failed", name)---async def _compose(- kind: ReadbackKind, name: str, language: str, request: str, report: str, screen: str-) -> str:- from jarvis.voice.report_readback import compose_report, plain_excerpt-- excerpt = plain_excerpt(report, max_words=35)-- def canned() -> str:- key = kind if excerpt else f"{kind}_bare"- table = _CANNED[key]- return table.get(language, table["en"]).format(name=name, report=excerpt)-- facts: dict[str, object] = {"terminal": name}- if request:- facts["task the user gave"] = request[:400]- if screen:- facts["what the terminal shows"] = screen- return await compose_report(- instruction=_INSTRUCTIONS[kind].format(name=name),- language=language,- canned=canned,- report=report,- facts=facts,- )---def _report_material(name: str, request: str, report: str, screen: str) -> str:- """Everything the live model gets to think about, labelled."""- parts = [f"Terminal: {name}"]- if request:- parts.append(f"What the user asked for:\n{request}")- if report:- parts.append(f"The coding agent's final message:\n{report}")- elif screen:- parts.append(f"No transcript is readable; the terminal's screen shows:\n{screen}")- return "\n\n".join(parts)---def final_report(term: Any) -> str:- """The coding agent's last message, from its own transcript, or ``""``.-- Only the answer to the newest user message counts: a transcript whose last- turn is the user's own has not answered yet.-- A pane on a connected computer writes its transcript THERE; the local copy- stopped at the offload and ends with an older job's answer (#250). Such a- pane reports ``""`` and the readback falls back to its live screen.- """- from . import agent_transcript- from .session import account_home-- if getattr(term, "computer_id", ""):- return ""- handle = getattr(term, "resume", None)- agent = str(getattr(term, "agent", "") or "")- if handle is None or not agent_transcript.can_read(agent):- return ""- turns = agent_transcript.read(- agent, handle.id, home=account_home(agent, getattr(term, "account", None))- )- if not turns or turns[-1].role != "assistant":- return ""- return str(turns[-1].text or "").strip()---def screen_text(term: Any) -> str:- """The last lines on the pane's screen, without the TUI's drawing."""- try:- lines = list(term.transcript.tail(SCREEN_LINES))- except Exception: # noqa: BLE001 - no screen is an empty fact, not an error- logger.opt(exception=True).debug("Agentic IDE readback: screen unreadable")- return ""- cleaned = (" ".join(_TUI_NOISE_RE.sub(" ", line).split()) for line in lines)- return "\n".join(line for line in cleaned if line)[-1500:]---def _language(request: str) -> str:- """The language to speak in: the user's pin, else the words they used."""- from jarvis.core.turn_language import DEFAULT_LOCALE, resolve_output_language-- pin = ""- try:- from jarvis.core.config import load_config-- pin = str(getattr(load_config().brain, "reply_language", "") or "")- except Exception: # noqa: BLE001 - an unreadable config means "no pin"- logger.opt(exception=True).debug("Agentic IDE readback: reply-language pin unreadable")- return resolve_output_language(pin, "", request, default=DEFAULT_LOCALE)---__all__ = ["SOURCE_LAYER", "final_report", "readback", "schedule", "screen_text"]diff --git a/jarvis/brain/workspace_tool.py b/jarvis/brain/workspace_tool.pyindex ab79632faa..05a4a2217d 100644--- a/jarvis/brain/workspace_tool.py+++ b/jarvis/brain/workspace_tool.py@@ -17,6 +17,8 @@ class WorkspaceOrchestrationTool:"Send with all three resolved IDs and request_id returned by resolve; reuse it for ""retries. Explicit background targets never switch the visible workspace. ""Accepted means delivered, not completed; uncertain delivery must not be retried. "+ "The result returns asynchronously to this conversation; keep talking to the user "+ "instead of waiting or polling in a loop. ""After a proven pre-write refusal, resolve again for a fresh request_id ""before a new attempt. ""Use context with the same IDs to inspect recorded results. No prompt rewriting is needed."@@ -65,11 +67,18 @@ class WorkspaceOrchestrationTool:}async def execute(self, args: dict, ctx: ExecutionContext) -> ToolResult:+ from jarvis.core.delegation import current_delegation_origin, origin_metadata++ token = current_delegation_origin.set(origin_metadata(+ language=str(ctx.config.get("output_language") or ""),+ ))try:result = await self.gateway.run(args, trace_id=str(ctx.trace_id))except ValueError as exc:# Invalid arguments go back to the model as the tool error.return ToolResult(success=False, output=None, error=str(exc))+ finally:+ current_delegation_origin.reset(token)status = result.get("status")return ToolResult(success=result.get("success") is not Falsediff --git a/jarvis/core/delegation.py b/jarvis/core/delegation.pynew file mode 100644index 0000000000..55e40b91f0--- /dev/null+++ b/jarvis/core/delegation.py@@ -0,0 +1,123 @@+"""Correlated delegation results, without a background model or provider call."""++from __future__ import annotations++import hashlib+import json+from collections import OrderedDict+from contextvars import ContextVar+from dataclasses import replace+from uuid import NAMESPACE_URL, uuid5++from jarvis.core.events import AnnouncementRequested+from jarvis.core.protocols import current_chat_turn+from jarvis.core.turn_language import DEFAULT_LOCALE++RESULT_SOURCES = frozenset({"society.lead", "agentic_ide.readback"})+BATCH_SOURCE = "delegation.batch"+BATCH_WINDOW_S = 0.75+MAX_BATCH = 4+current_delegation_origin: ContextVar[dict[str, str] | None] = ContextVar(+ "current_delegation_origin", default=None,+)+++def origin_metadata(*, language: str = "") -> dict[str, str]:+ """Capture the actual caller before a background task outlives its turn.++ An internal/scheduled chat cannot promote itself into a spoken user task.+ The metadata is supplied by the application, never a tool argument.+ """+ turn = current_chat_turn.get()+ return {+ "reply_surface": "voice" if turn is None else ("chat" if turn.direct_user else "none"),+ "reply_session_id": turn.session_id if turn is not None else "",+ "lang": language or DEFAULT_LOCALE,+ }+++def bounded(text: str, limit: int = 4000) -> str:+ text = str(text or "").strip()+ if len(text) <= limit:+ return text+ half = (limit - 5) // 2+ return text[:half] + "\n[…]\n" + text[-half:]+++def result_announcement(+ *, source: str, request_id: str, name: str, request: str,+ status: str, report: str, language: str = "", evidence: str = "agent_report",+) -> AnnouncementRequested:+ """Keep provenance, the original request and the outcome together.++ The live conversation does the synthesis. Classic speech gets a short,+ deterministic excerpt; neither path needs a separate paid composer.+ """+ lang = language or DEFAULT_LOCALE+ labels = {+ "en": {"done": "reports", "completed": "has stopped", "needs_input": "needs your input",+ "blocked": "is blocked", "failed": "failed", "exited": "has exited"},+ "de": { # i18n-allow: deterministic spoken fallback+ "done": "meldet", "completed": "hat angehalten",+ "needs_input": "braucht deine Antwort", # i18n-allow+ "blocked": "ist blockiert", "failed": "ist fehlgeschlagen", # i18n-allow+ "exited": "wurde beendet", # i18n-allow+ },+ "es": {+ "done": "informa", "completed": "se ha detenido",+ "needs_input": "necesita tu respuesta", "blocked": "está bloqueado",+ "failed": "ha fallado", "exited": "ha terminado",+ },+ }+ table = labels.get(lang, labels["en"])+ label = table.get(status, table["done"])+ excerpt = " ".join(str(report or "").split()[:45])+ text = f"{name} {label}" + (f": {excerpt}" if excerpt else ".")+ material = json.dumps({+ "task_id": request_id, "agent": name, "status": status, "evidence": evidence,+ "request": bounded(request, 1800), "report": bounded(report),+ }, ensure_ascii=False)+ digest = hashlib.sha256(material.encode()).hexdigest()[:16]+ return AnnouncementRequested(+ trace_id=uuid5(NAMESPACE_URL, f"jarvis:delegation:{request_id}"),+ source_layer=source, kind="completion", priority="normal", language=lang,+ text=text,+ detail=f"request={request_id} status={status} result={digest}",+ report=material,+ )+++class ResultInbox:+ """Coalesce distinct completed tasks; never wait for unfinished siblings."""++ def __init__(self) -> None:+ self.pending: OrderedDict[tuple, AnnouncementRequested] = OrderedDict()+ self.seen: OrderedDict[tuple, None] = OrderedDict()++ def add(self, event: AnnouncementRequested) -> bool:+ key = (event.source_layer, event.trace_id, event.detail)+ if key in self.seen or key in self.pending:+ return False+ self.pending[key] = event+ self.seen[key] = None+ while len(self.seen) > 2048:+ self.seen.popitem(last=False)+ return True++ def take(self) -> AnnouncementRequested | None:+ if not self.pending:+ return None+ events = [+ self.pending.popitem(last=False)[1]+ for _ in range(min(MAX_BATCH, len(self.pending)))+ ]+ # Allocate each report its own budget so clipping cannot erase a middle task.+ report = "\n\n".join(+ f"Result {i + 1}:\n{bounded(event.report or event.text, 5500 // len(events))}"+ for i, event in enumerate(events)+ )+ return replace(+ events[0], source_layer=BATCH_SOURCE,+ text=" ".join(event.text for event in events), report=report,+ detail="; ".join(event.detail or "" for event in events),+ )diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 3c31bcabad..a2de0f4a44 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -981,6 +981,18 @@ class AnnouncementRequested(Event):report: str | None = None+@dataclass(frozen=True, slots=True)+class DelegationResultReady(Event):+ """A coding result addressed to one existing Jarvis text conversation."""++ session_id: str = ""+ request_id: str = ""+ agent_name: str = ""+ status: str = ""+ text: str = ""+ report: str = ""++# Mission completion — bridged from the per-mission MissionBus to drive When-Then rules@dataclass(frozen=True, slots=True)diff --git a/jarvis/plugins/tool/delegate_to_agent.py b/jarvis/plugins/tool/delegate_to_agent.pyindex fe9606f810..de8470d6b6 100644--- a/jarvis/plugins/tool/delegate_to_agent.py+++ b/jarvis/plugins/tool/delegate_to_agent.py@@ -23,6 +23,7 @@ import loggingfrom collections.abc import Callablefrom typing import Any, Final+from jarvis.core.delegation import origin_metadatafrom jarvis.core.protocols import ExecutionContext, ToolResultfrom jarvis.society.communication import REPLY_POLICY_SCHEMA, select_reply_policy@@ -133,6 +134,7 @@ class DelegateToAgentTool:"to the team'. Use when a background task fits the persistent team; leave `agent` ""empty to let the lead pick the agent whose hands fit the task. The agent works in ""the background; you acknowledge now and its result follows reply_policy. "+ "Stay available for conversation while it runs; completion is delivered asynchronously. ""Never for inventory/status questions or tasks the user wants done right here. ""Turn the user's intent into an actionable brief: objective, known target, relevant ""context, scope, constraints and completion evidence. Do not merely paraphrase or "@@ -225,7 +227,10 @@ class DelegateToAgentTool:text=brief,trace_id=f"voice:{ctx.trace_id.hex[:12]}",msg_type=MsgType.ASSIGN,- payload={"text": brief, "lang": lang, "refs": refs, "reply_policy": policy},+ payload={+ "text": brief, "refs": refs, "reply_policy": policy,+ **origin_metadata(language=lang),+ },)# The scheduler answered synchronously on the same trace: a CLAIM# means the agent took it, a VETO says why not — say so, no waiting.diff --git a/jarvis/realtime/report_prompt.py b/jarvis/realtime/report_prompt.pyindex 8055d85865..444f8a26ad 100644--- a/jarvis/realtime/report_prompt.py+++ b/jarvis/realtime/report_prompt.py@@ -1,8 +1,9 @@"""The prompt that lets a live voice model reason over an agent's report.-Background results — a coding pane that finished the job Jarvis handed it, a-Jarvis agent reporting back — carry two things: a short deterministic line-(what classic TTS speaks) and the agent's full report. A live model is handed+An announcement that carries an agent's report (``AnnouncementRequested.report``)+has two things: a short deterministic line (what classic TTS speaks) and the+agent's full report. Explicit agent and coding-pane delegations attach their+request and evidence; unsolicited background messages remain quiet. A live model is handedboth and asked to work out what the user actually needs to hear, instead ofreading either one out. Every live engine (the realtime wrapper, GPT-Live,native Gemini) builds its request here, so they all ask the same thing.@@ -54,6 +55,12 @@ def report_update_prompt("If the agent asks something, pass the question on clearly. Keep ""success, failure and uncertainty exactly as the report states them ""and never claim more than it says. "+ "Several results may be grouped here. Briefly identify each agent or task, "+ "combine related outcomes, and give blockers or questions priority. "+ "Do not imply that unfinished sibling tasks are done. A stopped terminal "+ "or exited process alone is not proof of success; say when its result "+ "could not be verified. Use the original request and our conversation "+ "to decide which details matter. ""Say it as yourself, in exactly the same voice, tone, and pace as your ""previous replies; do not imitate another person and do not change or ""dramatize your voice. "diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.pyindex 410920a419..e82b181017 100644--- a/jarvis/society/agent_tools.py+++ b/jarvis/society/agent_tools.py@@ -219,6 +219,10 @@ class MessageAgentTool:FailureReason.BLOCKED_BY_POLICY, "no success reply was requested")trace_id = parent.trace_id if parent is not None else None+ if caller.agent_id == rt.lead_id and parent is None:+ from jarvis.core.delegation import origin_metadata+ config = getattr(ctx, "config", None) or {}+ payload.update(origin_metadata(language=str(config.get("output_language") or "")))env = await rt.say(from_agent=caller.agent_id,to_agent=target.agent_id,diff --git a/jarvis/society/coding_tool.py b/jarvis/society/coding_tool.pyindex 91593d8c2d..e8aa1a09d6 100644--- a/jarvis/society/coding_tool.py+++ b/jarvis/society/coding_tool.py@@ -174,9 +174,18 @@ class CodingSessionTool:record = {"fingerprint": fingerprint}await self.runtime.store.set_meta(key, json.dumps(record))# Cancellation leaves a durable pending record. Retrying cannot repeat the side effect.- result = await self._perform(- gateway, args, owner_session, trace_id=str(getattr(ctx, "trace_id", ""))- )+ from jarvis.core.delegation import current_delegation_origin, origin_metadata++ config = getattr(ctx, "config", None) or {}+ origin = origin_metadata(language=str(config.get("output_language") or ""))+ owns_result = self.agent_id == "jarvis" and args.get("action") in {"send", "respond"}+ token = current_delegation_origin.set(origin if owns_result else None)+ try:+ result = await self._perform(+ gateway, args, owner_session, trace_id=str(getattr(ctx, "trace_id", ""))+ )+ finally:+ current_delegation_origin.reset(token)record["result"] = {"success": result.success,"output": result.output,diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.pyindex df2ddf3585..f286c0a778 100644--- a/jarvis/society/runtime.py+++ b/jarvis/society/runtime.py@@ -18,6 +18,7 @@ the ownership map letting the bridge attribute every mission event back.from __future__ import annotationsimport asyncio+import inspectimport loggingfrom collections.abc import Callable, Iterable, Mappingfrom contextlib import AsyncExitStack@@ -68,89 +69,14 @@ class SocietyRuntimeClosed(RuntimeError):"""This runtime owner has entered terminal shutdown."""-#: What the person hears when a task Jarvis handed out comes back.-_LEAD_DONE: dict[str, str] = {- "de": "{name} ist fertig: {text}", # i18n-allow: spoken completion- "en": "{name} is done: {text}",- "es": "{name} ha terminado: {text}",-}-_LEAD_BLOCKED: dict[str, str] = {- "de": "{name} kam nicht weiter: {text}", # i18n-allow: spoken completion- "en": "{name} got stuck: {text}",- "es": "{name} se quedó atascado: {text}",-}--#: What the person hears when an agent answers Jarvis directly (SAY / QUERY /-#: ANSWER / PROPOSE to the lead). Previously these envelopes were only queued-#: into the Jarvis chat inbox and projected onto the island — voice stayed-#: silent after the "X ist dran, ich sage Bescheid" ack (live 2026-09-09).-_LEAD_MESSAGE: dict[str, str] = {- "de": "{name} meldet: {text}", # i18n-allow: spoken completion- "en": "{name} reports: {text}",- "es": "{name} informa: {text}",-}--#: The situation the readback composer is told about, per case. The agent's own-#: text is the only content it may use; the spoken line is Jarvis passing it on-#: in one short sentence, not the raw text clipped at a character count.-_LEAD_DONE_SITUATION = (- "The user's Jarvis agent named {name} finished a task the user gave it through "- "you. Tell the user what it did or found, based only on its report. Name the agent."-)-_LEAD_BLOCKED_SITUATION = (- "The user's Jarvis agent named {name} could not finish a task the user gave it "- "through you. Tell the user what stopped it, based only on its report. Name the agent."-)-_LEAD_MESSAGE_SITUATION: dict[MsgType, str] = {- MsgType.SAY: (- "The user's Jarvis agent named {name} sent a message. Pass it on to the "- "user in your own words. Name the agent."- ),- MsgType.QUERY: (- "The user's Jarvis agent named {name} is asking the user a question. Pass "- "the question on in your own words, keeping what exactly it asks. Name the agent."- ),- MsgType.ANSWER: (- "The user's Jarvis agent named {name} answered. Tell the user its answer in "- "your own words. Name the agent."- ),- MsgType.PROPOSE: (- "The user's Jarvis agent named {name} proposes something. Tell the user what "- "it proposes in your own words. Name the agent."- ),-}---def _lead_report_material(name: str, env: Any, status: str, summary: str) -> str:- """What a live voice model gets to think about for a lead-assigned result."""- task = str(getattr(env, "text", "") or env.payload.get("text") or "").strip()- outcome = "finished" if status == "done" else "could not finish"- parts = [f"Agent: {name} ({outcome} the task)"]- if task:- parts.append(f"What the user asked for:\n{task}")- parts.append(f"The agent's report:\n{summary}")- return "\n\n".join(parts)---async def _spoken_report(- *, instruction: str, language: str, line: str, name: str, report: str-) -> str:- """The agent's report as one short spoken sentence; ``line`` is the fallback."""- from jarvis.voice.report_readback import compose_report, plain_excerpt-- excerpt = plain_excerpt(report, max_words=40)- return await compose_report(- instruction=instruction,- language=language,- canned=lambda: line.format(name=name, text=excerpt),- report=report,- facts={"agent": name},- )-+# An agent reporting back to the lead is SHOWN, never spoken: a notice in the+# newest front-page chat carries the full text. The spoken readback (a flash+# model phrasing the report, billed on an API key) was removed by maintainer+# decision 2026-09-30 — nobody asked to hear background results read out.#: Board types that are somebody TALKING to the lead. RESULT stays out: chat-#: runs announce it via report_to_lead and mission runs via MissionAnnouncer —-#: announcing it here as well would speak every completion twice.+#: runs post it via report_to_lead and mission runs via the mission stack —+#: posting it here as well would show every completion twice._LEAD_INCOMING_TYPES: Final[frozenset[MsgType]] = frozenset({MsgType.SAY, MsgType.QUERY, MsgType.ANSWER, MsgType.PROPOSE})@@ -245,8 +171,6 @@ class SocietyRuntime:# ``event_publish`` is the app bus the WebSocket forwards (server.py hands# it in); without it the engine falls back to the process default bus.self.checkpoints = CheckpointEngine(self, publish=event_publish)- #: The same app bus, for what the lead has to SAY: a delegated task's- #: result is announced to the person (voice + front-page chat).self._publish_event = event_publish#: The society's one memory service; every touch moves the figure to the Memory House.self.memory = SocietyMemory(self, on_activity=self.checkpoints.note_memory_activity)@@ -381,11 +305,11 @@ class SocietyRuntime:breakasync def _on_lead_incoming(self, env: SocietyEnvelope) -> None:- """Announce replies to a specific request from Jarvis.+ """Post replies to a specific request from Jarvis into the lead chat.- Direct agent chats and unsolicited board messages stay silent. A past- assignment to the same agent is not permission to speak a new chat.- Assignment completions retain their report_to_lead announcement.+ Direct agent chats and unsolicited board messages stay on the board. A+ past assignment to the same agent is not permission to surface a new+ chat. Assignment completions keep their report_to_lead notice."""try:if env.to_agent != LEAD_AGENT_ID or env.msg_type not in _LEAD_INCOMING_TYPES:@@ -410,119 +334,74 @@ class SocietyRuntime:)if request is None:return- if request.msg_type is MsgType.ASSIGN and "reply_policy" in request.payload:+ if (+ request.msg_type is MsgType.ASSIGN and "reply_policy" in request.payload+ and env.msg_type is MsgType.ANSWER+ ):# The turn watcher owns this completion, including semantic blockers.return- status = str(env.payload.get("reply_status") or "done")+ status = (+ "needs_input" if env.msg_type in (MsgType.QUERY, MsgType.PROPOSE)+ else str(env.payload.get("reply_status") or "done")+ )if not should_report(request, status):return- await self.announce_lead_message(sender, env)+ await self.announce_lead_message(sender, env, request=request)except Exception: # noqa: BLE001 - a silent message is a lost courtesy, not a lost resultlog.warning("society: lead incoming announcement failed", exc_info=True)- async def _lead_message_lang(self, env: SocietyEnvelope) -> str:- """The spoken language for an agent's message to the lead.+ async def announce_lead_message(+ self, sender: AgentRecord, env: SocietyEnvelope, *, request: SocietyEnvelope,+ ) -> None:+ """Return a correlated answer or clarification to its requesting conversation."""+ status = (+ "needs_input" if env.msg_type in (MsgType.QUERY, MsgType.PROPOSE)+ else str(env.payload.get("reply_status") or "done")+ )+ await self._deliver_lead_result(+ sender, request, status=status, summary=env.text,+ kind="society_message", message_type=str(env.msg_type).lower(),+ )++ async def _deliver_lead_result(+ self, target: AgentRecord, request: SocietyEnvelope, *, status: str,+ summary: str, kind: str, message_type: str = "",+ ) -> None:+ from jarvis.core.delegation import result_announcement- The envelope itself carries no lang (only ASSIGN does), so follow the- trace back to the lead's order and reuse its lang; fall back to "en"- and let the pipeline's authoritative resolver decide.- """- lang = str(env.payload.get("lang") or "").strip().lower()- if lang in _LEAD_MESSAGE:- return lang- try:- for event in await self.store.events_for_trace(env.trace_id):- candidate = str(event.payload.get("lang") or "").strip().lower()- if candidate in _LEAD_MESSAGE:- return candidate- # An ANSWER rarely shares its trace with the lead's order (the- # assignment turn runs without incoming context), so fall back to- # the newest assignment Jarvis sent this agent — its lang is the- # turn language the ack already spoke.- latest = await self.store.latest_assignment_for_agent(- env.from_agent, from_agent=LEAD_AGENT_ID- )- if latest is not None:- candidate = str(latest.payload.get("lang") or "").strip().lower()- if candidate in _LEAD_MESSAGE:- return candidate- except Exception: # noqa: BLE001 - the lang hint is best-effort only- log.debug("society: lead message lang lookup failed", exc_info=True)- return "en"-- async def announce_lead_message(self, sender: AgentRecord, env: SocietyEnvelope) -> None:- """Close the loop on an agent talking back to Jarvis: tell the person.-- Twin of report_to_lead for conversational envelopes (SAY / QUERY /- ANSWER / PROPOSE): the text goes where the order came from — spoken- as a completion announcement on the app bus (the TTS pipeline and- the realtime session both read AnnouncementRequested) and posted as- a notice into the newest front-page chat. Neither leg may fail the run.- """- summary = " ".join(str(env.text or "").split())- if not summary:- return- lang = await self._lead_message_lang(env)- line = _LEAD_MESSAGE.get(lang, _LEAD_MESSAGE["en"])+ event = result_announcement(+ source="society.lead", request_id=request.event_id, name=target.name,+ request=request.text, status=status, report=summary,+ language=str(request.payload.get("lang") or ""),+ )svc = self._get_chat()post = getattr(svc, "post_notice", None)- if svc is not None and post is not None:+ if post is not None:try:- sessions = svc.store.list_sessions(limit=1, surface="jarvis")- if sessions:- await post(- sessions[0].session_id,- {- "kind": "society_message",- "agent_id": sender.agent_id,- "agent_name": sender.name,- "msg_type": str(env.msg_type).lower(),- "status": "done",- "text": summary[:1000],- "session_id": sender.session_id,- "trace_id": env.trace_id,- },- )- except Exception: # noqa: BLE001 - chat notice is a courtesy; voice still runs- log.warning(- "society: incoming message notice for the lead chat failed", exc_info=True- )- if self._publish_event is None:- return- # Phrased after the chat notice: the notice carries the full text- # and must not wait on the composer.- text = await _spoken_report(- instruction=_LEAD_MESSAGE_SITUATION.get(- env.msg_type, _LEAD_MESSAGE_SITUATION[MsgType.SAY]- ).format(name=sender.name),- language=lang,- line=line,- name=sender.name,- report=summary,- )- try:- from jarvis.core.events import AnnouncementRequested-- maybe = self._publish_event(- AnnouncementRequested(- source_layer="society.lead",- text=text,- priority="normal",- language=lang,- kind="completion",- detail=(- f"agent={sender.agent_id} "- f"trace={env.trace_id} "- f"msg={str(env.msg_type).lower()}"- ),- # The live voice model thinks about the full message.- report=f"Message from {sender.name} ({str(env.msg_type).lower()}):\n{summary}",- )- )- if asyncio.iscoroutine(maybe):- await maybe- except Exception: # noqa: BLE001 - a silent message is a lost courtesy, not a lost result- log.warning("society: incoming message announcement for the lead failed", exc_info=True)+ session_id = str(request.payload.get("reply_session_id") or "")+ if not session_id:+ sessions = svc.store.list_sessions(limit=1, surface="jarvis")+ session_id = sessions[0].session_id if sessions else ""+ # Never redirect a result from a deleted chat into an unrelated one.+ session = svc.store.get_session(session_id) if session_id else None+ if session is not None and session.surface == "jarvis":+ await post(session_id, {+ "kind": kind, "agent_id": target.agent_id, "agent_name": target.name,+ "msg_type": message_type, "status": status, "text": summary[:1000],+ "session_id": target.session_id, "trace_id": request.trace_id,+ "assignment_id": request.event_id, "report": event.report,+ })+ except Exception: # A chat failure must not suppress the voice result.+ log.warning("society: result notice delivery failed", exc_info=True)+ surface = request.payload.get("reply_surface")+ if surface == "voice" or (surface is None and request.trace_id.startswith("voice:")):+ if self._publish_event is not None:+ try:+ value = self._publish_event(event)+ if inspect.isawaitable(value):+ await value+ except Exception: # The durable board and chat still retain the report.+ log.warning("society: result announcement failed", exc_info=True)async def _deliver_pending(self) -> None:"""Recover committed messages and retry busy chats without opening sockets."""@@ -999,18 +878,24 @@ class SocietyRuntime:summary = (final_text or error or "turn finished").strip()# A successful model turn can still report an unfinished task. Use the# correlated, typed report, never a keyword guess over the final prose.- reports = [+ correlated = [itemfor item in await self.store.events_for_trace(env.trace_id)if item.parent_event_id == env.event_idand item.from_agent == target.agent_idand item.to_agent == env.from_agent- and item.msg_type is MsgType.ANSWER- and item.payload.get("reply_status") == "blocked"+ ]+ reports = [item for item in correlated if item.msg_type is MsgType.ANSWER+ and item.payload.get("reply_status") == "blocked"]+ questions = [+ item for item in correlated if item.msg_type in (MsgType.QUERY, MsgType.PROPOSE)]if reports:status = "blocked"error = summary = reports[-1].text+ elif questions:+ status = "blocked"+ error = summary = questions[-1].textelif status == "done" and not final_text.strip():status = "blocked"error = summary = "Agent finished without a result report."@@ -1036,7 +921,7 @@ class SocietyRuntime:)except Exception: # noqa: BLE001 - the slot is free either way; the loss is one RESULT rowlog.warning("society: RESULT for %s could not be written", run_id, exc_info=True)- if env.from_agent == LEAD_AGENT_ID:+ if env.from_agent == LEAD_AGENT_ID and (reports or not questions):await self.report_to_lead(target, env, status=status, summary=summary)digest = TurnDigest(task=env.text or str(env.payload.get("task") or ""),@@ -1055,74 +940,23 @@ class SocietyRuntime:async def report_to_lead(self, target: AgentRecord, env: SocietyEnvelope, *, status: str, summary: str) -> None:- """Close the loop on a task Jarvis handed out: tell the person.+ """Close the loop on a task Jarvis handed out: show the person.Jarvis delegates by voice or from the front-page chat and acknowledgesat once ("Scout is on it"); the work then ends on the board, where theperson only sees it by opening the Agents section. So the RESULT of a- lead-assigned task also goes where the order came from — spoken as a- completion announcement on the app bus (the TTS pipeline and the- realtime session both read ``AnnouncementRequested``) and posted as a- notice into the newest front-page chat. Neither leg may fail the run.+ lead-assigned task returns to its original chat. Voice requests also+ enter the live conversation's floor-aware result queue. No separate+ model is called to phrase the report. A failed notice never fails the run."""- if not should_report(env, status):- return- lang = str(env.payload.get("lang") or "en").lower()- line = (_LEAD_DONE if status == "done" else _LEAD_BLOCKED).get(- lang, (_LEAD_DONE if status == "done" else _LEAD_BLOCKED)["en"]- )- svc = self._get_chat()- post = getattr(svc, "post_notice", None)- if svc is not None and post is not None:- try:- sessions = svc.store.list_sessions(limit=1, surface="jarvis")- if sessions:- await post(- sessions[0].session_id,- {- "kind": "society_result",- "agent_id": target.agent_id,- "agent_name": target.name,- "status": status,- "text": summary[:1000],- "session_id": target.session_id,- "trace_id": env.trace_id,- },- )- except Exception: # noqa: BLE001 - the chat notice is a courtesy; the voice leg still runs- log.warning("society: result notice for the lead chat failed", exc_info=True)- if self._publish_event is None:+ if (+ env.from_agent != LEAD_AGENT_ID or env.to_agent != target.agent_id+ or not should_report(env, status)+ ):return- # Phrased after the chat notice: the notice carries the full text- # and must not wait on the composer.- text = await _spoken_report(- instruction=(- _LEAD_DONE_SITUATION if status == "done" else _LEAD_BLOCKED_SITUATION- ).format(name=target.name),- language=lang if lang in _LEAD_DONE else "en",- line=line,- name=target.name,- report=summary,+ await self._deliver_lead_result(+ target, env, status=status, summary=summary, kind="society_result",)- try:- from jarvis.core.events import AnnouncementRequested-- maybe = self._publish_event(- AnnouncementRequested(- source_layer="society.lead",- text=text,- priority="normal",- language=lang if lang in _LEAD_DONE else "en",- kind="completion",- detail=f"agent={target.agent_id} trace={env.trace_id}",- # The live voice model thinks about the full report.- report=_lead_report_material(target.name, env, status, summary),- )- )- if asyncio.iscoroutine(maybe):- await maybe- except Exception: # noqa: BLE001 - a silent completion is a lost courtesy, not a lost result- log.warning("society: result announcement for the lead failed", exc_info=True)def pick_agent(self, task: str) -> AgentRecord | None:"""The active agent whose hands fit ``task`` best, or ``None``.diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex ffa0de5f3b..5ed402f2a9 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -392,13 +392,13 @@ _READBACK_KINDS: frozenset[str] = frozenset(#: Readback sources that never speak outside a call (see ``_is_agent_reply``).#: A mission the user just asked for is not here: its answer may still punch-#: through the hangup gate (AD-OE5/OE6).+#: through the hangup gate (AD-OE5/OE6). Explicit delegations wait for a call+#: and a conversational pause; their results never open a call themselves._HELD_FOR_CALL_SOURCES: frozenset[str] = frozenset({"society.lead",- # A pane finishing a job Jarvis handed it (jarvis/agentic_ide/- # voice_readback.py): spoken inside the call, else at the next one."agentic_ide.readback",+ "delegation.batch","tasks.runner","workflows.runner","workflows.scheduler",@@ -3828,11 +3828,14 @@ class SpeechPipeline:):self._last_answer_floor_monotonic = time.monotonic()self._turn_state = new_state+ if new_state is TurnTakingState.LISTENING:+ self._schedule_delegation_results()if new_state is TurnTakingState.IDLE:- retry = getattr(self, "_agent_reply_retry_task", None)- if retry is not None and retry is not asyncio.current_task():- retry.cancel()- await asyncio.gather(retry, return_exceptions=True)+ for task_name in ("_agent_reply_retry_task", "_delegation_result_task"):+ retry = getattr(self, task_name, None)+ if retry is not None and retry is not asyncio.current_task():+ retry.cancel()+ await asyncio.gather(retry, return_exceptions=True)await self._transition(self._supervisor_state_for_turn(new_state))# Turn-boundary: the floor has cleared → flush any announcements that# were deferred while the user was speaking (AD-OE6 zero-silent-drop).@@ -4975,9 +4978,24 @@ class SpeechPipeline:"Realtime announcement context mirror failed",exc_info=True,)+ from jarvis.core.delegation import RESULT_SOURCES, ResultInbox++ if event.source_layer in RESULT_SOURCES:+ inbox = getattr(self, "_delegation_inbox", None)+ if inbox is None:+ inbox = self._delegation_inbox = ResultInbox()+ inbox.add(event)+ self._schedule_delegation_results()+ returnif is_agent_reply:if event == getattr(self, "_agent_reply_inflight", None):return+ if (+ event.source_layer == "delegation.batch"+ and self._turn_state is not TurnTakingState.LISTENING+ ):+ self._defer_agent_reply(event)+ returnif self._agent_reply_needs_session():self._defer_agent_reply(event)log.info("Agent reply retained until an unmuted voice session is available")@@ -5389,6 +5407,8 @@ class SpeechPipeline:chunks,should_play=lambda: (not self._agent_reply_needs_session()+ and (event.source_layer != "delegation.batch"+ or self._turn_state is TurnTakingState.LISTENING)if is_agent_replyelse getattr(self, "_turn_state", TurnTakingState.IDLE)is not TurnTakingState.JARVIS_SPEAKING@@ -5431,6 +5451,49 @@ class SpeechPipeline:session = getattr(self, "_active_realtime_handle", None)return session is not None+ def _schedule_delegation_results(self) -> None:+ """One coalescing task; a user's conversation always keeps the floor."""+ inbox = getattr(self, "_delegation_inbox", None)+ task = getattr(self, "_delegation_result_task", None)+ if (+ inbox is None or not inbox.pending+ or (task is not None and not task.done())+ or self._agent_reply_needs_session()+ or self._turn_state is not TurnTakingState.LISTENING+ or getattr(self, "_agent_reply_inflight", None) is not None+ ):+ return+ self._delegation_result_task = asyncio.create_task(+ self._flush_delegation_results(), name="delegation-results"+ )++ async def _flush_delegation_results(self) -> None:+ from jarvis.core.delegation import BATCH_WINDOW_S++ event = None+ try:+ await asyncio.sleep(BATCH_WINDOW_S)+ if (+ self._agent_reply_needs_session()+ or self._turn_state is not TurnTakingState.LISTENING+ or getattr(self, "_agent_reply_inflight", None) is not None+ ):+ return+ event = self._delegation_inbox.take()+ if event is not None:+ await self._on_announcement(event)+ except asyncio.CancelledError:+ if event is not None:+ self._defer_agent_reply(event)+ raise+ except Exception:+ if event is not None:+ self._defer_agent_reply(event)+ log.warning("Delegation result delivery deferred", exc_info=True)+ finally:+ self._delegation_result_task = None+ self._schedule_delegation_results()+async def _deliver_announcement_via_realtime(self,event: AnnouncementRequested,diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 83575f49c8..ab81db3d3c 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -4277,8 +4277,6 @@ async def terminal_prompt(workspace_id=found[0].id,typed=req.prompt,attachments=attachments,- # Asked of Jarvis, so Jarvis reports how it ended.- readback=True,)except SessionError as exc:raise HTTPException(status_code=409, detail=str(exc)) from excdiff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex b032d8adc9..6b5ccff97b 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -196,6 +196,20 @@ class WebServer:self.app: FastAPI = self._build_app()self.app.state.refresh_scheduler = None+ async def _forward_delegation_to_chat(self, event: Any) -> None:+ """Persist a result in its originating chat without starting another model turn."""+ service = getattr(self.app.state, "agent_chat", None)+ if service is None:+ return+ session = service.store.get_session(event.session_id)+ if session is None or session.surface != "jarvis":+ return+ await service.post_notice(event.session_id, {+ "kind": "coding_result", "agent_name": event.agent_name,+ "assignment_id": event.request_id, "status": event.status,+ "text": event.text, "report": event.report,+ })+async def _forward_preamble_to_chat(self, event: AnnouncementRequested) -> None:"""Bridge AnnouncementRequested(kind="preamble") → MessageSent.@@ -336,6 +350,8 @@ class WebServer:from .agentic_ide_git_routes import router as agentic_ide_git_routerfrom .agentic_ide_routes import router as agentic_ide_routerfrom .antigravity_routes import router as antigravity_router+ from .app_actions_routes import router as app_actions_router+ from .appshot_routes import router as appshot_routerfrom .board_routes import (board_router as board_meta_router,)@@ -391,8 +407,6 @@ class WebServer:from .provider_routes import router as provider_routerfrom .review_routes import router as review_routerfrom .routine_hooks_routes import router as routine_hooks_router- from .app_actions_routes import router as app_actions_router- from .appshot_routes import router as appshot_routerfrom .screen_context_routes import router as screen_context_routerfrom .self_mod_routes import router as self_mod_routerfrom .sessions_routes import router as sessions_router@@ -401,9 +415,9 @@ class WebServer:from .setup_routes import router as setup_routerfrom .skills_routes import router as skills_routerfrom .socials_routes import router as socials_router- from .society_routes import router as society_routerfrom .society_browser_routes import router as society_browser_routerfrom .society_figure_routes import router as society_figure_router+ from .society_routes import router as society_routerfrom .starter_plan_routes import router as starter_plan_routerfrom .sub_agents_routes import router as sub_agents_routerfrom .tasks_routes import router as tasks_router@@ -3453,7 +3467,10 @@ class WebServer:from jarvis.harness.manager import HarnessManagerdef workflow_services():- return (getattr(self.app.state, "workflow_store", None), getattr(self.app.state, "workflow_runner", None))+ return (+ getattr(self.app.state, "workflow_store", None),+ getattr(self.app.state, "workflow_runner", None),+ )runner = TaskRunner(store=store,@@ -3466,7 +3483,9 @@ class WebServer:owned_action_guard=self._guard_society_routine_action,workflow_services=workflow_services,)- scheduler = TaskScheduler(store=store, bus=self.bus, runner=runner, workflow_services=workflow_services)+ scheduler = TaskScheduler(+ store=store, bus=self.bus, runner=runner, workflow_services=workflow_services,+ )scheduler.bind_bus()await scheduler.hydrate()@@ -3824,6 +3843,11 @@ class WebServer:except Exception: # noqa: BLE001 — the name is cosmeticreturn "Jarvis"+ from jarvis.core.events import DelegationResultReady++ # Install on first chat use, keeping result tracking off the boot path.+ self.bus.unsubscribe(DelegationResultReady, self._forward_delegation_to_chat)+ self.bus.subscribe(DelegationResultReady, self._forward_delegation_to_chat)return AgentChatService(store, assistant_name=_name, bus=lambda: self.bus)async def stop(self) -> None:diff --git a/jarvis/voice/report_readback.py b/jarvis/voice/report_readback.pydeleted file mode 100644index cd1da2c0f4..0000000000--- a/jarvis/voice/report_readback.py+++ /dev/null@@ -1,146 +0,0 @@-"""Turn another agent's report into a short spoken sentence for the user.--Two things report back to the user through Jarvis: a coding agent in an-Agentic-IDE pane that finished the job Jarvis handed it, and a Jarvis agent-answering the lead. Both used to be read out raw — a markdown report clipped-at a character count, often mid-word, in whatever language the agent wrote.-What the user wants to hear is what Jarvis would say about it: one short,-natural sentence, in the conversation's language.--So the report goes through the same bounded flash composer every other-readback uses (:mod:`jarvis.voice.contextual_readback`), with the report as-the only facts it may use. When that composer is unavailable or its answer is-rejected, the canned line is spoken instead — built from the report's leading-sentences, cut at a sentence or word boundary and never inside a word.-"""--from __future__ import annotations--import asyncio-import re-from collections.abc import Callable-from typing import Any--from loguru import logger--__all__ = ["compose_report", "plain_excerpt", "set_composer"]--#: Off the turn-critical path: a background result may take a little longer to-#: phrase than an acknowledgement, but it must not hang on a dead provider.-LATENCY_BUDGET_MS = 4000--#: How much of a report the composer is shown. The end of a long report is-#: where an agent states its result, so a longer one keeps both ends.-MAX_REPORT_CHARS = 1800--_CODE_FENCE_RE = re.compile(r"```.*?```", re.DOTALL)-_INLINE_CODE_RE = re.compile(r"`([^`\n]*)`")-_LINK_RE = re.compile(r"\[([^\]]+)\]\([^)]*\)")-_MARKUP_RE = re.compile(r"(^|\s)(?:#{1,6}|[-*+>]|\d+[.)])\s+", re.MULTILINE)-_EMPHASIS_RE = re.compile(r"[*_~]{1,3}")-_SENTENCE_SPLIT_RE = re.compile(r"(?<=[.!?])\s+")--_composer: Any = None-_composer_lock = asyncio.Lock()---def _plain(text: str) -> str:- """``text`` without markdown, code blocks and line structure."""- value = _CODE_FENCE_RE.sub(" ", str(text or ""))- value = _LINK_RE.sub(r"\1", value)- value = _INLINE_CODE_RE.sub(r"\1", value)- value = _MARKUP_RE.sub(r"\1", value)- value = _EMPHASIS_RE.sub("", value)- return " ".join(value.split())---def plain_excerpt(text: str, *, max_words: int = 40) -> str:- """The leading sentences of ``text`` as plain speech, within ``max_words``.-- Cut at a sentence boundary when one fits, else at a word boundary — never- inside a word, which is how the old 400-character cut ended readbacks.- """- plain = _plain(text)- if not plain:- return ""- kept: list[str] = []- total = 0- for sentence in _SENTENCE_SPLIT_RE.split(plain):- words = sentence.split()- if not words:- continue- if total + len(words) > max_words:- if not kept:- kept.append(" ".join(words[:max_words]).rstrip(",;:") + " …")- break- kept.append(sentence.strip())- total += len(words)- return " ".join(kept)---def _report_facts(report: str) -> str:- plain = _plain(report)- if len(plain) <= MAX_REPORT_CHARS:- return plain- half = MAX_REPORT_CHARS // 2- return f"{plain[:half]} … {plain[-half:]}"---async def _get_composer() -> Any:- """The readback composer, built once and off the event loop.-- Building it reads ``jarvis.toml`` and constructs a provider client, so it- runs in a thread; it never raises and falls back to canned-only mode.- """- global _composer- if _composer is not None:- return _composer- async with _composer_lock:- if _composer is None:- from jarvis.brain.factory import build_readback_composer-- _composer = await asyncio.to_thread(build_readback_composer)- return _composer---async def compose_report(- *,- instruction: str,- language: str,- canned: Callable[[], str],- report: str,- facts: dict[str, object] | None = None,-) -> str:- """One short spoken sentence about ``report``, or the canned line.-- ``instruction`` describes the situation in English; ``report`` is the- agent's own words, the only content the sentence may draw on. Never raises.- """- from jarvis.voice.contextual_readback import render_readback-- all_facts: dict[str, object] = dict(facts or {})- if report.strip():- all_facts["report"] = _report_facts(report)- try:- composer = await _get_composer()- except Exception: # noqa: BLE001 - a missing composer only costs the phrasing- logger.opt(exception=True).warning("Report readback: composer unavailable")- composer = None- return await render_readback(- composer,- instruction=instruction,- language=language,- canned=canned,- facts=all_facts,- # The report is usually in another language than the speech (briefs are- # English), so the content-overlap guard would reject every good- # rephrasing; the digit and vocabulary guards still apply.- honesty_bound=False,- latency_budget_ms=LATENCY_BUDGET_MS,- )---def set_composer(composer: Any) -> None:- """Use ``composer`` from now on; ``None`` builds it again on next use."""- global _composer- _composer = composerdiff --git a/tests/conftest.py b/tests/conftest.pyindex 75eef9d023..d030b87040 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -242,23 +242,6 @@ def _app_action_state_in_tmp(tmp_path_factory, monkeypatch): # noqa: ANN001history.reset_for_tests()[email protected](autouse=True)-def _report_readback_canned_only():- """Keep spoken report readbacks off the real flash provider.-- ``jarvis.voice.report_readback`` builds its composer from the host's own- ``jarvis.toml`` on first use, which in a test would be a real model call.- A bare composer speaks the deterministic canned line; suites that test the- phrasing hand in their own composer on top of this.- """- from jarvis.voice import report_readback- from jarvis.voice.contextual_readback import ReadbackComposer-- report_readback.set_composer(ReadbackComposer())- yield- report_readback.set_composer(None)--@pytest.fixture(autouse=True)def _reset_bus():"""Reset the global default bus before and after each test."""diff --git a/tests/contract/test_society_communication.py b/tests/contract/test_society_communication.pyindex 4db94dd743..1bc1b89ef7 100644--- a/tests/contract/test_society_communication.py+++ b/tests/contract/test_society_communication.py@@ -149,7 +149,8 @@ async def test_question_returns_once_and_answer_ends_exchange(world):assert answers[0].text == "Navigation and reading succeeded."assert reply_policy(answers[0]) == "none"assert "No reply is requested" in frame_incoming(answers[0], "Scout")- assert len(chat.notices) == len(published) == 1+ assert len(chat.notices) == 1+ assert len(published) == 1refused = await MessageAgentTool(rt, "jarvis").execute({"target": "scout",@@ -209,7 +210,8 @@ async def test_message_reporting_matrix(world, policy, status, expected):rt, chat, published = worldrequest = await send(rt, reply_policy=policy)await finish_message(rt, chat, request, status=status)- assert len(chat.notices) == len(published) == expected+ assert len(chat.notices) == expected+ assert len(published) == expectedif expected and status == "error":replies = await rt.store.events_for_trace(request.trace_id)assert replies[-1].payload["reply_status"] == "blocked"@@ -275,7 +277,7 @@ async def test_assignment_reporting_preserves_result_and_releases_slot(ctx(),)assert reported.success- assert not published # The watcher owns the single completion announcement.+ assert not published # Nothing to the lead is spoken.assert not any(chat.store.incoming_message(session.session_id, reported.output["message_id"])for session in chat.store.list_sessions(surface="jarvis")@@ -290,7 +292,8 @@ async def test_assignment_reporting_preserves_result_and_releases_slot(]assert len(results) == 1 and results[0].payload["status"] == statusassert rt.scheduler.active_runs("scout") == 0- assert len(chat.notices) == len(published) == expected+ assert len(chat.notices) == expected+ assert len(published) == expected@pytest.mark.parametrize(diff --git a/tests/integration/test_delegation_followthrough.py b/tests/integration/test_delegation_followthrough.pynew file mode 100644index 0000000000..be615f88cf--- /dev/null+++ b/tests/integration/test_delegation_followthrough.py@@ -0,0 +1,135 @@+"""Real delegation lifecycle through the speech inbox, with fake providers only."""++import asyncio+from types import SimpleNamespace++import pytest++from jarvis.agent_chat.runner_api import messages_from_events+from jarvis.core.bus import EventBus+from jarvis.core.events import AnnouncementRequested, DelegationResultReady+from jarvis.plugins.tool.delegate_to_agent import DelegateToAgentTool+from jarvis.society.events import MsgType+from jarvis.speech.pipeline import TurnTakingState+from jarvis.ui.web.server import WebServer+from tests.contract import test_society_communication as communication+from tests.unit.speech.test_realtime_announcement_bridge import _pipeline++world = communication.world+++async def test_two_delegations_return_after_completion_without_blocking_conversation(+ world, monkeypatch,+):+ runtime, chat, _ = world+ pipeline, tts, _, live = _pipeline(accepted=True)+ bus = EventBus()+ bus.subscribe(AnnouncementRequested, pipeline._on_announcement)+ runtime._publish_event = bus.publish+ monkeypatch.setattr("jarvis.core.delegation.BATCH_WINDOW_S", 0.005)+ tool = DelegateToAgentTool(runtime_resolver=lambda: runtime)+ receipts = []+ for agent in ("Scout", "Archivist"):+ receipt = await asyncio.wait_for(tool.execute(+ {"agent": agent, "task": f"Research {agent}", "reply_policy": "always"},+ communication.ctx(),+ ), timeout=1)+ assert receipt.success and receipt.output["state"] == "running"+ receipts.append(receipt)+ assert not live.calls # Dispatch is acknowledged before either agent has finished.+ pipeline._turn_state = TurnTakingState.USER_SPEAKING+ for name in ("scout", "archivist"):+ await chat.queues[f"society:{name}"].put({+ "kind": "assistant_text", "payload": {"text": f"Recorded {name} findings."},+ })+ await chat.queues[f"society:{name}"].put({+ "kind": "turn_finished", "payload": {"status": "completed"},+ })+ await asyncio.wait_for(asyncio.gather(*list(runtime._watchers)), timeout=3)+ assert not live.calls+ assert len(chat.notices) == 2+ await pipeline._set_turn_state(TurnTakingState.LISTENING)+ await asyncio.sleep(0.04)+ assert len(live.calls) == 1 and not tts.calls+ for receipt in receipts:+ assert receipt.output["assignment_id"] in live.calls[0]["report"]+ assert "scout findings" in live.calls[0]["report"]+ assert "archivist findings" in live.calls[0]["report"]+++async def test_agent_question_is_returned_and_turn_end_does_not_claim_success(world):+ runtime, chat, published = world+ receipt = await DelegateToAgentTool(runtime_resolver=lambda: runtime).execute(+ {"agent": "Scout", "task": "Research it", "reply_policy": "on_error"},+ communication.ctx(),+ )+ request = await runtime.store.get_event(receipt.output["assignment_id"])+ await runtime.say(+ from_agent="scout", to_agent="jarvis", msg_type=MsgType.QUERY,+ text="Which repository do you mean?", trace_id=request.trace_id,+ parent_event_id=request.event_id,+ )+ await chat.queues["society:scout"].put({+ "kind": "turn_finished", "payload": {"status": "completed"},+ })+ await asyncio.wait_for(asyncio.gather(*list(runtime._watchers)), timeout=3)+ assert len(published) == 1+ assert "needs_input" in published[0].report+ assert len(chat.notices) == 1+ results = [e for e in await runtime.store.events_for_trace(request.trace_id)+ if e.msg_type is MsgType.RESULT]+ assert results[0].payload["status"] == "blocked"+++async def test_coding_result_survives_chat_event_storage_and_enters_followup_context(world):+ _, chat, _ = world+ original = chat.store.list_sessions(surface="jarvis")[0]+ notices = []++ async def post(session_id, payload):+ notices.append((session_id, payload))+ await chat._emit(session_id, {"kind": "notice", "payload": payload})++ chat.post_notice = post+ server = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(agent_chat=chat)))+ event = DelegationResultReady(+ session_id=original.session_id, request_id="task-1", agent_name="T1",+ status="completed", text="T1 reports: Fixed login.",+ report='{"request":"Fix login", "report":"Tests passed; deployment pending"}',+ )+ await WebServer._forward_delegation_to_chat(server, event)+ assert notices[0][0] == original.session_id+ messages = messages_from_events([{"kind": "notice", "payload": notices[0][1]}])+ assert "deployment pending" in messages[0].content+ assert "Fix login" in messages[0].content+++async def test_chat_factory_installs_one_lazy_result_bridge(tmp_path):+ server = WebServer.__new__(WebServer)+ server.cfg = SimpleNamespace(memory=SimpleNamespace(data_dir=str(tmp_path)))+ server.bus = EventBus()+ server.app = SimpleNamespace(state=SimpleNamespace(agent_chat=None))+ first = server._build_agent_chat_service()+ first.store.close()+ service = server._build_agent_chat_service()+ server.app.state.agent_chat = service+ session = service.store.create_session(+ provider="openai", model="", effort="", cwd=str(tmp_path), surface="jarvis",+ )+ queue = service.subscribe(session.session_id)+ try:+ await server.bus.publish(DelegationResultReady(+ session_id=session.session_id, request_id="job", agent_name="T1",+ status="completed", text="Reported outcome", report="Task and evidence",+ ))+ assert queue.qsize() == 1+ notice = queue.get_nowait()+ assert notice["kind"] == "notice"+ assert notice["payload"]["report"] == "Task and evidence"+ finally:+ service.unsubscribe(session.session_id, queue)+ service.store.close()diff --git a/tests/unit/agentic_ide/test_followthrough.py b/tests/unit/agentic_ide/test_followthrough.pynew file mode 100644index 0000000000..01989b7569--- /dev/null+++ b/tests/unit/agentic_ide/test_followthrough.py@@ -0,0 +1,115 @@+"""Only a fresh answer to the tracked prompt can be read back as its report."""++from types import SimpleNamespace++import pytest++from jarvis.agentic_ide import followthrough as ft+from jarvis.agentic_ide.agent_transcript import Turn+from jarvis.core.events import AnnouncementRequested, DelegationResultReady+++def pane(monkeypatch):+ turns = [Turn("user", "Old task"), Turn("assistant", "Old answer")]+ term = SimpleNamespace(+ name="T2", process_generation=1, last_submit_at=100.0, last_prompt="Fix the bug",+ submitted=True, delegation_result=None, exit_code=None,+ last_output_at=100.0, reading=lambda: SimpleNamespace(activity="waiting"),+ transcript=SimpleNamespace(tail=lambda n: ["Which repository should I change?"]),+ )+ monkeypatch.setattr(ft, "_turns", lambda t: list(turns))+ return term, turns+++async def arm(pane, **origin):+ term, _ = pane+ pending = await ft.prepare(term, "Fix the bug", "Fix the bug", {"lang": "en", **origin})+ ft.submitted(term, pending)+ return term.delegation_result+++async def test_fresh_correlated_answer_reaches_voice_once(pane):+ pending = await arm(pane)+ term, turns = pane+ turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Fixed login; tests passed.")])+ events = []+ assert await ft.publish_result("completed", term, pending, events.append)+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert len(events) == 1 and isinstance(events[0], AnnouncementRequested)+ assert "Fixed login" in events[0].report+ assert "Fix the bug" in events[0].report++[email protected]("stale", ["old", "same_prompt", "unrelated"])+async def test_stale_transcript_never_becomes_the_current_answer(pane, stale):+ term, turns = pane+ if stale == "same_prompt":+ turns[:] = [Turn("user", "Fix the bug"), Turn("assistant", "Old answer")]+ pending = await arm(pane)+ if stale == "unrelated":+ turns.extend([Turn("user", "Other task"), Turn("assistant", "Unrelated answer")])+ events = []+ await ft.publish_result("completed", term, pending, events.append)+ assert "Old answer" not in events[0].report and "Unrelated answer" not in events[0].report+ assert "unverified" in events[0].report++[email protected]("change", ["manual_prompt", "restarted", "replaced"])+async def test_later_prompt_or_process_cannot_claim_previous_result(pane, change):+ pending = await arm(pane)+ term, _ = pane+ if change == "manual_prompt":+ term.last_submit_at += 1+ elif change == "restarted":+ term.process_generation += 1+ else:+ term.delegation_result = None+ events = []+ assert not await ft.publish_result("completed", term, pending, events.append)+ assert not events+++async def test_question_does_not_consume_later_completion(pane):+ pending = await arm(pane)+ term, turns = pane+ events = []+ await ft.publish_result("needs_input", term, pending, events.append)+ assert "Which repository" in events[0].report+ assert term.delegation_result is pending+ turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Resolved.")])+ await ft.publish_result("completed", term, pending, events.append)+ assert len(events) == 2 and "Resolved" in events[1].report+++async def test_text_origin_is_returned_only_to_its_original_chat(pane):+ pending = await arm(pane, reply_session_id="original-chat")+ events = []+ await ft.publish_result("exited", pane[0], pending, events.append)+ assert isinstance(events[0], DelegationResultReady)+ assert events[0].session_id == "original-chat"+ assert events[0].status == "exited"+++async def test_refused_submission_has_no_pending_job(pane):+ pane[0].submitted = False+ assert await arm(pane) is None+++async def test_fast_job_finishing_between_sweeps_still_returns_its_fresh_answer(pane):+ await arm(pane)+ term, turns = pane+ registry = SimpleNamespace(sessions=[SimpleNamespace(terminals=[term])])+ events = []+ await ft.poll_ready(registry, events.append, now=130.0)+ assert not events # An idle terminal and an old answer are not completion evidence.+ turns.extend([Turn("user", "Fix the bug"), Turn("assistant", "Fixed immediately.")])+ await ft.poll_ready(registry, events.append, now=141.0)+ assert len(events) == 1 and "Fixed immediately" in events[0].reportdiff --git a/tests/unit/agentic_ide/test_pane_notifications.py b/tests/unit/agentic_ide/test_pane_notifications.pyindex de60a4aad0..d3398ca1b3 100644--- a/tests/unit/agentic_ide/test_pane_notifications.py+++ b/tests/unit/agentic_ide/test_pane_notifications.py@@ -1087,3 +1087,38 @@ def _entry(entry_id: str) -> notifications.Notification:detail="",created_at=1.0,)+++def test_manual_pane_jobs_remain_silent_and_no_paid_composer_returns() -> None:+ """Only explicit Jarvis requests opt into floor-aware result delivery."""+ import importlib.util+ import inspect++ from jarvis.speech.pipeline import _HELD_FOR_CALL_SOURCES++ assert importlib.util.find_spec("jarvis.agentic_ide.voice_readback") is None+ assert inspect.signature(Registry.send_prompt).parameters["followup"].default is None+ assert importlib.util.find_spec("jarvis.voice.report_readback") is None+ assert "agentic_ide.readback" in _HELD_FOR_CALL_SOURCES++[email protected]("tracked", [False, True])+async def test_result_tracking_is_independent_of_the_optional_bell(registry, tmp_path, tracked):+ watcher = notifications.watcher()+ _session, term = await _pane(registry, tmp_path)+ pending = object() if tracked else None+ term.delegation_result = pending+ _draw(term, REAL_WORKING)+ term.last_submit_at = 999.0+ term.submit_generation = term.process_generation+ term.last_output_at = 1000.0+ watcher.poll(registry, now=1000.5, emit=False)+ term.transcript.clear()+ _draw(term, REAL_FINISHED)+ _quiet_since(term, 1002.0)+ watcher.poll(registry, now=1002.5, emit=False)+ watcher.poll(registry, now=1010.0, emit=False)+ watcher.poll(registry, now=1010.0 + notifications.SETTLE_S + 1, emit=False)+ assert notifications.center().list() == []+ assert watcher.take_results() == ([("completed", term, pending)] if tracked else [])+ assert watcher.take_results() == []diff --git a/tests/unit/agentic_ide/test_voice_readback.py b/tests/unit/agentic_ide/test_voice_readback.pydeleted file mode 100644index ee4ad99452..0000000000--- a/tests/unit/agentic_ide/test_voice_readback.py+++ /dev/null@@ -1,230 +0,0 @@-"""A job the user gave a pane through Jarvis ends with Jarvis saying how it went.--The bell (``test_pane_notifications``) says THAT a pane stopped. This is the-spoken half: only for jobs handed over through Jarvis, once per job, phrased-from the pane's own report, and routed through the speech pipeline's-held-for-call gate so it never speaks into an idle room.-"""--from __future__ import annotations--from pathlib import Path-from typing import Any--import pytest--from jarvis.agentic_ide import notifications, voice_readback-from jarvis.agentic_ide import session as session_mod-from jarvis.agentic_ide.activity import STILL_S-from jarvis.agentic_ide.session import Registry-from jarvis.core.events import AnnouncementRequested-from jarvis.speech.pipeline import SpeechPipeline-from jarvis.voice.report_readback import plain_excerpt-from tests.fakes.fake_pty_manager import FakePtyManager--QUESTION_SCREEN = "\r\nDo you want to make this edit to config.py?\r\n❯ 1. Yes\r\n"--[email protected](autouse=True)-def _clean_store() -> Any:- notifications.reset()- yield- notifications.reset()---def registry(monkeypatch: pytest.MonkeyPatch) -> Registry:- monkeypatch.setattr(session_mod, "agent_argv", lambda name: (f"/usr/bin/{name}",))- return Registry(pty_manager=FakePtyManager())---def no_pin(monkeypatch: pytest.MonkeyPatch) -> None:- """Keep the host's real reply-language pin out of the language decision."""- from jarvis.core import config-- def _unreadable() -> Any:- raise OSError("no config in this test")-- monkeypatch.setattr(config, "load_config", _unreadable)---async def _noop(_data: Any) -> None:- return None---async def _pane(registry: Registry, folder: Path) -> tuple[Any, Any]:- session = await registry.start(str(folder), [{"agent": "claude", "name": "Alex"}])- term = await registry.attach("Alex", 100, 30, _noop, _noop)- return session, term---def _work_then_rest(- watcher: Any, registry: Registry, term: Any, screen: str, *, emit: bool-) -> None:- """Busy for three sweeps, then still until the stop is reported."""- term.last_submit_at = 99.9- term.submit_generation = term.process_generation- at = 100.0- for step in range(3):- at = 100.0 + step * notifications.SWEEP_INTERVAL_S- term.transcript.clear()- term.transcript.feed(f"\r\n· working, frame {step}\r\n")- watcher.poll(registry, now=at, emit=emit)- rest = at + 1- term.transcript.clear()- term.transcript.feed(screen)- term.last_output_at = rest- term.last_input_at = None- watcher.poll(registry, now=rest, emit=emit)- watcher.poll(registry, now=rest + STILL_S + 2, emit=emit)- watcher.poll(registry, now=rest + STILL_S + notifications.SETTLE_S + 4, emit=emit)---async def test_a_jarvis_job_that_finishes_owes_one_readback(- registry: Registry, tmp_path: Path-) -> None:- watcher = notifications.watcher()- _session, term = await _pane(registry, tmp_path)- term.voice_readback = True-- # The bell switch is off: the spoken readback does not depend on it.- _work_then_rest(watcher, registry, term, "\r\n❯ \r\n", emit=False)-- assert watcher.take_readbacks() == [("completed", term)]- assert term.voice_readback is False, "one readback per job"- assert watcher.take_readbacks() == []---async def test_a_job_nobody_gave_through_jarvis_is_not_announced(- registry: Registry, tmp_path: Path-) -> None:- watcher = notifications.watcher()- _session, term = await _pane(registry, tmp_path)-- _work_then_rest(watcher, registry, term, "\r\n❯ \r\n", emit=True)-- assert watcher.take_readbacks() == []---async def test_a_question_is_announced_and_keeps_the_job_open(- registry: Registry, tmp_path: Path-) -> None:- watcher = notifications.watcher()- _session, term = await _pane(registry, tmp_path)- term.voice_readback = True-- _work_then_rest(watcher, registry, term, QUESTION_SCREEN, emit=True)-- assert watcher.take_readbacks() == [("needs_input", term)]- assert term.voice_readback is True, "its end is still owed"---async def test_a_job_typed_by_hand_cancels_the_readback(- registry: Registry, tmp_path: Path-) -> None:- session, term = await _pane(registry, tmp_path)- term.voice_readback = True-- registry.write(term.key, "do something else\r", workspace_id=session.id)-- assert term.voice_readback is False---async def test_the_readback_is_phrased_from_the_agents_report(- monkeypatch: pytest.MonkeyPatch, no_pin: None-) -> None:- published: list[Any] = []-- async def publish(event: Any) -> None:- published.append(event)-- term = _FakeTerm(request="Behebe bitte den Login-Fehler") # i18n-allow: user's words- monkeypatch.setattr(- voice_readback,- "final_report",- lambda _term: "## Summary\n\nFixed the **login** bug in `auth.py`. All 12 tests pass.",- )-- await voice_readback.readback("completed", term, publish)-- assert len(published) == 1- event = published[0]- assert isinstance(event, AnnouncementRequested)- assert event.source_layer == voice_readback.SOURCE_LAYER- assert event.kind == "completion"- assert event.language == "de"- # The live model gets the whole report and the user's own words to think about.- assert "Fixed the **login** bug in `auth.py`." in (event.report or "")- assert "Behebe bitte den Login-Fehler" in (event.report or "") # i18n-allow: user's words- # The test composer is canned-only (root conftest): pane name + the- # report's first sentences, markdown gone.- spoken = (- "Alex ist fertig: " # i18n-allow: spoken readback- "Summary Fixed the login bug in auth.py. All 12 tests pass."- )- assert event.text == spoken---async def test_without_a_report_the_readback_still_names_the_pane(- monkeypatch: pytest.MonkeyPatch, no_pin: None-) -> None:- published: list[Any] = []-- async def publish(event: Any) -> None:- published.append(event)-- monkeypatch.setattr(voice_readback, "final_report", lambda _term: "")-- await voice_readback.readback("completed", _FakeTerm(request="Run the tests"), publish)-- assert [e.text for e in published] == ["Alex has finished your task."]---def test_a_remote_pane_never_reads_its_stale_local_transcript(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """#250: the transcript of a pane on a connected computer lives there; the- local copy ends with the previous job's answer."""- from jarvis.agentic_ide import agent_transcript-- def _stale(*_a: Any, **_k: Any) -> Any:- raise AssertionError("a remote pane's local transcript is stale")-- monkeypatch.setattr(agent_transcript, "read", _stale)- monkeypatch.setattr(agent_transcript, "can_read", lambda _agent: True)- term = _FakeTerm(request="Fix the login bug")- term.computer_id = "vps-1"- term.agent = "claude"- term.resume = type("Handle", (), {"id": "abc"})()-- assert voice_readback.final_report(term) == ""---def test_the_pipeline_holds_pane_readbacks_for_an_open_call() -> None:- event = AnnouncementRequested(- source_layer=voice_readback.SOURCE_LAYER, kind="completion", text="Alex is done."- )- assert SpeechPipeline._is_agent_reply(event)---def test_an_excerpt_is_never_cut_inside_a_word() -> None:- long = " ".join(f"word{i}" for i in range(80))- excerpt = plain_excerpt(long, max_words=10)- assert excerpt.split()[:10] == [f"word{i}" for i in range(10)]- assert excerpt.endswith("…")- assert plain_excerpt("First one. Second one. Third.", max_words=4) == "First one. Second one."---class _FakeTerm:- name = "Alex"-- def __init__(self, *, request: str) -> None:- self.voice_readback_request = request- self.transcript = _Screen()---class _Screen:- @staticmethod- def tail(_n: int) -> list[str]:- return []diff --git a/tests/unit/society/test_delegation_followthrough.py b/tests/unit/society/test_delegation_followthrough.pynew file mode 100644index 0000000000..173deeb2d3--- /dev/null+++ b/tests/unit/society/test_delegation_followthrough.py@@ -0,0 +1,62 @@+"""Results follow trusted turn provenance, even after another chat opens."""++from jarvis.core.delegation import origin_metadata+from jarvis.core.protocols import ChatTurn, current_chat_turn+from jarvis.society.events import MsgType, SocietyEnvelope+from tests.unit.society import test_lead_card++rt = test_lead_card.rt+++def session(runtime):+ return runtime.chat.store.create_session(+ provider="openai", model="test", effort="", cwd=str(runtime.data_dir), surface="jarvis",+ )+++async def test_result_returns_to_origin_after_user_opens_another_chat(rt):+ original = session(rt)+ newer = session(rt)+ target, _ = await rt.roster.create(name="Scout")+ request = SocietyEnvelope(+ msg_type=MsgType.ASSIGN, from_agent="jarvis", to_agent=target.agent_id,+ trace_id="voice:legacy-prefix",+ payload={"text": "Find the release", "reply_surface": "chat",+ "reply_session_id": original.session_id, "reply_policy": "always"},+ )+ await rt.report_to_lead(target, request, status="done", summary="Release found.")+ assert rt.chat.notices[0][0] == original.session_id != newer.session_id+ assert not [e for e in rt.published if type(e).__name__ == "AnnouncementRequested"]+ assert "Find the release" in rt.chat.notices[0][1]["report"]+++async def test_voice_report_does_not_depend_on_an_open_text_chat(rt):+ target, _ = await rt.roster.create(name="Scout")+ request = SocietyEnvelope(+ msg_type=MsgType.ASSIGN, from_agent="jarvis", to_agent=target.agent_id,+ trace_id="request",+ payload={"text": "Find the release", "reply_surface": "voice", "reply_policy": "always"},+ )+ await rt.report_to_lead(target, request, status="blocked", summary="Access unavailable.")+ reports = [e for e in rt.published if type(e).__name__ == "AnnouncementRequested"]+ assert len(reports) == 1 and "blocked" in reports[0].report+++async def test_deleted_origin_does_not_redirect_to_new_chat(rt):+ session(rt)+ target, _ = await rt.roster.create(name="Scout")+ request = SocietyEnvelope(+ msg_type=MsgType.ASSIGN, from_agent="jarvis", to_agent=target.agent_id,+ trace_id="request",+ payload={"text": "Task", "reply_surface": "chat", "reply_session_id": "deleted-chat"},+ )+ await rt.report_to_lead(target, request, status="done", summary="Finished.")+ assert not rt.chat.notices+++def test_scheduled_turn_cannot_promote_itself_to_voice():+ token = current_chat_turn.set(ChatTurn("society:scout", "turn", "Task", False, "trace"))+ try:+ assert origin_metadata()["reply_surface"] == "none"+ finally:+ current_chat_turn.reset(token)diff --git a/tests/unit/society/test_lead_card.py b/tests/unit/society/test_lead_card.pyindex 38329cc6b3..f17e4046e3 100644--- a/tests/unit/society/test_lead_card.py+++ b/tests/unit/society/test_lead_card.py@@ -12,8 +12,7 @@ society. The card is the fix, and these tests pin its contract:5. the rule block says what "agent" means and where the old system went;6. the realtime helper hands the planner the live names;7. the lead picks the fitting agent for a nameless delegation;-8. a lead-assigned RESULT reaches the person: a chat notice and a spoken- completion.+8. a lead-assigned RESULT reaches its chat and a requested voice conversation."""from __future__ import annotations@@ -227,18 +226,18 @@ async def test_a_lead_assigned_result_reaches_the_person(rt: SocietyRuntime):assert payload["agent_name"] == "Gmail agent"assert payload["status"] == "done"assert payload["text"] == "Invoice answered."+ # The active voice conversation receives evidence, with no extra composer call.published = rt.published # type: ignore[attr-defined]- announcements = [e for e in published if type(e).__name__ == "AnnouncementRequested"]- assert len(announcements) == 1- assert announcements[0].kind == "completion"- assert announcements[0].language == "de"- spoken = "Gmail agent ist fertig: Invoice answered." # i18n-allow: spoken completion- assert announcements[0].text == spoken+ spoken = [e for e in published if type(e).__name__ == "AnnouncementRequested"]+ assert len(spoken) == 1+ assert "Answer the invoice mail" in spoken[0].report+ assert "Invoice answered" in spoken[0].reportasync def test_an_agent_answer_to_the_lead_reaches_the_person(rt: SocietyRuntime):- """Live 2026-09-09: the ack promised a report, the ANSWER arrived, voice- stayed silent. The lead's incoming message is owed an answer too."""+ """Live 2026-09-09: the ack promised a report, the ANSWER arrived, and+ nothing reached the person. The lead's incoming message is owed a notice+ too, with the original task context for the active voice model."""import asynciochat: FakeChat = rt.chat # type: ignore[attr-defined]@@ -275,12 +274,15 @@ async def test_an_agent_answer_to_the_lead_reaches_the_person(rt: SocietyRuntimeassert payload["agent_name"] == "Gmail agent"assert payload["msg_type"] == "answer"assert payload["text"] == "Invoice answered."- announcements = [e for e in published if type(e).__name__ == "AnnouncementRequested"]- assert len(announcements) == 1- assert announcements[0].kind == "completion"- assert announcements[0].language == "de"- spoken = "Gmail agent meldet: Invoice answered." # i18n-allow: spoken completion- assert announcements[0].text == spoken+ assert len([e for e in published if type(e).__name__ == "AnnouncementRequested"]) == 1+++def test_no_model_phrases_a_background_report_anymore() -> None:+ """The flash composer that turned an agent's report into a spoken sentence+ (billed on an API key) is gone with the spoken readback (2026-09-30)."""+ import importlib.util++ assert importlib.util.find_spec("jarvis.voice.report_readback") is Noneasync def test_agent_to_agent_chatter_stays_silent(rt: SocietyRuntime):diff --git a/tests/unit/speech/test_agent_reply_readbacks.py b/tests/unit/speech/test_agent_reply_readbacks.pyindex a9b44ec12a..6d5ce8346a 100644--- a/tests/unit/speech/test_agent_reply_readbacks.py+++ b/tests/unit/speech/test_agent_reply_readbacks.py@@ -12,7 +12,9 @@ from tests.unit.speech.test_realtime_mode import _FakeRealtimeSession, _FakeTTS,def reply(name="Nala"):return AnnouncementRequested(- source_layer="society.lead",+ # A routine an agent ran: the held-for-call path society.lead used to+ # share before agent messages stopped being spoken (2026-09-30).+ source_layer="tasks.runner",kind="completion",language="en",text=f"{name} reports: The draft is ready.",diff --git a/tests/unit/speech/test_delegation_results.py b/tests/unit/speech/test_delegation_results.pynew file mode 100644index 0000000000..ccb07782d4--- /dev/null+++ b/tests/unit/speech/test_delegation_results.py@@ -0,0 +1,120 @@+"""Delegation completion never occupies the user's conversational floor."""++import asyncio+import json+from dataclasses import replace++import pytest++from jarvis.core.delegation import ResultInbox, result_announcement+from jarvis.speech.pipeline import TurnTakingState+from tests.unit.speech.test_realtime_announcement_bridge import _pipeline+++def result(name="Scout", status="done"):+ return result_announcement(+ source="society.lead", request_id=name, name=name,+ request=f"Research {name}", status=status, report=f"Findings from {name}", language="en",+ )++[email protected](autouse=True)+def quick_batch(monkeypatch):+ monkeypatch.setattr("jarvis.core.delegation.BATCH_WINDOW_S", 0.005)+++async def test_simultaneous_results_make_one_natural_live_request_with_both_tasks():+ pipe, tts, _, live = _pipeline(accepted=True)+ first, second = result(), result("Coder", "blocked")+ await asyncio.gather(pipe._on_announcement(first), pipe._on_announcement(second))+ assert not live.calls # Producers return without waiting for speech or a model.+ await asyncio.sleep(0.03)+ assert len(live.calls) == 1+ assert "Research Scout" in live.calls[0]["report"]+ assert "Research Coder" in live.calls[0]["report"]+ assert "blocked" in live.calls[0]["report"]+ assert not tts.calls+ pipe._settle_agent_reply(completed=True)+ # A replayed transport callback must not read the same result twice.+ await pipe._on_announcement(replace(first, timestamp_ns=first.timestamp_ns + 1))+ await asyncio.sleep(0.02)+ assert len(live.calls) == 1++[email protected]("state", [+ TurnTakingState.IDLE, TurnTakingState.USER_SPEAKING,+ TurnTakingState.PROCESSING, TurnTakingState.JARVIS_SPEAKING,+])+async def test_result_waits_while_user_keeps_talking_or_another_answer_is_running(state):+ pipe, tts, player, live = _pipeline(accepted=True)+ pipe._turn_state = state+ await pipe._on_announcement(result())+ await asyncio.sleep(0.02)+ assert not live.calls and not tts.calls and not player.plays+ assert live.remembered # Follow-up context is available even before it is spoken.+ await pipe._set_turn_state(TurnTakingState.LISTENING)+ await asyncio.sleep(0.03)+ assert len(live.calls) == 1+++async def test_user_begins_speaking_during_coalescing_window():+ pipe, _, _, live = _pipeline(accepted=True)+ await pipe._on_announcement(result())+ pipe._turn_state = TurnTakingState.USER_SPEAKING+ await asyncio.sleep(0.03)+ assert not live.calls+ await pipe._set_turn_state(TurnTakingState.LISTENING)+ await asyncio.sleep(0.03)+ assert len(live.calls) == 1+++async def test_muted_or_hung_up_result_waits_for_next_call():+ pipe, tts, _, live = _pipeline(accepted=True)+ pipe._hangup_event.set()+ pipe._muted = True+ await pipe._on_announcement(result())+ await asyncio.sleep(0.03)+ assert not live.calls and not tts.calls+ pipe._hangup_event.clear()+ pipe._muted = False+ await pipe._set_turn_state(TurnTakingState.LISTENING)+ await asyncio.sleep(0.03)+ assert len(live.calls) == 1+++async def test_arrivals_during_readback_wait_until_audio_finishes():+ pipe, _, _, live = _pipeline(accepted=True)+ await pipe._on_announcement(result())+ await asyncio.sleep(0.03)+ await pipe._on_announcement(result("Coder"))+ await asyncio.sleep(0.03)+ assert len(live.calls) == 1+ pipe._settle_agent_reply(completed=True)+ await pipe._set_turn_state(TurnTakingState.LISTENING)+ await asyncio.sleep(0.03)+ assert len(live.calls) == 2+++def test_batch_has_bounded_fair_context_and_preserves_overflow():+ inbox = ResultInbox()+ for i in range(5):+ inbox.add(replace(result(str(i)), report=f"task-{i} " + "x" * 8000 + f" verdict-{i}"))+ batch = inbox.take()+ assert len(batch.report) < 6000+ for i in range(4):+ assert f"task-{i}" in batch.report and f"verdict-{i}" in batch.report+ assert "task-4" in inbox.take().report+ assert inbox.take() is None+++def test_report_is_data_and_stopped_is_not_claimed_success():+ event = result("Coder", "completed")+ assert "is done" not in event.text+ data = json.loads(event.report)+ assert data["request"] == "Research Coder"+ assert data["status"] == "completed"