Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(dictation): every stop gesture ends a running dictation, and a hold recording follows the physical key

rubenluetke10-beep2ccb1ec4a06f
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2f8bcd8823..5b9348419f 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -917,6 +917,21 @@ _DICTATION_FINAL_RETRY_DELAY_S = 0.6
# ceiling at all — and is preserved rather than replaced by this.
_DICTATION_DEFAULT_MAX_S = 1800.0
+# The hold-key watchdog (BUG-191). While a HOLD-started dictation records, the
+# hotkey backend is asked whether the chord is still physically down. The
+# press/release EDGES can be lost between the OS poller and this pipeline — a
+# checker restart mid-hold, a handler that raised, a registry re-arm — and a
+# lane that only ever hears edges then records until its 30-minute cap with
+# nothing the user presses able to stop it. The keyboard itself cannot go
+# stale: a chord that reads "up" for this long, with no release edge having
+# arrived, IS the release, and the recording is finished the way a release
+# would finish it. One second is far longer than any poll jitter and far
+# shorter than a user notices; the poll is cheap (one ``GetAsyncKeyState``
+# sweep). A backend that cannot see the keyboard answers ``None`` and the
+# watchdog stands down — it never invents a release.
+_DICTATE_HOLD_LOST_RELEASE_S = 1.0
+_DICTATE_HOLD_WATCH_POLL_S = 0.25
+
# How long the wake word stays blocked when the recording itself is unbounded.
# The block exists so a wedged dictation task cannot leave the wake word deaf
# until the app is restarted (BUG-037), so it may never be unbounded even when
@@ -2342,14 +2357,31 @@ class SpeechPipeline:
# a single-key install re-resolves on every failed turn.
self._voice_stt_fallback_chain: tuple[str, ...] | None = None
self._voice_stt_fallback_instances: dict[str, Any] = {}
- # True while a hold-mode dictation key is physically down. Mirrors
- # ``_ptt_mode`` for the dictation lane so a repeated press edge (the
- # Windows backend polls and re-fires on_press while held) is idempotent.
+ # True while a hold-mode dictation key is physically down, as far as
+ # the press/release EDGES have told us. Mirrors ``_ptt_mode`` for the
+ # dictation lane. (The Windows poller fires on_press ONCE per chord-down
+ # — ``HotkeyChecker.run`` gates it on ``key_state != 1`` — so this is an
+ # edge latch, not a heartbeat; the physical truth is asked separately
+ # through ``HotkeyTrigger.chord_is_down`` while a hold records.)
self._dictate_key_down = False
# Monotonic time of the last press edge that reported the key as down.
# It is what makes the latch above self-healing: see
# ``_on_dictate_press`` and ``_DICTATE_HOLD_REPEAT_GRACE_S``.
self._dictate_key_seen_at = 0.0
+ # The live ``HotkeyTrigger`` while the pipeline runs — the hold-key
+ # watchdog asks it whether the dictation chord is physically down.
+ self._hotkey_trigger: Any = None
+ # Which door the running dictation came through (``hold_key``,
+ # ``toggle_key``, ``ws``, ``rest``, ``api``). Logged on start so the
+ # next "it never stopped" report can be read, and it decides whether the
+ # hold-key watchdog applies: only a hold-started recording is owed a
+ # release edge.
+ self._dictation_started_by = ""
+ # Set by ``request_dictation_stop(discard=True)`` — the bar's close-X.
+ # The recording ends through the ordinary stop event, and this flag
+ # makes the session treat it as a hangup: nothing transcribed, nothing
+ # delivered. Reset at every commit.
+ self._dictation_discard_requested = False
# ``self._stt`` is the LOCAL FasterWhisperProvider used by the wake
# backstop + VAD endpoint-probe (many calls/sec, a cloud round-trip
# would be too slow). In the cloud-first lightweight path it is None:
@@ -5998,6 +6030,9 @@ class SpeechPipeline:
)
async with HotkeyTrigger(hotkey_bindings, push_to_talk=ptt_events) as trigger:
+ # Kept for the hold-key watchdog (``_watch_dictation_hold_key``),
+ # which asks the live trigger whether the chord is physically down.
+ self._hotkey_trigger = trigger
hotkey_task = asyncio.create_task(self._hotkey_loop(trigger), name="hotkey")
hotkey_task.add_done_callback(_log_task_exit)
# Live keybind re-arm: set_keybinds() flips _hotkey_reload_event and
@@ -6034,6 +6069,7 @@ class SpeechPipeline:
try:
await main_task
finally:
+ self._hotkey_trigger = None
self._cron_stop.set()
tasks_to_cancel: list[asyncio.Task] = [hotkey_task, hotkey_reload_task]
if wake_task is not None:
@@ -6467,32 +6503,44 @@ class SpeechPipeline:
async def _hotkey_loop(self, trigger: HotkeyTrigger) -> None:
async for event_name in trigger.events():
- if event_name == "call":
- log.info("📞 CALL via Hotkey")
- # A deliberate key press — exempt from the post-hangup wake
- # lock (no speaker-echo path), same contract as PTT below.
- self._explicit_call_pending = True
- self._call_event.set()
- elif event_name == "ptt_press":
- self._on_ptt_press()
- elif event_name == "ptt_release":
- self._on_ptt_release()
- elif event_name == "dictate_press":
- self._on_dictate_press()
- elif event_name == "dictate_release":
- self._on_dictate_release()
- elif event_name == "dictate":
- # Legacy [dictation].mode = "toggle": one press starts, the
- # next stops. Only reached when the HOLD key is in toggle mode.
- self._on_dictate_toggle()
- elif event_name == "dictate_toggle":
- # The dedicated hands-free key. Same handler, its own binding.
- self._on_dictate_toggle()
- elif event_name == "paste_last":
- self._on_paste_last()
- elif event_name == "hangup":
- log.info("📵 HANGUP via Hotkey")
- self._trigger_voice_hangup()
+ # One raising handler must not end this loop: it is the ONLY
+ # consumer of every global shortcut, and its death is invisible
+ # from the desktop (a log line the WebView cannot show) — every
+ # key simply stops working until a restart. The edge is dropped,
+ # the next one is served (AP-18 for the hotkey lane, BUG-191).
+ try:
+ self._dispatch_hotkey_event(event_name)
+ except Exception: # noqa: BLE001 — contained on purpose, logged in full
+ log.exception("Hotkey %r handler failed; the edge was dropped.", event_name)
+
+ def _dispatch_hotkey_event(self, event_name: str) -> None:
+ """Route one hotkey edge to its handler (the body of ``_hotkey_loop``)."""
+ if event_name == "call":
+ log.info("📞 CALL via Hotkey")
+ # A deliberate key press — exempt from the post-hangup wake
+ # lock (no speaker-echo path), same contract as PTT below.
+ self._explicit_call_pending = True
+ self._call_event.set()
+ elif event_name == "ptt_press":
+ self._on_ptt_press()
+ elif event_name == "ptt_release":
+ self._on_ptt_release()
+ elif event_name == "dictate_press":
+ self._on_dictate_press()
+ elif event_name == "dictate_release":
+ self._on_dictate_release()
+ elif event_name == "dictate":
+ # Legacy [dictation].mode = "toggle": one press starts, the
+ # next stops. Only reached when the HOLD key is in toggle mode.
+ self._on_dictate_toggle()
+ elif event_name == "dictate_toggle":
+ # The dedicated hands-free key. Same handler, its own binding.
+ self._on_dictate_toggle()
+ elif event_name == "paste_last":
+ self._on_paste_last()
+ elif event_name == "hangup":
+ log.info("📵 HANGUP via Hotkey")
+ self._trigger_voice_hangup()
# ------------------------------------------------------------------
# Dictation hotkey edges
@@ -6501,9 +6549,12 @@ class SpeechPipeline:
def _on_dictate_press(self) -> None:
"""Dictation key DOWN — start recording into the focused text field.
- Idempotent by design: the Windows backend polls, so ``on_press`` fires
- again on every poll while the chord is held. Only the first edge from
- "key up" starts anything.
+ Idempotent by design: every backend reports a press exactly once per
+ real chord-down (the Windows poller too — ``HotkeyChecker.run`` fires
+ ``on_press`` only on the ``key_state != 1`` transition, whatever older
+ comments in this file claimed), but a stray duplicate edge inside the
+ grace window is still treated as the same hold. Only the first edge
+ from "key up" starts anything.
**The latch heals itself.** A key-up edge can be lost — the pynput and
Quartz backends clear their own chord state without firing ``on_release``
@@ -6513,13 +6564,21 @@ class SpeechPipeline:
"the dictation shortcut just stopped working" with no error and no way
back except an app restart. So a press that arrives long after the last
one reported the key down is treated as what it physically is — a fresh
- press on a key nobody is holding — not as a repeat.
-
- The two cases are told apart by TIME, not by guessing: a real hold
- re-reports itself every poll tick on the polling backend (tens of
- milliseconds), while the edge-driven backends report a press exactly once
- per real chord-down. Anything past the grace window is therefore either a
- lost key-up or a genuinely new press, and both want the same repair.
+ press on a key nobody is holding — not as a repeat. A second press edge
+ can only exist if the chord went up in between, so anything past the
+ grace window is either a lost key-up or a genuinely new press, and both
+ want the same repair.
+
+ **A press while a dictation nobody is holding is running is its STOP**
+ (BUG-191). The latch says "up", yet the lane is busy: a hands-free key,
+ the bar, a REST call started it — or a release edge never made it here
+ and the recording is still open. Before this, that press went to
+ ``start_dictation``, was refused as ``already_running`` (a refusal the
+ bar deliberately paints as nothing), and the latch was dropped again:
+ the key did nothing, visibly, forever, and only a restart ended the
+ recording. The dictation key is the kill switch of its own lane — an
+ explicit press ends whatever is running and delivers it, which is what
+ the user pressing it means.
"""
now = time.monotonic()
last_seen = float(getattr(self, "_dictate_key_seen_at", 0.0))
@@ -6527,7 +6586,7 @@ class SpeechPipeline:
stale = latched and (now - last_seen) > _DICTATE_HOLD_REPEAT_GRACE_S
self._dictate_key_seen_at = now
if latched and not stale:
- return # the same hold, re-reported by a polling backend
+ return # the same hold, re-reported inside the grace window
if stale:
log.info(
"Dictation key-up edge was lost %.1fs ago — clearing the stale "
@@ -6543,20 +6602,38 @@ class SpeechPipeline:
# press starts a fresh one.
self.stop_dictation()
return
+ if self.dictation_active():
+ log.info(
+ "Dictation key pressed while a dictation nobody is holding is "
+ "still running (via=%s, %.1fs since the last edge) — finishing "
+ "it instead of refusing the press.",
+ getattr(self, "_dictation_started_by", "") or "unknown",
+ now - last_seen if last_seen else 0.0,
+ )
+ self.stop_dictation()
+ return
self._dictate_key_down = True
- if not self.start_dictation(target=self._configured_dictation_target()):
- # Could not start (no microphone, no STT, already recording). Drop
- # the latch immediately so the NEXT press is a fresh attempt rather
- # than being swallowed as a repeat. A live voice session is NOT one
- # of these: it is accepted and handed over, and the latch has to
- # stay so the release can cancel a handover that is still running.
+ log.info("Dictation key down — starting a hold recording.")
+ if not self.start_dictation(
+ target=self._configured_dictation_target(), source="hold_key"
+ ):
+ # Could not start (no microphone, no STT). Drop the latch
+ # immediately so the NEXT press is a fresh attempt rather than
+ # being swallowed as a repeat. A live voice session is NOT one of
+ # these: it is accepted and handed over, and the latch has to stay
+ # so the release can cancel a handover that is still running.
self._dictate_key_down = False
def _on_dictate_release(self) -> None:
"""Dictation key UP — stop recording and submit what was held."""
if not self._dictate_key_down:
+ log.debug("Dictation key up with no hold latched — nothing to submit.")
return
self._dictate_key_down = False
+ log.info(
+ "Dictation key up after %.1fs — submitting the hold recording.",
+ time.monotonic() - float(getattr(self, "_dictate_key_seen_at", 0.0) or 0.0),
+ )
self.stop_dictation()
def _on_dictate_toggle(self) -> None:
@@ -6567,9 +6644,13 @@ class SpeechPipeline:
finished instead of falling through and asking for a second dictation.
"""
if self.dictation_active():
+ log.info("Dictation toggle key — stopping the running dictation.")
self.stop_dictation()
return
- self.start_dictation(target=self._configured_dictation_target())
+ log.info("Dictation toggle key — starting a hands-free recording.")
+ self.start_dictation(
+ target=self._configured_dictation_target(), source="toggle_key"
+ )
def _on_paste_last(self) -> None:
""""Insert the last dictation again" key — re-deliver the last transcript.
@@ -7420,7 +7501,23 @@ class SpeechPipeline:
# ``close()`` sets ``released`` before it awaits anything, so
# the wake owner is freed even if this task is being cancelled.
await buffer.close()
- await self._wake_capture_released.wait()
+ # BOUNDED. This used to wait forever, and a wake owner whose
+ # teardown wedged would have held the dictation task — and
+ # every "a dictation is already running" refusal — open until
+ # a restart (BUG-191 family). The wake side is told, loudly,
+ # and the dictation goes on to deliver what it recorded.
+ try:
+ await asyncio.wait_for(
+ self._wake_capture_released.wait(),
+ timeout=_DICTATION_WAKE_RELEASE_TIMEOUT_S,
+ )
+ except TimeoutError:
+ log.warning(
+ "The wake microphone did not confirm its release within "
+ "%.1fs after the dictation gave the stream back — "
+ "finishing the dictation anyway.",
+ _DICTATION_WAKE_RELEASE_TIMEOUT_S,
+ )
return
async with MicrophoneCapture(
@@ -10088,9 +10185,15 @@ class SpeechPipeline:
and self._capture_permission_allowed()
)
- def start_dictation(self, *, target: str = "chat") -> bool:
+ def start_dictation(self, *, target: str = "chat", source: str = "api") -> bool:
"""Begin a transcribe-only dictation session (idempotent-safe).
+ ``source`` names the door the request came through — ``hold_key``,
+ ``toggle_key``, ``ws``, ``rest`` or the default ``api`` — purely so the
+ start line in the log says so and the hold-key watchdog knows whether a
+ release edge is owed (BUG-191: a recording that never ended could not
+ be traced to its trigger, because the log never said which one it was).
+
``target`` decides where the finished transcript goes:
* ``"chat"`` — publish the transcript only. This is the chat composer's
@@ -10159,8 +10262,8 @@ class SpeechPipeline:
)
return False
if self._voice_session_holds_microphone():
- return self._begin_dictation_handover(loop, target=target)
- return self._commit_dictation(loop, target=target)
+ return self._begin_dictation_handover(loop, target=target, source=source)
+ return self._commit_dictation(loop, target=target, source=source)
def _voice_session_holds_microphone(self) -> bool:
"""True while the VOICE lane owns the one input device.
@@ -10175,7 +10278,7 @@ class SpeechPipeline:
)
def _begin_dictation_handover(
- self, loop: asyncio.AbstractEventLoop, *, target: str
+ self, loop: asyncio.AbstractEventLoop, *, target: str, source: str = "api"
) -> bool:
"""Take the microphone from a live voice conversation, then dictate.
@@ -10221,7 +10324,7 @@ class SpeechPipeline:
)
return False
task = loop.create_task(
- self._dictate_when_the_microphone_is_free(loop, target=target),
+ self._dictate_when_the_microphone_is_free(loop, target=target, source=source),
name="dictation-handover",
)
# The terminal guarantee lives in a done-callback, not in the
@@ -10235,7 +10338,7 @@ class SpeechPipeline:
return True
async def _dictate_when_the_microphone_is_free(
- self, loop: asyncio.AbstractEventLoop, *, target: str
+ self, loop: asyncio.AbstractEventLoop, *, target: str, source: str = "api"
) -> None:
"""Wait for the hung-up session to release the device, then dictate.
@@ -10264,7 +10367,7 @@ class SpeechPipeline:
)
return
await asyncio.sleep(_DICTATION_HANDOVER_POLL_S)
- self._commit_dictation(loop, target=target)
+ self._commit_dictation(loop, target=target, source=source)
finally:
# Not the terminal guarantee — a task cancelled before its first
# step never runs this. ``_on_handover_settled`` is what always
@@ -10309,7 +10412,7 @@ class SpeechPipeline:
log.debug("Dictation handover callback failed", exc_info=True)
def _commit_dictation(
- self, loop: asyncio.AbstractEventLoop, *, target: str
+ self, loop: asyncio.AbstractEventLoop, *, target: str, source: str = "api"
) -> bool:
"""Arm the wake block, announce the turn and spawn the recording task.
@@ -10317,6 +10420,8 @@ class SpeechPipeline:
arrive in the dictation lane through exactly one door. Always returns
``True``; every reason not to be here is checked by ``start_dictation``.
"""
+ self._dictation_started_by = str(source or "api")
+ self._dictation_discard_requested = 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
# VOICE session is accepted (``_run_session``). The dictation lane shares
@@ -10371,8 +10476,9 @@ class SpeechPipeline:
self._dictation_session(), name="dictation"
)
log.info(
- "🎙️ dictation started (transcribe-only, target=%s).",
+ "🎙️ dictation started (transcribe-only, target=%s, via=%s).",
self._dictation_target,
+ self._dictation_started_by,
)
return True
@@ -10424,12 +10530,111 @@ class SpeechPipeline:
handover = getattr(self, "_dictation_handover_task", None)
if handover is not None and not handover.done():
handover.cancel()
+ # Belt and braces: should a recording ALSO be alive (a handover
+ # that already committed but has not cleared its handle yet), the
+ # stop must reach it too — returning here used to leave the
+ # recording running with the stop swallowed (BUG-191).
+ task = getattr(self, "_dictation_task", None)
+ if task is not None and not task.done():
+ self._dictation_stop_event.set()
return True
if self._dictation_task is None or self._dictation_task.done():
return False
self._dictation_stop_event.set()
return True
+ def request_dictation_stop(self, *, discard: bool = False) -> bool:
+ """End a running dictation from OUTSIDE the pipeline's loop — the bar's X.
+
+ The dictation counterpart of ``request_hangup``: the Jarvis Bar runs on
+ its own Tk thread (or in a child process, on macOS), while the stop
+ event and its waiter belong to the pipeline's asyncio loop, so the
+ request is marshalled onto that loop. ``discard=True`` is what the
+ close-X means — make it go away, deliver nothing — and matches what the
+ same X does to a voice session; the default finishes and delivers, like
+ the key. Returns whether a dictation was there to stop, so a caller can
+ tell "stopped" from "nothing was running".
+
+ Until BUG-191 the bar drew its X in the dictation modes and resolved
+ every click on it to nothing, on the theory that another way to stop
+ always existed. With a lost release edge there was none.
+ """
+ active = self.dictation_active()
+ if not active:
+ log.debug("request_dictation_stop: no dictation is running.")
+ return False
+ log.info(
+ "📵 request_dictation_stop — %s the running dictation (via=%s).",
+ "discarding" if discard else "finishing",
+ getattr(self, "_dictation_started_by", "") or "unknown",
+ )
+
+ def _dispatch() -> None:
+ try:
+ if discard:
+ self._dictation_discard_requested = True
+ self._dictate_key_down = False
+ self.stop_dictation()
+ except Exception: # noqa: BLE001 — a stop gesture must never crash
+ log.exception("request_dictation_stop dispatch failed")
+
+ owner = getattr(self, "_runtime_loop", None)
+ try:
+ current = asyncio.get_running_loop()
+ except RuntimeError:
+ current = None
+ if owner is not None and owner.is_running() and current is not owner:
+ try:
+ owner.call_soon_threadsafe(_dispatch)
+ return True
+ except RuntimeError:
+ log.debug("request_dictation_stop: owner loop closed during dispatch")
+ _dispatch()
+ return True
+
+ async def _watch_dictation_hold_key(self) -> None:
+ """Finish a HOLD recording whose key is physically up — the lost release.
+
+ Runs beside the recording only for a dictation the hold key started.
+ Every ``_DICTATE_HOLD_WATCH_POLL_S`` it asks the live trigger whether
+ the dictation chord is down. ``None`` means this backend cannot tell
+ (no listener, no package, Wayland): the watchdog stands down at once
+ and the lane keeps working from edges alone — it never invents a
+ release. ``False`` for ``_DICTATE_HOLD_LOST_RELEASE_S`` straight means
+ the key-up happened and its edge never arrived; the recording is then
+ ended through the same stop event a real release sets, so what was
+ said is delivered exactly as if the edge had come (BUG-191).
+ """
+ trigger = getattr(self, "_hotkey_trigger", None)
+ probe = getattr(trigger, "chord_is_down", None)
+ if trigger is None or not callable(probe):
+ return
+ up_since: float | None = None
+ while True:
+ answer = probe("dictate")
+ if answer is None:
+ log.debug(
+ "hold-key watchdog: this hotkey backend cannot report key "
+ "state — the recording relies on the release edge alone."
+ )
+ return
+ now = time.monotonic()
+ if answer:
+ up_since = None
+ elif up_since is None:
+ up_since = now
+ elif now - up_since >= _DICTATE_HOLD_LOST_RELEASE_S:
+ log.warning(
+ "The dictation hold key has been physically up for %.1fs and "
+ "no release edge arrived — finishing the recording as the "
+ "release would have (the key-up edge was lost).",
+ now - up_since,
+ )
+ self._dictate_key_down = False
+ self._dictation_stop_event.set()
+ return
+ await asyncio.sleep(_DICTATE_HOLD_WATCH_POLL_S)
+
def _dictation_stt(self) -> Any:
"""The provider this lane transcribes with — NOT the voice one (F14).
@@ -12215,6 +12420,17 @@ class SpeechPipeline:
)
stop_task = asyncio.create_task(self._dictation_stop_event.wait())
hangup_task = asyncio.create_task(self._hangup_event.wait())
+ # Only a recording the HOLD key started is owed a release edge;
+ # the watchdog ends it when the key is physically up and that
+ # edge never came (BUG-191). It sets the stop event, so it is
+ # not a waiter of its own.
+ hold_task = (
+ asyncio.create_task(
+ self._watch_dictation_hold_key(), name="dictation-hold-watch"
+ )
+ if getattr(self, "_dictation_started_by", "") == "hold_key"
+ else None
+ )
wait_set = {stop_task, hangup_task, drain_task}
try:
done, _pending = await asyncio.wait(
@@ -12227,6 +12443,28 @@ class SpeechPipeline:
return_when=asyncio.FIRST_COMPLETED,
)
hung_up = hangup_task in done or self._hangup_event.is_set()
+ if getattr(self, "_dictation_discard_requested", False):
+ # The bar's close-X: end it like a hangup — nothing
+ # transcribed, nothing delivered.
+ hung_up = True
+ # Say which way the recording ended. The one report that
+ # started BUG-191 had four minutes of "final window" reads
+ # and not one line saying what the recording was waiting
+ # for, or that nothing had reached it.
+ if stop_task in done:
+ ended_by = "discard" if hung_up else "stop"
+ elif hangup_task in done:
+ ended_by = "hangup"
+ elif drain_task in done:
+ ended_by = "input ended"
+ else:
+ ended_by = f"the {self._dictation_max_s:.0f}s recording cap"
+ log.info(
+ "dictation recording ended by %s after %.1fs (via=%s).",
+ ended_by,
+ time.monotonic() - started_at,
+ getattr(self, "_dictation_started_by", "") or "unknown",
+ )
if drain_task in done and not drain_task.cancelled():
# The RECORDING stopped on its own. Every way that
# happens (a handoff buffer whose replay window the
@@ -12276,9 +12514,12 @@ class SpeechPipeline:
# Freeze the probe BEFORE tearing anything else down so a
# stop edge cannot race one more transcription into flight.
stop_event.set()
- for t in (drain_task, stop_task, hangup_task):
+ side_tasks = [drain_task, stop_task, hangup_task]
+ if hold_task is not None:
+ side_tasks.append(hold_task)
+ for t in side_tasks:
t.cancel()
- for t in (drain_task, stop_task, hangup_task):
+ for t in side_tasks:
try:
await t
except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
diff --git a/jarvis/ui/jarvisbar/host.py b/jarvis/ui/jarvisbar/host.py
index b02b9a0ad6..156821f361 100644
--- a/jarvis/ui/jarvisbar/host.py
+++ b/jarvis/ui/jarvisbar/host.py
@@ -222,6 +222,7 @@ class _EchoBar:
def set_on_voice_action(self, cb: Any) -> None: ...
def set_on_talk(self, cb: Any) -> None: ...
def set_on_hangup(self, cb: Any) -> None: ...
+ def set_on_dictation_stop(self, cb: Any) -> None: ...
def set_feedback_publisher(self, cb: Any) -> None: ...
def set_on_show_window(self, cb: Any) -> None: ...
def set_on_speaker_toggle(self, cb: Any) -> None: ...
@@ -368,17 +369,20 @@ def _wire_surface_events(surface: Any) -> None:
def _emit_voice_action(action: str) -> None:
normalized = str(action).strip().lower()
- if normalized in {"talk", "hangup"}:
+ if normalized in {"talk", "hangup", "dictation_stop"}:
emit(normalized)
else:
log.warning("bar-host: dropping unknown voice action %r", action)
- # Qt exposes the compact action callback; Tk keeps the two explicit
+ # Qt exposes the compact action callback; Tk keeps the explicit
# setters. Wiring both is safe because each surface invokes only the
# callback contract it implements.
_call(surface, "set_on_voice_action", _emit_voice_action)
_call(surface, "set_on_talk", lambda: emit("talk"))
_call(surface, "set_on_hangup", lambda: emit("hangup"))
+ # The close-X while DICTATING: the recording is ended in the parent, where
+ # the pipeline lives (BUG-191 — this X used to resolve to nothing).
+ _call(surface, "set_on_dictation_stop", lambda: emit("dictation_stop"))
_call(surface, "set_on_mute_toggle", lambda: emit("mute_toggle"))
# The orb's control row adds one action the bar never had: muting the
# ASSISTANT's voice. Like talk/hang-up it needs the parent, because the
diff --git a/jarvis/ui/jarvisbar/interaction.py b/jarvis/ui/jarvisbar/interaction.py
index baada8a6d8..c7107e6b31 100644
--- a/jarvis/ui/jarvisbar/interaction.py
+++ b/jarvis/ui/jarvisbar/interaction.py
@@ -56,7 +56,8 @@ def resolve_click(
) -> str:
"""Resolve a click on the bar into an action by its horizontal zone + state.
- Returns one of ``"hangup"`` / ``"mute"`` / ``"talk"`` / ``"none"``.
+ Returns one of ``"hangup"`` / ``"dictation_stop"`` / ``"mute"`` / ``"talk"``
+ / ``"none"``.
The RIGHT zone is the microphone mute toggle (mic muted FOR JARVIS only —
non-destructive, so it keeps a generous zone). When IDLE, a click anywhere
@@ -72,13 +73,18 @@ def resolve_click(
trap (live bug 2026-06-19): the old code hung up on ANY click in the left
40% of the bar, decoupled from the visible affordance.
- EVERY dictation mode (``dictate`` while recording, ``dictate_transcribing``
- while the text is being produced) is inert on purpose: without this branch
- they would fall through to "not active" and a stray click would START A
- VOICE SESSION in the middle of dictating. There is always another way to
- stop — release the key, press it again in toggle mode, the Dictation view,
- or ``jarvis api dictation stop`` — so an inert bar costs nothing and cannot
- misfire.
+ The dictation modes (``dictate`` while recording, ``dictate_transcribing``
+ while the text is being produced) resolve exactly ONE thing: a click on the
+ visible close-X is ``"dictation_stop"``. Everything else there is inert on
+ purpose — without that, a stray click would fall through to "not active"
+ and START A VOICE SESSION in the middle of dictating, and the mic zone
+ would mute Jarvis's ear while the user is dictating into it. The X used to
+ be inert too, on the theory that another way to stop always existed (the
+ key, the Dictation view, the CLI). It did not: a hold recording whose
+ release edge was lost had the key refusing every press as "already
+ running", and the one control the user could see — the X the renderer
+ draws for these modes — resolved to nothing (BUG-191). The renderer and
+ this resolver now agree: a drawn X is a working X.
``NOTICE_MODES`` is inert for the same reason and one more. A notice is a
transient ANSWER, not a control: it appears unrequested, it opens the pill
@@ -91,7 +97,11 @@ def resolve_click(
bar the user could not see the truth of.
"""
frac = x / max(1, width)
- if mode in DICTATION_MODES or mode in NOTICE_MODES:
+ if mode in NOTICE_MODES:
+ return "none"
+ if mode in DICTATION_MODES:
+ if hovered and _on_close_x(x, width, pill_w):
+ return "dictation_stop"
return "none"
active = mode in ("listen", "think", "speak")
if frac >= 0.60: # right zone → the mic mute toggle (non-destructive)
@@ -100,18 +110,24 @@ def resolve_click(
return "talk"
# Active session: the ONLY destructive bar action is the close-X hang-up,
# which must be a deliberate click ON the visible X glyph.
- if hovered:
- # In production `pill_w` is always the active pill width (ACTIVE_W); the
- # caller only passes None for idle mode, which returns above before this
- # branch. The `width` fallback is just a sane default for direct callers.
- pw = float(pill_w) if pill_w is not None else float(width)
- x_glyph = width / 2.0 - _CLOSE_X_CENTRE_FRAC * pw # mirror renderer._draw_close_x
- hit = max(_CLOSE_X_HIT_PX, _CLOSE_X_HIT_FRAC * pw)
- if abs(x - x_glyph) <= hit:
- return "hangup"
+ if hovered and _on_close_x(x, width, pill_w):
+ return "hangup"
return "none" # active body / no visible X → nothing
+def _on_close_x(x: float, width: int, pill_w: float | None) -> bool:
+ """Does a click at ``x`` land on the close-X glyph the renderer draws?
+
+ In production ``pill_w`` is always the active pill width (ACTIVE_W); the
+ ``width`` fallback is just a sane default for direct callers. The glyph
+ centre mirrors ``renderer._draw_close_x`` (``cx - 0.42*pw``).
+ """
+ pw = float(pill_w) if pill_w is not None else float(width)
+ x_glyph = width / 2.0 - _CLOSE_X_CENTRE_FRAC * pw
+ hit = max(_CLOSE_X_HIT_PX, _CLOSE_X_HIT_FRAC * pw)
+ return abs(x - x_glyph) <= hit
+
+
def default_bottom_center(
*, screen_w: int, screen_h: int, bar_w: int, bar_h: int, margin: int
) -> tuple[int, int]:
diff --git a/jarvis/ui/jarvisbar/overlay.py b/jarvis/ui/jarvisbar/overlay.py
index 7fbb0ba8d0..fecc3da7c8 100644
--- a/jarvis/ui/jarvisbar/overlay.py
+++ b/jarvis/ui/jarvisbar/overlay.py
@@ -36,6 +36,7 @@ from collections.abc import Callable
from typing import Any
from jarvis.ui.jarvisbar import interaction, renderer
+from jarvis.ui.jarvisbar.modes import DICTATION_MODES
log = logging.getLogger("jarvis.ui.jarvisbar")
@@ -484,6 +485,9 @@ class JarvisBarOverlay:
# runtime_refs fallback when no callback is installed.
self._on_talk: Callable[[], None] | None = None
self._on_hangup: Callable[[], None] | None = None
+ # The close-X while DICTATING (an external host routes it to the
+ # parent; in-process it reaches the pipeline directly).
+ self._on_dictation_stop: Callable[[], None] | None = None
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
self._hovered = False # mouse over the bar → reveal the close cross
@@ -622,6 +626,10 @@ class JarvisBarOverlay:
"""Register the active close-X action for an external host."""
self._on_hangup = callback
+ def set_on_dictation_stop(self, callback: Callable[[], None] | None) -> None:
+ """Register the dictating close-X action for an external host."""
+ self._on_dictation_stop = callback
+
def set_feedback_publisher(self, callback: Callable[[str, dict], None] | None) -> None:
self._feedback_publisher = callback
@@ -1758,7 +1766,12 @@ class JarvisBarOverlay:
if time.monotonic() < self._hangup_click_block_until:
return
try:
- active = self._mode in ("listen", "think", "speak")
+ # The dictation modes render on the active pill too (dictate →
+ # "speak", dictate_transcribing → "think"), so their close-X sits
+ # where the active pill puts it.
+ active = self._mode in ("listen", "think", "speak") or (
+ self._mode in DICTATION_MODES
+ )
pill_w = renderer.ACTIVE_W if active else None
action = interaction.resolve_click(
click_x,
@@ -1767,6 +1780,26 @@ class JarvisBarOverlay:
hovered=hovered,
pill_w=pill_w,
)
+ if action == "dictation_stop":
+ # The X while dictating ends the recording and delivers
+ # nothing — the same "make it go away" the X means for a
+ # voice session. Until BUG-191 this click resolved to nothing
+ # while the glyph was drawn.
+ callback = self._on_dictation_stop
+ if callback is not None:
+ callback()
+ else:
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ stop = getattr(pipeline, "request_dictation_stop", None)
+ if callable(stop):
+ stop(discard=True)
+ # Immediate local feedback; the bridge reconciles on
+ # ``DictationCompleted``.
+ self._mode = "idle"
+ self._hangup_click_block_until = time.monotonic() + HANGUP_CLICK_GUARD_S
+ return
if action == "mute":
# The mic button toggles voice mute via the bridge-wired
# callback (publishes VoiceMuteToggleRequested → pipeline flips
diff --git a/jarvis/ui/jarvisbar/qt_overlay.py b/jarvis/ui/jarvisbar/qt_overlay.py
index c36ff495b1..75d103f0bc 100644
--- a/jarvis/ui/jarvisbar/qt_overlay.py
+++ b/jarvis/ui/jarvisbar/qt_overlay.py
@@ -34,6 +34,7 @@ from typing import Any
from PIL import Image
from jarvis.ui.jarvisbar import interaction, renderer
+from jarvis.ui.jarvisbar.modes import DICTATION_MODES
log = logging.getLogger("jarvis.ui.jarvisbar.qt")
@@ -578,7 +579,8 @@ class QtJarvisBarOverlay:
self._on_show_window = callback
def set_on_voice_action(self, callback: Callable[[str], None] | None) -> None:
- """Register parent-owned handling for ``"talk"`` and ``"hangup"``.
+ """Register parent-owned handling for ``"talk"``, ``"hangup"`` and
+ ``"dictation_stop"`` (the close-X while dictating).
The macOS surface lives in a companion process, so importing
``runtime_refs.get_speech_pipeline`` here would always return ``None``.
@@ -1439,7 +1441,12 @@ class QtJarvisBarOverlay:
log.debug("Qt bar: ignoring click (a file drop is in flight)")
return "none"
is_hovered = self._hovered if hovered is None else bool(hovered)
- active = self._mode in ("listen", "think", "speak")
+ # The dictation modes render on the active pill (dictate → "speak",
+ # dictate_transcribing → "think"), so their close-X sits where the
+ # active pill puts it.
+ active = self._mode in ("listen", "think", "speak") or (
+ self._mode in DICTATION_MODES
+ )
action = interaction.resolve_click(
click_x,
renderer.WIN_W,
@@ -1453,7 +1460,7 @@ class QtJarvisBarOverlay:
self._invoke_callback(callback, "mute-toggle")
self._muted = not self._muted
self._invalidate_static_frame()
- elif action in {"talk", "hangup"}:
+ elif action in {"talk", "hangup", "dictation_stop"}:
callback = self._on_voice_action
if callback is None:
log.warning(
@@ -1462,7 +1469,7 @@ class QtJarvisBarOverlay:
)
else:
self._invoke_callback(lambda: callback(action), f"voice-{action}")
- if action == "hangup":
+ if action in ("hangup", "dictation_stop"):
# Match the Tk surface's optimistic collapse while the
# authoritative parent tears the session down (or repairs
# a stuck active state). The next bus state reconciles it.
diff --git a/jarvis/ui/jarvisbar/subprocess_overlay.py b/jarvis/ui/jarvisbar/subprocess_overlay.py
index c2b6ecfe76..7665a1ec53 100644
--- a/jarvis/ui/jarvisbar/subprocess_overlay.py
+++ b/jarvis/ui/jarvisbar/subprocess_overlay.py
@@ -130,6 +130,7 @@ class SubprocessBarOverlay:
self._on_mute_toggle: Callable[[], None] | None = None
self._on_talk: Callable[[], None] | None = None
self._on_hangup: Callable[[], None] | None = None
+ self._on_dictation_stop: Callable[[], None] | None = None
self._feedback_publisher: Callable[[str, dict], None] | None = None
self._on_show_window: Callable[[], None] | None = None
self._on_speaker_toggle: Callable[[], None] | None = None
@@ -322,6 +323,9 @@ class SubprocessBarOverlay:
def set_on_hangup(self, callback: Callable[[], None] | None) -> None:
self._on_hangup = callback
+ def set_on_dictation_stop(self, callback: Callable[[], None] | None) -> None:
+ self._on_dictation_stop = callback
+
def set_feedback_publisher(self, callback: Callable[[str, dict], None] | None) -> None:
self._feedback_publisher = callback
@@ -509,6 +513,8 @@ class SubprocessBarOverlay:
self._dispatch_talk_action()
elif event == "hangup":
self._dispatch_hangup_action()
+ elif event == "dictation_stop":
+ self._dispatch_dictation_stop_action()
elif event == "mute_toggle":
cb = self._on_mute_toggle
if cb is not None:
@@ -621,6 +627,27 @@ class SubprocessBarOverlay:
if callable(hangup):
hangup()
+ def _dispatch_dictation_stop_action(self) -> None:
+ """The close-X while dictating: discard the recording in the parent.
+
+ Same shape as the hang-up: an installed callback wins for embedders and
+ tests, the desktop path reaches the live pipeline through
+ ``runtime_refs`` (populated here, deliberately empty in the child).
+ """
+ callback = self._on_dictation_stop
+ if callback is not None:
+ callback()
+ return
+
+ from jarvis.core.runtime_refs import get_speech_pipeline
+
+ pipeline = get_speech_pipeline()
+ if pipeline is None:
+ return
+ stop = getattr(pipeline, "request_dictation_stop", None)
+ if callable(stop):
+ stop(discard=True)
+
def _pump_stderr(self, stream: IO[str] | None) -> None:
if stream is None:
return
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index 4878a96995..35f61beb42 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -691,7 +691,7 @@ async def start(body: StartBody, request: Request) -> dict[str, Any]:
getattr(_dictation_cfg(request), "target", "auto") or "auto"
)
try:
- started = bool(pipeline.start_dictation(target=target))
+ started = bool(pipeline.start_dictation(target=target, source="rest"))
except Exception as exc: # noqa: BLE001
log.warning("dictation start failed: %s", exc, exc_info=True)
raise HTTPException(status_code=500, detail="Dictation could not start.") from exc
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index f2332565c5..2574222d5a 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -1910,7 +1910,7 @@ class WebServer:
if mode == "stop":
pipeline.stop_dictation()
else:
- started = pipeline.start_dictation(target=target)
+ started = pipeline.start_dictation(target=target, source="ws")
if not started:
await self.bus.publish(
ErrorOccurred(
diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.py
index cc006f3bbf..1d25fd66df 100644
--- a/tests/unit/dictation/test_dictate_keybind.py
+++ b/tests/unit/dictation/test_dictate_keybind.py
@@ -275,12 +275,14 @@ class _RecordingPipeline(SpeechPipeline):
def __init__(self) -> None: # noqa: D107 — deliberately bypasses the real ctor
self.started: list[str] = []
+ self.sources: list[str] = []
self.stopped = 0
self._dictate_key_down = False
self._dictation_task = None
- def start_dictation(self, *, target: str = "chat") -> bool: # type: ignore[override]
+ def start_dictation(self, *, target: str = "chat", source: str = "api") -> bool: # type: ignore[override]
self.started.append(target)
+ self.sources.append(source)
return True
def stop_dictation(self) -> bool: # type: ignore[override]
@@ -388,15 +390,80 @@ def test_release_submits_once() -> None:
def test_a_refused_start_does_not_swallow_the_next_press() -> None:
pipe = _RecordingPipeline()
- def _refuse(*, target: str = "chat") -> bool:
+ def _refuse(*, target: str = "chat", source: str = "api") -> bool:
return False
pipe.start_dictation = _refuse # type: ignore[assignment]
pipe._on_dictate_press()
assert pipe._dictate_key_down is False
- pipe.start_dictation = lambda *, target="chat": pipe.started.append(target) or True # type: ignore[assignment]
+ pipe.start_dictation = ( # type: ignore[assignment]
+ lambda *, target="chat", source="api": pipe.started.append(target) or True
+ )
+ pipe._on_dictate_press()
+ assert pipe.started == ["auto"]
+
+
+def test_a_press_while_a_dictation_nobody_holds_is_running_stops_it() -> None:
+ """REGRESSION (BUG-191): the press used to be REFUSED as already_running.
+
+ The latch says "up" — the release edge arrived, or the recording was
+ started by the hands-free key, the bar or a REST call — and the lane is
+ still busy. Before this, ``start_dictation`` refused the press (a refusal
+ the bar paints as nothing) and dropped the latch again, so the key did
+ nothing, silently, for as long as the recording ran: with a lost key-up,
+ until the 30-minute cap or a restart. The dictation key is the kill switch
+ of its own lane: the press ends the recording and delivers it.
+ """
+ pipe = _RecordingPipeline()
+
+ class _RunningTask:
+ def done(self) -> bool:
+ return False
+
+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]
pipe._on_dictate_press()
+
+ assert pipe.stopped == 1
+ assert pipe.started == [], "never a second dictation on top of the first"
+ assert pipe._dictate_key_down is False, "nothing is being held after a stop press"
+
+ # The matching release is a no-op — the stop already went out once.
+ pipe._on_dictate_release()
+ assert pipe.stopped == 1
+
+ # The lane is free again: the next press records normally.
+ pipe._dictation_task = None
+ pipe._on_dictate_press()
+ assert pipe.started == ["auto"]
+ assert pipe._dictate_key_down is True
+
+
+def test_the_hold_key_names_itself_as_the_source() -> None:
+ pipe = _RecordingPipeline()
+ pipe._on_dictate_press()
+ assert pipe.sources == ["hold_key"]
+
+
+def test_the_toggle_key_names_itself_as_the_source() -> None:
+ pipe = _RecordingPipeline()
+ pipe._on_dictate_toggle()
+ assert pipe.sources == ["toggle_key"]
+
+
+async def test_the_hotkey_loop_survives_a_handler_that_raises() -> None:
+ """One raising handler used to end the loop — and with it EVERY global
+ shortcut in the process, invisibly, until a restart (BUG-191)."""
+ pipe = _RecordingPipeline()
+
+ def _boom() -> None:
+ raise RuntimeError("edge handler blew up")
+
+ pipe._on_dictate_press = _boom # type: ignore[method-assign]
+ await pipe._hotkey_loop(_ScriptedTrigger(["dictate_press", "dictate_toggle"]))
+
+ # The bad edge was dropped; the NEXT edge was still served.
assert pipe.started == ["auto"]
diff --git a/tests/unit/speech/test_dictation_hold_watchdog.py b/tests/unit/speech/test_dictation_hold_watchdog.py
new file mode 100644
index 0000000000..ad0961d919
--- /dev/null
+++ b/tests/unit/speech/test_dictation_hold_watchdog.py
@@ -0,0 +1,194 @@
+"""The hold-key watchdog and the out-of-loop stop (BUG-191).
+
+A HOLD-started dictation is owed a release edge. When that edge is lost between
+the OS poller and the pipeline, the recording used to run to its 30-minute cap
+with nothing the user pressed able to end it. The watchdog asks the live hotkey
+trigger whether the chord is physically down and finishes the recording when it
+has been up for longer than any poll jitter — through the very stop event a
+real release sets. A backend that cannot see the keyboard answers ``None`` and
+the watchdog stands down: it must never invent a release.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+import jarvis.speech.pipeline as pipeline_mod
+from jarvis.speech.pipeline import SpeechPipeline
+
+
+class _FakeTrigger:
+ """Answers ``chord_is_down`` from a script; records what was asked."""
+
+ def __init__(self, answers: list[bool | None]) -> None:
+ self._answers = list(answers)
+ self.asked: list[str] = []
+
+ def chord_is_down(self, event_name: str) -> bool | None:
+ self.asked.append(event_name)
+ if len(self._answers) > 1:
+ return self._answers.pop(0)
+ return self._answers[0]
+
+
+def _pipeline(trigger: object | None) -> SpeechPipeline:
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._dictate_key_down = True
+ pipe._hotkey_trigger = trigger
+ pipe._dictation_started_by = "hold_key"
+ return pipe
+
+
[email protected](autouse=True)
+def _fast_watchdog(monkeypatch):
+ monkeypatch.setattr(pipeline_mod, "_DICTATE_HOLD_LOST_RELEASE_S", 0.05)
+ monkeypatch.setattr(pipeline_mod, "_DICTATE_HOLD_WATCH_POLL_S", 0.005)
+
+
+async def test_a_chord_that_stays_up_finishes_the_recording_like_a_release() -> None:
+ trigger = _FakeTrigger([False])
+ pipe = _pipeline(trigger)
+
+ await asyncio.wait_for(pipe._watch_dictation_hold_key(), timeout=2.0)
+
+ assert pipe._dictation_stop_event.is_set(), "the lost release must end the recording"
+ assert pipe._dictate_key_down is False, "the latch is cleared like a real release"
+ assert trigger.asked and set(trigger.asked) == {"dictate"}
+
+
+async def test_a_chord_that_is_held_never_stops_the_recording() -> None:
+ pipe = _pipeline(_FakeTrigger([True]))
+ task = asyncio.create_task(pipe._watch_dictation_hold_key())
+
+ await asyncio.sleep(0.2) # many times the lost-release window
+ assert not task.done()
+ assert not pipe._dictation_stop_event.is_set()
+ assert pipe._dictate_key_down is True
+
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_a_brief_up_reading_is_forgiven_when_the_key_comes_back() -> None:
+ """One 'up' sample inside the window is poll jitter, not a release."""
+ pipe = _pipeline(_FakeTrigger([False, True]))
+ task = asyncio.create_task(pipe._watch_dictation_hold_key())
+
+ await asyncio.sleep(0.2)
+ assert not pipe._dictation_stop_event.is_set()
+
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+
+
+async def test_a_backend_that_cannot_see_the_keyboard_stands_down() -> None:
+ """``None`` is "I cannot tell" — never "up". The watchdog ends, silently."""
+ pipe = _pipeline(_FakeTrigger([None]))
+
+ await asyncio.wait_for(pipe._watch_dictation_hold_key(), timeout=2.0)
+
+ assert not pipe._dictation_stop_event.is_set()
+ assert pipe._dictate_key_down is True
+
+
+async def test_no_live_trigger_means_no_watchdog() -> None:
+ pipe = _pipeline(None)
+
+ await asyncio.wait_for(pipe._watch_dictation_hold_key(), timeout=2.0)
+
+ assert not pipe._dictation_stop_event.is_set()
+
+
+# ----------------------------------------------------------------------
+# request_dictation_stop — the bar's close-X, from another thread
+# ----------------------------------------------------------------------
+
+
+class _RunningTask:
+ def done(self) -> bool:
+ return False
+
+
+class _StopCounting(SpeechPipeline):
+ def __init__(self) -> None: # noqa: D107 — bypasses the real ctor on purpose
+ self.stopped = 0
+ self._dictation_task = None
+ self._dictation_handover_task = None
+ self._dictation_discard_requested = False
+ self._dictate_key_down = True
+ self._dictation_started_by = "hold_key"
+
+ def stop_dictation(self) -> bool: # type: ignore[override]
+ self.stopped += 1
+ return True
+
+
+def test_request_dictation_stop_with_nothing_running_says_so() -> None:
+ pipe = _StopCounting()
+ assert pipe.request_dictation_stop() is False
+ assert pipe.stopped == 0
+
+
+def test_request_dictation_stop_finishes_by_default_and_discards_for_the_x() -> None:
+ pipe = _StopCounting()
+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]
+
+ assert pipe.request_dictation_stop() is True
+ assert pipe.stopped == 1
+ assert pipe._dictation_discard_requested is False
+ assert pipe._dictate_key_down is False
+
+ assert pipe.request_dictation_stop(discard=True) is True
+ assert pipe.stopped == 2
+ assert pipe._dictation_discard_requested is True
+
+
+async def test_request_dictation_stop_is_marshalled_onto_the_owner_loop() -> None:
+ """Called from a foreign thread, the stop lands on the pipeline's loop."""
+ pipe = _StopCounting()
+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]
+ loop = asyncio.get_running_loop()
+ pipe._runtime_loop = loop
+
+ result = await asyncio.to_thread(pipe.request_dictation_stop, discard=True)
+ assert result is True
+ # The dispatch was queued, not run on the caller's thread.
+ for _ in range(50):
+ if pipe.stopped:
+ break
+ await asyncio.sleep(0.01)
+ assert pipe.stopped == 1
+ assert pipe._dictation_discard_requested is True
+
+
+def test_stop_dictation_reaches_a_recording_even_while_a_handover_is_cancelled() -> None:
+ """Swallow point B: cancelling a handover used to return before the stop
+ event, so a recording alive at the same moment kept running."""
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]
+
+ class _Handover(_RunningTask):
+ def __init__(self) -> None:
+ self.cancelled = 0
+
+ def cancel(self) -> None:
+ self.cancelled += 1
+
+ handover = _Handover()
+ pipe._dictation_handover_task = handover # type: ignore[assignment]
+
+ assert pipe.stop_dictation() is True
+ assert handover.cancelled == 1
+ assert pipe._dictation_stop_event.is_set()
diff --git a/tests/unit/speech/test_dictation_mic_handoff.py b/tests/unit/speech/test_dictation_mic_handoff.py
index d24599975a..13709a48d9 100644
--- a/tests/unit/speech/test_dictation_mic_handoff.py
+++ b/tests/unit/speech/test_dictation_mic_handoff.py
@@ -449,3 +449,31 @@ async def test_a_wake_dropped_by_a_dictation_says_so_in_the_log(
finally:
blocking.cancel()
pipeline._dictation_task = None
+
+
+async def test_a_wake_side_that_never_confirms_its_release_cannot_hold_the_dictation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """REGRESSION (BUG-191 family): the lease waited for the confirmation forever.
+
+ A wake owner whose teardown wedges never sets ``_wake_capture_released``.
+ The dictation used to await it with no bound, so its task never ended,
+ every later press was refused as "already running", and only a restart
+ cleared it. The wait is bounded now: the wake side is told, the dictation
+ finishes.
+ """
+ pipeline, mic, _ = _wake_pipeline(monkeypatch)
+ monkeypatch.setattr(pipeline_mod, "_DICTATION_WAKE_RELEASE_TIMEOUT_S", 0.05)
+
+ wake_task = asyncio.create_task(pipeline._run_parallel_wake())
+ await asyncio.wait_for(mic.entered.wait(), timeout=1.0)
+
+ async def _dictate_under_a_wedged_wake() -> None:
+ async with pipeline._capture_dictation_input():
+ # The confirmation nobody will ever give: swap in an event no
+ # teardown knows about, so the wait can only end on its bound.
+ pipeline._wake_capture_released = asyncio.Event()
+
+ await asyncio.wait_for(_dictate_under_a_wedged_wake(), timeout=1.0)
+ await asyncio.wait_for(wake_task, timeout=1.0)
diff --git a/tests/unit/ui/jarvisbar/test_host_protocol.py b/tests/unit/ui/jarvisbar/test_host_protocol.py
index 2e574fed05..5b409812cc 100644
--- a/tests/unit/ui/jarvisbar/test_host_protocol.py
+++ b/tests/unit/ui/jarvisbar/test_host_protocol.py
@@ -28,6 +28,7 @@ class _RecordingBar:
self.on_voice_action = None
self.on_talk = None
self.on_hangup = None
+ self.on_dictation_stop = None
self.on_mute_toggle = None
self.feedback_publisher = None
self.on_show_window = None
@@ -84,6 +85,9 @@ class _RecordingBar:
def set_on_hangup(self, callback) -> None:
self.on_hangup = callback
+ def set_on_dictation_stop(self, callback) -> None:
+ self.on_dictation_stop = callback
+
def set_on_mute_toggle(self, callback) -> None:
self.on_mute_toggle = callback
@@ -147,12 +151,17 @@ def test_surface_interactions_are_wired_to_child_events(monkeypatch) -> None:
assert bar.on_voice_action is not None
assert bar.on_talk is not None
assert bar.on_hangup is not None
+ assert bar.on_dictation_stop is not None
assert bar.on_mute_toggle is not None
assert bar.feedback_publisher is not None
assert bar.on_show_window is not None
bar.on_voice_action("talk")
bar.on_voice_action("hangup")
+ # The close-X while dictating crosses the process boundary like the
+ # hang-up (BUG-191): both the compact Qt action and the Tk setter.
+ bar.on_voice_action("dictation_stop")
+ bar.on_dictation_stop()
bar.on_mute_toggle()
bar.feedback_publisher("bar", {"value": 1})
bar.on_show_window()
@@ -160,6 +169,8 @@ def test_surface_interactions_are_wired_to_child_events(monkeypatch) -> None:
assert emitted == [
("talk", {}),
("hangup", {}),
+ ("dictation_stop", {}),
+ ("dictation_stop", {}),
("mute_toggle", {}),
("feedback", {"kind": "bar", "payload": {"value": 1}}),
("show_window", {}),
diff --git a/tests/unit/ui/jarvisbar/test_interaction.py b/tests/unit/ui/jarvisbar/test_interaction.py
index 073a5b9b5c..3b5dfa93d9 100644
--- a/tests/unit/ui/jarvisbar/test_interaction.py
+++ b/tests/unit/ui/jarvisbar/test_interaction.py
@@ -75,6 +75,40 @@ def test_hangup_hitbox_at_real_bar_geometry():
assert I.resolve_click(x_glyph, W, "speak", hovered=False, pill_w=PW) == "none"
+def test_dictating_bar_close_x_stops_the_dictation():
+ """REGRESSION (BUG-191): the X the renderer draws while dictating was inert.
+
+ ``dictate`` renders as "speak" and ``dictate_transcribing`` as "think", so
+ the close-X is on screen — and every click on it resolved to ``"none"``.
+ With a lost key-up edge that left the user with a recording nothing could
+ end. A drawn X is a working X: on the glyph, controls shown → stop.
+ """
+ W, PW = 100, 100
+ for mode in ("dictate", "dictate_transcribing"):
+ assert I.resolve_click(20, W, mode, hovered=True, pill_w=PW) == "dictation_stop"
+ # Same spot, controls NOT shown → nothing (matches the visible affordance).
+ assert I.resolve_click(20, W, mode, hovered=False, pill_w=PW) == "none"
+ # The body and the mic zone stay inert while dictating: a stray click
+ # must neither start a voice session nor mute the ear being dictated into.
+ assert I.resolve_click(48, W, mode, hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(90, W, mode, hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(50, W, mode, hovered=False, pill_w=PW) == "none"
+
+
+def test_dictating_close_x_hitbox_at_real_bar_geometry():
+ """Anchor the dictation X to the deployed pill, like the hang-up test."""
+ W, PW = R.WIN_W, R.ACTIVE_W
+ x_glyph = round(W / 2.0 - 0.30 * PW)
+ assert I.resolve_click(x_glyph, W, "dictate", hovered=True, pill_w=PW) == "dictation_stop"
+ assert I.resolve_click(round(W / 2.0), W, "dictate", hovered=True, pill_w=PW) == "none"
+ assert I.resolve_click(x_glyph, W, "dictate", hovered=False, pill_w=PW) == "none"
+
+
+def test_a_notice_stays_inert_even_on_the_x_spot():
+ """A notice is an answer, not a control — unchanged by the dictation X."""
+ assert I.resolve_click(20, 100, "notice", hovered=True, pill_w=100) == "none"
+
+
def test_default_bottom_center_placement():
x, y = I.default_bottom_center(
screen_w=1920, screen_h=1080, bar_w=300, bar_h=72, margin=12
diff --git a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
index ce94ae05ae..c26afbae32 100644
--- a/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
+++ b/tests/unit/ui/jarvisbar/test_subprocess_overlay.py
@@ -243,6 +243,39 @@ class _FakeSpeechPipeline:
def request_hangup(self) -> None:
self.hangup_calls += 1
+ def request_dictation_stop(self, *, discard: bool = False) -> bool:
+ self.dictation_stops = getattr(self, "dictation_stops", [])
+ self.dictation_stops.append(discard)
+ return True
+
+
+def test_dictation_stop_event_discards_the_parent_recording(monkeypatch) -> None:
+ """The dictating close-X (BUG-191) reaches the parent's pipeline and
+ DISCARDS — the same "make it go away" the X means for a voice session —
+ without touching the voice hang-up or starting a session."""
+ pipeline = _FakeSpeechPipeline(session_active=False)
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+
+ surface._dispatch_event({"event": "dictation_stop"})
+
+ assert pipeline.dictation_stops == [True]
+ assert pipeline.hangup_calls == 0
+ assert pipeline.talk_calls == 0
+
+
+def test_dictation_stop_event_prefers_an_installed_callback(monkeypatch) -> None:
+ pipeline = _FakeSpeechPipeline(session_active=False)
+ monkeypatch.setattr("jarvis.core.runtime_refs.get_speech_pipeline", lambda: pipeline)
+ surface = SubprocessBarOverlay()
+ fired: list[str] = []
+ surface.set_on_dictation_stop(lambda: fired.append("stop"))
+
+ surface._dispatch_event({"event": "dictation_stop"})
+
+ assert fired == ["stop"]
+ assert getattr(pipeline, "dictation_stops", []) == []
+
def test_talk_event_executes_the_parent_pipeline(monkeypatch) -> None:
pipeline = _FakeSpeechPipeline(session_active=False)