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): instant acknowledgment — the first sign of life comes from the plan, not the model
Haralde88516663b26
diff --git a/docs/adr/0033-instant-acknowledgment.md b/docs/adr/0033-instant-acknowledgment.mdnew file mode 100644index 0000000000..5c7aa69d13--- /dev/null+++ b/docs/adr/0033-instant-acknowledgment.md@@ -0,0 +1,100 @@+# ADR-0033 — Instant acknowledgment: the first sign of life comes from the plan, not the model++**Status:** Accepted · **Date:** 2026-08-17 · **Phase:** Voice UX (both engines)++## Context++When a request needs the Tool Model or a background agent, the user waited+5–30 s with no sign of life. Measured on the maintainer's box (BUG-072):+delegated realtime turns p50 12–18 s before the fix, 4.5–12.5 s after; the+classic pipeline's action turns are non-streaming by construction+(`manager.generate_stream` withholds every chunk while+`plan_turn(...).requires_orchestrator`).++Every earlier interim-speech mechanism was structurally late or gated away:++| Mechanism | Why it did not cover the wait |+|---|---|+| Flash-Brain preamble (ADR-0014) | speculative, median 2.98 s to first token, only output on 22 % of turns — retired 2026-06-21 |+| Grounded per-tool ack (`brain.router.ack`) | fires only after the router's FIRST model round has streamed (2–16 s), then 2.5 s commit grace, 30 s min gap, 3/min cap, 180 s dedup |+| Realtime delegate bridge (BUG-051/054) | deliberately 6 s after dispatch (the "double-tap" fear), one generic pool line ("still on it") |+| Provider-requested delegate | no bridge at all |+| Public-fact grounding ack | immediate, but a surface-TTS second voice reading the whole question back |++The maintainer's rule (2026-08-17): under two seconds, always, for heavy+work — never for plain conversation; never a stock filler; never an+ack-then-answer double-tap; the ack for an ACTION must reference the request.++## Decision++One shared core, `jarvis/voice/instant_ack.py`, used by both voice engines.++1. **Trigger = the committed plan, at dispatch.** `plan_instant_ack(plan_turn(text))`+ maps the deterministic planner reasons to a work class with an expected+ duration: RESEARCH / SCREEN / MISSION and connected personal lookups speak+ **immediately**; ACTION and local personal lookups wait a **1.2 s grace**+ and speak only if the turn is still processing. Plain conversation, voice+ control and vague orchestrator turns get nothing.+2. **State only what Jarvis is doing.** Closed de/en/es pools per class+ (no-repeat memory, `{agent}` = wake-word brand). The ACTION pool is empty+ by design: an action line is model-composed (the live model in realtime,+ the flash `ReadbackComposer` in the pipeline) and accepted only by the+ structural validator `contextual_ack_is_valid` — intent grammar, ≤ 12+ words, every content word from the user's own request, no digits, no+ result marker, no forbidden vocabulary, at least one subject word. An+ invented outcome needs new words or a non-intent verb, so it cannot pass.+ No composer → silence, never "on it".+3. **No double-tap.** A result ready before the line's first sample wins; a+ line already playing finishes (never cut mid-word). Realtime passes the+ spoken line into the trusted-result rendering order (*continue, do not+ repeat*); the pipeline drops the grounded router ack within 8 s of an+ instant ack (later it doubles as the progress line) and the spawn+ announcer receives the recently spoken line as context.+4. **One voice per call.** Realtime renders the line through the live model+ (existing bridge mechanics: exact-line or contextual order, transcript+ validated at the response boundary); verbatim-speech transports use the+ composer or stay silent for actions. The public-fact grounding path hands+ its surface-TTS ack to the bridge whenever a plan exists.+5. **Gates.** The instant ack is exempt from the pipeline's anti-loop cap and+ wording dedup (it is armed once per user utterance and cancels its+ predecessor); the "user holds the floor" and "Jarvis already speaking"+ drops and the `should_play` predicate still apply. `[ack_brain].instant_ack+ = false` is the kill switch. Mission heartbeat first beat 30 → 20 s.++## Consequences++- Realtime: first audio for a research question moves from ~7 s (generic) to+ ~1.5–2 s (class line, same voice); actions get "I'm opening Spotify."+ after 1.2 s if still running. `_DELEGATE_BRIDGE_DELAY_S` (6 s) is now only+ the cap / the delay for unclassified turns.+- Pipeline: heavy turns speak at 0 / 1.2 s instead of after round one; the+ grounded router ack becomes the 8 s+ progress line.+- Two chargeable flash calls per action turn at most (ack + spawn/interim),+ both bounded (700 ms ack budget) and breaker-guarded.+- Amends ADR-0014 gate 1 (suppress-if-fast) — superseded by the class grace+ for the classic pipeline; BUG-054's closed-pool rule is extended, not+ relaxed: the contextual class is validated structurally, never by prompt+ compliance.++## Alternatives considered++- **Earcon at t≈0** — fastest honest signal, but the maintainer's target is+ a conversational partner, not a beep; kept out (the chime generator exists+ if wanted later).+- **Surface TTS for the realtime ack** (~0.8 s) — a second voice mid-call is+ the exact BUG-090 failure; rejected in favour of the live model (+~1 s).+- **Flash-LLM topic line for every class** — the pool line already fits+ research/personal/screen/mission and costs 0 ms; the composed line stays+ the ACTION-only path (and an Etappe-2 opt-in elsewhere).+- **Prompt-only "do not invent" for the action line** — BUG-054 proved+ prompt compliance is not a boundary; the structural validator is.++## References++- `jarvis/voice/instant_ack.py`, `tests/unit/voice/test_instant_ack.py`+- `jarvis/realtime/session.py` (`_run_delegate_bridge`, boundary validation,+ `_delegate_result_prompt(already_said=…)`), `tests/unit/realtime/test_session.py`+- `jarvis/speech/pipeline.py` (`_arm_instant_ack`, `_on_announcement` gates),+ `tests/unit/speech/test_instant_ack_pipeline.py`+- `jarvis/brain/turn_planner.py::is_lookup_shape`+- ADR-0014, BUG-051, BUG-054, BUG-070, BUG-072, BUG-090diff --git a/jarvis/brain/ack_brain/config.py b/jarvis/brain/ack_brain/config.pyindex 0f3bbaa170..bbe68ca7d9 100644--- a/jarvis/brain/ack_brain/config.py+++ b/jarvis/brain/ack_brain/config.py@@ -137,6 +137,14 @@ class AckBrainConfig(BaseModel):# (skip-list-aware) and re-scrubbed at the speech layer. Set False to go# back to pure silence during tool execution.grounded_tool_ack: bool = Field(default=True)+ # Instant acknowledgment (2026-08-17, jarvis/voice/instant_ack.py): the+ # turn's FIRST sign of life for heavy work, decided from the deterministic+ # turn plan at dispatch (research / screen / mission speak at once; an+ # action or personal lookup after a 1.2 s grace, only if still running).+ # Independent of `enabled` (the closed pools need no LLM); the ACTION+ # class alone uses the flash composer and stays silent without one.+ # False = back to the pre-2026-08-17 silence until the router acks.+ instant_ack: bool = Field(default=True)# 2026-07-06 interim-ack redesign (spec: docs/superpowers/specs/# 2026-07-06-interim-ack-redesign-design.md). Forensic finding: one voice# session spoke the identical grounded ack once per utterance, threediff --git a/jarvis/brain/ack_brain/spawn_announcement.py b/jarvis/brain/ack_brain/spawn_announcement.pyindex c1bdd5dcc2..fc42788ce6 100644--- a/jarvis/brain/ack_brain/spawn_announcement.py+++ b/jarvis/brain/ack_brain/spawn_announcement.py@@ -581,6 +581,21 @@ class SpawnAnnouncementComposer:f"{content}\n[Task: {interpreted}]" if contentelse f"[Task: {interpreted}]")+ # Instant acknowledgment (2026-08-17): when the user already heard a+ # first line for this very request seconds ago, the handover must+ # continue from it -- name the handover, do not re-announce the task.+ try:+ from jarvis.voice.instant_ack import recently_spoken++ already = recently_spoken()+ except Exception: # noqa: BLE001 -- the note is a hint, never a dependency+ already = ""+ if already:+ content = (+ f"{content}\n[Already said to the user seconds ago: "+ f"\"{already}\" -- continue from it, do not repeat it or "+ "re-announce the task; state only the handover.]"+ )return contentasync def _try_provider(diff --git a/jarvis/brain/turn_planner.py b/jarvis/brain/turn_planner.pyindex e165b67860..54bbefad2a 100644--- a/jarvis/brain/turn_planner.py+++ b/jarvis/brain/turn_planner.py@@ -599,6 +599,33 @@ def is_contextual_follow_up(text: str, context: Sequence[str]) -> bool:)+# Recall-shaped openers ("do you remember", "weisst du noch") read as ACTION to+# the planner (``remember`` is a save verb) although the user is asking, not+# ordering. Kept next to the lookup regex so ``is_lookup_shape`` covers both.+_RECALL_QUESTION_RE = re.compile(+ r"(?:do you (?:remember|know|recall)|weisst du(?: noch)?|" # i18n-allow: speech input+ r"erinnerst du dich|kennst du|te acuerdas|recuerdas|sabes)" # i18n-allow: speech input+)+++def is_lookup_shape(text: str) -> bool:+ """Return whether ``text`` is phrased as a lookup / question, not an order.++ A form classifier only (deterministic, hot-path safe): a trailing question+ mark, a lookup opener ("what", "wann", "zeig", ...) or a recall opener+ ("weisst du noch", "do you remember"). Callers use it to tell "read my+ notes" from "write to my notes" when both carry the same planner reasons.+ """+ normalized = _normalize(text).strip()+ if not normalized:+ return False+ if normalized.endswith("?"):+ return True+ return bool(+ _LOOKUP_SHAPE_RE.search(normalized) or _RECALL_QUESTION_RE.search(normalized)+ )++def is_public_fact_question(text: str) -> bool:"""Return whether ``text`` asks for a concrete public-world fact.diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex bd80c8306c..be36404ec1 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -1512,6 +1512,9 @@ class LatencyPhase(StrEnum):REALTIME_FIRST_TRANSCRIPT = "realtime_first_transcript"REALTIME_FIRST_AUDIO = "realtime_first_audio"REALTIME_DELEGATE_STARTED = "realtime_delegate_started"+ # The instant acknowledgment / bridge line was ordered from the live+ # model (detail carries class, delay and whether it is contextual).+ REALTIME_DELEGATE_BRIDGE_REQUESTED = "realtime_delegate_bridge_requested"REALTIME_DELEGATE_COMPLETED = "realtime_delegate_completed"REALTIME_TOOL_COMPLETED = "realtime_tool_completed"REALTIME_SCRUB_CANCEL = "realtime_scrub_cancel"diff --git a/jarvis/realtime/session.py b/jarvis/realtime/session.pyindex b4500471e3..31a648eff4 100644--- a/jarvis/realtime/session.py+++ b/jarvis/realtime/session.py@@ -76,6 +76,17 @@ from jarvis.speech.interrupt_intent import (INTERRUPT_STOP,classify_interrupt,)+from jarvis.voice.instant_ack import (+ InstantAckPlan,+ WorkClass,+ all_instant_ack_lines,+ compose_contextual_ack,+ contextual_ack_is_valid,+ contextual_ack_prompt,+ instant_ack_pool,+ pick_instant_ack_text,+ plan_instant_ack,+)log = logging.getLogger(__name__)@@ -441,14 +452,21 @@ class _LoopLagProbe:)-# A realtime bridge is useful only for a genuinely long delegated turn. Providers-# with native tools can keep the longer threshold because their normal action-# path already stays inside the live model. A capability-limited provider must-# hand every action to the slower orchestrator, so waiting six seconds before it-# even acknowledges the request creates subscription-only dead air. Its earlier-# bridge is safe: ready results pre-empt the bridge lifecycle below.+# Instant acknowledgment (2026-08-17): the bridge is no longer a late "still+# on it" filler but the turn's FIRST sign of life. When the shared instant-ack+# planner (``jarvis.voice.instant_ack``) classifies the delegated work, the+# bridge fires at the class delay — immediately for research / screen /+# mission work, after ``_INSTANT_ACK_GRACE_S`` for short actions and memory+# reads so a fast result stays chatter-free — and speaks a line that names+# the KIND of work (closed pools) or, for actions, a model-composed line that+# names the request's own subject and passes the structural validator.+# ``_DELEGATE_BRIDGE_DELAY_S`` remains the delay for turns the planner cannot+# classify and the upper cap for every bridge (tests pin it low). A+# capability-limited provider hands every action to the slower orchestrator,+# so its cap is tighter still. Ready results pre-empt the bridge lifecycle._DELEGATE_BRIDGE_DELAY_S = 6.0_CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S = 1.0+_INSTANT_ACK_GRACE_S = 1.2# 20 messages, not 8: a failed screen action typically costs the user several# correction turns, and each background completion adds a context note. With 8,# the original task was trimmed out exactly when the recovery turn needed it@@ -875,6 +893,7 @@ def _delegate_result_prompt(language: str,success: bool,late: bool = False,+ already_said: str = "",) -> str:"""Wrap one trusted Brain result for tool-free native voice rendering.@@ -913,6 +932,18 @@ def _delegate_result_prompt(if lateelse "")+ spoken = str(already_said or "").strip()+ if spoken:+ # Instant acknowledgment (2026-08-17): the user already heard an+ # interim line for this very request. Continue from it -- a second+ # "let me check" or a re-announcement is the double-tap this exists+ # to avoid.+ framing += (+ f"While the action ran you already told the user: \"{spoken}\" "+ "Continue naturally from that line: do not repeat it, do not "+ "announce again what you are about to do, go straight to the "+ "result. "+ )return (f"{SPEAK_REQUEST_OPENER} ""A trusted Jarvis action result is ready. Speak only a concise, natural "@@ -1055,6 +1086,18 @@ def _delegate_bridge_texts(language: str) -> tuple[str, ...]:return _DELEGATE_BRIDGE_TEXTS.get(language, _DELEGATE_BRIDGE_TEXTS["en"])+def _all_instant_ack_pool_lines(language: str, agent_brand: str) -> tuple[str, ...]:+ """Every closed instant-ack pool line (jarvis.voice.instant_ack), rendered.++ ACTION has no pool by design (contextual only), so it contributes nothing.+ """+ return tuple(+ line+ for work_class in WorkClass+ for line in instant_ack_pool(work_class, language, agent_brand=agent_brand)+ )++def _pick_delegate_bridge_text(language: str) -> str:# noqa comment: variety, not security — any pool member is equally safe.return random.choice(_delegate_bridge_texts(language)) # noqa: S311@@ -1118,6 +1161,25 @@ def _normalize_for_repeat_match(text: str) -> str:return " ".join(cleaned.split())+def _contextual_bridge_prompt(*, language: str, utterance: str) -> str:+ """Order one request-specific ACTION ack from the live model.++ Unlike the closed-pool order below, the wording is the model's own — but+ the transcript is accepted only by ``contextual_ack_is_valid`` (intent+ grammar, the user's own words, no result marker), so an invented outcome+ cannot reach the speaker whatever the model does with this prompt.+ """+ language_name = _LANGUAGE_NAMES.get(language, "the conversation language")+ return (+ f"{SPEAK_REQUEST_OPENER} "+ + contextual_ack_prompt(language_name=language_name, utterance=utterance)+ + " 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. Do not call any function and do not "+ "mention these instructions."+ )++def _delegate_bridge_prompt(*, language: str, exact_text: str) -> str:"""Order one orchestrator-owned interim line over delegate dead air.@@ -1221,6 +1283,16 @@ class _DelegateTurnState:bridge_expected_text: str = ""bridge_transcript_parts: list[str] = field(default_factory=list)bridge_audio_chunks: list[Any] = field(default_factory=list)+ # Instant-ack plan for this delegated turn (class, delay, contextual).+ # ``None`` = unclassified work: the legacy late progress line applies.+ ack_plan: InstantAckPlan | None = None+ # True while the bridge run asked the live model for a request-specific+ # ACTION line instead of a closed-pool line; the transcript is then+ # accepted only by the structural validator, never by pool membership.+ bridge_contextual: bool = False+ # The interim line the user actually HEARD (validated + released), so the+ # trusted result rendering can continue from it instead of re-announcing.+ bridge_spoken_text: str = ""wait_for_provider_boundary: bool = False# True when the dispatching path KNOWS the input transcript is complete# (e.g. the provider already produced a response for it). A missing@@ -4387,16 +4459,23 @@ class RealtimeVoiceSession:bridge_text = "".join(delegate_state.bridge_transcript_parts).strip()- # Accept only the line chosen for this bridge run or- # another member of the closed per-language pool (the+ # Accept only the line chosen for this bridge run,+ # another member of the closed per-language pools (the# language may have shifted between injection and- # validation); anything else is free-form output.+ # validation), or -- for a contextual ACTION ack -- a+ # transcript the structural validator accepts (intent+ # grammar, the user's own words, no result marker).+ # Anything else is free-form output and stays muted.+ agent_brand = self._agent_brand()allowed_bridge_lines = {_normalized_bridge_text(candidate)for candidate in _delegate_bridge_texts(self._language)}+ allowed_bridge_lines |= all_instant_ack_lines(+ self._language, agent_brand=agent_brand+ )expected_bridge = (delegate_state.bridge_expected_textor next(iter(_delegate_bridge_texts(self._language)))@@ -4404,14 +4483,30 @@ class RealtimeVoiceSession:allowed_bridge_lines.add(_normalized_bridge_text(expected_bridge))+ contextual_ok = bool(+ delegate_state.bridge_contextual+ and bridge_text+ and contextual_ack_is_valid(+ bridge_text,+ utterance=delegate_state.user_text,+ language=self._language,+ extra_allowed_words=(agent_brand,),+ )+ )bridge_valid = bool(bridge_completedand (delegate_state.bridge_direct_speechor _normalized_bridge_text(bridge_text)in allowed_bridge_lines+ or contextual_ok))+ # A result that is ready BEFORE the first sample of the+ # line wins outright (no double-tap); a line that starts+ # playing finishes -- it is one short sentence, and a+ # mid-word cut is worse than a one-second wait for the+ # answer that follows on the provider's next response.bridge_may_speak = bool(bridge_validand not delegate_state.bridge_preempted@@ -4419,12 +4514,6 @@ class RealtimeVoiceSession:)if bridge_may_speak:for chunk in delegate_state.bridge_audio_chunks:- # The result can become ready between buffered- # chunks. Stop immediately rather than queueing- # progress audio ahead of the trusted answer.- if delegate_state.result_ready.is_set():- delegate_state.bridge_preempted = True- breakawait self._emit_audio(chunk)elif bridge_completed and bridge_text and not bridge_valid:log.warning(@@ -4455,19 +4544,24 @@ class RealtimeVoiceSession:# the final answer will open a new SPEAKING segment.await self._send_json({"type": "thinking"})if bridge_was_audible:- # Persist the pool line the model actually spoke,- # not merely the one requested for this run.+ # Persist the line the model actually spoke -- the+ # matched pool member, or the validated contextual+ # sentence -- not merely the one requested.spoken_bridge = next((candidate- for candidate in _delegate_bridge_texts(- self._language+ for candidate in (+ *_delegate_bridge_texts(self._language),+ *_all_instant_ack_pool_lines(+ self._language, agent_brand+ ),)if _normalized_bridge_text(candidate)== _normalized_bridge_text(bridge_text)),- expected_bridge,+ bridge_text if contextual_ok else expected_bridge,)+ delegate_state.bridge_spoken_text = spoken_bridgeawait self._publish_delegate_bridge_spoken(spoken_bridge)@@ -6120,6 +6214,15 @@ class RealtimeVoiceSession:if tracker is not None and phase not in tracker.stages_snapshot():tracker.mark(phase, detail=self._latency_detail(detail))+ def _agent_brand(self) -> str:+ """The wake-word-derived agent brand for spoken lines (never hardcoded)."""+ try:+ from jarvis.brain.assistant_name import agent_brand++ return agent_brand(self._config)+ except Exception: # noqa: BLE001 -- a spoken line must not depend on config shape+ return "Assistant-Agent"+def _mark_latency_named(self, phase_name: str, *, detail: str = "") -> Any | None:"""Mark optional telemetry without letting enum skew break voice."""try:@@ -7883,6 +7986,16 @@ class RealtimeVoiceSession:turn_state.deterministic = Trueturn_state.input_final = turn_state.input_final or bool(input_final)turn_state.user_text = str(user_text or "").strip()+ if turn_state.ack_plan is None:+ # The instant-ack class is decided HERE, at dispatch, from the+ # same deterministic plan that routed the turn — never from what+ # the model says later.+ plan_for_ack = (+ turn_plan+ if turn_plan is not None+ else self._plan_turn(turn_state.user_text)+ )+ turn_state.ack_plan = plan_instant_ack(plan_for_ack, turn_state.user_text)if turn_plan is not None and turn_plan.requires_public_fact_grounding:turn_state.requires_public_fact_grounding = Trueturn_state.public_fact_grounding_timeout_s = float(@@ -8036,21 +8149,33 @@ class RealtimeVoiceSession:turn_id: str,turn_state: _DelegateTurnState,) -> None:- """Speak one interim line when a delegated action outlasts patience.-- The bridge is realtime-only and deliberately later than the classic- pipeline acknowledgement: normal delegated turns should finish before- it. Its provider output is buffered and accepted only when the complete- transcript matches the progress line chosen for this run (or another- member of the closed localized pool). A ready trusted result preempts- the bridge lifecycle.+ """Speak the turn's first sign of life while the delegate is running.++ Instant acknowledgment (2026-08-17): the delay comes from the+ instant-ack plan decided at dispatch — immediately for long work+ (research, screen, mission), after a short grace for actions and+ memory reads so a fast result stays chatter-free — capped by the+ legacy ``_DELEGATE_BRIDGE_DELAY_S`` (which alone applies to+ unclassified turns). The line names the KIND of work from a closed+ pool, or for actions is a model-composed line naming the request's+ subject; its provider output is buffered and accepted only when the+ complete transcript is a closed-pool member or passes the structural+ contextual validator. A trusted result that is ready before the line+ was released preempts it; a line already playing finishes."""try:+ capability_limited = not bool(+ getattr(self._provider, "supports_direct_tools", True)+ )bridge_delay_s = (_CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S- if not bool(getattr(self._provider, "supports_direct_tools", True))+ if capability_limitedelse _DELEGATE_BRIDGE_DELAY_S)+ plan = turn_state.ack_plan+ if plan is not None:+ planned_delay_s = 0.0 if plan.immediate else _INSTANT_ACK_GRACE_S+ bridge_delay_s = min(bridge_delay_s, planned_delay_s)try:await asyncio.wait_for(turn_state.result_ready.wait(),@@ -8077,13 +8202,46 @@ class RealtimeVoiceSession:)if not authoritative_speech and not callable(send_text):return+ contextual = bool(plan is not None and plan.contextual)+ if contextual and authoritative_speech:+ # A verbatim direct-speech channel cannot compose; ask the+ # flash composer the Brain already carries (bounded, breaker+ # guarded). No composer or no valid line -> stay silent: a+ # stock line is exactly what an ACTION ack must not be, and+ # the result speaks for itself.+ composed = await compose_contextual_ack(+ getattr(self._brain, "_readback_composer", None),+ utterance=turn_state.user_text,+ language=self._language,+ agent_brand=self._agent_brand(),+ )+ if self._delegate_bridge_must_stand_down(turn_id, turn_state):+ return+ if not composed:+ log.debug(+ "realtime[%s] instant ack skipped: no valid contextual "+ "action line for a verbatim-speech transport",+ self.session_id,+ )+ return+ bridge_line = composed+ elif contextual:+ bridge_line = ""+ elif plan is not None:+ bridge_line = pick_instant_ack_text(+ plan.work_class,+ self._language,+ agent_brand=self._agent_brand(),+ )+ else:+ bridge_line = _pick_delegate_bridge_text(self._language)turn_state.bridge_delivery_started = Trueturn_state.bridge_preempted = Falseturn_state.bridge_direct_speech = Falseturn_state.bridge_direct_audio_emitted = False- turn_state.bridge_expected_text = _pick_delegate_bridge_text(- self._language- )+ turn_state.bridge_contextual = contextual+ turn_state.bridge_spoken_text = ""+ turn_state.bridge_expected_text = bridge_lineturn_state.bridge_transcript_parts.clear()turn_state.bridge_audio_chunks.clear()# The bridge renderer starts a distinct provider response. The@@ -8101,6 +8259,13 @@ class RealtimeVoiceSession:slot=f"bridge:{turn_id}",)await send_speech(turn_state.bridge_expected_text)+ elif contextual:+ await send_text(+ _contextual_bridge_prompt(+ language=self._language,+ utterance=turn_state.user_text,+ )+ )else:await send_text(_delegate_bridge_prompt(@@ -8117,10 +8282,23 @@ class RealtimeVoiceSession:exc_info=True,)return+ self._mark_latency_named(+ "REALTIME_DELEGATE_BRIDGE_REQUESTED",+ detail=(+ f"class={plan.work_class.value if plan is not None else 'unclassified'};"+ f"delay_s={bridge_delay_s:.2f};contextual={contextual}"+ ),+ )log.info(- "realtime[%s] delegate bridge: interim line requested while "- "the action is still running",+ "realtime[%s] delegate bridge: %s line requested %.2f s after "+ "dispatch while the action is still running",self.session_id,+ (+ "contextual action"+ if contextual+ else (plan.work_class.value if plan is not None else "progress")+ ),+ bridge_delay_s,)except asyncio.CancelledError:raise@@ -8349,13 +8527,20 @@ class RealtimeVoiceSession:*,timeout_s: float,language: str,+ speak_ack: bool = True,) -> tuple[str, bool]:- """Execute exactly one bounded search, then synthesize without tools."""+ """Execute exactly one bounded search, then synthesize without tools.++ ``speak_ack=False`` when the instant-ack bridge already owns the+ turn's first sign of life (one voice per call): the legacy surface-TTS+ line read the whole question back in a second voice.+ """uncertainty = _PUBLIC_FACT_UNCERTAINTY.get(language,_PUBLIC_FACT_UNCERTAINTY["en"],)- await self._speak_public_fact_ack(query, language=language)+ if speak_ack:+ await self._speak_public_fact_ack(query, language=language)try:from jarvis.core import runtime_refsfrom jarvis.core.protocols import SupervisorToolRequest@@ -8513,6 +8698,7 @@ class RealtimeVoiceSession:user_text,timeout_s=turn_state.public_fact_grounding_timeout_s,language=turn_language,+ speak_ack=turn_state.ack_plan is None,)turn_state.last_reply = replyresult = {@@ -8691,6 +8877,7 @@ class RealtimeVoiceSession:trusted_reply,language=turn_language,success=succeeded,+ already_said=turn_state.bridge_spoken_text,))except Exception: # noqa: BLE001 — preserve an honest surface fallbackdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex fb07170e0c..60e4113e21 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -49,6 +49,7 @@ from jarvis.audio.player import AudioPlayerfrom jarvis.audio.vad import SileroEndpointerfrom jarvis.audio.vad_reasons import FORCED_CUT_REASONSfrom jarvis.brain.output_filter import scrub_for_voice+from jarvis.brain.turn_planner import plan_turnfrom jarvis.core.events import (CU_PROGRESS_EVENTS,DICTATION_REFUSAL_REASONS,@@ -147,6 +148,14 @@ from jarvis.speech.wake_verifier import ()from jarvis.telemetry.latency import LatencyPhase, LatencyTrackerfrom jarvis.trigger.hotkey import HotkeyTrigger+from jarvis.voice.instant_ack import (+ PROGRESS_AFTER_S,+ InstantAckPlan,+ compose_contextual_ack,+ note_spoken,+ pick_instant_ack_text,+ plan_instant_ack,+)if TYPE_CHECKING:from jarvis.core.bus import EventBus@@ -2603,7 +2612,10 @@ class SpeechPipeline:# apart, while the mission is in flight — hard-bounded so it can never run# forever (the in-flight hold equals the watchdog lifetime, see# _live_spawn_watchdogs). Tests override these.- self._spawn_watchdog_delay_s: float = 30.0+ # 30 -> 20 s (2026-08-17, instant-ack contract): the user heard the+ # handover line at the start; twenty seconds of nothing afterwards+ # is where "is it still working?" begins.+ self._spawn_watchdog_delay_s: float = 20.0self._heartbeat_interval_s: float = 60.0self._heartbeat_max_count: int = 3self._heartbeat_recent: deque[str] = deque(maxlen=2)@@ -4432,9 +4444,28 @@ class SpeechPipeline:# the Flash-Brain streaming path uses); a turn that answers within# the grace stays ack-free. Announcements arriving with no voice turn# in flight (chat path) keep legacy behavior.+ source_layer = getattr(event, "source_layer", None)+ is_instant_ack = bool(+ is_preamble and source_layer == self._INSTANT_ACK_SOURCE_LAYER+ )if (is_preamble- and getattr(event, "source_layer", None) == "brain.router.ack"+ and source_layer == "brain.router.ack"+ and self._instant_ack_spoke_recently(PROGRESS_AFTER_S)+ ):+ # Instant acknowledgment (2026-08-17): the user just heard the+ # turn's first line. A second "let me check" seconds later is the+ # double-tap; the grounded router ack is welcome again only once+ # the wait has grown long enough to deserve a progress line.+ log.info(+ "Grounded ack dropped — instant ack spoken %.1fs ago: %r",+ time.monotonic() - float(getattr(self, "_instant_ack_spoken_at", 0.0)),+ event.text[:80],+ )+ return+ if (+ is_preamble+ and source_layer == "brain.router.ack"and getattr(self, "_turn_state", TurnTakingState.IDLE)is TurnTakingState.PROCESSING):@@ -4502,7 +4533,8 @@ class SpeechPipeline:spoken_text = scrubbed.cleaned.strip()last_spoken = getattr(self, "_last_preamble_spoken", None)if (- dedup_window_s > 0+ not is_instant_ack+ and dedup_window_s > 0and last_spoken is not Noneand last_spoken[0] == spoken_textand (time.monotonic() - last_spoken[1]) < dedup_window_s@@ -4526,7 +4558,11 @@ class SpeechPipeline:spoken_times = deque(maxlen=32)self._preamble_spoken_times = spoken_timesnow_monotonic = time.monotonic()- if rate_limit > 0:+ # The instant ack is exempt from the anti-loop cap: it is armed+ # exactly once per user utterance and cancels its predecessor, so+ # it cannot loop -- and a user issuing four commands in a minute+ # deserves four first-signs-of-life (maintainer rule 2026-08-17).+ if rate_limit > 0 and not is_instant_ack:recent_count = sum(1 for t in spoken_times if now_monotonic - t < 60.0)@@ -4538,7 +4574,12 @@ class SpeechPipeline:)returnself._last_preamble_spoken = (spoken_text, now_monotonic)- spoken_times.append(now_monotonic)+ if is_instant_ack:+ # Not counted against the cap either: one instant line must+ # never eat the budget of a later owed progress line.+ self._note_instant_ack_spoken(spoken_text)+ else:+ spoken_times.append(now_monotonic)if await self._deliver_announcement_via_realtime(event,text=scrubbed.cleaned,@@ -4721,6 +4762,137 @@ class SpeechPipeline:)return accepted+ # ------------------------------------------------------------------+ # Instant acknowledgment (2026-08-17)+ # ------------------------------------------------------------------++ _INSTANT_ACK_SOURCE_LAYER = "brain.instant_ack"++ def _instant_ack_enabled(self) -> bool:+ ack_cfg = getattr(getattr(self, "_config", None), "ack_brain", None)+ return bool(getattr(ack_cfg, "instant_ack", True))++ def _agent_brand_name(self) -> str:+ """Wake-word-derived agent brand for spoken lines (never hardcoded)."""+ try:+ from jarvis.brain.assistant_name import agent_brand++ return agent_brand(getattr(self, "_config", None))+ except Exception: # noqa: BLE001 — a spoken line must not depend on config shape+ return "Assistant-Agent"++ def _arm_instant_ack(self, text: str, language: str) -> None:+ """Schedule the instant ack for a heavy turn; a no-op for plain talk.++ The plan comes from the same deterministic planner the brain uses+ (regex, no I/O). Long work (research, screen, mission) speaks at+ once; short work (an action, a personal lookup) waits a grace window+ and speaks only if the turn is STILL processing — a fast result stays+ chatter-free. Actions get a request-specific line from the flash+ composer or nothing (maintainer rule: no stock "on it" for actions).+ """+ seq = int(getattr(self, "_instant_ack_turn_seq", 0)) + 1+ self._instant_ack_turn_seq = seq+ previous = getattr(self, "_instant_ack_task", None)+ if previous is not None and not previous.done():+ previous.cancel()+ self._instant_ack_task = None+ if not self._instant_ack_enabled():+ return+ try:+ from jarvis.brain.ack_generator import is_voice_control_utterance++ if is_voice_control_utterance(text):+ return+ plan = plan_instant_ack(plan_turn(text), text)+ except Exception: # noqa: BLE001 — planning must never break the turn+ log.debug("Instant ack: planning failed", exc_info=True)+ return+ if plan is None:+ return+ log.info(+ "Instant ack armed: class=%s delay=%.1fs contextual=%s",+ plan.work_class.value,+ plan.delay_s,+ plan.contextual,+ )+ self._instant_ack_task = asyncio.create_task(+ self._instant_ack_body(plan, text, language, seq),+ name="instant-ack",+ )++ async def _instant_ack_body(+ self, plan: InstantAckPlan, text: str, language: str, seq: int+ ) -> None:+ try:+ if plan.delay_s > 0:+ if not await self._await_ack_turn_commit(int(plan.delay_s * 1000)):+ log.info(+ "Instant ack dropped — turn left PROCESSING inside the "+ "%.1fs grace (class=%s)",+ plan.delay_s,+ plan.work_class.value,+ )+ return+ if not self._instant_ack_still_wanted(seq):+ return+ if plan.contextual:+ line = await compose_contextual_ack(+ getattr(self._brain, "_readback_composer", None),+ utterance=text,+ language=language,+ agent_brand=self._agent_brand_name(),+ )+ if not line:+ log.info(+ "Instant ack skipped — no valid contextual line for the "+ "action (no composer, timeout, or rejected output)"+ )+ return+ else:+ line = pick_instant_ack_text(+ plan.work_class, language, agent_brand=self._agent_brand_name()+ )+ if not line or not self._instant_ack_still_wanted(seq):+ return+ tracker = getattr(self, "_latency_tracker", None)+ if tracker is not None:+ try:+ tracker.mark(LatencyPhase.ACK_FIRST_TOKEN)+ except Exception: # noqa: BLE001, S110 — telemetry never breaks voice+ pass+ await self._publish_event(+ AnnouncementRequested(+ source_layer=self._INSTANT_ACK_SOURCE_LAYER,+ text=line,+ priority="normal",+ language=language,+ kind="preamble",+ )+ )+ except asyncio.CancelledError:+ raise+ except Exception: # noqa: BLE001 — the ack is best-effort by design+ log.warning("Instant ack failed", exc_info=True)++ def _instant_ack_still_wanted(self, seq: int) -> bool:+ """The line is only coherent while THIS turn is still thinking."""+ if int(getattr(self, "_instant_ack_turn_seq", 0)) != seq:+ return False+ if getattr(self, "_turn_state", TurnTakingState.IDLE) is not TurnTakingState.PROCESSING:+ return False+ return not bool(getattr(self, "_brain_first_frame_played", False))++ def _note_instant_ack_spoken(self, text: str) -> None:+ """Record the moment an instant ack actually went to the speaker."""+ self._instant_ack_spoken_at = time.monotonic()+ self._instant_ack_spoken_text = text+ note_spoken(text)++ def _instant_ack_spoke_recently(self, within_s: float) -> bool:+ spoken_at = getattr(self, "_instant_ack_spoken_at", None)+ return spoken_at is not None and (time.monotonic() - spoken_at) < within_s+async def _await_ack_turn_commit(self, grace_ms: int) -> bool:"""Poll the turn-state for up to ``grace_ms``; True only if it staysPROCESSING throughout — the continuation grace from AD-OE5.@@ -12757,6 +12929,12 @@ class SpeechPipeline:name="flash-brain-ack",)+ # Instant acknowledgment (2026-08-17): the turn's first sign of life+ # for heavy work, decided HERE from the deterministic turn plan —+ # never after the router's first model round. See+ # jarvis/voice/instant_ack.py for the contract.+ self._arm_instant_ack(text, lang)+# Latenz-Sprint-1: Streaming-Pfad — Brain-Output wird Satz-fuer-Satz# an die TTS gereicht waehrend das Brain noch generiert. Speakt# selbst; danach return ohne den klassischen Filter+_speak-Pfad.diff --git a/jarvis/voice/instant_ack.py b/jarvis/voice/instant_ack.pynew file mode 100644index 0000000000..40c98aca6b--- /dev/null+++ b/jarvis/voice/instant_ack.py@@ -0,0 +1,1036 @@+"""Instant acknowledgment for heavy voice turns — the "under two seconds" contract.++When a user request needs the Tool Model or a background agent, the user+waits 5-30 s for the result. Nobody waits that long for a conversation partner+without a sign of life, so the orchestrator speaks ONE short line first that+says what Jarvis is DOING (never what it found). This module is the shared,+provider-neutral core used by BOTH voice engines:++- the classic speech pipeline (``jarvis/speech/pipeline.py``) speaks the line+ through its own TTS queue;+- the realtime session (``jarvis/realtime/session.py``) lets the LIVE model+ voice the line (one voice per call, BUG-090) and validates its transcript.++Design constraints, each of which killed an earlier attempt:++1. **Trigger = the moment heavy work is committed, never a model's guess.**+ :func:`plan_instant_ack` derives the work class from the deterministic+ :class:`~jarvis.brain.turn_planner.TurnPlan` (regex, no I/O), so the+ decision exists at t≈0 — not after the router's first model round+ (BUG-051) and not after a fixed 6 s of silence.+2. **State only what Jarvis is doing.** The closed per-class pools below+ name the kind of work ("checking your records", "looking that up online").+ A model-composed line is allowed ONLY for the ACTION class and ONLY when+ :func:`contextual_ack_is_valid` accepts it: intent grammar, at most 12+ words, every content word taken from the user's own request, no result+ markers, no numbers. An invented outcome needs new content words or a+ non-intent verb and is therefore structurally impossible (BUG-054).+3. **No double-tap.** Each class carries an expected duration; short work+ gets a grace window and only speaks if it is still running.+4. **No stock filler for actions.** The maintainer's rule (2026-08-17): an+ action ack must reference the request ("I'm opening Spotify."), never a+ canned "On it." — so the ACTION pool is deliberately empty and the class+ is marked ``contextual``.++German/Spanish strings below are runtime voice output (CLAUDE.md §1).+"""++from __future__ import annotations++import random+import re+import time+import unicodedata+from collections import deque+from dataclasses import dataclass+from enum import StrEnum++from jarvis.brain.turn_planner import TurnPlan, TurnReason, is_lookup_shape++_SUPPORTED_LANGUAGES = ("de", "en", "es")+_DEFAULT_LANGUAGE = "en"++#: Grace window for SHORT work: speak only if the turn is still running+#: afterwards. 1.2 s covers the local fast paths (local-action gate, wiki+#: ingest, navigation) and a single-round Tool Model answer on a warm+#: provider; anything slower deserves the line.+SHORT_GRACE_S = 1.2+#: LONG work (web research, screen control, missions) never finishes inside+#: the ack itself — speak immediately.+IMMEDIATE_DELAY_S = 0.0+#: One grounded progress line if the work outlasts the ack by this much.+PROGRESS_AFTER_S = 8.0++_MAX_CONTEXTUAL_WORDS = 12+_MIN_CONTEXTUAL_WORDS = 2+_MAX_INTENT_VERB_POSITION = 4+_INFLECTION_PREFIX_CHARS = 4+++class WorkClass(StrEnum):+ """What kind of heavy work the turn committed to (drives the ack line)."""++ RESEARCH = "research" # web / current / connected data lookups+ PERSONAL = "personal" # the user's own world: notes, mail, calendar, past (read)+ SCREEN = "screen" # look at or operate the screen+ MISSION = "mission" # background agent+ ACTION = "action" # do something concrete — contextual line only+++@dataclass(frozen=True, slots=True)+class InstantAckPlan:+ """Provider-neutral decision for one turn."""++ work_class: WorkClass+ delay_s: float+ contextual: bool++ @property+ def immediate(self) -> bool:+ return self.delay_s <= 0.0+++def plan_instant_ack(turn_plan: TurnPlan | None, utterance: str = "") -> InstantAckPlan | None:+ """Return the ack plan for a turn, or ``None`` when no ack is warranted.++ ``None`` covers plain conversation (no orchestrator), voice control, and+ orchestrator turns whose only reasons are too vague to promise anything+ honest (``UNCERTAIN`` / ``WORKSPACE`` / ``CAPABILITY`` / ``SKILL`` alone).+ """+ if turn_plan is None or not turn_plan.requires_orchestrator:+ return None+ reasons = set(turn_plan.reasons)+ if TurnReason.MISSION in reasons:+ return InstantAckPlan(WorkClass.MISSION, IMMEDIATE_DELAY_S, False)+ if TurnReason.SCREEN_CONTEXT in reasons:+ return InstantAckPlan(WorkClass.SCREEN, IMMEDIATE_DELAY_S, False)+ if TurnReason.PRIVATE_DATA in reasons and is_lookup_shape(utterance):+ # A recall QUESTION ("do you remember", "what's in my notes") carries+ # the planner's ACTION reason too (``remember`` is a save verb), but+ # the user is asking, not ordering: the personal-lookup pool line fits+ # and needs no composer. A connected lookup (calendar, mail) never+ # finishes inside the grace, so it speaks at once; a wiki recall may+ # hit the local fast path and gets the grace.+ connected = bool(TurnReason.CONNECTED_DATA in reasons or TurnReason.CURRENT_DATA in reasons)+ return InstantAckPlan(+ WorkClass.PERSONAL,+ IMMEDIATE_DELAY_S if connected else SHORT_GRACE_S,+ False,+ )+ if TurnReason.ACTION in reasons:+ return InstantAckPlan(WorkClass.ACTION, SHORT_GRACE_S, True)+ if (+ TurnReason.CURRENT_DATA in reasons+ or TurnReason.CONNECTED_DATA in reasons+ or turn_plan.requires_public_fact_grounding+ or TurnReason.PUBLIC_FACT in reasons+ ):+ return InstantAckPlan(WorkClass.RESEARCH, IMMEDIATE_DELAY_S, False)+ if TurnReason.PRIVATE_DATA in reasons:+ return InstantAckPlan(WorkClass.PERSONAL, SHORT_GRACE_S, False)+ return None+++# ---------------------------------------------------------------------------+# Closed pools — what Jarvis is doing, never what it found.+# ---------------------------------------------------------------------------++# i18n-allow: localized runtime voice output (whole table)+_POOLS: dict[WorkClass, dict[str, tuple[str, ...]]] = {+ WorkClass.RESEARCH: {+ "de": ( # i18n-allow: localized runtime voice output+ "Ich suche das gerade online.", # i18n-allow+ "Moment, ich schaue online nach.", # i18n-allow+ "Ich hole mir dazu aktuelle Infos.", # i18n-allow+ "Kurze Online-Suche, einen Moment.", # i18n-allow+ ),+ "en": (+ "I'm looking that up online.",+ "One moment, checking online.",+ "Let me pull the latest on that.",+ "Quick online search, one moment.",+ ),+ "es": ( # i18n-allow: localized runtime voice output+ "Lo estoy buscando en línea.",+ "Un momento, lo consulto en línea.",+ "Estoy buscando información actual.",+ "Una búsqueda rápida, un momento.",+ ),+ },+ WorkClass.PERSONAL: {+ "de": ( # i18n-allow: localized runtime voice output+ "Ich schaue kurz in deinen Unterlagen nach.", # i18n-allow+ "Moment, ich sehe in deinen Sachen nach.", # i18n-allow+ "Ich suche das bei dir raus.", # i18n-allow+ "Ich schaue nach, was ich dazu von dir habe.", # i18n-allow+ ),+ "en": (+ "I'm checking your records.",+ "One moment, looking through your things.",+ "Let me find that in your data.",+ "Checking what I have from you on that.",+ ),+ "es": ( # i18n-allow: localized runtime voice output+ "Estoy revisando tus registros.",+ "Un momento, miro en tus cosas.",+ "Busco eso en tus datos.",+ "Reviso lo que tengo tuyo sobre eso.",+ ),+ },+ WorkClass.SCREEN: {+ "de": ( # i18n-allow: localized runtime voice output+ "Ich schaue mir den Bildschirm an.", # i18n-allow+ "Moment, ich sehe mir den Bildschirm an.", # i18n-allow+ "Ich übernehme kurz den Bildschirm.", # i18n-allow+ "Ich schaue, was auf dem Bildschirm ist.", # i18n-allow+ ),+ "en": (+ "I'm looking at the screen.",+ "One moment, checking the screen.",+ "I'll take the screen for a moment.",+ "Let me see what's on screen.",+ ),+ "es": ( # i18n-allow: localized runtime voice output+ "Estoy mirando la pantalla.",+ "Un momento, reviso la pantalla.",+ "Tomo la pantalla un momento.",+ "Veo qué hay en pantalla.",+ ),+ },+ # ``{agent}`` is the wake-word-derived agent brand ("<Name>-Agent"),+ # rendered by the caller — never a hardcoded product name (CLAUDE.md §4).+ WorkClass.MISSION: {+ "de": ( # i18n-allow: localized runtime voice output+ "Das gebe ich einem {agent} weiter.", # i18n-allow+ "Ein {agent} übernimmt das, ich melde mich.", # i18n-allow+ "Ich setze einen {agent} darauf an.", # i18n-allow+ "Das läuft ab jetzt bei einem {agent}.", # i18n-allow+ ),+ "en": (+ "I'm handing that to a {agent}.",+ "A {agent} will take that, I'll report back.",+ "I'm putting a {agent} on it.",+ "That's with a {agent} from now on.",+ ),+ "es": ( # i18n-allow: localized runtime voice output+ "Se lo paso a un {agent}.",+ "Un {agent} se encarga, te aviso.",+ "Pongo a un {agent} en ello.",+ "Eso queda con un {agent} desde ahora.",+ ),+ },+ # ACTION: deliberately empty — an action ack must reference the request.+ WorkClass.ACTION: {"de": (), "en": (), "es": ()},+}++# No-repeat memory per (class, language): back-to-back acks never share a+# wording. Module-level on purpose — both voice engines draw from one memory.+_RECENT: dict[tuple[WorkClass, str], deque[str]] = {}+_RECENT_DEPTH = 2+++def _language_key(language: str) -> str:+ code = (language or "").strip().lower()[:2]+ return code if code in _SUPPORTED_LANGUAGES else _DEFAULT_LANGUAGE+++def instant_ack_pool(+ work_class: WorkClass, language: str, *, agent_brand: str = ""+) -> tuple[str, ...]:+ """Closed pool for ``work_class`` in ``language`` (rendered, brand filled)."""+ raw = _POOLS.get(work_class, {}).get(_language_key(language), ())+ if work_class is WorkClass.MISSION:+ brand = (agent_brand or "").strip() or "Assistant-Agent"+ return tuple(line.format(agent=brand) for line in raw)+ return tuple(raw)+++def pick_instant_ack_text(work_class: WorkClass, language: str, *, agent_brand: str = "") -> str:+ """Pick one pool line, avoiding the most recent wordings. ``""`` when none."""+ pool = instant_ack_pool(work_class, language, agent_brand=agent_brand)+ if not pool:+ return ""+ key = (work_class, _language_key(language))+ recent = _RECENT.setdefault(key, deque(maxlen=_RECENT_DEPTH))+ candidates = [line for line in pool if line not in recent] or list(pool)+ # noqa comment: variety, not security — any pool member is equally safe.+ chosen = random.choice(candidates) # noqa: S311+ recent.append(chosen)+ return chosen+++def normalize_ack_line(text: str) -> str:+ """Casefold + collapse whitespace + drop trailing punctuation (transcript match)."""+ return " ".join(str(text or "").strip().rstrip(".!?¡¿").casefold().split())+++def all_instant_ack_lines(language: str, *, agent_brand: str = "") -> frozenset[str]:+ """Every closed-pool line for ``language``, normalized — the transcript whitelist."""+ lines: set[str] = set()+ for work_class in WorkClass:+ for line in instant_ack_pool(work_class, language, agent_brand=agent_brand):+ lines.add(normalize_ack_line(line))+ return frozenset(lines)+++# ---------------------------------------------------------------------------+# Contextual (ACTION) line — structural validator+# ---------------------------------------------------------------------------+++def _fold(text: str) -> str:+ """Casefold, strip diacritics, and unify apostrophes for token comparison."""+ folded = unicodedata.normalize("NFKD", str(text or "").casefold())+ folded = "".join(ch for ch in folded if not unicodedata.combining(ch))+ return folded.replace("’", "'").replace("`", "'")+++_TOKEN_RE = re.compile(r"[a-z0-9]+(?:'[a-z]+)?", re.IGNORECASE)+++def _tokens(text: str) -> list[str]:+ return _TOKEN_RE.findall(_fold(text))+++# Verbs that make a sentence an INTENT ("I'm opening …"), per language. A+# contextual ack must carry one of these within its first few tokens; a result+# claim ("Spotify is open") has none and is rejected on grammar alone.+# i18n-allow: multilingual output-grammar data+_INTENT_VERBS: dict[str, frozenset[str]] = {+ "de": frozenset(+ {+ "offne",+ "offnen",+ "mache",+ "mach",+ "starte",+ "schaue",+ "schau",+ "gucke",+ "suche",+ "such",+ "hole",+ "hol",+ "prufe",+ "pruf",+ "checke",+ "lese",+ "les",+ "schreibe",+ "schreib",+ "trage",+ "trag",+ "schicke",+ "schick",+ "sende",+ "stelle",+ "stell",+ "schalte",+ "schalt",+ "spiele",+ "spiel",+ "rufe",+ "ruf",+ "gebe",+ "geb",+ "kummere",+ "kummer",+ "erledige",+ "ubernehme",+ "gehe",+ "leite",+ "richte",+ "lege",+ "leg",+ "setze",+ "setz",+ "aktiviere",+ "deaktiviere",+ "wechsle",+ "wechsel",+ "andere",+ "speichere",+ "speicher",+ "notiere",+ "merke",+ "merk",+ "frage",+ "frag",+ "buche",+ "buch",+ "sage",+ "sag",+ "teile",+ "teil",+ "informiere",+ "melde",+ "melden",+ "ubergebe",+ "reiche",+ "tippe",+ "tipp",+ "klicke",+ "klick",+ "schliesse",+ "schließe",+ "verschiebe",+ "kopiere",+ "losche",+ "lösche",+ "erstelle",+ "installiere",+ "aktualisiere",+ "stoppe",+ "stopp",+ "pausiere",+ "diktiere",+ "nehme",+ "plane",+ "erinnere",+ "beende",+ "lade",+ "lad",+ }+ ),+ "en": frozenset(+ {+ "open",+ "opening",+ "start",+ "starting",+ "check",+ "checking",+ "look",+ "looking",+ "search",+ "searching",+ "get",+ "getting",+ "read",+ "reading",+ "write",+ "writing",+ "send",+ "sending",+ "set",+ "setting",+ "switch",+ "switching",+ "play",+ "playing",+ "call",+ "calling",+ "run",+ "running",+ "take",+ "taking",+ "pull",+ "pulling",+ "save",+ "saving",+ "add",+ "adding",+ "put",+ "putting",+ "launch",+ "launching",+ "turn",+ "turning",+ "bring",+ "bringing",+ "book",+ "booking",+ "tell",+ "telling",+ "ask",+ "asking",+ "note",+ "noting",+ "change",+ "changing",+ "handle",+ "handling",+ "do",+ "doing",+ "work",+ "working",+ "queue",+ "queuing",+ "hand",+ "handing",+ "pass",+ "passing",+ "give",+ "giving",+ "brief",+ "briefing",+ "prompt",+ "prompting",+ "kick",+ "kicking",+ "type",+ "typing",+ "click",+ "clicking",+ "close",+ "closing",+ "move",+ "moving",+ "copy",+ "copying",+ "delete",+ "deleting",+ "create",+ "creating",+ "install",+ "installing",+ "update",+ "updating",+ "restart",+ "restarting",+ "stop",+ "stopping",+ "mute",+ "muting",+ "pause",+ "pausing",+ "resume",+ "resuming",+ "dictate",+ "dictating",+ "record",+ "recording",+ "schedule",+ "scheduling",+ "remind",+ "reminding",+ }+ ),+ "es": frozenset(+ {+ "abro",+ "voy",+ "busco",+ "miro",+ "reviso",+ "leo",+ "escribo",+ "envio",+ "mando",+ "pongo",+ "cambio",+ "llamo",+ "guardo",+ "ejecuto",+ "tomo",+ "anoto",+ "activo",+ "desactivo",+ "inicio",+ "arranco",+ "consulto",+ "preparo",+ "reservo",+ "pregunto",+ "hago",+ "empiezo",+ "paso",+ "doy",+ "cierro",+ "muevo",+ "copio",+ "borro",+ "creo",+ "instalo",+ "actualizo",+ "reinicio",+ "paro",+ "detengo",+ "pauso",+ "reanudo",+ "dicto",+ "grabo",+ "programo",+ "recuerdo",+ "termino",+ }+ ),+}++# Function words, politeness, and time adverbs a contextual line may use+# freely — none of them can carry a fact.+# i18n-allow: multilingual output-grammar data+_FREE_WORDS: dict[str, frozenset[str]] = {+ "de": frozenset(+ {+ "ich",+ "das",+ "dir",+ "dich",+ "fur",+ "kurz",+ "mal",+ "gleich",+ "jetzt",+ "sofort",+ "gerade",+ "eben",+ "einen",+ "eine",+ "ein",+ "einem",+ "einer",+ "den",+ "die",+ "der",+ "dem",+ "des",+ "in",+ "im",+ "ins",+ "auf",+ "an",+ "am",+ "zu",+ "zum",+ "zur",+ "mit",+ "bei",+ "beim",+ "von",+ "vom",+ "und",+ "es",+ "ja",+ "okay",+ "ok",+ "klar",+ "gut",+ "alles",+ "moment",+ "bitte",+ "sekunde",+ "gern",+ "gerne",+ "dann",+ "so",+ "noch",+ "doch",+ "schon",+ "wird",+ "werde",+ "will",+ "kann",+ "lass",+ "mich",+ "mir",+ "dein",+ "deine",+ "deinen",+ "deinem",+ "deiner",+ "dazu",+ "damit",+ "drauf",+ "darauf",+ "daran",+ "drum",+ "darum",+ "los",+ "direkt",+ "schnell",+ "nach",+ "aus",+ "ab",+ "um",+ "uber",+ "durch",+ "hier",+ "da",+ "dort",+ "wie",+ "gewunscht",+ "naturlich",+ "sehr",+ "einmal",+ "erst",+ "nun",+ "mache",+ "ich's",+ "ichs",+ "auch",+ "dass",+ "ob",+ "wenn",+ "soll",+ "sollen",+ "sich",+ "ihn",+ "ihm",+ "ihr",+ "ihnen",+ "er",+ "sie",+ }+ ),+ "en": frozenset(+ {+ "i",+ "i'm",+ "im",+ "am",+ "will",+ "i'll",+ "ill",+ "let",+ "me",+ "that",+ "this",+ "it",+ "the",+ "a",+ "an",+ "for",+ "you",+ "your",+ "up",+ "on",+ "in",+ "to",+ "of",+ "at",+ "now",+ "right",+ "away",+ "just",+ "quickly",+ "quick",+ "one",+ "moment",+ "sec",+ "second",+ "okay",+ "ok",+ "sure",+ "alright",+ "all",+ "and",+ "then",+ "going",+ "gonna",+ "about",+ "into",+ "with",+ "over",+ "off",+ "out",+ "down",+ "as",+ "asked",+ "requested",+ "straight",+ "here",+ "there",+ "so",+ "yes",+ "yeah",+ "please",+ "course",+ "way",+ "onto",+ "them",+ "those",+ "these",+ "back",+ "again",+ "first",+ "already",+ "next",+ "should",+ "if",+ "whether",+ "he",+ "she",+ "him",+ "her",+ "his",+ "its",+ }+ ),+ "es": frozenset(+ {+ "yo",+ "a",+ "lo",+ "la",+ "el",+ "los",+ "las",+ "un",+ "una",+ "unos",+ "unas",+ "en",+ "de",+ "del",+ "al",+ "para",+ "por",+ "con",+ "te",+ "tu",+ "tus",+ "ti",+ "ahora",+ "mismo",+ "ya",+ "momento",+ "vale",+ "claro",+ "eso",+ "esto",+ "y",+ "que",+ "se",+ "me",+ "enseguida",+ "rapido",+ "rapida",+ "si",+ "bien",+ "sobre",+ "hacia",+ "desde",+ "esta",+ "este",+ "aqui",+ "alli",+ "primero",+ "luego",+ "todo",+ "como",+ "pediste",+ "pedido",+ "voy",+ }+ ),+}++# A completion / result claim in an ack is the one thing that must never+# pass, however short. Present-perfect and copula-state shapes per language.+# i18n-allow: multilingual output matcher+_RESULT_MARKER_RE = re.compile(+ r"(?:"+ r"\b(?:ist|sind|war|waren)\s+(?:jetzt\s+|nun\s+|bereits\s+|schon\s+)?"+ r"(?:offen|geoffnet|fertig|erledigt|gestartet|gespeichert|eingetragen|"+ r"gesendet|geschickt|aktiviert|deaktiviert|an|aus|da|dran|drin|bereit)\b|"+ r"\b(?:habe|hab|hatte)\s+(?:ich\s+)?(?:\w+\s+){0,3}"+ r"(?:geoffnet|gemacht|gestartet|gespeichert|eingetragen|gesendet|"+ r"geschickt|gefunden|nachgeschaut|nachgesehen|geprueft|gepruft|erledigt)\b|"+ r"\b(?:erledigt|fertig|geschafft|gefunden)\b|"+ r"\b(?:is|are|was|were)\s+(?:now\s+|already\s+)?"+ r"(?:open|opened|done|ready|started|saved|sent|on|off|set|running|"+ r"playing|finished|complete|completed)\b|"+ r"\b(?:i've|i have|ive)\s+(?:\w+\s+){0,3}"+ r"(?:opened|done|started|saved|sent|found|checked|finished|set|played)\b|"+ r"\b(?:done|finished|found it|all set)\b|"+ r"\b(?:esta|estan|ya esta|ya estan)\s+"+ r"(?:abierto|abierta|listo|lista|hecho|hecha|guardado|guardada|"+ r"enviado|enviada|activado|activada)\b|"+ r"\b(?:he|ya he)\s+(?:\w+\s+){0,3}"+ r"(?:abierto|hecho|guardado|enviado|encontrado|revisado|terminado)\b|"+ r"\b(?:hecho|listo|terminado|encontrado)\b"+ r")"+)++# Words no spoken line may contain (defense in depth next to scrub_for_voice).+_FORBIDDEN_RE = re.compile(+ r"\b(?:sub-?agent|worker|provider|sir|jawohl|sehr wohl|boss|chef|" # i18n-allow: matcher+ r"router|orchestrator|delegate|tool[- ]?model|backend|api|json)\b",+ re.IGNORECASE,+)+++def _matches_utterance(token: str, utterance_tokens: set[str]) -> bool:+ if token in utterance_tokens:+ return True+ if len(token) < _INFLECTION_PREFIX_CHARS:+ return False+ # Inflection tolerance ("Notiz" / "Notizen", "Spotify" / "Spotifys"):+ # both words are at least four characters and share their first four.+ stem = token[:_INFLECTION_PREFIX_CHARS]+ return any(+ len(candidate) >= _INFLECTION_PREFIX_CHARS and candidate[:_INFLECTION_PREFIX_CHARS] == stem+ for candidate in utterance_tokens+ )+++def contextual_ack_is_valid(+ text: str,+ *,+ utterance: str,+ language: str,+ extra_allowed_words: tuple[str, ...] = (),+) -> bool:+ """Accept a model-composed ACTION ack only when it is structurally an intent.++ Rules (all deterministic, no model):+ - 2..12 words, no question mark, no forbidden vocabulary;+ - no digit unless that very digit token appears in the user's request;+ - no result / completion marker (present-perfect, copula-state, "done");+ - an intent verb of the language within the first four tokens;+ - every remaining content word comes from the user's own request (exact+ or by 4-char inflection prefix), the free-word list, the intent verbs,+ or ``extra_allowed_words`` (the assistant/agent brand).++ Anything the model adds beyond the user's words is rejected — which is+ exactly the property that makes an invented result impossible.+ """+ raw = str(text or "").strip()+ if not raw or "?" in raw:+ return False+ if _FORBIDDEN_RE.search(raw):+ return False+ lang = _language_key(language)+ tokens = _tokens(raw)+ if not (_MIN_CONTEXTUAL_WORDS <= len(tokens) <= _MAX_CONTEXTUAL_WORDS):+ return False+ folded = _fold(raw)+ if _RESULT_MARKER_RE.search(folded):+ return False+ utterance_tokens = set(_tokens(utterance))+ intent_verbs = _INTENT_VERBS.get(lang, frozenset())+ if not any(token in intent_verbs for token in tokens[:_MAX_INTENT_VERB_POSITION]):+ return False+ free = _FREE_WORDS.get(lang, frozenset())+ allowed_extra = {tok for word in extra_allowed_words for tok in _tokens(word)}+ # A line made only of verbs and free words ("Mache ich.", "On it.") is the+ # stock filler this class forbids: at least one word must name the+ # request's own subject.+ names_subject = False+ for token in tokens:+ if token.isdigit():+ if token in utterance_tokens:+ names_subject = True+ continue+ return False+ if token in free or token in intent_verbs or token in allowed_extra:+ continue+ # Contractions: "i'm" -> "i" + "m"; check the head.+ head = token.split("'", 1)[0]+ if head in free or head in intent_verbs:+ continue+ if _matches_utterance(token, utterance_tokens):+ names_subject = True+ continue+ return False+ return names_subject+++# ---------------------------------------------------------------------------+# Process-wide "what did we just say" note — so a later spoken line for the+# SAME request (the router's grounded tool ack, the spawn handover) can+# continue instead of re-announcing. One user, one voice, one process.+# ---------------------------------------------------------------------------++_last_spoken: tuple[str, float] | None = None+++def note_spoken(text: str, *, now: float | None = None) -> None:+ """Record that an instant ack was actually released to the speaker."""+ global _last_spoken # noqa: PLW0603 — deliberate process-wide note+ line = str(text or "").strip()+ if not line:+ return+ _last_spoken = (line, time.monotonic() if now is None else float(now))+++def recently_spoken(within_s: float = PROGRESS_AFTER_S, *, now: float | None = None) -> str:+ """The instant ack spoken less than ``within_s`` ago, or ``""``."""+ if _last_spoken is None:+ return ""+ line, at = _last_spoken+ current = time.monotonic() if now is None else float(now)+ return line if (current - at) < float(within_s) else ""+++#: Hard budget for a flash-LLM composed ACTION line. The line is worthless+#: after the result, so a slow provider simply costs the ack, never the turn.+CONTEXTUAL_BUDGET_MS = 700++_LANGUAGE_NAMES = {"de": "German", "en": "English", "es": "Spanish"}+++def language_name(language: str) -> str:+ return _LANGUAGE_NAMES.get(_language_key(language), "English")+++async def compose_contextual_ack(+ composer: object | None,+ *,+ utterance: str,+ language: str,+ agent_brand: str = "",+ budget_ms: int = CONTEXTUAL_BUDGET_MS,+) -> str:+ """Compose a request-specific ACTION line with a flash composer, or ``""``.++ ``composer`` is a :class:`jarvis.voice.contextual_readback.ReadbackComposer`+ (duck-typed: ``has_llm`` + ``compose``). Never raises. The composer's own+ guards run first; :func:`contextual_ack_is_valid` is the final boundary,+ so a line the model padded with anything beyond the user's words is+ dropped and the caller stays silent — silence beats a stock filler for+ an action (maintainer rule 2026-08-17).+ """+ if composer is None or not bool(getattr(composer, "has_llm", False)):+ return ""+ compose = getattr(composer, "compose", None)+ if not callable(compose):+ return ""+ request = str(utterance or "").strip()+ if not request:+ return ""+ try:+ text = await compose(+ instruction=contextual_ack_prompt(+ language_name=language_name(language), utterance=request+ ),+ language=_language_key(language),+ canned=lambda: "",+ facts={"user_request": request},+ in_progress=True,+ honesty_bound=False,+ latency_budget_ms=int(budget_ms),+ )+ except Exception: # noqa: BLE001 — an ack composer must never break a turn+ return ""+ line = str(text or "").strip()+ if not line or not contextual_ack_is_valid(+ line,+ utterance=request,+ language=language,+ extra_allowed_words=(agent_brand,) if agent_brand else (),+ ):+ return ""+ return line+++def contextual_ack_prompt(*, language_name: str, utterance: str) -> str:+ """Instruction for a model that composes the ACTION ack (live or flash).++ The validator above is the trust boundary; this prompt only raises the+ hit rate. It names the shape, forbids results, and pins the vocabulary to+ the user's own words.+ """+ return (+ "The Jarvis orchestrator is executing the user's request right now and "+ f"has no result yet. Say ONE short sentence in {language_name}, at most "+ "ten words, that tells the user what you are doing for exactly this "+ "request — name its concrete subject with the user's own words (the "+ "app, the person, the file, the setting, the terminal), for example the "+ "shape 'I'm opening <thing>.' or 'I'm sending that to <thing>.'. "+ "Present tense only. No result, no success, no promise about the "+ "outcome, no question, no new facts, no numbers, no words the user did "+ "not use except 'I'm', 'now', 'for you'. Then stop. "+ f'The user\'s request was: "{str(utterance or "").strip()}"'+ )diff --git a/scripts/ci/german-allowlist.txt b/scripts/ci/german-allowlist.txtindex 66e5861040..fe125acd9a 100644--- a/scripts/ci/german-allowlist.txt+++ b/scripts/ci/german-allowlist.txt@@ -19,6 +19,11 @@ jarvis/speech/persona.pytests/unit/brain/test_spawn_announcement.pytests/unit/plugins/tool/test_spawn_worker_ack.py+# --- Instant acknowledgment (2026-08-17): the closed de/en/es voice pools, the+# multilingual intent/result matchers, and the fixtures that pin them ---+jarvis/voice/instant_ack.py+tests/unit/voice/test_instant_ack.py+# --- Smalltalk-head/action-tail guard: the verbatim German voice utterances# (the live Bill-Gates turn) ARE the regression fixtures under test ---tests/unit/brain/test_smalltalk_action_tail.pydiff --git a/tests/unit/core/test_realtime_latency_phases.py b/tests/unit/core/test_realtime_latency_phases.pyindex e113810f05..bb6e0c5245 100644--- a/tests/unit/core/test_realtime_latency_phases.py+++ b/tests/unit/core/test_realtime_latency_phases.py@@ -10,6 +10,7 @@ def test_realtime_phases_exist_and_are_accepted_by_the_span_guard():LatencyPhase.REALTIME_FIRST_TRANSCRIPT,LatencyPhase.REALTIME_FIRST_AUDIO,LatencyPhase.REALTIME_DELEGATE_STARTED,+ LatencyPhase.REALTIME_DELEGATE_BRIDGE_REQUESTED,LatencyPhase.REALTIME_DELEGATE_COMPLETED,LatencyPhase.REALTIME_TOOL_COMPLETED,LatencyPhase.REALTIME_SCRUB_CANCEL,diff --git a/tests/unit/realtime/test_session.py b/tests/unit/realtime/test_session.pyindex b1f4d25a5b..2368f3c50d 100644--- a/tests/unit/realtime/test_session.py+++ b/tests/unit/realtime/test_session.py@@ -3790,16 +3790,20 @@ class _SlowDelegateBridgeSession(FakeSession):bridge_sent,result_delivered,bridge_line="I'm still working on it.",+ utterance="Write this to my wiki.",+ result_line="Stored on your page: note.",):super().__init__(events)self._bridge_sent = bridge_sentself._result_delivered = result_deliveredself._bridge_line = bridge_line+ self._utterance = utterance+ self._result_line = result_lineasync def receive(self):yield RealtimeEvent(type="input_transcript",- text="Write this to my wiki.",+ text=self._utterance,is_final=True,)await self._bridge_sent.wait()@@ -3821,7 +3825,7 @@ class _SlowDelegateBridgeSession(FakeSession):await self._result_delivered.wait()yield RealtimeEvent(type="output_transcript_delta",- text="Stored on your page: note.",+ text=self._result_line,)yield RealtimeEvent(type="audio_delta",@@ -3848,11 +3852,15 @@ class _SlowDelegateBridgeProvider(FakeProvider):bridge_sent,result_delivered,bridge_line="I'm still working on it.",+ utterance="Write this to my wiki.",+ result_line="Stored on your page: note.",):super().__init__([])self._bridge_sent = bridge_sentself._result_delivered = result_deliveredself._bridge_line = bridge_line+ self._utterance = utterance+ self._result_line = result_lineasync def open_session(self, cfg):self.opened_with = cfg@@ -3861,25 +3869,50 @@ class _SlowDelegateBridgeProvider(FakeProvider):bridge_sent=self._bridge_sent,result_delivered=self._result_delivered,bridge_line=self._bridge_line,+ utterance=self._utterance,+ result_line=self._result_line,)return self.session-async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):- """BUG-051: dead air between dispatch and result gets one interim line."""- monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 0.05)- # Pin the varied progress-line pick to the line the fake session speaks.+# A connected-data question is LONG work for the instant-ack planner: the+# pooled line fires immediately, and the turn runs through the Brain delegate+# (a public-fact question would take the bounded grounding path instead). An+# action like "Write this to my wiki." is the CONTEXTUAL class and is covered+# by its own tests below.+_RESEARCH_UTTERANCE = "What's on my calendar tomorrow?"+_RESEARCH_RESULT = "Tomorrow you have the standup and a lunch meeting."+++def _pin_instant_ack(monkeypatch, line):+ """Pin both the class pool pick and the legacy progress pick to ``line``."""+ monkeypatch.setattr(+ "jarvis.realtime.session.pick_instant_ack_text",+ lambda work_class, language, *, agent_brand="": line,+ )monkeypatch.setattr("jarvis.realtime.session._pick_delegate_bridge_text",- lambda language: "I'm still working on it.",+ lambda language: line,)+++async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):+ """BUG-051 / instant ack: a delegated research turn gets its first sign of+ life immediately -- a closed-pool line naming the kind of work."""+ # The research class fires at 0 s; the legacy delay is only the cap.+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 6.0)+ # Pin the varied pool pick to the line the fake session speaks.+ _pin_instant_ack(monkeypatch, "I'm still working on it.")gate = asyncio.Event()bridge_sent = asyncio.Event()result_delivered = asyncio.Event()- brain = FakeBrain(replies=("Stored on your page: note.",), gate=gate)+ brain = FakeBrain(replies=(_RESEARCH_RESULT,), gate=gate)provider = _SlowDelegateBridgeProvider(- bridge_sent=bridge_sent, result_delivered=result_delivered+ bridge_sent=bridge_sent,+ result_delivered=result_delivered,+ utterance=_RESEARCH_UTTERANCE,+ result_line=_RESEARCH_RESULT,)thinking_sent = asyncio.Event()@@ -3910,7 +3943,7 @@ async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):# (a quoted line flipped Gemini's native voice, forensic 2026-07-17).assert '"I\'m still working on it."' not in bridgeassert "same voice" in bridge- assert "Write this to my wiki." not in bridge+ assert _RESEARCH_UTTERANCE not in bridge# While the bridge response is live, provider output must flow.assert sess._must_withhold_provider_output() is False@@ -3921,35 +3954,123 @@ async def test_slow_deterministic_delegate_speaks_a_bridge_line(monkeypatch):await asyncio.wait_for(result_delivered.wait(), timeout=2)result = provider.session.text_inputs[-1]assert "<trusted_action_result>" in result- assert "Stored on your page: note." in result+ assert _RESEARCH_RESULT in result# The bridge's completed response must not have closed the turn: the# result is delivered into the live turn, not as a late follow-up.assert "finished only now" not in result+ # The rendering order continues from the line the user already heard.+ assert "already told the user" in result+ assert "I'm still working on it." in resultawait sess.wait_finished()assert binariesspoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]assert [(event.text, event.spoken_kind) for event in spoken] == [("I'm still working on it.", "progress"),- ("Stored on your page: note.", "reply"),+ (_RESEARCH_RESULT, "reply"),]await sess.end(reason="test")@pytest.mark.asyncio-async def test_capability_limited_provider_acknowledges_delegate_early(monkeypatch):- """A capability-limited provider streams its trusted acknowledgement early."""- monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 60.0)- monkeypatch.setattr(- "jarvis.realtime.session._CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S",- 0.01,+async def test_action_delegate_speaks_a_contextual_line(monkeypatch):+ """Instant ack for an ACTION: the live model composes a request-specific+ line ("I'm writing this to your wiki.") that the structural validator+ accepts; a stock filler is never ordered for actions."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 6.0)+ monkeypatch.setattr("jarvis.realtime.session._INSTANT_ACK_GRACE_S", 0.05)+ gate = asyncio.Event()+ bridge_sent = asyncio.Event()+ result_delivered = asyncio.Event()+ brain = FakeBrain(replies=("Stored on your page: note.",), gate=gate)+ provider = _SlowDelegateBridgeProvider(+ bridge_sent=bridge_sent,+ result_delivered=result_delivered,+ bridge_line="I'm writing this to your wiki.",)- monkeypatch.setattr(- "jarvis.realtime.session._pick_delegate_bridge_text",- lambda language: "I'm still working on it.",+ thinking_sent = asyncio.Event()++ class _StatusMessages(list[dict]):+ def append(self, message: dict) -> None:+ super().append(message)+ if message == {"type": "thinking"}:+ thinking_sent.set()++ jsons = _StatusMessages()+ binaries: list[bytes] = []+ bus = FakeBus()+ sess = _session(provider, brain=brain, jsons=jsons, binaries=binaries, bus=bus)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(bridge_sent.wait(), timeout=2)++ bridge = provider.session.text_inputs[0]+ assert "<trusted_action_result>" not in bridge+ # A contextual order: it names the request and asks for the subject in the+ # user's own words -- no closed-pool line is dictated.+ assert "Write this to my wiki." in bridge+ assert "I'm still working on it." not in bridge+ assert "no result" in bridge+ assert "same voice" in bridge++ await asyncio.wait_for(thinking_sent.wait(), timeout=2)+ gate.set()+ await asyncio.wait_for(result_delivered.wait(), timeout=2)+ result = provider.session.text_inputs[-1]+ assert "<trusted_action_result>" in result+ assert "already told the user" in result+ assert "I'm writing this to your wiki." in result+ await sess.wait_finished()+ assert binaries+ spoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]+ assert [(event.text, event.spoken_kind) for event in spoken] == [+ ("I'm writing this to your wiki.", "progress"),+ ("Stored on your page: note.", "reply"),+ ]+ await sess.end(reason="test")+++async def test_contextual_action_line_that_claims_a_result_is_dropped(monkeypatch):+ """A contextual ACTION ack is trusted only through the structural validator:+ a result claim ("Your wiki is updated.") never reaches the speaker, and the+ grounded result still arrives."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 6.0)+ monkeypatch.setattr("jarvis.realtime.session._INSTANT_ACK_GRACE_S", 0.05)+ gate = asyncio.Event()+ bridge_sent = asyncio.Event()+ result_delivered = asyncio.Event()+ brain = FakeBrain(replies=("Stored on your page: note.",), gate=gate)+ provider = _SlowDelegateBridgeProvider(+ bridge_sent=bridge_sent,+ result_delivered=result_delivered,+ bridge_line="Your wiki is updated with the note.",)+ binaries: list[bytes] = []+ bus = FakeBus()+ sess = _session(provider, brain=brain, jsons=[], binaries=binaries, bus=bus)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(bridge_sent.wait(), timeout=2)+ # Let the hostile bridge response complete, then release the result.+ await asyncio.sleep(0.2)+ assert binaries == [] # not one leaked sample+ gate.set()+ await asyncio.wait_for(result_delivered.wait(), timeout=2)+ result = provider.session.text_inputs[-1]+ assert "<trusted_action_result>" in result+ # Nothing was heard, so nothing is claimed as already said.+ assert "already told the user" not in result+ await sess.wait_finished()+ spoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]+ assert [(event.text, event.spoken_kind) for event in spoken] == [+ ("Stored on your page: note.", "reply"),+ ]+ await sess.end(reason="test")- speech_requested = asyncio.Event()- first_audio = asyncio.Event()++def _authoritative_speech_provider(*, utterance, speech_requested):+ """A tool-less transport whose direct-speech channel renders text verbatim."""class _AuthoritativeSpeechSession(FakeSession):direct_speech_is_authoritative = True@@ -3957,7 +4078,7 @@ async def test_capability_limited_provider_acknowledges_delegate_early(monkeypatasync def receive(self):yield RealtimeEvent(type="input_transcript",- text="Write this to my wiki.",+ text=utterance,is_final=True,)await speech_requested.wait()@@ -3983,17 +4104,51 @@ async def test_capability_limited_provider_acknowledges_delegate_early(monkeypatself.session = _AuthoritativeSpeechSession([])return self.session+ return _CapabilityLimitedProvider([])+++class _FakeAckComposer:+ """Duck-typed ReadbackComposer: one canned contextual line, or nothing."""++ def __init__(self, line: str = "") -> None:+ self.line = line+ self.calls: list[dict] = []++ @property+ def has_llm(self) -> bool:+ return True++ async def compose(self, **kwargs):+ self.calls.append(kwargs)+ return self.line or kwargs["canned"]()+++async def test_capability_limited_provider_acknowledges_delegate_early(monkeypatch):+ """A capability-limited provider streams its pooled acknowledgement early."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 60.0)+ monkeypatch.setattr(+ "jarvis.realtime.session._CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S",+ 0.01,+ )+ _pin_instant_ack(monkeypatch, "I'm still working on it.")++ speech_requested = asyncio.Event()+ first_audio = asyncio.Event()+class _AudioMessages(list[bytes]):def append(self, data: bytes) -> None:super().append(data)first_audio.set()gate = asyncio.Event()- provider = _CapabilityLimitedProvider([])+ provider = _authoritative_speech_provider(+ utterance=_RESEARCH_UTTERANCE, speech_requested=speech_requested+ )binaries = _AudioMessages()sess = _session(provider,- brain=FakeBrain(replies=("Stored.",), gate=gate),+ brain=FakeBrain(replies=(_RESEARCH_RESULT,), gate=gate),binaries=binaries,)@@ -4006,6 +4161,81 @@ async def test_capability_limited_provider_acknowledges_delegate_early(monkeypatawait sess.end(reason="test")+async def test_verbatim_transport_action_ack_comes_from_the_flash_composer(monkeypatch):+ """On a verbatim-speech transport an ACTION ack is composed by the Brain's+ flash composer (bounded) and validated; the user hears the request's own+ subject, never a stock line."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 60.0)+ monkeypatch.setattr(+ "jarvis.realtime.session._CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S",+ 0.01,+ )+ monkeypatch.setattr("jarvis.realtime.session._INSTANT_ACK_GRACE_S", 0.01)+ _pin_instant_ack(monkeypatch, "I'm still working on it.")++ speech_requested = asyncio.Event()+ first_audio = asyncio.Event()++ class _AudioMessages(list[bytes]):+ def append(self, data: bytes) -> None:+ super().append(data)+ first_audio.set()++ gate = asyncio.Event()+ provider = _authoritative_speech_provider(+ utterance="Write this to my wiki.", speech_requested=speech_requested+ )+ brain = FakeBrain(replies=("Stored.",), gate=gate)+ brain._readback_composer = _FakeAckComposer("I'm writing this to your wiki.")+ binaries = _AudioMessages()+ sess = _session(provider, brain=brain, binaries=binaries)++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.wait_for(first_audio.wait(), timeout=1)++ assert provider.session.text_inputs == ["I'm writing this to your wiki."]+ assert brain._readback_composer.calls[0]["in_progress"] is True+ assert "Write this to my wiki." in brain._readback_composer.calls[0]["instruction"]+ assert binaries+ await sess.end(reason="test")+++async def test_verbatim_transport_action_without_composer_stays_silent(monkeypatch):+ """No composer, no valid contextual line -> no stock filler for an action.++ The maintainer's rule: an action ack must reference the request. A+ verbatim transport without a composing model therefore says nothing and+ lets the result speak (the pooled classes are unaffected)."""+ monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 60.0)+ monkeypatch.setattr(+ "jarvis.realtime.session._CAPABILITY_LIMITED_DELEGATE_BRIDGE_DELAY_S",+ 0.01,+ )+ monkeypatch.setattr("jarvis.realtime.session._INSTANT_ACK_GRACE_S", 0.01)+ _pin_instant_ack(monkeypatch, "I'm still working on it.")++ speech_requested = asyncio.Event()+ gate = asyncio.Event()+ provider = _authoritative_speech_provider(+ utterance="Write this to my wiki.", speech_requested=speech_requested+ )+ binaries: list[bytes] = []+ sess = _session(+ provider,+ brain=FakeBrain(replies=("Stored.",), gate=gate),+ binaries=binaries,+ )++ await sess.handle_control({"type": "audio_start", "sample_rate": 16_000})+ await asyncio.sleep(0.3)++ assert provider.session.text_inputs == []+ assert binaries == []+ await sess.end(reason="test")++@pytest.mark.asyncioasync def test_varied_bridge_line_passes_validation_and_is_persisted(monkeypatch):"""A non-default pool line must clear the withhold and reach the record.@@ -4016,18 +4246,17 @@ async def test_varied_bridge_line_passes_validation_and_is_persisted(monkeypatch""" # i18n-allow: quoted German forensic phrasevaried_line = "One moment, almost there."monkeypatch.setattr("jarvis.realtime.session._DELEGATE_BRIDGE_DELAY_S", 0.05)- monkeypatch.setattr(- "jarvis.realtime.session._pick_delegate_bridge_text",- lambda language: varied_line,- )+ _pin_instant_ack(monkeypatch, varied_line)gate = asyncio.Event()bridge_sent = asyncio.Event()result_delivered = asyncio.Event()- brain = FakeBrain(replies=("Stored on your page: note.",), gate=gate)+ brain = FakeBrain(replies=(_RESEARCH_RESULT,), gate=gate)provider = _SlowDelegateBridgeProvider(bridge_sent=bridge_sent,result_delivered=result_delivered,bridge_line=varied_line,+ utterance=_RESEARCH_UTTERANCE,+ result_line=_RESEARCH_RESULT,)thinking_sent = asyncio.Event()@@ -4059,7 +4288,7 @@ async def test_varied_bridge_line_passes_validation_and_is_persisted(monkeypatchspoken = [event for event in bus.events if isinstance(event, SpeechSpoken)]assert [(event.text, event.spoken_kind) for event in spoken] == [(varied_line, "progress"),- ("Stored on your page: note.", "reply"),+ (_RESEARCH_RESULT, "reply"),]await sess.end(reason="test")diff --git a/tests/unit/speech/test_instant_ack_pipeline.py b/tests/unit/speech/test_instant_ack_pipeline.pynew file mode 100644index 0000000000..a73828370e--- /dev/null+++ b/tests/unit/speech/test_instant_ack_pipeline.py@@ -0,0 +1,363 @@+"""Instant acknowledgment on the classic speech pipeline (2026-08-17).++The contract (jarvis/voice/instant_ack.py): a heavy turn gets its first sign+of life at dispatch time from the deterministic turn plan -- research, screen+and mission work immediately, actions and personal lookups after a short+grace and only if the turn is still processing. Actions get a request-specific+line from the flash composer or nothing. The router's grounded ack that+follows within seconds is dropped (no double-tap); the instant ack itself is+exempt from the anti-loop cap because it is one line per user utterance.+"""++from __future__ import annotations++import asyncio+from collections.abc import AsyncIterator+from dataclasses import dataclass, field+from types import SimpleNamespace++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import AnnouncementRequested+from jarvis.core.protocols import AudioChunk+from jarvis.speech.pipeline import SpeechPipeline, TurnTakingState+from jarvis.voice import instant_ack as instant_ack_module+++@dataclass+class FakeTTS:+ calls: list[tuple[str, str | None]] = field(default_factory=list)+ name: str = "fake-tts"+ supports_streaming: bool = True++ async def synthesize(+ self,+ text: str,+ voice: str | None = None,+ language_code: str | None = None,+ ) -> AsyncIterator[AudioChunk]:+ self.calls.append((text, language_code))+ if False: # pragma: no cover+ yield # type: ignore[unreachable]+++@dataclass+class FakePlayer:+ plays: int = 0++ async def play_chunks(+ self,+ chunks: AsyncIterator[AudioChunk],+ *,+ should_play=None,+ ) -> None:+ if should_play is not None and not should_play():+ async for _ in chunks:+ pass+ return+ self.plays += 1+ async for _ in chunks:+ pass++ def stop(self) -> None:+ return None+++class _FakeComposer:+ def __init__(self, line: str = "") -> None:+ self.line = line+ self.calls: list[dict] = []++ @property+ def has_llm(self) -> bool:+ return True++ async def compose(self, **kwargs):+ self.calls.append(kwargs)+ return self.line or kwargs["canned"]()+++def _make_pipeline(+ tts: FakeTTS,+ bus: EventBus,+ player: FakePlayer,+ *,+ instant_ack: bool = True,+ composer: _FakeComposer | None = None,+) -> SpeechPipeline:+ pipeline = SpeechPipeline(tts=tts, bus=bus, enable_whisper_wake=False)+ pipeline._player = player # type: ignore[assignment]+ pipeline._config = SimpleNamespace( # type: ignore[attr-defined]+ ack_brain=SimpleNamespace(+ suppress_preamble_after_interrupt_ms=5000,+ grounded_ack_commit_grace_ms=0,+ preamble_dedup_window_s=180,+ preamble_rate_limit_per_min=3,+ instant_ack=instant_ack,+ )+ )+ pipeline._brain = SimpleNamespace(_readback_composer=composer) # type: ignore[attr-defined]+ pipeline._turn_state = TurnTakingState.PROCESSING+ pipeline._brain_first_frame_played = False+ return pipeline+++def _instant_acks(published: list[AnnouncementRequested]) -> list[AnnouncementRequested]:+ return [e for e in published if e.source_layer == "brain.instant_ack"]+++async def _settle(seconds: float = 0.15) -> None:+ await asyncio.sleep(seconds)+++async def test_research_turn_speaks_immediately(monkeypatch) -> None:+ """LONG work: the pooled line goes out at once and reaches the speaker."""+ monkeypatch.setattr(+ instant_ack_module,+ "_POOLS",+ {+ **instant_ack_module._POOLS,+ instant_ack_module.WorkClass.RESEARCH: {+ "de": ("Ich suche das gerade online.",), # i18n-allow: fixture+ "en": ("I'm looking that up online.",),+ "es": ("Lo estoy buscando en línea.",),+ },+ },+ )+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)++ pipeline._arm_instant_ack("What's the weather in Berlin right now?", "en")+ await _settle()++ acks = _instant_acks(seen)+ assert [a.text for a in acks] == ["I'm looking that up online."]+ assert acks[0].kind == "preamble"+ assert player.plays == 1+ assert tts.calls[0][0] == "I'm looking that up online."+ # The moment of speaking is recorded for the continue-not-repeat rule.+ assert pipeline._instant_ack_spoke_recently(5.0)+++async def test_plain_conversation_and_voice_control_arm_nothing() -> None:+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)++ pipeline._arm_instant_ack("Hallo, wie geht's?", "de") # i18n-allow: fixture+ pipeline._arm_instant_ack("Sei still", "de") # i18n-allow: fixture+ pipeline._arm_instant_ack("When was Ada Lovelace born?", "en")+ await _settle()++ assert _instant_acks(seen) == []+ assert player.plays == 0+ assert getattr(pipeline, "_instant_ack_task", None) is None+++async def test_kill_switch_arms_nothing() -> None:+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ pipeline = _make_pipeline(FakeTTS(), bus, FakePlayer(), instant_ack=False)++ pipeline._arm_instant_ack("What's the weather in Berlin right now?", "en")+ await _settle()++ assert _instant_acks(seen) == []+++async def test_short_work_waits_the_grace_and_speaks_only_if_still_processing(+ monkeypatch,+) -> None:+ """A personal lookup answered inside the grace stays chatter-free; one that+ outlasts it gets the line."""+ monkeypatch.setattr(instant_ack_module, "SHORT_GRACE_S", 0.1)+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)++ # Fast answer: the turn leaves PROCESSING before the grace elapses.+ pipeline._arm_instant_ack("What's in my notes about Albel?", "en")+ await asyncio.sleep(0.02)+ pipeline._turn_state = TurnTakingState.JARVIS_SPEAKING+ await _settle(0.25)+ assert _instant_acks(seen) == []++ # Slow answer: still PROCESSING after the grace -> the line is spoken.+ pipeline._turn_state = TurnTakingState.PROCESSING+ pipeline._arm_instant_ack("What's in my notes about Albel?", "en")+ await _settle(0.35)+ acks = _instant_acks(seen)+ assert len(acks) == 1+ assert acks[0].text in instant_ack_module.instant_ack_pool(+ instant_ack_module.WorkClass.PERSONAL, "en"+ )+ assert player.plays == 1+++async def test_action_without_composer_stays_silent(monkeypatch) -> None:+ """No stock 'on it' for an action: without a composer nothing is spoken."""+ monkeypatch.setattr(instant_ack_module, "SHORT_GRACE_S", 0.05)+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ pipeline = _make_pipeline(FakeTTS(), bus, FakePlayer(), composer=None)++ pipeline._arm_instant_ack("Open Spotify", "en")+ await _settle(0.3)++ assert _instant_acks(seen) == []+++async def test_action_with_composer_speaks_a_request_specific_line(monkeypatch) -> None:+ monkeypatch.setattr(instant_ack_module, "SHORT_GRACE_S", 0.05)+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ composer = _FakeComposer("I'm opening Spotify.")+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player, composer=composer)++ pipeline._arm_instant_ack("Open Spotify", "en")+ await _settle(0.3)++ assert [a.text for a in _instant_acks(seen)] == ["I'm opening Spotify."]+ assert composer.calls[0]["in_progress"] is True+ assert "Open Spotify" in composer.calls[0]["instruction"]+ assert player.plays == 1+++async def test_action_composer_line_that_claims_a_result_is_rejected(monkeypatch) -> None:+ monkeypatch.setattr(instant_ack_module, "SHORT_GRACE_S", 0.05)+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ composer = _FakeComposer("Spotify is open now.")+ pipeline = _make_pipeline(FakeTTS(), bus, FakePlayer(), composer=composer)++ pipeline._arm_instant_ack("Open Spotify", "en")+ await _settle(0.3)++ assert _instant_acks(seen) == []+++async def test_router_ack_shortly_after_an_instant_ack_is_dropped(monkeypatch) -> None:+ """The grounded router ack seconds after the instant ack is the double-tap;+ once the wait has grown past the progress threshold it may speak again."""+ monkeypatch.setattr(+ instant_ack_module,+ "_POOLS",+ {+ **instant_ack_module._POOLS,+ instant_ack_module.WorkClass.RESEARCH: {+ "de": ("Ich suche das gerade online.",), # i18n-allow: fixture+ "en": ("I'm looking that up online.",),+ "es": ("Lo estoy buscando en línea.",),+ },+ },+ )+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ pipeline = _make_pipeline(tts, bus, player)++ pipeline._arm_instant_ack("What's the weather in Berlin right now?", "en")+ await _settle()+ assert player.plays == 1++ await bus.publish(+ AnnouncementRequested(+ text="Checking your calendar for tomorrow.",+ language="en",+ priority="normal",+ kind="preamble",+ source_layer="brain.router.ack",+ )+ )+ assert player.plays == 1, "the router ack double-tapped the instant ack"++ # Long wait: the router ack becomes the progress line.+ pipeline._instant_ack_spoken_at -= 30.0+ await bus.publish(+ AnnouncementRequested(+ text="Still checking your calendar for tomorrow.",+ language="en",+ priority="normal",+ kind="preamble",+ source_layer="brain.router.ack",+ )+ )+ assert player.plays == 2+++async def test_instant_ack_is_exempt_from_the_anti_loop_cap() -> None:+ """Four heavy commands in a minute -> four first-signs-of-life. The cap+ still applies to every other emitter."""+ bus = EventBus()+ tts = FakeTTS()+ player = FakePlayer()+ _make_pipeline(tts, bus, player)++ for i in range(5):+ await bus.publish(+ AnnouncementRequested(+ text=f"Instant line number {i}.",+ language="en",+ priority="normal",+ kind="preamble",+ source_layer="brain.instant_ack",+ )+ )+ assert player.plays == 5++ for i in range(5):+ await bus.publish(+ AnnouncementRequested(+ text=f"Other line number {i}.",+ language="en",+ priority="normal",+ kind="preamble",+ source_layer="brain.other",+ )+ )+ assert player.plays == 8, "the anti-loop cap must still bind other emitters"+++async def test_a_new_utterance_cancels_the_pending_ack_of_the_previous_one(+ monkeypatch,+) -> None:+ monkeypatch.setattr(instant_ack_module, "SHORT_GRACE_S", 0.2)+ bus = EventBus()+ seen: list[AnnouncementRequested] = []+ bus.subscribe(AnnouncementRequested, lambda e: seen.append(e))+ pipeline = _make_pipeline(FakeTTS(), bus, FakePlayer())++ pipeline._arm_instant_ack("What's in my notes about Albel?", "en")+ first = pipeline._instant_ack_task+ pipeline._arm_instant_ack("Hallo", "de") # i18n-allow: fixture+ await _settle(0.35)++ assert first is not None and first.cancelled()+ assert _instant_acks(seen) == []diff --git a/tests/unit/telemetry/test_latency_span_event.py b/tests/unit/telemetry/test_latency_span_event.pyindex ef2cf82104..b699c3d12a 100644--- a/tests/unit/telemetry/test_latency_span_event.py+++ b/tests/unit/telemetry/test_latency_span_event.py@@ -70,6 +70,7 @@ def test_latency_phase_is_a_string_enum_source_of_truth() -> None:"realtime_first_transcript","realtime_first_audio","realtime_delegate_started",+ "realtime_delegate_bridge_requested","realtime_delegate_completed","realtime_tool_completed","realtime_scrub_cancel",diff --git a/tests/unit/voice/test_instant_ack.py b/tests/unit/voice/test_instant_ack.pynew file mode 100644index 0000000000..8b4c7c5ba9--- /dev/null+++ b/tests/unit/voice/test_instant_ack.py@@ -0,0 +1,243 @@+"""Instant acknowledgment core: work classes, pools, and the contextual validator."""++from __future__ import annotations++import pytest++from jarvis.brain.turn_planner import plan_turn+from jarvis.voice.instant_ack import (+ IMMEDIATE_DELAY_S,+ SHORT_GRACE_S,+ WorkClass,+ all_instant_ack_lines,+ contextual_ack_is_valid,+ instant_ack_pool,+ normalize_ack_line,+ pick_instant_ack_text,+ plan_instant_ack,+)++# ---------------------------------------------------------------------------+# plan_instant_ack — the trigger is the deterministic turn plan+# ---------------------------------------------------------------------------+++ ("utterance", "work_class", "delay_s"),+ [+ (+ "Was gibt es aktuell für Bugatti Divos in Europa?",+ WorkClass.RESEARCH,+ IMMEDIATE_DELAY_S,+ ), # i18n-allow: speech input+ ("What's the weather tomorrow?", WorkClass.RESEARCH, IMMEDIATE_DELAY_S),+ (+ "Wie viele Termine habe ich morgen?",+ WorkClass.RESEARCH,+ IMMEDIATE_DELAY_S,+ ), # i18n-allow: speech input+ (+ "Was steht in meinen Notizen zu Albel?",+ WorkClass.PERSONAL,+ SHORT_GRACE_S,+ ), # i18n-allow: speech input+ (+ "Weißt du noch, wann ich in Paris war?",+ WorkClass.PERSONAL,+ SHORT_GRACE_S,+ ), # i18n-allow: speech input+ (+ "Was ist auf meinem Bildschirm?",+ WorkClass.SCREEN,+ IMMEDIATE_DELAY_S,+ ), # i18n-allow: speech input+ ("What's on my screen?", WorkClass.SCREEN, IMMEDIATE_DELAY_S),+ ("Mach Spotify auf", WorkClass.ACTION, SHORT_GRACE_S), # i18n-allow: speech input+ ("Open Spotify", WorkClass.ACTION, SHORT_GRACE_S),+ (+ "Öffne den Browser und such das Wetter raus",+ WorkClass.ACTION,+ SHORT_GRACE_S,+ ), # i18n-allow: speech input+ ],+)+def test_plan_maps_orchestrator_turns_to_work_classes(utterance, work_class, delay_s):+ plan = plan_instant_ack(plan_turn(utterance), utterance)+ assert plan is not None+ assert plan.work_class is work_class+ assert plan.delay_s == pytest.approx(delay_s)+ assert plan.contextual is (work_class is WorkClass.ACTION)+++ "utterance",+ [+ "Hallo, wie geht's?", # i18n-allow: speech input+ "Wann wurde Einstein geboren?", # i18n-allow: speech input+ "Sei still", # i18n-allow: speech input+ "Thanks!",+ ],+)+def test_plain_conversation_gets_no_ack(utterance):+ assert plan_instant_ack(plan_turn(utterance), utterance) is None+++def test_none_plan_gets_no_ack():+ assert plan_instant_ack(None, "anything") is None+++# ---------------------------------------------------------------------------+# pools+# ---------------------------------------------------------------------------++[email protected]("language", ["de", "en", "es"])+ "work_class", [WorkClass.RESEARCH, WorkClass.PERSONAL, WorkClass.SCREEN, WorkClass.MISSION]+)+def test_every_pooled_class_has_varied_lines_in_every_locale(work_class, language):+ pool = instant_ack_pool(work_class, language, agent_brand="Test-Agent")+ assert len(pool) >= 3+ assert len(set(pool)) == len(pool)+ for line in pool:+ assert line.strip() == line+ assert line.endswith((".", "!"))+ assert len(line.split()) <= 12+++def test_action_pool_is_empty_by_design():+ for language in ("de", "en", "es"):+ assert instant_ack_pool(WorkClass.ACTION, language) == ()+ assert pick_instant_ack_text(WorkClass.ACTION, language) == ""+++def test_mission_lines_carry_the_dynamic_agent_brand_never_a_product_name():+ for language in ("de", "en", "es"):+ for line in instant_ack_pool(WorkClass.MISSION, language, agent_brand="Athena-Agent"):+ assert "Athena-Agent" in line+ assert "{agent}" not in line+ assert "Jarvis" not in line+++def test_unknown_language_falls_back_to_english():+ assert instant_ack_pool(WorkClass.RESEARCH, "fr") == instant_ack_pool(WorkClass.RESEARCH, "en")+++def test_pick_avoids_back_to_back_repeats():+ seen = [pick_instant_ack_text(WorkClass.RESEARCH, "de") for _ in range(12)]+ for first, second in zip(seen, seen[1:], strict=False):+ assert first != second+++def test_all_lines_are_normalized_for_transcript_matching():+ lines = all_instant_ack_lines("de", agent_brand="Athena-Agent")+ assert normalize_ack_line("Ich suche das gerade online.") in lines # i18n-allow: voice output+ assert normalize_ack_line("Ich Suche Das Gerade ONLINE") in lines # i18n-allow: voice output+ assert (+ normalize_ack_line("Das gebe ich einem Athena-Agent weiter.") in lines+ ) # i18n-allow: voice output+++# ---------------------------------------------------------------------------+# contextual validator — intent grammar + the user's own words only+# ---------------------------------------------------------------------------+++ ("text", "utterance", "language"),+ [+ ("Ich öffne Spotify.", "Mach Spotify auf", "de"), # i18n-allow: voice output / speech input+ ("Ich mache Spotify für dich auf.", "Mach Spotify auf", "de"), # i18n-allow+ (+ "Ich stelle die Stimme auf Cartesia um.",+ "Stell die Stimme auf Cartesia um",+ "de",+ ), # i18n-allow+ (+ "Ich sage T1, dass er die Tests laufen lassen soll.",+ "Sag T1, er soll die Tests laufen lassen",+ "de",+ ), # i18n-allow+ (+ "Ich merke mir, dass Alex Signal bevorzugt.",+ "Merk dir: Alex bevorzugt Signal",+ "de",+ ), # i18n-allow+ ("Ich rufe die Praxis an.", "Ruf die Praxis an und mach einen Termin", "de"), # i18n-allow+ ("I'm opening Spotify.", "Open Spotify", "en"),+ ("Opening Spotify for you now.", "Open Spotify", "en"),+ ("I'm telling T1 to run the tests.", "Tell T1 to run the tests", "en"),+ ("Abro Spotify.", "Abre Spotify", "es"),+ ],+)+def test_contextual_intent_lines_pass(text, utterance, language):+ assert contextual_ack_is_valid(text, utterance=utterance, language=language)+++ ("text", "utterance", "language", "why"),+ [+ ("Spotify ist offen.", "Mach Spotify auf", "de", "copula result claim"), # i18n-allow+ (+ "Ich habe Spotify geöffnet.",+ "Mach Spotify auf",+ "de",+ "perfect-tense result",+ ), # i18n-allow+ (+ "Ich öffne Spotify und spiele dein Lieblingslied.",+ "Mach Spotify auf",+ "de",+ "invented content",+ ), # i18n-allow+ (+ "Ich rufe die Praxis an, Termin um 15 Uhr.",+ "Ruf die Praxis an",+ "de",+ "invented number",+ ), # i18n-allow+ ("Mache ich.", "Mach Spotify auf", "de", "stock filler, no subject"), # i18n-allow+ (+ "Ich kümmere mich drum.",+ "Mach Spotify auf",+ "de",+ "stock filler, no subject",+ ), # i18n-allow+ ("Soll ich Spotify öffnen?", "Mach Spotify auf", "de", "question"), # i18n-allow+ ("Spotify is open.", "Open Spotify", "en", "copula result claim"),+ ("I've opened Spotify.", "Open Spotify", "en", "perfect-tense result"),+ ("On it.", "Open Spotify", "en", "stock filler"),+ ("I'm sending that to terminal one.", "Tell T1 to run the tests", "en", "invented words"),+ ("Done, Spotify is running.", "Open Spotify", "en", "completion"),+ ("Spotify ya está abierto.", "Abre Spotify", "es", "copula result claim"),+ ("I'm opening Spotify, Sir.", "Open Spotify", "en", "forbidden honorific"),+ ("The worker is opening Spotify.", "Open Spotify", "en", "forbidden internal name"),+ ("", "Open Spotify", "en", "empty"),+ (+ "I'm opening Spotify and then I'm also going to check the weather "+ "for you right now okay.",+ "Open Spotify",+ "en",+ "too long",+ ),+ ],+)+def test_contextual_lines_that_claim_invent_or_fill_are_rejected(text, utterance, language, why):+ assert not contextual_ack_is_valid(text, utterance=utterance, language=language), why+++def test_extra_allowed_words_admit_the_agent_brand():+ text = "I'm handing Spotify to an Athena-Agent."+ assert not contextual_ack_is_valid(text, utterance="Open Spotify", language="en")+ assert contextual_ack_is_valid(+ text, utterance="Open Spotify", language="en", extra_allowed_words=("Athena-Agent",)+ )+++def test_a_digit_from_the_request_is_allowed_a_new_one_is_not():+ assert contextual_ack_is_valid(+ "I'm opening terminal 3.", utterance="Open terminal 3", language="en"+ )+ assert not contextual_ack_is_valid(+ "I'm opening terminal 4.", utterance="Open terminal 3", language="en"+ )