Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(ultrawiki): let the settings screen repair a store it already agrees with
Ruben Lütke52cca20baa69
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex 32ee0d2774..7f4f733d63 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -44,11 +44,15 @@ from jarvis.audio.vad_reasons import FORCED_CUT_REASONSfrom jarvis.brain.output_filter import scrub_for_voicefrom jarvis.core.events import (CU_PROGRESS_EVENTS,+ DICTATION_REFUSAL_REASONS,ActionPlanned,AnnouncementRequested,AudioOutFirst,BrainTTFT,DictationCompleted,+ DictationRefused,+ DictationStarted,+ DictationTranscribing,DictationTranscript,JarvisAgentAnnouncement,JarvisAgentBackgroundCompleted,@@ -1328,6 +1332,16 @@ class SpeechPipeline:self._dictation_max_s = float(getattr(self._dictation_cfg, "max_seconds", 300.0) or 300.0)+ # Strong references to fire-and-forget bus publishes (see+ # ``_publish_event_soon``); entries remove themselves when they finish.+ self._detached_publishes: set[asyncio.Task[None]] = set()+ # Deadline that BOUNDS the wake-word block a dictation imposes. 0.0 is+ # "no block", so an instance that never dictates can never go deaf.+ self._dictation_wake_block_until = 0.0+ # Whether the current dictation already published its terminal+ # ``DictationCompleted``. Starts True ("nothing owed") so no teardown+ # can fire a completion for a dictation that never ran.+ self._dictation_completion_published = True# Where the finished transcript goes for the CURRENT dictation run:# "chat" only publishes the transcript event (the chat composer's mic# button), "insert" additionally pastes it into the focused field of@@ -2844,6 +2858,54 @@ class SpeechPipeline:log.warning("Voice capture permission gate failed closed: %s", exc)return False+ def _dictation_blocks_activation(self) -> bool:+ """True while a running dictation must keep the wake word silent.++ The maintainer's contract: a dictation turn owns the microphone, so the+ words being dictated must never trip the wake word (and two native input+ streams must never race for the same device — BUG-014 / AP-24).++ This is a STATE gate, not the content gate AP-27 forbids: it asks+ whether an application task is alive, with zero reference to audio or to+ any transcript, exactly like the three gates it sits beside+ (``_wake_lock_until``, mute, ``_state != IDLE``). It changes WHEN wake is+ listened to, never HOW a candidate is judged.++ Two independent things must BOTH hold for wake to stay blocked:++ 1. ``_dictation_task`` is alive. Derived from ``task.done()``, never a+ bare bool somebody has to remember to clear — a crashed, cancelled or+ returned task is ``done()``, so the block lifts by itself.+ 2. The watchdog deadline has not passed. ``_dictation_wake_block_until``+ is a timestamp set at start, mirroring ``_wake_lock_until``. A task+ that somehow hangs forever therefore still cannot deafen the wake+ word beyond it.++ Both defaults fail OPEN (no task → False, missing deadline → 0.0 →+ False), because the failure this guards against is BUG-037: permanently+ deaf with no visible cause and only a restart to fix.+ """+ task = getattr(self, "_dictation_task", None)+ if task is None or task.done():+ return False+ return time.time() < float(getattr(self, "_dictation_wake_block_until", 0.0))++ def _activation_block_reason(self) -> str:+ """The honest English reason ``_activation_allowed`` is saying no.++ One source for every log line that reports the closed gate. It exists+ because those lines used to hardcode two guesses ("muted" /+ "window not visible?"), and the wrong guess once misled a live freeze+ diagnosis. Returns an empty string when the gate is open.+ """+ if getattr(self, "_muted", False):+ return "voice is muted"+ if self._dictation_blocks_activation():+ return "a dictation is running"+ if not self._capture_permission_allowed():+ return "microphone capture is not permitted (desktop window not visible?)"+ return ""+def _activation_allowed(self) -> bool:"""True when external UI/lifecycle state permits voice activation.@@ -2851,12 +2913,23 @@ class SpeechPipeline:return False so the wake-loop ignores every detection. The loopkeeps spinning; unmuting is one bool flip away.+ A running dictation closes the same gate (``_dictation_blocks_activation``)+ — one edit reaches all three wake gates (loop entry, pre-emit, state+ loop) plus the push-to-talk and ``request_voice_session`` entry points,+ because this predicate is the only one all of them consult.+``getattr`` defaults to False for pipelines constructed via``__new__`` (used by privacy/vision unit tests that bypass``__init__``) — those instances are never muted by definition.++ NB: ``dictation_available`` / ``start_dictation`` deliberately consult+ ``_capture_permission_allowed`` and NOT this predicate. Routing them+ through here would make a dictation forbid its own successor."""if getattr(self, "_muted", False):return False+ if self._dictation_blocks_activation():+ return Falsereturn self._capture_permission_allowed()@property@@ -2925,6 +2998,49 @@ class SpeechPipeline:except Exception as exc: # noqa: BLE001log.warning("%s publish failed: %s", type(event).__name__, exc)+ def _publish_event_soon(self, event: Any) -> None:+ """Publish from SYNCHRONOUS code without blocking the caller.++ ``start_dictation`` and the dictation teardown both have to announce+ themselves from places that cannot ``await``: a plain method, and a+ ``finally`` in a task that may already be cancelled. Scheduling the+ publish as its own task keeps both honest — a cancelled dictation still+ gets its terminal event out, and a broken subscriber can never propagate+ back into the caller (AP-18).++ A missing bus or a missing loop is a clean no-op: unit tests build+ pipelines via ``__new__`` and must not need an event bus to exercise the+ dictation lane.+ """+ if getattr(self, "_bus", None) is None:+ return++ def _spawn(loop: asyncio.AbstractEventLoop) -> None:+ # Hold a strong reference until the publish finishes: the event loop+ # only keeps a weak one, so a fire-and-forget task can be collected+ # mid-flight and the event would simply vanish.+ pending = getattr(self, "_detached_publishes", None)+ if pending is None:+ pending = set()+ self._detached_publishes = pending+ task = loop.create_task(self._publish_event(event))+ pending.add(task)+ task.add_done_callback(pending.discard)++ try:+ _spawn(asyncio.get_running_loop())+ return+ except RuntimeError:+ pass+ owner = getattr(self, "_runtime_loop", None)+ if owner is None or not owner.is_running():+ log.debug("%s not published: no running loop.", type(event).__name__)+ return+ try:+ owner.call_soon_threadsafe(_spawn, owner)+ except RuntimeError as exc:+ log.debug("%s publish scheduling failed: %s", type(event).__name__, exc)+async def _publish_utterance_captured(self, pcm: bytes) -> None:duration_ms = int((len(pcm) / 2) / 16_000 * 1000)audio_ref = hashlib.sha256(pcm).hexdigest()[:16]@@ -4657,7 +4773,15 @@ class SpeechPipeline:if self._ptt_mode or self._state != PipelineState.IDLE:returnif not self._activation_allowed():- log.info("PTT press ignored: Desktop-App not visible.")+ # Push-to-talk is gated by the SAME predicate as wake, so a running+ # dictation refuses it too — deliberately: both lanes open their own+ # microphone stream, and two native input streams on one device is+ # the BUG-014 family. The reason is resolved, never guessed, so the+ # log cannot claim "window not visible" during a dictation.+ log.info(+ "PTT press ignored: %s",+ self._activation_block_reason() or "activation not allowed",+ )return# NB: the post-hangup wake-lock is deliberately NOT consulted here. That# lock exists to stop Jarvis' own TTS tail from re-triggering the *wake@@ -4705,7 +4829,10 @@ class SpeechPipeline:log.info("request_voice_session ignored: pipeline not idle.")return Falseif not self._activation_allowed():- log.info("request_voice_session ignored: activation not allowed.")+ log.info(+ "request_voice_session ignored: %s",+ self._activation_block_reason() or "activation not allowed",+ )return Falseif seed_messages:brain = getattr(self, "_brain", None)@@ -5240,17 +5367,14 @@ class SpeechPipeline:if not self._activation_allowed():now = time.time()if now - gate_blocked_logged_at > 30.0:- # Name the REAL reason: mute is checked first in- # _activation_allowed, so a muted user must not be told the- # window is hidden (that misled a live freeze diagnosis).- reason = (- "voice is muted"- if getattr(self, "_muted", False)- else "desktop window not visible?"- )+ # Name the REAL reason. This line used to guess between two+ # causes and the wrong guess once misled a live freeze+ # diagnosis, so the reason comes from ONE resolver that+ # knows every branch of the gate — including a running+ # dictation, which is the third way to close it.log.info(- "Wake-Loop wartet — Activation-Gate geschlossen (%s).",- reason,+ "Wake loop is waiting — activation gate closed (%s).",+ self._activation_block_reason() or "reason unknown",)gate_blocked_logged_at = nowawait asyncio.sleep(0.25)@@ -5281,6 +5405,11 @@ class SpeechPipeline:"""if self._state != PipelineState.IDLE:return False+ if self._dictation_blocks_activation():+ # A dictation leaves ``_state`` at IDLE on purpose, so without this+ # clause an unverified candidate would still flash the bar out of+ # its dictation look and back, mid-recording.+ return Falseplan = getattr(self, "_wake_plan", None)if plan is None:return True@@ -5300,6 +5429,8 @@ class SpeechPipeline:"""if active and self._state != PipelineState.IDLE:return # a session is already running; nothing to reveal+ if active and self._dictation_blocks_activation():+ return # a dictation owns the bar; never flash the wake look over itif active:self._begin_wake_preroll()else:@@ -7434,28 +7565,59 @@ class SpeechPipeline:Returns ``False`` when it cannot start — a voice/PTT session is active,the pipeline is busy, dictation is already running, or no STT is wired.- The caller (hotkey edge, WS handler, REST route) turns ``False`` into an- honest message rather than silently doing nothing.++ **Every refusal is announced**, not just logged: each one publishes a+ ``DictationRefused`` carrying a stable reason token and a finished+ English sentence. Before that, a refused shortcut produced a+ ``log.info`` in a file the desktop app cannot display (CLAUDE.md §9), so+ the key simply did nothing and the user had no way to learn why. The+ boolean return is unchanged, so every existing caller (hotkey edge, WS+ handler, REST route) keeps working.This NEVER routes to the brain: it spawns ``_dictation_session`` which- only publishes ``DictationTranscript`` / ``DictationCompleted`` events.+ only publishes ``DictationStarted`` / ``DictationTranscript`` /+ ``DictationTranscribing`` / ``DictationCompleted`` events."""if not self._capture_permission_allowed():- log.info("start_dictation ignored: microphone access is not ready.")+ self._refuse_dictation(+ "microphone_unavailable",+ "Microphone access is not ready — check the microphone "+ "permission and make sure the desktop window is available.",+ )return Falseif self._utterance_stt is None:- log.info("start_dictation ignored: no STT provider.")+ self._refuse_dictation(+ "no_stt",+ "No speech-to-text provider is configured, so there is nothing "+ "to transcribe with. Add a provider key in Settings.",+ )return Falseif self._dictation_task is not None and not self._dictation_task.done():- log.info("start_dictation ignored: dictation already running.")+ self._refuse_dictation(+ "already_running",+ "A dictation is already recording.",+ )return Falseif self._ptt_mode or self._state != PipelineState.IDLE:- log.info("start_dictation ignored: pipeline not idle.")+ # Deliberate: a live voice conversation owns the microphone, and the+ # dictation lane opens its own stream. Preempting the session on a+ # keypress was considered and rejected — a hold gesture released+ # before the handover finished would leave a dictation nobody stops,+ # running to the duration cap. Refusing is the honest behaviour; the+ # defect was that the refusal was SILENT.+ self._refuse_dictation(+ "voice_session_active",+ "A voice conversation is running and is using the microphone. "+ "Hang up first, then dictate.",+ )return Falsetry:loop = asyncio.get_running_loop()except RuntimeError:- log.warning("start_dictation: no running loop.")+ self._refuse_dictation(+ "pipeline_not_running",+ "The voice pipeline is not running, so dictation cannot start.",+ )return False# A fresh dictation session must NOT inherit a stale hangup. ``_hangup_event``# is set by every "auflegen" and is otherwise only cleared when the next@@ -7474,6 +7636,30 @@ class SpeechPipeline:# resolving at start would have sent that text to the chat box.self._dictation_target = target if target in ("insert", "chat") else "auto"self._dictation_stop_event = asyncio.Event()+ # Watchdog deadline for the wake-word block (see+ # ``_dictation_blocks_activation``). It is a TIMESTAMP, copying the+ # ``_wake_lock_until`` pattern, so a dictation task that somehow never+ # terminates still cannot leave the wake word deaf forever — the worst+ # case is bounded instead of needing an app restart (BUG-037). The+ # allowance on top of the recording cap covers the closing+ # transcription, which runs after the microphone is already released.+ self._dictation_wake_block_until = (+ time.time() + float(getattr(self, "_dictation_max_s", 300.0) or 300.0) + 60.0+ )+ # Reset BEFORE the task exists: the teardown guarantee below reads this+ # to decide whether a terminal event still has to be published.+ self._dictation_completion_published = False+ # Announce the turn BEFORE the first audio frame. Queued ahead of the+ # session task on purpose: nothing has opened the microphone yet when+ # this method returns, so a UI surface can show "listening" at key-down+ # speed instead of waiting for the first partial transcript — which+ # costs a partial interval plus an STT round-trip, and for a short press+ # never arrives at all.+ self._publish_event_soon(+ DictationStarted(+ source_layer="speech.dictation", target=self._dictation_target+ )+ )self._dictation_task = loop.create_task(self._dictation_session(), name="dictation")@@ -7483,6 +7669,27 @@ class SpeechPipeline:)return True+ def _refuse_dictation(self, reason: str, detail: str) -> None:+ """Log AND announce a refused dictation start.++ ``reason`` must come from ``DICTATION_REFUSAL_REASONS`` — the single+ vocabulary for this value, checked here so a new branch that forgets to+ extend it is caught in the log instead of reaching a UI that has never+ heard of the token (AP-4 / BUG-008).+ """+ if reason not in DICTATION_REFUSAL_REASONS:+ log.warning(+ "Unknown dictation refusal reason %r — add it to "+ "DICTATION_REFUSAL_REASONS.",+ reason,+ )+ log.info("start_dictation refused (%s): %s", reason, detail)+ self._publish_event_soon(+ DictationRefused(+ source_layer="speech.dictation", reason=reason, detail=detail+ )+ )+def dictation_active(self) -> bool:"""Is a dictation running right now? (REST/UI status, cheap.)"""task = self._dictation_task@@ -7524,6 +7731,19 @@ class SpeechPipeline:"""stt = self._utterance_sttif stt is None:+ # ``start_dictation`` already refused this case; only a provider+ # swapped out between the two calls can land here. Close the turn+ # anyway, so a surface that opened on ``DictationStarted`` can never+ # be left showing a dictation that is not running.+ self._dictation_completion_published = True+ self._publish_event_soon(+ DictationCompleted(+ source_layer="speech.dictation",+ outcome="failed",+ detail="No speech-to-text provider is available.",+ error="no_stt",+ )+ )return# ``getattr`` defaults keep pipelines built via ``__new__`` working —# a widely used pattern in this repo's unit tests, which bypass@@ -7708,6 +7928,18 @@ class SpeechPipeline:except (asyncio.CancelledError, Exception): # noqa: BLE001pass+ # The microphone lease is now closed on EVERY end path — key+ # release, hands-free toggle, duration cap, REST/WS stop. That is+ # the honest moment to say "no longer listening, still working":+ # announce it here rather than from ``stop_dictation``, which only+ # sets an event and does not know when the stream actually stopped.+ # A hangup skips it: nothing will be transcribed, and+ # ``DictationCompleted`` follows immediately.+ if not hung_up:+ await self._publish_event(+ DictationTranscribing(source_layer="speech.dictation")+ )+# The mic lease is closed before waiting on the probe, so releasing# the key always ends the recording even if a probe call is slow.if probe_task is not None:@@ -7780,6 +8012,27 @@ class SpeechPipeline:)except Exception: # noqa: BLE001pass+ finally:+ # Terminal-event guarantee. Consumers open on ``DictationStarted``+ # and close on ``DictationCompleted``, so any path that ends without+ # a completion leaves a surface showing a dictation that is not+ # running — and, until the task is collected, the wake-word block+ # depends on the same task, not on this event, so the two can never+ # disagree. ``asyncio.CancelledError`` is a ``BaseException`` and+ # skips the handler above; a crash inside ``_finish_dictation`` can+ # also abort before it publishes. Both land here. Scheduled rather+ # than awaited, because awaiting inside a cancelled task is not+ # reliable.+ if not getattr(self, "_dictation_completion_published", True):+ self._dictation_completion_published = True+ self._publish_event_soon(+ DictationCompleted(+ source_layer="speech.dictation",+ outcome="cancelled",+ detail="The dictation ended before it produced text.",+ duration_s=max(0.0, time.monotonic() - started_at),+ )+ )async def _finish_dictation(self,@@ -7882,6 +8135,10 @@ class SpeechPipeline:detail = insert_result.detailmethod = insert_result.method+ # Mark the turn closed BEFORE the publish attempt: this flag answers+ # "does the teardown still owe a terminal event", and a publish that+ # raised is not a reason to fire a second, contradictory completion.+ self._dictation_completion_published = Truetry:await self._publish_event(DictationCompleted(diff --git a/jarvis/ui/web/ultrawiki_routes.py b/jarvis/ui/web/ultrawiki_routes.pyindex 53b53d29b1..94ee81b82a 100644--- a/jarvis/ui/web/ultrawiki_routes.py+++ b/jarvis/ui/web/ultrawiki_routes.py@@ -1051,24 +1051,7 @@ async def activate_mode(body: ActivateBody, request: Request) -> dict[str, Any]:# in silence — the 2026-07-28 forensic. `reconcile_space` is idempotent# and a no-op when the model already matches, so the ordinary "switch# Ultra back on" path costs two primary-key reads.- space_rebuild = ""- try:- store = await _store_of(service)- verdict = await store.reconcile_space(- _effective_embedding_model(_uw_cfg(request), values)- )- if verdict == "started":- space_rebuild = "started"- elif verdict == "rebuilding":- space_rebuild = "running"- except Exception: # noqa: BLE001 — activation succeeded; the pipeline retries- # `_reconcile_embedding_space` asks again on every pass, so a failure- # here delays the rebuild by one pass instead of losing it.- log.warning(- "UltraWiki: could not reconcile the embedding space during "- "activation; the pipeline reconciles on its next pass",- exc_info=True,- )+ space_rebuild = await _register_embedding_space(service, _uw_cfg(request), values)# The pipeline only starts while the mode is on, so it is started here —# after the flip, never before it.@@ -1179,6 +1162,31 @@ def _effective_embedding_model(uw: Any, changes: dict[str, str]) -> str:return embeddings_mod.DEFAULT_MODELS.get(provider.strip(), "")+async def _register_embedding_space(+ service: Any, uw: Any, changes: dict[str, str]+) -> str:+ """Tell the store which vector space the config now names.++ Returns the store's verdict — ``"started"`` (a rebuild was registered),+ ``"rebuilding"``, ``"active"`` — or ``""`` when the store could not be+ asked. Never raises: the pipeline reconciles again on its next pass, so a+ failure here delays the switch, it does not lose it.+ """+ model = _effective_embedding_model(uw, changes)+ if not model:+ return ""+ try:+ store = await _store_of(service)+ return str(await store.reconcile_space(model) or "")+ except Exception: # noqa: BLE001 — a settings save must not 500 on this+ log.warning(+ "UltraWiki: could not reconcile the embedding space; the pipeline "+ "reconciles on its next pass",+ exc_info=True,+ )+ return ""++@router.put("/settings",summary="Change UltraWiki slot settings",@@ -1219,7 +1227,23 @@ async def update_settings(body: UpdateSettingsBody, request: Request) -> dict[st}ranking_changes = _ranking_changes(body, uw)if not changes and not ranking_changes:- return {"ok": True, "changed": [], "persisted": True, "reembed_started": False}+ # Nothing to WRITE — but "the config already says this" is not the same+ # as "the store already does this", and treating them as equal is what+ # locked a maintainer out of his own repair path for a day (forensic+ # 2026-07-28). The config named gemini-embedding-001 while the store was+ # still pinned to text-embedding-3-large, so every vector was rejected;+ # re-picking Gemini produced exactly this branch — `changed: []`, a+ # cheerful 200, and nothing done. The screen that exists to fix the+ # divergence was the one screen that could not, and the harder he tried+ # the more certain it became.+ verdict = await _register_embedding_space(service, uw, {})+ return {+ "ok": True,+ "changed": [],+ "persisted": True,+ "reembed_started": verdict in ("started", "rebuilding"),+ "embedding_space_rebuild": verdict,+ }if "db_backend" in changes and changes["db_backend"] not in ("sqlite", "postgres"):raise HTTPException(diff --git a/tests/unit/speech/test_dictation_lifecycle_events.py b/tests/unit/speech/test_dictation_lifecycle_events.pynew file mode 100644index 0000000000..1b2542806b--- /dev/null+++ b/tests/unit/speech/test_dictation_lifecycle_events.py@@ -0,0 +1,358 @@+"""The dictation turn announces itself: started → transcribing → completed.++Before this, the only signals a dictation produced were the live transcript and+the completion — both at or after the END. A surface therefore could not show+"listening" until the first partial arrived (a partial interval plus an STT+round-trip later, and never at all for a short press), and a refused start was+a ``log.info`` in a file the desktop app cannot display (CLAUDE.md §9), so the+shortcut simply did nothing with no way to learn why.++Pinned here:++* ``DictationStarted`` is published before any audio is captured.+* ``DictationTranscribing`` is published when the microphone lease closes.+* ``DictationCompleted`` is published on EVERY end path, including a task+ killed mid-flight — otherwise a surface stays open on a dictation that is+ not running.+* Every refusal publishes ``DictationRefused`` with a reason from the one+ shared vocabulary.+"""++from __future__ import annotations++import asyncio++import pytest++import jarvis.speech.pipeline as pipeline_mod+from jarvis.core.bus import EventBus+from jarvis.core.events import (+ DICTATION_REFUSAL_REASONS,+ DictationCompleted,+ DictationRefused,+ DictationStarted,+ DictationTranscribing,+)+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+++class _StubSTT:+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover - never called+ raise AssertionError("no transcription in this unit test")+++class _FakeMic:+ """A microphone that opens, never delivers a frame, and closes cleanly."""++ opened = 0++ def __init__(self, *args: object, **kwargs: object) -> None:+ pass++ async def __aenter__(self) -> _FakeMic:+ type(self).opened += 1+ return self++ async def __aexit__(self, *exc: object) -> bool:+ return False++ async def stream(self): # type: ignore[no-untyped-def]+ await asyncio.Event().wait()+ yield # pragma: no cover - unreachable, keeps this an async generator+++class _Collector:+ def __init__(self, bus: EventBus) -> None:+ self.started: list[DictationStarted] = []+ self.transcribing: list[DictationTranscribing] = []+ self.completed: list[DictationCompleted] = []+ self.refused: list[DictationRefused] = []+ bus.subscribe(DictationStarted, self._started)+ bus.subscribe(DictationTranscribing, self._transcribing)+ bus.subscribe(DictationCompleted, self._completed)+ bus.subscribe(DictationRefused, self._refused)++ async def _started(self, event: DictationStarted) -> None:+ self.started.append(event)++ async def _transcribing(self, event: DictationTranscribing) -> None:+ self.transcribing.append(event)++ async def _completed(self, event: DictationCompleted) -> None:+ self.completed.append(event)++ async def _refused(self, event: DictationRefused) -> None:+ self.refused.append(event)+++def _dictation_pipeline(bus: EventBus) -> SpeechPipeline:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._bus = bus+ pipe._utterance_stt = _StubSTT()+ pipe._dictation_task = None+ pipe._dictation_stop_event = asyncio.Event()+ pipe._dictation_cfg = None+ pipe._dictation_max_s = 5.0+ pipe._dictation_wake_block_until = 0.0+ pipe._dictation_completion_published = True+ pipe._ptt_mode = False+ pipe._ptt_partial_interval_s = 0.0 # no live probe in these tests+ pipe._state = PipelineState.IDLE+ pipe._muted = False+ pipe._input_device = "default"+ pipe._input_priority = ()+ pipe._hangup_event = asyncio.Event()+ return pipe+++async def _drain_bus() -> None:+ """Let the scheduled publish tasks run (``_publish_event_soon``)."""+ for _ in range(4):+ await asyncio.sleep(0)+++async def _cancel_dictation(pipe: SpeechPipeline) -> None:+ task = pipe._dictation_task+ if task is not None and not task.done():+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ pass+++# --------------------------------------------------------------------------+# started+# --------------------------------------------------------------------------+++async def test_start_announces_the_turn_before_any_audio(monkeypatch) -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _FakeMic)+ opened_before = _FakeMic.opened++ assert pipe.start_dictation(target="insert") is True+ assert _FakeMic.opened == opened_before, (+ "the turn is announced at the commit point — no audio yet"+ )++ await _drain_bus()++ assert len(seen.started) == 1+ assert seen.started[0].target == "insert"+ assert seen.started[0].source_layer == "speech.dictation"++ await _cancel_dictation(pipe)+++async def test_start_arms_the_wake_watchdog_deadline(monkeypatch) -> None:+ bus = EventBus()+ _Collector(bus)+ pipe = _dictation_pipeline(bus)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _FakeMic)++ assert pipe.start_dictation() is True+ # Bounded: recording cap + a finalization allowance, never open-ended.+ assert pipe._dictation_blocks_activation() is True+ assert pipe._activation_allowed() is False++ await _cancel_dictation(pipe)+ assert pipe._activation_allowed() is True+++# --------------------------------------------------------------------------+# transcribing + completed+# --------------------------------------------------------------------------+++async def test_releasing_the_key_announces_the_transcribing_phase(monkeypatch) -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _FakeMic)++ async def _fake_finish(**kwargs: object) -> str:+ pipe._dictation_completion_published = True+ await bus.publish(DictationCompleted(source_layer="speech.dictation"))+ return ""++ pipe._finish_dictation = _fake_finish # type: ignore[method-assign]++ assert pipe.start_dictation() is True+ await _drain_bus()+ pipe.stop_dictation()+ await asyncio.wait_for(pipe._dictation_task, timeout=5.0)+ await _drain_bus()++ assert len(seen.transcribing) == 1, (+ "the transcribing phase is announced exactly once, when the microphone lease closes"+ )+ assert len(seen.completed) == 1+ # Ordering is the whole point: listening → transcribing → done.+ assert seen.started[0].timestamp_ns <= seen.transcribing[0].timestamp_ns+++async def test_a_dictation_killed_mid_flight_still_closes_its_turn(+ monkeypatch,+) -> None:+ """A cancelled task must not leave a surface stuck showing a dictation."""+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _FakeMic)++ assert pipe.start_dictation() is True+ await _drain_bus()+ assert len(seen.started) == 1+ assert seen.completed == []++ await _cancel_dictation(pipe)+ await _drain_bus()++ assert len(seen.completed) == 1+ assert seen.completed[0].outcome == "cancelled"+ assert seen.completed[0].detail+ # ...and wake is listening again.+ assert pipe._activation_allowed() is True+++async def test_a_crashing_dictation_publishes_exactly_one_completion(+ monkeypatch,+) -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)++ class _ExplodingMic(_FakeMic):+ async def __aenter__(self): # type: ignore[no-untyped-def]+ raise RuntimeError("microphone is on fire")++ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _ExplodingMic)++ async def _fake_finish(**kwargs: object) -> str:+ pipe._dictation_completion_published = True+ await bus.publish(DictationCompleted(source_layer="speech.dictation", outcome="failed"))+ return ""++ pipe._finish_dictation = _fake_finish # type: ignore[method-assign]++ assert pipe.start_dictation() is True+ await asyncio.wait_for(pipe._dictation_task, timeout=5.0)+ await _drain_bus()++ assert len(seen.completed) == 1, "the teardown must never double-publish"+ assert seen.completed[0].outcome == "failed"+ assert pipe._activation_allowed() is True+++# --------------------------------------------------------------------------+# refusals+# --------------------------------------------------------------------------+++async def test_a_closed_capture_gate_is_refused_out_loud() -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ pipe._activation_gate = lambda: False++ assert pipe.start_dictation() is False+ await _drain_bus()++ assert [e.reason for e in seen.refused] == ["microphone_unavailable"]+ assert seen.refused[0].detail+ assert seen.started == []+++async def test_a_missing_stt_provider_is_refused_out_loud() -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ pipe._utterance_stt = None++ assert pipe.start_dictation() is False+ await _drain_bus()++ assert [e.reason for e in seen.refused] == ["no_stt"]+++async def test_a_second_start_while_recording_is_refused_out_loud(+ monkeypatch,+) -> None:+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", _FakeMic)++ assert pipe.start_dictation() is True+ assert pipe.start_dictation() is False+ await _drain_bus()++ assert [e.reason for e in seen.refused] == ["already_running"]++ await _cancel_dictation(pipe)+++async def test_the_dictation_key_during_a_voice_session_says_so() -> None:+ """The collision case: a live voice conversation owns the microphone.++ Refusing is deliberate — preempting the session on a keypress would leave a+ hold gesture released before the handover finished with a dictation nobody+ stops. What is NOT acceptable is refusing silently, which is what happened+ before: the key did nothing at all.+ """+ bus = EventBus()+ seen = _Collector(bus)+ pipe = _dictation_pipeline(bus)+ pipe._state = PipelineState.ACTIVE++ assert pipe.start_dictation() is False+ await _drain_bus()++ assert [e.reason for e in seen.refused] == ["voice_session_active"]+ assert "microphone" in seen.refused[0].detail.lower()++ # Push-to-talk is the same collision through a different door.+ pipe._state = PipelineState.IDLE+ pipe._ptt_mode = True+ seen.refused.clear()+ assert pipe.start_dictation() is False+ await _drain_bus()+ assert [e.reason for e in seen.refused] == ["voice_session_active"]+++async def test_every_refusal_reason_comes_from_the_shared_vocabulary() -> None:+ """AP-4: the reason token crosses pipeline → bus → REST → UI."""+ bus = EventBus()+ seen = _Collector(bus)++ closed_gate = _dictation_pipeline(bus)+ closed_gate._activation_gate = lambda: False+ closed_gate.start_dictation()++ no_stt = _dictation_pipeline(bus)+ no_stt._utterance_stt = None+ no_stt.start_dictation()++ busy = _dictation_pipeline(bus)+ busy._state = PipelineState.ACTIVE+ busy.start_dictation()++ await _drain_bus()++ assert seen.refused, "the refusals must actually reach the bus"+ for event in seen.refused:+ assert event.reason in DICTATION_REFUSAL_REASONS+ assert event.detail.strip(), "a refusal without a sentence is not observable"diff --git a/tests/unit/speech/test_dictation_wake_gate.py b/tests/unit/speech/test_dictation_wake_gate.pynew file mode 100644index 0000000000..bb33c06525--- /dev/null+++ b/tests/unit/speech/test_dictation_wake_gate.py@@ -0,0 +1,227 @@+"""The wake word must stay silent while a dictation is running — and only then.++Maintainer contract: pressing the dictation shortcut is a dictation turn, so+the words being dictated must never trip the wake word. Everywhere else wake+behaves exactly as before.++The gate lives in ``SpeechPipeline._activation_allowed`` because that predicate+is the ONE thing all three wake gates consult (wake-loop entry, the pre-emit+activation point, and the state-loop backstop), plus push-to-talk and+``request_voice_session``.++Why the shape of the gate matters more than the gate itself: a leaked "a+dictation is running" flag is BUG-037 — permanently deaf with no visible cause+and only an app restart to fix it. So the condition is derived from the live+task (``task.done()`` clears it even on a crash) AND bounded by a watchdog+deadline (a task that hangs forever still cannot deafen wake forever). These+tests pin both halves, including a task killed mid-flight.++This is a STATE gate, not the transcript-CONTENT gate AP-27 forbids: it never+looks at audio or at any recognized text.+"""++from __future__ import annotations++import asyncio+import time++import pytest++from jarvis.core.bus import EventBus+from jarvis.core.events import WakeCandidateDetected+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+++class _StubSTT:+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover - never called+ raise AssertionError("no transcription in this unit test")+++def _gate_pipeline() -> SpeechPipeline:+ """A pipeline reduced to exactly what the activation gate reads."""+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._muted = False+ pipe._state = PipelineState.IDLE+ pipe._dictation_task = None+ pipe._dictation_wake_block_until = 0.0+ return pipe+++async def _blocking_task() -> None:+ await asyncio.Event().wait()+++# --------------------------------------------------------------------------+# The gate itself+# --------------------------------------------------------------------------+++def test_wake_is_allowed_when_no_dictation_runs() -> None:+ pipe = _gate_pipeline()+ assert pipe._dictation_blocks_activation() is False+ assert pipe._activation_allowed() is True+ assert pipe._activation_block_reason() == ""+++async def test_a_running_dictation_closes_the_activation_gate() -> None:+ pipe = _gate_pipeline()+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0+ try:+ assert pipe._dictation_blocks_activation() is True+ assert pipe._activation_allowed() is False+ assert pipe._activation_block_reason() == "a dictation is running"+ finally:+ pipe._dictation_task.cancel()+++async def test_wake_returns_the_moment_the_dictation_task_finishes() -> None:+ pipe = _gate_pipeline()++ done_now = asyncio.Event()++ async def _short() -> None:+ await done_now.wait()++ pipe._dictation_task = asyncio.create_task(_short())+ pipe._dictation_wake_block_until = time.time() + 300.0+ await asyncio.sleep(0)+ assert pipe._activation_allowed() is False++ done_now.set()+ await pipe._dictation_task++ assert pipe._activation_allowed() is True+ assert pipe._activation_block_reason() == ""+++async def test_a_dictation_task_killed_mid_flight_leaves_wake_working() -> None:+ """The BUG-037 case: the dictation dies, nobody clears anything.++ Nothing runs a ``finally`` here — the task is cancelled outright — so this+ is exactly the situation in which a bare bool would stay True and Jarvis+ would go permanently deaf.+ """+ pipe = _gate_pipeline()+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0+ await asyncio.sleep(0)+ assert pipe._activation_allowed() is False++ pipe._dictation_task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await pipe._dictation_task++ assert pipe._dictation_blocks_activation() is False+ assert pipe._activation_allowed() is True+++async def test_a_crashed_dictation_task_leaves_wake_working() -> None:+ pipe = _gate_pipeline()++ async def _boom() -> None:+ raise RuntimeError("dictation exploded")++ pipe._dictation_task = asyncio.create_task(_boom())+ pipe._dictation_wake_block_until = time.time() + 300.0+ with pytest.raises(RuntimeError):+ await pipe._dictation_task++ assert pipe._activation_allowed() is True+++async def test_the_block_expires_even_if_the_dictation_task_never_ends() -> None:+ """The watchdog half: a hung task must not deafen wake beyond the deadline."""+ pipe = _gate_pipeline()+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ try:+ pipe._dictation_wake_block_until = time.time() + 5.0+ assert pipe._activation_allowed() is False++ # The task is still very much alive; only the deadline has passed.+ pipe._dictation_wake_block_until = time.time() - 0.001+ assert pipe._dictation_task.done() is False+ assert pipe._dictation_blocks_activation() is False+ assert pipe._activation_allowed() is True+ finally:+ pipe._dictation_task.cancel()+++def test_a_pipeline_that_never_dictated_is_never_blocked() -> None:+ """Both defaults fail OPEN — a missing attribute can never cause deafness."""+ bare = SpeechPipeline.__new__(SpeechPipeline)+ assert bare._dictation_blocks_activation() is False+++async def test_mute_still_wins_and_is_reported_first() -> None:+ """Mute is checked before dictation, so a muted user is told the truth."""+ pipe = _gate_pipeline()+ pipe._muted = True+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0+ try:+ assert pipe._activation_allowed() is False+ assert pipe._activation_block_reason() == "voice is muted"+ finally:+ pipe._dictation_task.cancel()+++def test_a_closed_capture_gate_is_named_without_guessing() -> None:+ pipe = _gate_pipeline()+ pipe._activation_gate = lambda: False+ assert pipe._activation_allowed() is False+ assert "microphone capture is not permitted" in pipe._activation_block_reason()+++# --------------------------------------------------------------------------+# The bar must not flicker out of its dictation look+# --------------------------------------------------------------------------+++async def test_the_optimistic_wake_candidate_is_suppressed_during_dictation() -> None:+ """A dictation leaves ``_state`` at IDLE, so this needs its own clause."""+ pipe = _gate_pipeline()+ assert pipe._should_show_optimistic_candidate() is True++ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0+ try:+ assert pipe._should_show_optimistic_candidate() is False+ finally:+ pipe._dictation_task.cancel()+++async def test_an_early_vosk_candidate_is_suppressed_but_a_retract_still_passes() -> None:+ bus = EventBus()+ seen: list[WakeCandidateDetected] = []++ async def _collect(event: WakeCandidateDetected) -> None:+ seen.append(event)++ bus.subscribe(WakeCandidateDetected, _collect)++ pipe = _gate_pipeline()+ pipe._bus = bus+ pipe._begin_wake_preroll = lambda: None # type: ignore[method-assign]+ pipe._discard_wake_preroll = lambda: None # type: ignore[method-assign]+ pipe._dictation_task = asyncio.create_task(_blocking_task())+ pipe._dictation_wake_block_until = time.time() + 300.0+ try:+ await pipe._vosk_early_candidate_listener(True)+ assert seen == [], "a dictation owns the bar; no wake look may flash"++ # A retract must ALWAYS pass through, or a bar shown before the+ # dictation started could stay stuck in the wake look.+ await pipe._vosk_early_candidate_listener(False)+ assert len(seen) == 1+ assert seen[0].active is False+ finally:+ pipe._dictation_task.cancel()diff --git a/tests/unit/web/test_ultrawiki_routes.py b/tests/unit/web/test_ultrawiki_routes.pyindex ac290629d5..bf02f7340c 100644--- a/tests/unit/web/test_ultrawiki_routes.py+++ b/tests/unit/web/test_ultrawiki_routes.py@@ -405,9 +405,50 @@ def test_update_settings_without_changes_is_noop(env) -> None:"changed": [],"persisted": True,"reembed_started": False,+ "embedding_space_rebuild": "active",}+def test_picking_the_already_configured_model_still_repairs_the_store(env) -> None:+ """The trap that locked a maintainer out of his own repair path.++ "Nothing to WRITE" was treated as "nothing to DO". Once the config named+ one embedding model while the store was still pinned to another — however+ that divergence arose — the store rejected every vector the provider+ produced and the embed lane failed 100 % of its work. Re-picking the model+ in the settings screen was the obvious fix, and it hit this branch: the+ values matched the config, `changed` came back empty, the screen reported+ success, and the store was never told. The one screen that exists to+ resolve the divergence was the one screen that could not, and clicking+ again only made it more certain (forensic 2026-07-28).+ """+ _activate(env)+ _source_id, job_id = _approve_and_sync_folder(env)+ _wait_for_job(env, job_id)+ _drive_pipeline(env)++ # The divergence: the config names a model the store has never seen. This+ # is reachable through every path that writes config without registering+ # the switch — the activation route, a voice config change, a hand-edited+ # jarvis.toml, a config carried over from another machine.+ env.cfg.ultrawiki.embedding_model = "fake-embed-2"++ response = env.client.put(+ "/api/ultrawiki/settings", json={"embedding_model": "fake-embed-2"}+ )+ assert response.status_code == 200, response.text+ body = response.json()+ assert body["changed"] == [] # still nothing to write...+ assert body["embedding_space_rebuild"] == "started" # ...but plenty to do+ assert body["reembed_started"] is True++ # The store now builds the space the config actually names, and semantic+ # search keeps answering from the live vectors until it is complete.+ status = env.client.get("/api/ultrawiki/status").json()+ assert status["reembed"].get("model") == "fake-embed-2"+ assert status["slots"]["storage"]["vector"]["ready"] is True++# ---------------------------------------------------------------------------# Ranking settings (rerank slot + the knobs it governs)# ---------------------------------------------------------------------------