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(agentic-ide): report a finished agent out loud, one at a time
rubenluetke10-beep5dac2fbe1614
diff --git a/jarvis/agentic_ide/deck_voice.py b/jarvis/agentic_ide/deck_voice.pynew file mode 100644index 0000000000..1ac2ec098a--- /dev/null+++ b/jarvis/agentic_ide/deck_voice.py@@ -0,0 +1,176 @@+"""Give the Command Deck's report queue a voice — EventBus <-> :mod:`.standup`.++:mod:`.standup` decides what should be said and when. It deliberately knows+nothing about how speech works: it runs inside the pane sweep, which has to keep+working in a headless install, in the tests, and on a machine with no audio at+all. This module is the one place the two meet.++Modelled on :class:`jarvis.missions.voice.announcer.MissionAnnouncer`, and for+the same reasons it exists: an ``AnnouncementRequested`` on the speech bus gets+``scrub_for_voice``, the barge-in rules, the transcript's spoken track and the+TTS provider for free, and it is the path every other unprompted line in this+app already takes. A second, private TTS route would be a second set of edge+cases to get wrong.++Three things travel the other way, and all three are READ rather than derived:++* **The language.** One resolver decides a turn's output language for every+ layer (CLAUDE.md §1, ``core/turn_language.py``). This module never calls it —+ it caches what the turn already resolved to, off ``ResponseGenerated`` and+ ``VoiceSessionStarted``. Re-deriving it here is exactly the divergence the+ doctrine exists to stop.+* **Whether a conversation is open.** The deck talks to a person who is+ listening. Outside a session the queue fills and says nothing, and the next+ session opens with one "while you were away" line.+* **Hanging up.** ``VoiceSessionEnded`` ends the conversation here too. Speech+ itself is already dead by then — the killswitch is the pipeline's contract,+ not ours — but the queue must stop offering, or it would greet the next+ session with a report from an hour ago as though it were news.++Everything is best-effort. A bus subscriber that raises would take a voice turn+down with it (AP-18), and none of this is worth that: the worst honest outcome+is a deck whose lane fills up silently, which is exactly what an install with no+speech stack gets anyway (§3).+"""++from __future__ import annotations++import logging+from typing import TYPE_CHECKING, Any++from jarvis.core.events import (+ AnnouncementRequested,+ ResponseGenerated,+ VoiceSessionEnded,+ VoiceSessionStarted,+)++from . import standup++if TYPE_CHECKING: # pragma: no cover - typing only+ from jarvis.core.bus import EventBus++logger = logging.getLogger(__name__)++#: What the pipeline is told this line is. ``info`` rather than ``completion``:+#: a completion is the answer to something the user asked for in this turn, and+#: a deck report is news arriving on its own. The distinction drives the+#: pipeline's own idle-window and barge-in handling.+ANNOUNCEMENT_KIND = "info"++#: Fallback when nothing has been spoken yet in this process. Only reachable+#: for a report that lands before the user's first answer, which is a very+#: short window and not worth guessing about.+DEFAULT_LANGUAGE = "en"+++class DeckVoice:+ """Subscribes on ``start()``, publishes announcements, remembers nothing else."""++ def __init__(self, bus: EventBus, *, composer: Any = None) -> None:+ self._bus = bus+ self._composer = composer+ self._language = DEFAULT_LANGUAGE+ # (event type, handler) pairs rather than unsubscribe callables: this+ # bus's `subscribe` returns None and `unsubscribe` takes both halves+ # back. Kept so `stop()` is a real detach — a bridge that only stopped+ # publishing would still be holding a dead handler on a live bus.+ self._bound: list[tuple[type[Any], Any]] = []+ self._started = False++ # ------------------------------------------------------------- lifecycle++ def start(self) -> None:+ """Wire the queue to this bus. Idempotent."""+ if self._started:+ return+ try:+ for event_type, handler in (+ (VoiceSessionStarted, self._on_started),+ (VoiceSessionEnded, self._on_ended),+ (ResponseGenerated, self._on_response),+ ):+ self._bus.subscribe(event_type, handler)+ self._bound.append((event_type, handler))+ except Exception as exc: # noqa: BLE001 - an optional surface never breaks boot+ logger.warning("Command Deck voice not subscribed: %s", exc)+ self._unsubscribe()+ return+ standup.wire(+ speak=self._speak,+ language=lambda: self._language,+ composer=self._composer,+ )+ self._started = True++ def stop(self) -> None:+ """Unsubscribe and take the queue's voice away. Idempotent."""+ self._unsubscribe()+ standup.unwire()+ self._started = False++ def _unsubscribe(self) -> None:+ for event_type, handler in self._bound:+ try:+ self._bus.unsubscribe(event_type, handler)+ except Exception: # noqa: BLE001 - shutdown must not raise+ logger.debug("Command Deck voice: unsubscribe failed", exc_info=True)+ self._bound.clear()++ # ---------------------------------------------------------------- events++ async def _on_started(self, event: VoiceSessionStarted) -> None:+ self._remember_language(getattr(event, "language", ""))+ standup.queue().conversation_started()++ async def _on_ended(self, event: VoiceSessionEnded) -> None:+ _ = event+ standup.queue().conversation_ended()++ async def _on_response(self, event: ResponseGenerated) -> None:+ """Cache the language the turn resolved to, and wake the queue.++ Both halves matter. The language is read here rather than resolved+ because one resolver owns that decision. And an answer means the user+ is engaged with the deck right now, which is precisely when a queue+ that went quiet after an unanswered line should be allowed to speak+ again (``standup`` rule 8).+ """+ self._remember_language(getattr(event, "language", ""))+ queue = standup.queue()+ if queue.in_conversation():+ queue.wake()++ def _remember_language(self, language: object) -> None:+ text = str(language or "").strip().lower()[:2]+ if text:+ self._language = text++ # ----------------------------------------------------------------- speak++ async def _speak(self, text: str, language: str) -> None:+ """Publish one report. Never ``interrupt`` — see ``standup`` rule 5."""+ line = (text or "").strip()+ if not line:+ return+ try:+ await self._bus.publish(+ AnnouncementRequested(+ text=line,+ priority="normal",+ language=language or self._language,+ kind=ANNOUNCEMENT_KIND,+ )+ )+ except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep+ logger.warning("Command Deck report not announced: %s", exc)+++def attach(bus: EventBus, *, composer: Any = None) -> DeckVoice:+ """Build and start the bridge — the one call a host needs."""+ voice = DeckVoice(bus, composer=composer)+ voice.start()+ return voice+++__all__ = ["ANNOUNCEMENT_KIND", "DEFAULT_LANGUAGE", "DeckVoice", "attach"]diff --git a/jarvis/agentic_ide/notifications.py b/jarvis/agentic_ide/notifications.pyindex 2beb7439ff..2c4cee46ce 100644--- a/jarvis/agentic_ide/notifications.py+++ b/jarvis/agentic_ide/notifications.py@@ -94,6 +94,7 @@ from typing import TYPE_CHECKING, Any, Literal, NamedTuplefrom loguru import logger+from . import standupfrom .activity import (RESIZE_SHADOW_S,STILL_S,@@ -866,9 +867,17 @@ async def _run(registry: Registry) -> None:# Resume evidence is independent of the optional bell. Even# with notifications disabled, restored panes must not be# offered a blind Continue merely because history exists.- _WATCHER.poll(registry, emit=await _enabled_off_loop())+ filed = _WATCHER.poll(registry, emit=await _enabled_off_loop())if _WATCHER.take_resume_dirty():await registry.persist_resume_activity()+ # The Command Deck speaks what the bell only counts. It hangs+ # off this sweep rather than polling for itself: the panes are+ # already being looked at every two seconds, and a second loop+ # asking the same question would be pure cost on the event loop+ # that also carries the wake microphone (AP-9). It is a no-op+ # unless a workspace is actually being read as a deck, and it+ # never raises — see `standup.pump`.+ await standup.pump(registry, filed)except Exception as exc: # noqa: BLE001 - one bad pane must not end the sweeplogger.warning("Agentic IDE: pane notification sweep failed: {}", exc)except asyncio.CancelledError: # pragma: no cover - shutdowndiff --git a/jarvis/agentic_ide/standup.py b/jarvis/agentic_ide/standup.pynew file mode 100644index 0000000000..08543948c5--- /dev/null+++ b/jarvis/agentic_ide/standup.py@@ -0,0 +1,790 @@+"""One agent reports at a time — the Command Deck's way back to the user.++## The gap this closes++:mod:`.notifications` already knows the moment a pane stops working, and the+header bell already carries the count. What nobody ever does is SAY it. In the+grid and in chat that is the right behaviour: the user is looking at the panes,+and a wall of terminals that talks would be unbearable. In the Command Deck it+is the whole point — the user is a team lead who handed out work by voice and+then looked away, and the work coming back is the half that was missing.++## Why a queue rather than "announce each one"++Eight agents can stop inside the same ten seconds. Spoken naively that is eight+announcements stacked on each other, or — with the speech pipeline's own+queueing — one long recital nobody asked for, delivered while the user is+mid-sentence about something else.++So nothing is announced directly. Reports land here, and this module answers+one question per sweep: *is there something to say right now, and what is the+one thing it is?* The rules, in the order they were argued out with the+maintainer:++1. **One speaker.** Exactly one report is on air. Everything else waits.+2. **Headline before detail.** Several landing in the same silence produce ONE+ line — "three are done: Mika, Nova and Kai" — not three reports. That is the+ sentence a team lead would actually get, and it clears the pile-up in one+ breath instead of spending a minute on it.+3. **The user's answer advances the queue.** Asking for one by name puts that+ report on air; "later" puts the queue to sleep.+4. **A blocker cuts the line.** ``needs_input`` outranks ``completed``: a pane+ holding a question has work STOPPED on it, a finished pane has work merely+ waiting to be read.+5. **Never interrupt.** Everything leaves here as ``priority="normal"``, which+ the speech pipeline queues behind whatever is being said. Nothing this+ module produces is ever worth cutting the user off for.+6. **Read means silent.** A pane the user opened and read in the deck drops out+ of the queue without ever being spoken — they already know.+7. **Hanging up is still the killswitch.** Speech stops instantly, because that+ is the pipeline's contract, not ours. The queue SURVIVES and is offered once+ at the start of the next conversation. It is never shouted after the user+ (see ``auflegen`` mandate + the no-nagging one).+8. **Said once.** An unanswered headline is not repeated, and a report that has+ been spoken is not spoken again. After an unanswered line the queue goes+ quiet until the user does something — with one exception, which is rule 4:+ a pane that is BLOCKED wakes it, because there the work has stopped.+9. **Bounded.** :data:`MAX_PENDING` reports; past that the oldest ``completed``+ ones collapse into the count instead of growing a backlog nobody will hear.++## What it will not claim++Nothing here reads the agent's prose to decide whether the work went well. A+"finished" report means the pane went quiet, exactly as the bell's entry does+(:mod:`.notifications`) — the wording says so, and the deck's card says so.+Promising the other thing would be the one lie this whole surface cannot+afford, because the user asked for it precisely so they could stop looking.++## Cost++Zero polling of its own: the sweep in :mod:`.notifications` already looks at+every pane every couple of seconds, and hands its findings here. Announcing is+one bounded flash call through :func:`jarvis.voice.contextual_readback.render_readback`+with a deterministic multilingual fallback, so an install with no provider at+all still gets a spoken line (§3).+"""++from __future__ import annotations++import logging+import time+from dataclasses import dataclass+from itertools import count+from typing import TYPE_CHECKING, Any, Literal++if TYPE_CHECKING: # pragma: no cover - typing only+ from collections.abc import Callable, Iterable, Sequence++ from .notifications import Notification++logger = logging.getLogger(__name__)++#: What one report is about — the same four kinds the bell files.+Kind = Literal["completed", "needs_input", "exited", "failed"]++#: Where a report is in its life.+#:+#: ``pending`` waiting · ``on_air`` the one being reported right now · ``reported``+#: delivered · ``dropped`` taken out without being said (the user read the pane,+#: or asked for it to go away).+#:+#: ``reported`` rather than "answered" on purpose: what the deck knows is that+#: it said the line, never that the user took it in. Naming the state after the+#: stronger claim is how the first version ended up treating an ignored report+#: as a closed one.+ReportState = Literal["pending", "on_air", "reported", "dropped"]++#: What the user can do about a report.+Action = Literal["next", "later", "drop"]++#: How many reports wait at once. A dozen is already more than anyone will sit+#: through; past it the oldest finished ones are folded into the headline count,+#: which is the honest way to lose them — they are still on their cards.+MAX_PENDING = 12++#: Kinds that may wake a settled queue, because work has STOPPED rather than+#: finished. Rule 4 and rule 8's one exception.+BLOCKING_KINDS: frozenset[str] = frozenset({"needs_input"})++#: Reporting order. A blocked pane first, then a crashed one (it is not coming+#: back on its own either), then the ordinary finishes.+_PRIORITY: dict[str, int] = {"needs_input": 0, "failed": 1, "exited": 2, "completed": 3}++_ids = count(1)+++@dataclass(slots=True)+class Report:+ """One pane's news, waiting for its turn to be said."""++ id: str+ workspace_id: str+ pane_key: str+ pane: str+ agent: str+ kind: Kind+ #: One clause: what happened. Taken from the bell's entry so the spoken+ #: line, the deck card and the notification panel cannot disagree.+ headline: str+ #: What the pane was working on, from its own recap. May be empty.+ detail: str+ at: float+ state: ReportState = "pending"+ #: Has this report itself been spoken? Distinct from having been counted in+ #: a headline — "three are done" names the panes without reporting them.+ spoken: bool = False+ #: Was this one of the panes a headline counted? Stops a second headline+ #: from being produced for a set the user has already been told about.+ in_headline: bool = False++ def to_dict(self) -> dict[str, Any]:+ return {+ "id": self.id,+ "workspace_id": self.workspace_id,+ "pane_key": self.pane_key,+ "pane": self.pane,+ "agent": self.agent,+ "kind": self.kind,+ "headline": self.headline,+ "detail": self.detail,+ "at": self.at,+ "state": self.state,+ "spoken": self.spoken,+ }+++@dataclass(frozen=True, slots=True)+class Utterance:+ """What should be said right now, and what saying it covers.++ ``form`` is the shape rather than the wording: ``report`` is one pane's+ news, ``headline`` is the "three are done" line that stands in for several,+ and ``resumed`` is the once-only "while you were away" opening. The words+ themselves are composed later — this is the decision, not the sentence.+ """++ form: Literal["report", "headline", "resumed"]+ reports: tuple[Report, ...]++ @property+ def panes(self) -> tuple[str, ...]:+ return tuple(report.pane for report in self.reports)+++class StandupQueue:+ """The per-process queue, and every rule about when it may speak.++ Deliberately synchronous and loop-free: the whole decision is a function of+ (reports, clock, what the user last did), so it can be tested without a+ PTY, a voice session or a wait — which is what the four failure modes in+ the module docstring all needed and none of them got.++ Not thread-safe, by the same reasoning as :class:`.notifications.NotificationCenter`:+ the sweep that fills it and the routes that read it are all on the event+ loop.+ """++ def __init__(self, limit: int = MAX_PENDING) -> None:+ self._reports: list[Report] = []+ self._limit = limit+ #: True once a line has gone out that nobody answered. Rule 8: the+ #: queue then holds its tongue until the user does something. Blocking+ #: news clears it — see :meth:`offer`.+ self._settled = False+ #: True while the user is away (they hung up) and reports arrived. The+ #: next conversation opens with one "while you were away" line.+ self._missed = False+ #: Is a conversation happening at all? Nothing is spoken outside one:+ #: the deck talks to a person who is listening, not to an empty room.+ self._in_conversation = False++ # ------------------------------------------------------------------ fill++ def offer(self, entries: Iterable[Notification], *, now: float | None = None) -> list[Report]:+ """Take what the sweep just found. Returns the reports actually filed.++ Duplicates are dropped rather than stacked: the same pane finishing the+ same episode twice is one piece of news, and the bell's own+ ``announced`` latch already means a second entry is a new episode — but+ a pane that finishes, is asked something, and finishes again inside one+ silence must not produce three lines about the same work.+ """+ moment = time.time() if now is None else now+ filed: list[Report] = []+ for entry in entries:+ report = self._file(entry, moment)+ if report is None:+ continue+ filed.append(report)+ # Rule 4 / rule 8's exception: a pane waiting on the user is not+ # news that can sit. It wakes a queue that had gone quiet.+ if report.kind in BLOCKING_KINDS:+ self._settled = False+ if filed and not self._in_conversation:+ self._missed = True+ self._trim()+ return filed++ def _file(self, entry: Notification, now: float) -> Report | None:+ ident = (entry.workspace_id, entry.pane_key)+ for existing in self._reports:+ if (existing.workspace_id, existing.pane_key) != ident:+ continue+ if existing.state not in ("pending", "on_air"):+ continue+ if existing.kind == entry.kind:+ # Same news about the same pane, still unsaid. Refresh what it+ # says (a recap can improve between sweeps) and keep its place.+ existing.headline = entry.title+ existing.detail = entry.detail+ return None+ if _PRIORITY.get(entry.kind, 9) < _PRIORITY.get(existing.kind, 9):+ # It finished, and now it is asking. The question is the news;+ # the finish is what led to it.+ existing.kind = entry.kind # type: ignore[assignment]+ existing.headline = entry.title+ existing.detail = entry.detail+ existing.at = now+ existing.in_headline = False+ return None+ return None+ report = Report(+ id=f"sr{next(_ids)}",+ workspace_id=entry.workspace_id,+ pane_key=entry.pane_key,+ pane=entry.pane,+ agent=entry.agent,+ kind=entry.kind,+ headline=entry.title,+ detail=entry.detail,+ at=now,+ )+ self._reports.append(report)+ return report++ def _trim(self) -> None:+ """Rule 9 — keep the waiting list bounded, losing the least useful end.++ Only ``completed`` reports are ever dropped, and only the oldest. A+ blocked or crashed pane is never quietly forgotten: those are the two+ the user most needs to hear about, and a queue that silently loses them+ is worse than one that says nothing at all.+ """+ waiting = [r for r in self._reports if r.state == "pending"]+ excess = len(waiting) - self._limit+ if excess <= 0:+ return+ droppable = [r for r in waiting if r.kind == "completed"]+ for report in droppable[:excess]:+ report.state = "dropped"++ # ------------------------------------------------------------------ read++ def pending(self) -> list[Report]:+ """Everything still waiting, blockers first, then oldest first."""+ return sorted(+ (r for r in self._reports if r.state == "pending"),+ key=lambda r: (_PRIORITY.get(r.kind, 9), r.at),+ )++ def on_air(self) -> Report | None:+ return next((r for r in self._reports if r.state == "on_air"), None)++ def find(self, report_id: str) -> Report | None:+ return next((r for r in self._reports if r.id == report_id), None)++ def sleeping(self) -> bool:+ """Has a line gone unanswered, so the queue is holding its tongue?"""+ return self._settled++ # --------------------------------------------------------------- speaking++ def take_due(self, *, now: float | None = None) -> Utterance | None:+ """The one thing to say right now, marked as said. ``None`` for silence.++ Marking happens HERE rather than after the sentence is spoken, and that+ is deliberate: composing a line is an awaited call, the sweep runs+ every couple of seconds, and a second sweep arriving mid-compose would+ otherwise decide the same report is still due and say it twice.+ """+ _ = now+ if not self._in_conversation:+ return None+ # A report the user asked for BY NAME jumps every rule below it: they+ # said "tell me about Nova", and anything else answering that is the+ # deck deciding it knows better.+ requested = next((r for r in self._reports if r.state == "on_air" and not r.spoken), None)+ if requested is not None:+ requested.spoken = True+ self._settled = True+ return Utterance(form="report", reports=(requested,))+ waiting = self.pending()+ if not waiting:+ return None+ if self._missed:+ # Rule 7: one opening line for everything that happened while the+ # user was away. It is a headline even for a single report — the+ # point is the handover, not the count.+ self._missed = False+ self._settled = True+ for report in waiting:+ report.in_headline = True+ return Utterance(form="resumed", reports=tuple(waiting))+ if self._settled:+ return None # rule 8+ unheralded = [r for r in waiting if not r.in_headline]+ if not unheralded:+ return None+ if len(unheralded) == 1:+ # One piece of news is simply said. A "one agent is done, shall I+ # tell you?" would be a question with one possible answer, which+ # costs the user a turn and tells them nothing.+ report = unheralded[0]+ self._retire_on_air()+ report.state = "on_air"+ report.spoken = True+ self._settled = True+ return Utterance(form="report", reports=(report,))+ for report in unheralded:+ report.in_headline = True+ self._settled = True+ return Utterance(form="headline", reports=tuple(unheralded))++ # ------------------------------------------------------------- user input++ def acknowledge(self, report_id: str, action: Action) -> Report | None:+ """What the user said about a report. Returns it, or ``None`` if gone.++ ``next`` is the interesting one: it is both "I heard that" for whatever+ was on air and "tell me this one" for the report named. One call rather+ than two because that is one utterance — "yes, and what about Nova?".+ """+ report = self.find(report_id)+ if report is None:+ return None+ if action == "drop":+ report.state = "dropped"+ self._settled = False+ return report+ if action == "later":+ # The queue sleeps, but nothing is thrown away: the deck keeps+ # showing the lane, and the next thing the user says wakes it.+ self._retire_on_air()+ self._settled = True+ return report+ self._retire_on_air()+ # Put ON AIR but not yet spoken: the sentence is composed on the next+ # beat, and marking it said here would mean a compose that fails leaves+ # the user having asked for a report they never get.+ report.state = "on_air"+ report.spoken = False+ self._settled = False+ return report++ def _retire_on_air(self) -> None:+ """Whatever was being reported is finished with.++ Deliberately not a state called "answered": the user may well have said+ nothing at all. What is true is that the report was DELIVERED, and a+ delivered report must not sit on air blocking the queue behind it —+ which is exactly what it did in the first version, where one unanswered+ line silenced the deck permanently.+ """+ current = self.on_air()+ if current is not None:+ current.state = "reported" if current.spoken else "pending"++ def wake(self) -> None:+ """The user did something — the queue may speak again.++ Called when a turn is taken in the deck. Rule 8 stops the queue from+ repeating itself into silence; it must not stop it from answering a+ person who has just come back to it.+ """+ self._settled = False+ self._retire_on_air()++ def conversation_started(self) -> None:+ self._in_conversation = True+ self._settled = False++ def conversation_ended(self) -> None:+ """Hung up. Speech is already dead; the queue simply stops offering.++ Whatever is on air is retired rather than left mid-report: the user did+ not answer it, and it must not be waiting on air for a conversation+ that may be an hour away.+ """+ self._in_conversation = False+ self._retire_on_air()+ if self.pending():+ self._missed = True++ def in_conversation(self) -> bool:+ return self._in_conversation++ # ------------------------------------------------------------- housekeeping++ def drop_pane(self, workspace_id: str, pane_key: str) -> int:+ """Rule 6 — the user read this pane, so there is nothing to tell them."""+ dropped = 0+ for report in self._reports:+ if report.state not in ("pending", "on_air"):+ continue+ if report.workspace_id != workspace_id or report.pane_key != pane_key:+ continue+ report.state = "dropped"+ dropped += 1+ return dropped++ def forget_workspace(self, workspace_id: str) -> int:+ before = len(self._reports)+ self._reports = [r for r in self._reports if r.workspace_id != workspace_id]+ return before - len(self._reports)++ def retain(self, live: Sequence[tuple[str, str]]) -> int:+ """Drop reports whose pane is gone — nothing to jump to, nothing to say."""+ alive = set(live)+ before = len(self._reports)+ self._reports = [r for r in self._reports if (r.workspace_id, r.pane_key) in alive]+ return before - len(self._reports)++ def clear(self) -> None:+ self._reports.clear()+ self._settled = False+ self._missed = False+ self._in_conversation = False++ def state(self) -> dict[str, Any]:+ """Everything the deck's lane needs in one response."""+ on_air = self.on_air()+ return {+ "sleeping": self._settled,+ "in_conversation": self._in_conversation,+ "on_air": None if on_air is None else on_air.to_dict(),+ "pending": [r.to_dict() for r in self.pending()],+ "reports": [r.to_dict() for r in self._reports if r.state in ("pending", "on_air")],+ }+++# --------------------------------------------------------------------- wording+++def spoken_facts(utterance: Utterance) -> dict[str, object]:+ """The ground truth a composed sentence may rephrase and nothing else.++ Handed to :func:`~jarvis.voice.contextual_readback.render_readback`, whose+ honesty guard rejects anything the model adds on top. Kept small on+ purpose: the pane names and what happened to them is the whole message, and+ every extra field is another thing a rephrasing can get subtly wrong.+ """+ if utterance.form == "report":+ report = utterance.reports[0]+ return {+ "agent": report.pane,+ "what_happened": report.headline,+ "was_working_on": report.detail,+ }+ return {+ "agents": list(utterance.panes),+ "count": len(utterance.reports),+ "what_happened": [r.headline for r in utterance.reports],+ }+++def canned_line(utterance: Utterance, language: str) -> str:+ """The deterministic sentence, in the three languages the pipeline speaks.++ This is what an install with no provider — or a provider that timed out —+ actually says, so it has to stand on its own rather than read as a+ placeholder. It is also the honesty floor the composed version is checked+ against.++ Product surface, so German and Spanish are allowed here (CLAUDE.md §1,+ closed-list item: runtime voice output).+ """+ lang = (language or "en").lower()[:2]+ names = _spoken_list(utterance.panes, lang)+ count_ = len(utterance.reports)+ if utterance.form == "report":+ report = utterance.reports[0]+ if report.kind in BLOCKING_KINDS:+ if lang == "de":+ return f"{report.pane} wartet auf dich." # i18n-allow: voice output+ if lang == "es":+ return f"{report.pane} está esperando tu respuesta." # i18n-allow: voice output+ return f"{report.pane} is waiting on you."+ if lang == "de":+ return f"{report.pane} ist durch." # i18n-allow: voice output+ if lang == "es":+ return f"{report.pane} ha terminado." # i18n-allow: voice output+ return f"{report.pane} is done."+ if utterance.form == "resumed":+ if lang == "de":+ return f"Während du weg warst: {names}." # i18n-allow: voice output+ if lang == "es":+ return f"Mientras no estabas: {names}." # i18n-allow: voice output+ return f"While you were away: {names}."+ if lang == "de":+ return f"{count_} sind durch: {names}. Womit fange ich an?" # i18n-allow: voice output+ if lang == "es":+ return f"{count_} han terminado: {names}. ¿Por cuál empiezo?" # i18n-allow: voice output+ return f"{count_} are done: {names}. Which one first?"+++def _spoken_list(names: Sequence[str], language: str) -> str:+ """ "Mika, Nova and Kai" — a list said the way a person says one."""+ items = [n for n in names if n]+ if not items:+ return ""+ if len(items) == 1:+ return items[0]+ joiner = {"de": "und", "es": "y"}.get(language, "and") # i18n-allow: voice output+ return f"{', '.join(items[:-1])} {joiner} {items[-1]}"+++# ----------------------------------------------------------------------- store+_QUEUE = StandupQueue()+++def queue() -> StandupQueue:+ """The process-wide queue the sweep fills and the routes read."""+ return _QUEUE+++def reset() -> None:+ """Drop everything — for tests, and for a registry that was torn down."""+ _QUEUE.clear()+ reset_switch_cache()+++@dataclass(slots=True)+class _Wiring:+ """How this module reaches the voice, injected rather than imported.++ Nothing here imports the speech pipeline, and that is not tidiness: this+ runs inside the pane sweep, which must keep working in a headless install,+ in the tests, and on a machine with no audio at all. Unwired, the queue+ still fills and the deck still shows the lane — it simply says nothing,+ which is the honest degradation (§3).+ """++ #: Publish an announcement. Given the text and the language.+ speak: Callable[[str, str], Any] | None = None+ #: The language this turn should be spoken in. ONE resolver decides that+ #: for every layer (CLAUDE.md §1); this asks it rather than guessing.+ language: Callable[[], str] | None = None+ #: The flash composer that turns facts into a sentence. ``None`` keeps the+ #: deterministic line, which is a complete answer rather than a fallback.+ composer: Any = None+++_wiring = _Wiring()+++def wire(+ *,+ speak: Callable[[str, str], Any] | None = None,+ language: Callable[[], str] | None = None,+ composer: Any = None,+) -> None:+ """Give the queue a voice. Called once, where the speech stack is built."""+ _wiring.speak = speak+ _wiring.language = language+ _wiring.composer = composer+++def unwire() -> None:+ """Take the voice away again — shutdown, and tests that assert silence."""+ _wiring.speak = None+ _wiring.language = None+ _wiring.composer = None+++#: How long the config switch is trusted before it is read again. Same reason+#: and same number as :data:`.notifications.SWITCH_TTL_S`: ``load_config``+#: parses the TOML on every call and this runs beside a two-second sweep.+SWITCH_TTL_S = 15.0++_switch: tuple[float, bool] = (0.0, True)+++def enabled() -> bool:+ """Is the deck allowed to speak on this install?++ A config that cannot be read answers "on", matching the bell: failing+ closed here would make a broken config look like a broken feature, and the+ surface is opt-in already — you have to be in the deck for any of it.+ """+ global _switch+ cached_at, value = _switch+ now = time.monotonic()+ if now - cached_at < SWITCH_TTL_S:+ return value+ try:+ from jarvis.core.config import load_config++ value = bool(getattr(load_config().agentic_ide, "deck_reports", True))+ except Exception: # noqa: BLE001 - never let a config read stop the sweep+ value = True+ _switch = (now, value)+ return value+++def reset_switch_cache() -> None:+ """Forget the cached switch — for tests, and for a live config change."""+ global _switch+ _switch = (0.0, True)+++def deck_workspaces(registry: Any) -> set[str]:+ """Which open workspaces are being READ as a Command Deck right now.++ The deck is the only surface that speaks, and "is it on screen" is the+ frontend's answer, reported through ``set_surface_context``. Asking per+ sweep rather than remembering it means navigating away goes quiet on the+ next beat instead of whenever something else happens to notice.+ """+ from .workspace_view import VIEW_DECK++ found: set[str] = set()+ try:+ for session in registry.sessions:+ if getattr(session, "surface_view", "") == VIEW_DECK:+ found.add(str(session.id))+ except Exception: # noqa: BLE001 - a registry read must not end the sweep+ return set()+ return found+++async def pump(registry: Any, entries: Sequence[Notification]) -> str:+ """The sweep's one call into this module: take the news, say what is due.++ Everything is filtered to workspaces currently being read as a deck. A+ finished pane in a workspace the user is watching as a grid is not news+ they need told — they are looking at it.++ Never raises. It runs inside the pane sweep, which also files the bell's+ entries and the resume checkpoints, and none of those may die because the+ deck could not think of a sentence.+ """+ try:+ if not enabled():+ return ""+ decks = deck_workspaces(registry)+ if not decks:+ # Nothing is being read as a deck. The queue keeps whatever it+ # holds — the user may come back to it — but takes nothing new.+ return ""+ fresh = [entry for entry in entries if entry.workspace_id in decks]+ if fresh:+ _QUEUE.offer(fresh)+ return await announce_due()+ except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep+ logger.warning("Agentic IDE: standup pump failed: %s", exc)+ return ""+++async def announce_due() -> str:+ """Say the one thing that is due, if anything is. Returns what was said.++ Never raises: this is called from the pane sweep, and a failure to speak+ must not take down the loop that also files the bell's entries and the+ resume checkpoints.+ """+ if _wiring.speak is None:+ return ""+ try:+ utterance = _QUEUE.take_due()+ if utterance is None:+ return ""+ language = _resolve_language()+ text = await _compose(utterance, language)+ if not text:+ return ""+ await _deliver(text, language)+ return text+ except Exception as exc: # noqa: BLE001 - a mute deck beats a dead sweep+ logger.warning("Agentic IDE: standup announcement failed: %s", exc)+ return ""+++def _resolve_language() -> str:+ if _wiring.language is None:+ return "en"+ try:+ return str(_wiring.language() or "en")+ except Exception: # noqa: BLE001 - a language lookup must not silence the deck+ return "en"+++async def _compose(utterance: Utterance, language: str) -> str:+ from jarvis.voice.contextual_readback import render_readback++ return await render_readback(+ _wiring.composer,+ instruction=_INSTRUCTION[utterance.form],+ language=language,+ canned=lambda: canned_line(utterance, language),+ facts=spoken_facts(utterance),+ # The report IS the fact. A rephrasing that adds an outcome ("Mika+ # fixed the tests") would be inventing the one thing this surface+ # promised not to claim — see "What it will not claim" above.+ honesty_bound=True,+ )+++async def _deliver(text: str, language: str) -> None:+ speak = _wiring.speak+ if speak is None:+ return+ result = speak(text, language)+ if hasattr(result, "__await__"):+ await result+++#: What the composer is asked to write, per shape. Instructions rather than+#: templates: the maintainer's standing rule is that Jarvis must not read fixed+#: sentences out of a table, and these say what the line is FOR while leaving+#: the wording to the moment.+_INSTRUCTION: dict[str, str] = {+ "report": (+ "Tell the user, in one short spoken sentence, that this coding agent "+ "has stopped working. Do not claim the work succeeded — only that the "+ "agent is done and waiting. Do not offer to summarise."+ ),+ "headline": (+ "Several coding agents finished at once. Say so in ONE short spoken "+ "sentence naming them, and ask which one to start with. Do not report "+ "any of them yet."+ ),+ "resumed": (+ "The user has just come back to the conversation. In one short spoken "+ "sentence, tell them which coding agents finished while they were "+ "away. Do not report any of them in detail yet."+ ),+}+++__all__ = [+ "BLOCKING_KINDS",+ "MAX_PENDING",+ "SWITCH_TTL_S",+ "Action",+ "Kind",+ "Report",+ "ReportState",+ "StandupQueue",+ "Utterance",+ "announce_due",+ "canned_line",+ "deck_workspaces",+ "enabled",+ "pump",+ "queue",+ "reset",+ "reset_switch_cache",+ "spoken_facts",+ "unwire",+ "wire",+]diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 5e3113c2a0..ba9b16ecc9 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3427,6 +3427,17 @@ class AgenticIdeConfig(BaseModel):),)+ deck_reports: bool = Field(+ default=True,+ description=(+ "In the Command Deck, say a finished agent out loud instead of only "+ "counting it in the bell — one report at a time, and only while a "+ "conversation is open. Off leaves the deck's report lane on screen "+ "and silent. Has no effect in the terminal grid or chat view, "+ "which never speak."+ ),+ )+@field_validator("prompt_writer", mode="before")@classmethoddef _usable_writer(cls, value: object) -> str:diff --git a/jarvis/ui/web/agentic_ide_routes.py b/jarvis/ui/web/agentic_ide_routes.pyindex 17cafb111f..490ac6c683 100644--- a/jarvis/ui/web/agentic_ide_routes.py+++ b/jarvis/ui/web/agentic_ide_routes.py@@ -81,6 +81,7 @@ from jarvis.agentic_ide import (recap_engine,recents,resume_store,+ standup,)from jarvis.agentic_ide.activity import has_work_behind_itfrom jarvis.agentic_ide.agent_sessions import has_conversation@@ -344,6 +345,27 @@ class SurfaceContextRequest(BaseModel):)+#: Layer 3 for the report actions, guarded the same way as the view enum above.+DeckAction = Literal["next", "later", "drop"]+if set(get_args(DeckAction)) != set(get_args(standup.Action)): # pragma: no cover - guard+ raise RuntimeError(+ "DeckAction drifted from standup.Action — update both "+ "(jarvis/agentic_ide/standup.py is the source of truth)."+ )+++class DeckAckRequest(BaseModel):+ """What the user said about one Command Deck report."""++ id: str = Field(description="The report being answered.")+ action: DeckAction = Field(+ description=(+ "`next` reports this one now, `later` puts the queue to sleep "+ "without losing anything, `drop` takes this report away."+ )+ )++class TerminalTextSizeRequest(BaseModel):"""How large the text in the workspace's terminals should be, in pixels."""@@ -1859,6 +1881,32 @@ async def clear_notification(notification_id: str) -> NotificationsChangedResponreturn NotificationsChangedResponse(changed=dropped, unread=center.unread)[email protected]("/deck/queue", summary="What the Command Deck still has to report")+async def get_deck_queue() -> dict:+ """The report lane: what is waiting, and what is being reported right now.++ Only the Command Deck renders this — the same events reach the bell in the+ other two views and are never spoken there. `sleeping` is true once a line+ has gone unanswered: the deck says so rather than looking broken, because+ "nothing new" and "it has stopped talking to you" are very different and+ were indistinguishable from the outside in the first version.+ """+ return standup.queue().state()++[email protected]("/deck/ack", summary="Answer a Command Deck report")+async def ack_deck_report(req: DeckAckRequest) -> dict:+ """"Tell me that one" / "later" / "drop it", from voice or from the lane.++ Not a 404 for an unknown id: a report goes away when its pane does, and a+ click that lands a moment after that got the outcome it wanted. `found`+ says which happened, so a caller that cares can tell.+ """+ queue = standup.queue()+ report = queue.acknowledge(req.id, req.action)+ return {"found": report is not None, **queue.state()}++@router.post("/terminals/close-batch",summary="Close several terminals",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex e7ad6476a7..c13aafa808 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -585,6 +585,21 @@ class WebServer:app.state.config = self.cfgapp.state.bus = self.bus+ # The Command Deck's way back to the user: when a coding agent stops,+ # say so instead of only counting it in the header bell. Attached here+ # because this is where the speech bus becomes available, and it is+ # cheap — three subscriptions and nothing running. The queue behind it+ # only ever fills while a workspace is actually being READ as a deck+ # (see agentic_ide/standup.py), so an install that never opens the IDE+ # pays for three handlers that are never called.+ try:+ from jarvis.agentic_ide import deck_voice++ app.state.deck_voice = deck_voice.attach(self.bus)+ except Exception as exc: # noqa: BLE001 - an optional surface never breaks boot+ logger.opt(exception=exc).warning("Command Deck voice not attached")+ app.state.deck_voice = None+# Voice boot-readiness mirror. WS events are one-shot, so a tab that# connects after warm-up finished would never see VoiceBootStatus.# Persist the latest state on this (long-lived) server instance fordiff --git a/tests/unit/agentic_ide/test_deck_routes.py b/tests/unit/agentic_ide/test_deck_routes.pynew file mode 100644index 0000000000..d177ca1570--- /dev/null+++ b/tests/unit/agentic_ide/test_deck_routes.py@@ -0,0 +1,128 @@+"""The report lane the Command Deck renders, and answering from it.++Voice and click go through the same two routes on purpose: "tell me about Nova"+and pressing Nova's card are the same instruction, and a second path for the+second one is a second thing to keep in step.+"""++from __future__ import annotations++from typing import Any++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from jarvis.agentic_ide import standup+from jarvis.ui.web import agentic_ide_routes++from .test_standup import entry++[email protected](autouse=True)+def _fresh() -> Any:+ standup.reset()+ standup.unwire()+ yield+ standup.reset()+ standup.unwire()+++def client() -> TestClient:+ app = FastAPI()+ app.include_router(agentic_ide_routes.router)+ return TestClient(app)+++def filled(*panes: str, kind: str = "completed") -> standup.StandupQueue:+ queue = standup.queue()+ queue.conversation_started()+ queue.offer([entry(pane, kind) for pane in panes])+ return queue+++def test_an_empty_lane_reads_as_empty_rather_than_missing(client: TestClient) -> None:+ body = client.get("/api/agentic-ide/deck/queue").json()++ assert body["pending"] == []+ assert body["on_air"] is None+ assert body["sleeping"] is False+++def test_the_lane_lists_what_is_waiting_blockers_first(client: TestClient) -> None:+ filled("Mika")+ standup.queue().offer([entry("Nova", "needs_input")])++ body = client.get("/api/agentic-ide/deck/queue").json()++ assert [r["pane"] for r in body["pending"]] == ["Nova", "Mika"]+++def test_asking_for_one_report_puts_it_on_air(client: TestClient) -> None:+ queue = filled("Mika", "Nova")+ queue.take_due()+ nova = next(r for r in queue.pending() if r.pane == "Nova")++ body = client.post(+ "/api/agentic-ide/deck/ack", json={"id": nova.id, "action": "next"}+ ).json()++ assert body["found"] is True+ assert body["on_air"]["pane"] == "Nova"+++def test_later_puts_the_lane_to_sleep_without_losing_anything(client: TestClient) -> None:+ queue = filled("Mika", "Nova")+ queue.take_due()+ first = queue.pending()[0]++ body = client.post(+ "/api/agentic-ide/deck/ack", json={"id": first.id, "action": "later"}+ ).json()++ assert body["sleeping"] is True+ assert len(body["pending"]) == 2+++def test_dropping_one_takes_it_out_of_the_lane(client: TestClient) -> None:+ queue = filled("Mika", "Nova")+ mika = next(r for r in queue.pending() if r.pane == "Mika")++ body = client.post(+ "/api/agentic-ide/deck/ack", json={"id": mika.id, "action": "drop"}+ ).json()++ assert [r["pane"] for r in body["pending"]] == ["Nova"]+++def test_answering_a_report_that_is_already_gone_is_not_an_error(+ client: TestClient,+) -> None:+ # A report goes away when its pane does, and a click that lands a moment+ # later got the outcome it wanted. A 404 here would put an error toast in+ # front of a user who did nothing wrong.+ response = client.post(+ "/api/agentic-ide/deck/ack", json={"id": "sr-gone", "action": "next"}+ )++ assert response.status_code == 200+ assert response.json()["found"] is False+++def test_an_action_nobody_defined_is_refused_at_the_door(client: TestClient) -> None:+ queue = filled("Mika")+ mika = queue.pending()[0]++ response = client.post(+ "/api/agentic-ide/deck/ack", json={"id": mika.id, "action": "snooze"}+ )++ assert response.status_code == 422+++def test_the_route_literal_still_matches_the_source_of_truth() -> None:+ """Layer 3 against layer 0, same guard as the workspace-view enum."""+ from typing import get_args++ assert set(get_args(agentic_ide_routes.DeckAction)) == set(get_args(standup.Action))diff --git a/tests/unit/agentic_ide/test_deck_voice.py b/tests/unit/agentic_ide/test_deck_voice.pynew file mode 100644index 0000000000..647678dc1c--- /dev/null+++ b/tests/unit/agentic_ide/test_deck_voice.py@@ -0,0 +1,169 @@+"""The Command Deck's report queue reaches the user through the speech bus.++The bridge itself is thin on purpose — what these tests pin is the three things+it must not get wrong: never interrupting, never re-deriving the turn language,+and going quiet the moment the user hangs up.+"""++from __future__ import annotations++from typing import Any++import pytest++from jarvis.agentic_ide import deck_voice, standup+from jarvis.core.bus import EventBus+from jarvis.core.events import (+ AnnouncementRequested,+ ResponseGenerated,+ VoiceSessionEnded,+ VoiceSessionStarted,+)++from .test_standup import entry++[email protected](autouse=True)+def _fresh() -> Any:+ standup.reset()+ standup.unwire()+ yield+ standup.reset()+ standup.unwire()+++class Recorder:+ """Collects what would have been spoken."""++ def __init__(self, bus: EventBus) -> None:+ self.said: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, self._on)++ async def _on(self, event: AnnouncementRequested) -> None:+ self.said.append(event)+++class FakeSession:+ def __init__(self, ident: str = "ide_test", view: str = "deck") -> None:+ self.id = ident+ self.surface_view = view+++class FakeRegistry:+ def __init__(self, *sessions: Any) -> None:+ self.sessions = list(sessions or [FakeSession()])+++async def test_a_finished_pane_is_announced_once_a_session_is_open() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)++ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))+ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert len(heard.said) == 1+ assert "Mika" in heard.said[0].text+++async def test_it_never_interrupts() -> None:+ # Rule 5. Nothing the deck has to say is worth cutting the user off for —+ # `interrupt` stops playback mid-word, and this is news, not an emergency.+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))++ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert heard.said[0].priority == "normal"+++async def test_nothing_is_said_before_a_session_starts() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)++ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert heard.said == []+ # Kept, not lost — it is offered when the user comes back.+ assert [r.pane for r in standup.queue().pending()] == ["Mika"]+++async def test_hanging_up_stops_the_deck_talking() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))+ await bus.publish(VoiceSessionEnded(session_id="s1"))++ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert heard.said == []+++async def test_and_the_next_session_gets_it_once() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))+ await bus.publish(VoiceSessionEnded(session_id="s1"))+ await standup.pump(FakeRegistry(), [entry("Mika"), entry("Nova")])++ await bus.publish(VoiceSessionStarted(session_id="s2", language="en"))+ await standup.pump(FakeRegistry(), [])++ assert len(heard.said) == 1+ assert "While you were away" in heard.said[0].text+ # Once. Coming back to the deck a third time is not a reason to hear it+ # again — the reports are on their cards and in the lane.+ await standup.pump(FakeRegistry(), [])+ assert len(heard.said) == 1+++async def test_the_line_is_spoken_in_the_language_the_turn_resolved_to() -> None:+ # Read, never re-derived: one resolver owns the output language for every+ # layer, and a second opinion here is exactly the divergence it prevents.+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))+ await bus.publish(ResponseGenerated(text="Alles klar.", language="de"))++ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert heard.said[0].language == "de"+ assert "durch" in heard.said[0].text # i18n-allow: asserting voice output+++async def test_an_answer_wakes_a_queue_that_had_gone_quiet() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))+ await standup.pump(FakeRegistry(), [entry("Mika")])+ assert len(heard.said) == 1++ # Unanswered, so the queue settles (rule 8) — until the user says something.+ await standup.pump(FakeRegistry(), [entry("Nova")])+ assert len(heard.said) == 1++ await bus.publish(ResponseGenerated(text="Go on.", language="en"))+ await standup.pump(FakeRegistry(), [])++ assert len(heard.said) == 2+ assert "Nova" in heard.said[1].text+++async def test_stopping_the_bridge_leaves_the_queue_mute_but_working() -> None:+ bus = EventBus()+ heard = Recorder(bus)+ voice = deck_voice.attach(bus)+ await bus.publish(VoiceSessionStarted(session_id="s1", language="en"))++ voice.stop()+ await standup.pump(FakeRegistry(), [entry("Mika")])++ assert heard.said == []+ assert [r.pane for r in standup.queue().pending()] == ["Mika"]diff --git a/tests/unit/agentic_ide/test_standup.py b/tests/unit/agentic_ide/test_standup.pynew file mode 100644index 0000000000..95ea63d128--- /dev/null+++ b/tests/unit/agentic_ide/test_standup.py@@ -0,0 +1,454 @@+"""The Command Deck reports one agent at a time.++What is pinned here is the behaviour the maintainer asked for by describing the+failure: eight agents finishing inside ten seconds must not produce eight+announcements, and the queue must never turn into something that talks at+somebody who has stopped listening.+"""++from __future__ import annotations++from typing import Any++import pytest++from jarvis.agentic_ide import standup+from jarvis.agentic_ide.notifications import Notification++[email protected](autouse=True)+def _fresh() -> Any:+ standup.reset()+ standup.unwire()+ yield+ standup.reset()+ standup.unwire()+++def entry(+ pane: str,+ kind: str = "completed",+ *,+ workspace: str = "ide_test",+ title: str = "Finished and waiting at its prompt",+ detail: str = "",+) -> Notification:+ """One bell entry, as the sweep files it."""+ return Notification(+ id=f"n-{workspace}-{pane}-{kind}",+ kind=kind, # type: ignore[arg-type]+ workspace_id=workspace,+ workspace="project",+ pane_key=pane.lower(),+ pane=pane,+ agent="claude",+ display_name="Claude Code",+ title=title,+ detail=detail,+ created_at=0.0,+ )+++def open_queue() -> standup.StandupQueue:+ """A queue with a conversation open — nothing is ever said without one."""+ queue = standup.StandupQueue()+ queue.conversation_started()+ return queue+++class TestSeveralAtOnce:+ """The pile-up this whole module exists for."""++ def test_three_finishing_together_produce_one_headline(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])++ utterance = queue.take_due()++ assert utterance is not None+ assert utterance.form == "headline"+ assert set(utterance.panes) == {"Mika", "Nova", "Kai"}+ # And nothing follows it on its own — the user answers first.+ assert queue.take_due() is None++ def test_the_headline_names_them_rather_than_counting_them(self) -> None:+ # "Three are done" without names is a notification, not a handover:+ # the next thing the user has to say is "which three?".+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])++ line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]++ assert "Mika" in line+ assert "Nova" in line++ def test_one_piece_of_news_is_simply_said(self) -> None:+ # A "one agent is done, shall I tell you?" is a question with one+ # possible answer. It costs the user a turn and tells them nothing.+ queue = open_queue()+ queue.offer([entry("Mika")])++ utterance = queue.take_due()++ assert utterance is not None+ assert utterance.form == "report"+ assert utterance.panes == ("Mika",)++ def test_asking_for_one_by_name_puts_that_report_on_air(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])+ queue.take_due()+ nova = next(r for r in queue.pending() if r.pane == "Nova")++ queue.acknowledge(nova.id, "next")++ assert queue.on_air() is not None+ assert queue.on_air().pane == "Nova" # type: ignore[union-attr]++ def test_a_report_nobody_answered_does_not_silence_the_deck_forever(self) -> None:+ """The first version's real bug, found by the blocker test below it.++ A report went ON AIR when it was spoken and stayed there until the user+ acknowledged it — and "one report on air" was also the gate on saying+ anything at all. So a single unanswered line, which is the ordinary+ case for somebody who is reading code, muted the deck permanently.+ """+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.take_due() # spoken, never acknowledged++ queue.offer([entry("Nova")])+ queue.wake()++ utterance = queue.take_due()+ assert utterance is not None+ assert utterance.panes == ("Nova",)++ def test_a_report_asked_for_by_name_is_spoken_on_the_next_beat(self) -> None:+ # `acknowledge` only decides WHAT is next; the sentence is composed a+ # beat later. Marking it said at the moment of asking would mean a+ # failed compose leaves the user waiting for a report that never comes.+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])+ queue.take_due()+ nova = next(r for r in queue.pending() if r.pane == "Nova")+ queue.acknowledge(nova.id, "next")++ utterance = queue.take_due()++ assert utterance is not None+ assert utterance.form == "report"+ assert utterance.panes == ("Nova",)+ # ...and it is not said a second time on the beat after that.+ assert queue.take_due() is None++ def test_only_one_report_is_ever_on_air(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])+ queue.take_due()+ first, second = queue.pending()[0], queue.pending()[1]++ queue.acknowledge(first.id, "next")+ queue.acknowledge(second.id, "next")++ on_air = [r for r in queue.state()["reports"] if r["state"] == "on_air"]+ assert len(on_air) == 1+ assert on_air[0]["pane"] == second.pane+++class TestPriority:+ def test_a_blocked_pane_outranks_a_finished_one(self) -> None:+ # Work has STOPPED on a pane holding a question; a finished pane is+ # merely waiting to be read.+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova", "needs_input")])++ assert queue.pending()[0].pane == "Nova"++ def test_a_blocker_wakes_a_queue_that_had_gone_quiet(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.take_due()+ assert queue.sleeping()++ queue.offer([entry("Nova", "needs_input")])++ utterance = queue.take_due()+ assert utterance is not None+ assert utterance.panes == ("Nova",)++ def test_another_ordinary_finish_does_not(self) -> None:+ # Rule 8. Somebody who did not answer the first line is not helped by+ # a second one, and this is the difference between a deck and a nag.+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.take_due()++ queue.offer([entry("Nova")])++ assert queue.take_due() is None+ # Still there, still listed — it is on the card and in the lane.+ assert [r.pane for r in queue.pending()] == ["Nova"]++ def test_the_user_saying_something_brings_it_back(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.take_due()+ queue.offer([entry("Nova")])++ queue.wake()++ utterance = queue.take_due()+ assert utterance is not None+ assert utterance.panes == ("Nova",)+++class TestNothingIsSaidIntoAnEmptyRoom:+ def test_no_conversation_means_no_announcement(self) -> None:+ queue = standup.StandupQueue() # never started a conversation+ queue.offer([entry("Mika")])++ assert queue.take_due() is None+ assert queue.pending() # kept, not thrown away++ def test_hanging_up_keeps_the_queue_and_offers_it_once_on_return(self) -> None:+ # The killswitch mandate cuts speech dead. It does not cancel the work+ # that came back while the user was away — that is theirs to hear.+ queue = open_queue()+ queue.conversation_ended()+ queue.offer([entry("Mika"), entry("Nova")])++ queue.conversation_started()+ first = queue.take_due()++ assert first is not None+ assert first.form == "resumed"+ assert set(first.panes) == {"Mika", "Nova"}+ # Once. It is a handover, not a thing that repeats every time the user+ # comes back to the deck.+ assert queue.take_due() is None++ def test_a_report_on_air_at_hangup_is_not_left_hanging(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])+ queue.take_due()+ queue.acknowledge(queue.pending()[0].id, "next")+ assert queue.on_air() is not None++ queue.conversation_ended()++ # Otherwise it would still be "being reported" an hour later, and+ # rule 1 would keep the whole queue silent behind it.+ assert queue.on_air() is None+++class TestReadMeansSilent:+ def test_a_pane_the_user_read_drops_out_unspoken(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])++ queue.drop_pane("ide_test", "mika")++ assert [r.pane for r in queue.pending()] == ["Nova"]++ def test_later_puts_the_queue_to_sleep_without_losing_anything(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])+ queue.take_due()++ queue.acknowledge(queue.pending()[0].id, "later")++ assert queue.sleeping()+ assert len(queue.pending()) == 2+++class TestOnePieceOfNewsPerPane:+ def test_the_same_finish_twice_is_reported_once(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.offer([entry("Mika")])++ assert len(queue.pending()) == 1++ def test_a_finish_that_becomes_a_question_is_upgraded_in_place(self) -> None:+ # The agent stopped, then put a permission prompt on screen. The+ # question is the news; two entries about one pane would have the user+ # hear "Mika is done" and then "Mika needs you" about the same moment.+ queue = open_queue()+ queue.offer([entry("Mika")])+ queue.offer([entry("Mika", "needs_input", title="Waiting for your answer")])++ pending = queue.pending()+ assert len(pending) == 1+ assert pending[0].kind == "needs_input"++ def test_a_later_finish_does_not_downgrade_a_pending_question(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika", "needs_input")])+ queue.offer([entry("Mika")])++ assert queue.pending()[0].kind == "needs_input"+++class TestBounded:+ def test_past_the_limit_the_oldest_finishes_fall_away(self) -> None:+ queue = standup.StandupQueue(limit=3)+ queue.conversation_started()++ queue.offer([entry(f"T{i}") for i in range(6)])++ assert len(queue.pending()) == 3++ def test_but_never_a_blocked_or_crashed_pane(self) -> None:+ # Those are the two the user most needs to hear about. A queue that+ # silently loses them is worse than one that says nothing.+ queue = standup.StandupQueue(limit=2)+ queue.conversation_started()++ queue.offer(+ [+ entry("Blocked", "needs_input"),+ entry("Dead", "exited"),+ *[entry(f"T{i}") for i in range(5)],+ ]+ )++ kinds = {r.pane for r in queue.pending()}+ assert "Blocked" in kinds+ assert "Dead" in kinds+++class TestWording:+ """The deterministic floor — what an install with no provider says."""++ @pytest.mark.parametrize(+ ("language", "must_contain"),+ [("en", "are done"), ("de", "sind durch"), ("es", "han terminado")],+ )+ def test_a_headline_reads_as_a_sentence_in_every_language(+ self, language: str, must_contain: str+ ) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova")])+ utterance = queue.take_due()++ line = standup.canned_line(utterance, language) # type: ignore[arg-type]++ assert must_contain in line+ assert "Mika" in line and "Nova" in line++ def test_a_list_is_said_the_way_a_person_says_one(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika"), entry("Nova"), entry("Kai")])++ line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]++ assert "Mika, Nova and Kai" in line++ def test_a_blocked_pane_is_not_described_as_finished(self) -> None:+ queue = open_queue()+ queue.offer([entry("Mika", "needs_input")])++ line = standup.canned_line(queue.take_due(), "en") # type: ignore[arg-type]++ assert "waiting on you" in line+ assert "done" not in line++ def test_the_facts_handed_to_the_composer_carry_no_verdict(self) -> None:+ # The honesty guard can only reject what it was not given. "Finished"+ # is the whole claim; whether the work is any good is not knowable from+ # a pane going quiet, and must not be inventable from these fields.+ queue = open_queue()+ queue.offer([entry("Mika", detail="Fixing the wake-path tests")])++ facts = standup.spoken_facts(queue.take_due()) # type: ignore[arg-type]++ assert facts["agent"] == "Mika"+ assert "succeeded" not in str(facts).lower()+ assert "fixed" not in str(facts).lower()+++class TestPump:+ """The sweep's one call in, and the surface gate on it."""++ class FakeSession:+ def __init__(self, ident: str, view: str) -> None:+ self.id = ident+ self.surface_view = view++ class FakeRegistry:+ def __init__(self, *sessions: Any) -> None:+ self.sessions = list(sessions)++ async def test_a_workspace_read_as_a_grid_is_never_spoken(self) -> None:+ said: list[str] = []+ standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")+ registry = self.FakeRegistry(self.FakeSession("ide_test", "grid"))++ await standup.pump(registry, [entry("Mika")])++ assert said == []+ assert standup.queue().pending() == []++ async def test_a_deck_workspace_is(self) -> None:+ said: list[str] = []+ standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")+ standup.queue().conversation_started()+ registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))++ await standup.pump(registry, [entry("Mika")])++ assert said and "Mika" in said[0]++ async def test_only_that_workspace_s_news(self) -> None:+ # Call-signs repeat between workspaces, and a deck must not report a+ # pane from the grid the user has open in the next tab.+ said: list[str] = []+ standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")+ standup.queue().conversation_started()+ registry = self.FakeRegistry(+ self.FakeSession("ide_deck", "deck"),+ self.FakeSession("ide_grid", "grid"),+ )++ await standup.pump(+ registry,+ [entry("Mika", workspace="ide_grid"), entry("Nova", workspace="ide_deck")],+ )++ assert said and "Nova" in said[0]+ assert "Mika" not in said[0]++ async def test_an_unwired_deck_fills_the_lane_and_stays_silent(self) -> None:+ # No speech stack (headless, tests, a machine with no audio). The queue+ # still works and the deck still shows it — honest degradation, not a+ # broken feature.+ standup.queue().conversation_started()+ registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))++ spoken = await standup.pump(registry, [entry("Mika")])++ assert spoken == ""++ async def test_a_broken_speaker_does_not_take_the_sweep_down(self) -> None:+ def explode(_text: str, _lang: str) -> None:+ raise RuntimeError("no audio device")++ standup.wire(speak=explode, language=lambda: "en")+ standup.queue().conversation_started()+ registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))++ assert await standup.pump(registry, [entry("Mika")]) == ""++ async def test_the_switch_being_off_means_nothing_is_collected(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ monkeypatch.setattr(standup, "enabled", lambda: False)+ said: list[str] = []+ standup.wire(speak=lambda text, _lang: said.append(text), language=lambda: "en")+ standup.queue().conversation_started()+ registry = self.FakeRegistry(self.FakeSession("ide_test", "deck"))++ await standup.pump(registry, [entry("Mika")])++ assert said == []