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(speech): make push-to-talk release reliable

Ruben Lütke66abca22b849
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 0a1f561c9f..4ec55cc308 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -6645,17 +6645,23 @@ class SpeechPipeline:
hangup_task = asyncio.create_task(self._hangup_event.wait())
# Background live-transcript feed (cosmetic — the bubble). NOT part
# of the wait-set: it must never end the session, only mirror what
- # is being held into the orb bubble. Cancelled + awaited in cleanup.
+ # is being held into the orb bubble. It is quiesced after the input
+ # lease closes so releasing the key always ends capture first.
+ live_stop_event = asyncio.Event()
+ live_inference_active = asyncio.Event()
live_task = (
asyncio.create_task(
- self._ptt_live_transcribe(lambda: bytes(buffer)),
+ self._ptt_live_transcribe(
+ lambda: bytes(buffer),
+ stop_event=live_stop_event,
+ inference_active=live_inference_active,
+ ),
name="ptt-live-transcript",
)
if self._ptt_partial_interval_s > 0
else None
)
wait_set = {drain_task, release_task, hangup_task}
- all_tasks = list(wait_set) + ([live_task] if live_task else [])
try:
done, _pending = await asyncio.wait(
wait_set,
@@ -6663,7 +6669,9 @@ class SpeechPipeline:
return_when=asyncio.FIRST_COMPLETED,
)
except asyncio.CancelledError:
- for t in all_tasks:
+ if live_task is not None:
+ live_stop_event.set()
+ for t in list(wait_set) + ([live_task] if live_task else []):
t.cancel()
raise
if not done:
@@ -6672,16 +6680,41 @@ class SpeechPipeline:
self._ptt_max_hold_s,
)
hung_up = hangup_task in done or self._hangup_event.is_set()
- # Stop draining + the live feed and let every task settle. ALL must
- # be awaited after cancel — leaving any pending throws "Task was
- # destroyed but it is pending" on the GC pass after the mic closes.
- for t in all_tasks:
+ # Freeze the cosmetic probe before awaiting any other teardown so
+ # key-up cannot race one more growing-buffer transcription into
+ # flight after capture has ended.
+ live_stop_event.set()
+ # The key-up edge ends CAPTURE immediately. The cosmetic live-STT
+ # probe is stopped separately below: blindly cancelling an
+ # ``asyncio.to_thread`` local-Whisper call only cancels its asyncio
+ # wrapper, not the native inference. Starting final STT against the
+ # same model then deterministically raises TranscribeBusy and drops
+ # the submitted prompt (AP-24).
+ for t in wait_set:
t.cancel()
- for t in all_tasks:
+ for t in wait_set:
try:
await t
- except (asyncio.CancelledError, Exception): # noqa: BLE001
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
pass
+ if input_buffer is not None:
+ # PTT is one-shot, so it will never replay this capture. Release
+ # a wake-handoff/fallback pump now instead of retaining its mic
+ # lease while final STT and the answer run.
+ await input_buffer.close()
+
+ # The microphone/input lease is closed before waiting for a cosmetic
+ # native transcription to settle: key-up therefore ends recording even
+ # if the partial STT call itself is slow or wedged.
+ if not hung_up:
+ await self._set_turn_state(TurnTakingState.WAITING_FOR_FINAL_TRANSCRIPT)
+ if live_task is not None:
+ await self._stop_ptt_live_transcription(
+ live_task,
+ stop_event=live_stop_event,
+ inference_active=live_inference_active,
+ wait_for_inference=not hung_up,
+ )
if hung_up:
return HANGUP_HOTKEY
@@ -6704,7 +6737,6 @@ class SpeechPipeline:
self._carry_pcm = bytearray()
self._carry_started_monotonic = None
self._last_endpoint_reason = None
- await self._set_turn_state(TurnTakingState.WAITING_FOR_FINAL_TRANSCRIPT)
await self._publish_utterance_captured(pcm)
# One-shot: run exactly one turn, then end the session regardless of the
# _handle_utterance return value (it may request continuation, which PTT
@@ -6716,7 +6748,88 @@ class SpeechPipeline:
return self._session_end_reason or HANGUP_VOICE_PATTERN
return HANGUP_TURN_COMPLETE
- async def _ptt_live_transcribe(self, snapshot: Callable[[], bytes]) -> None:
+ async def _stop_ptt_live_transcription(
+ self,
+ task: asyncio.Task[None],
+ *,
+ stop_event: asyncio.Event,
+ inference_active: asyncio.Event,
+ wait_for_inference: bool,
+ ) -> None:
+ """Quiesce the cosmetic PTT probe before final STT or wake re-arm.
+
+ Native STT calls running through ``asyncio.to_thread`` cannot be
+ cancelled. On a normal key release, allow the one already-running
+ probe to finish before the authoritative final transcription starts.
+ Bound that wait by the same ceiling as final STT; a provider exposing
+ ``recover()`` then swaps in a fresh engine/lock before the orphaned call
+ is cancelled, which is the AP-24 recovery contract. A hard hangup does
+ not wait for cosmetic output, but still recovers a busy native engine so
+ the wake listener never inherits it.
+ """
+ stop_event.set()
+ if task.done():
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+ return
+
+ timed_out = False
+ if wait_for_inference:
+ try:
+ await asyncio.wait_for(
+ asyncio.shield(task),
+ timeout=max(0.1, self._stt_final_timeout_s),
+ )
+ return
+ except TimeoutError:
+ timed_out = True
+ log.warning(
+ "PTT live transcript did not quiesce within %.1fs; "
+ "recovering before final transcription.",
+ self._stt_final_timeout_s,
+ )
+ except asyncio.CancelledError:
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+ raise
+ except Exception: # noqa: BLE001 — cosmetic probe failure is contained
+ if task.done():
+ return
+
+ if inference_active.is_set():
+ recover = getattr(self._utterance_stt, "recover", None)
+ if callable(recover):
+ try:
+ recover()
+ except Exception: # noqa: BLE001 — cleanup must never drop teardown
+ log.warning(
+ "PTT live-transcript STT recovery failed; continuing "
+ "with provider-level fallback.",
+ exc_info=True,
+ )
+ elif timed_out:
+ log.warning(
+ "PTT live-transcript provider has no recovery hook; "
+ "cancelling the timed-out probe before final STT."
+ )
+ task.cancel()
+ try:
+ await task
+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110
+ pass
+
+ async def _ptt_live_transcribe(
+ self,
+ snapshot: Callable[[], bytes],
+ *,
+ stop_event: asyncio.Event,
+ inference_active: asyncio.Event,
+ ) -> None:
"""Background live-transcript feed for the held push-to-talk audio.
Every ``_ptt_partial_interval_s`` it transcribes the held-so-far buffer
@@ -6725,8 +6838,9 @@ class SpeechPipeline:
wake-word path's VAD stability probe (PTT bypasses the VAD, so it needs
its own feed). Purely cosmetic and best-effort: every error is swallowed
and the loop continues. It NEVER drives the turn — the authoritative
- transcription is the final one in ``_handle_utterance``. ``_ptt_session``
- cancels it on release / hangup / max-hold.
+ transcription is the final one in ``_handle_utterance``. On release,
+ ``_ptt_session`` signals ``stop_event`` and lets an in-flight native call
+ settle before final STT, so the two never share one inference engine.
"""
interval = self._ptt_partial_interval_s
stt = getattr(self, "_utterance_stt", None)
@@ -6736,16 +6850,27 @@ class SpeechPipeline:
# near-silence; wait until enough audio has accumulated before probing.
min_bytes = int(0.4 * 16_000 * 2)
try:
- while True:
- await asyncio.sleep(interval)
+ while not stop_event.is_set():
+ try:
+ await asyncio.wait_for(stop_event.wait(), timeout=interval)
+ except TimeoutError:
+ pass
+ if stop_event.is_set():
+ return
pcm = snapshot()
if len(pcm) < min_bytes:
continue
try:
- transcript = await stt.transcribe_pcm(pcm)
+ inference_active.set()
+ try:
+ transcript = await stt.transcribe_pcm(pcm)
+ finally:
+ inference_active.clear()
except Exception as exc: # noqa: BLE001 — cosmetic, keep going
log.debug("PTT live-transcript probe failed: %s", exc)
continue
+ if stop_event.is_set():
+ return
text = (getattr(transcript, "text", "") or "").strip() if transcript else ""
if not text:
continue
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index fda9052c92..4c112cf07f 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -1,4 +1,4 @@
-"""macOS / Linux-X11 hotkey backend via ``pynput`` (AD-8).
+"""Linux-X11 hotkey backend via ``pynput`` (AD-8).
``pynput`` provides cross-platform global keyboard listeners. This backend maps
the jarvis combo vocabulary onto pynput key objects and tracks the live
@@ -76,6 +76,18 @@ _MODIFIER_TO_KEY_ATTR = {
"window": "cmd",
}
+# ``pynput`` reports the right-hand modifier keys with side-specific names
+# (``alt_r``, ``shift_r``, ``cmd_r``), while a generic configured modifier such
+# as ``alt`` must accept either physical side. The old subset comparison only
+# matched the left aliases (which pynput names simply ``alt``/``shift``/etc.),
+# so the shipped ``right_alt`` PTT default could never fire on Linux-X11.
+_GENERIC_MODIFIER_ALIASES: dict[str, frozenset[str]] = {
+ "ctrl": frozenset({"ctrl", "ctrl_l", "ctrl_r"}),
+ "alt": frozenset({"alt", "alt_l", "alt_r", "alt_gr"}),
+ "shift": frozenset({"shift", "shift_l", "shift_r"}),
+ "cmd": frozenset({"cmd", "cmd_l", "cmd_r"}),
+}
+
# --------------------------------------------------------------------------
# Module-level single-listener guard (mirrors the Windows refcount intent):
# two live HotkeyTriggers must share ONE listener thread, else every press
@@ -102,8 +114,16 @@ def _parse_combo_tokens(normalized: str) -> tuple[str, ...]:
return tuple(_MODIFIER_TO_KEY_ATTR.get(p, p) for p in parts)
+def _combo_is_down(tokens: frozenset[str], held: set[str]) -> bool:
+ """Whether every configured token is represented by a held physical key."""
+ return all(
+ bool(_GENERIC_MODIFIER_ALIASES.get(token, frozenset({token})) & held)
+ for token in tokens
+ )
+
+
class PynputBackend:
- """``pynput`` global-hotkey backend for macOS / Linux-X11 (AD-8).
+ """``pynput`` global-hotkey backend for Linux-X11 (AD-8).
Satisfies the ``HotkeyBackend`` ``Protocol``. Receives the same normalized
``[combo_str, on_press, on_release]`` rows the Windows backend does, so the
@@ -119,6 +139,7 @@ class PynputBackend:
self._started = False
self._got_event = False
self._incremented = False
+ self._teardown_failed = False
# The live set of canonical tokens currently held down.
self._held: set[str] = set()
self._permission_check = lambda: True
@@ -182,7 +203,7 @@ class PynputBackend:
combo["down"] = False
return
for combo in self._combos:
- is_down = combo["tokens"].issubset(self._held)
+ is_down = _combo_is_down(combo["tokens"], self._held)
if is_down and not combo["down"]:
combo["down"] = True
self._got_event = True
@@ -200,6 +221,13 @@ class PynputBackend:
"""Build + start the shared pynput listener. Degrades, never raises."""
if self._started:
return
+ if self._teardown_failed:
+ log.warning(
+ "pynput hotkeys remain disabled after a listener teardown "
+ "failure; restart Jarvis to re-arm them safely. Voice still "
+ "works via the wake word."
+ )
+ return
try:
from pynput import keyboard # type: ignore[import-untyped] # lazy (HN-7)
except Exception as exc: # noqa: BLE001 — optional [desktop] extra
@@ -288,6 +316,21 @@ class PynputBackend:
except Exception: # noqa: BLE001 — teardown must never propagate
log.debug("pynput listener.stop() failed (non-fatal)",
exc_info=True)
+ try:
+ # A live keybind edit immediately constructs the replacement
+ # listener. Wait for the old hook thread to leave first so it
+ # cannot emit a second press/release edge after re-arm.
+ listener.join(timeout=2.0) # type: ignore[attr-defined]
+ except Exception: # noqa: BLE001 — teardown must never propagate
+ log.debug("pynput listener.join() failed (non-fatal)",
+ exc_info=True)
+ is_alive = getattr(listener, "is_alive", None)
+ if callable(is_alive) and is_alive():
+ self._teardown_failed = True
+ log.warning(
+ "pynput hotkey listener did not stop within two seconds; "
+ "the replacement listener will not be started."
+ )
self._listener = None
self._held.clear()
for combo in self._combos:
@@ -308,4 +351,9 @@ class PynputBackend:
return self._got_event
-__all__ = ["PynputBackend", "_parse_combo_tokens", "_reset_listener_state_for_tests"]
+__all__ = [
+ "PynputBackend",
+ "_combo_is_down",
+ "_parse_combo_tokens",
+ "_reset_listener_state_for_tests",
+]
diff --git a/jarvis/trigger/backends/quartz.py b/jarvis/trigger/backends/quartz.py
index 83a125b45c..11749a7ba0 100644
--- a/jarvis/trigger/backends/quartz.py
+++ b/jarvis/trigger/backends/quartz.py
@@ -85,8 +85,10 @@ class QuartzHotkeyBackend:
self._held: set[str] = set()
self._permission_check = _macos_hotkey_permissions_granted
self._tap: object | None = None
+ self._source: object | None = None
self._runloop: object | None = None
self._thread: threading.Thread | None = None
+ self._teardown_failed = False
# ------------------------------------------------------------------
# Registration + chord matching (mirrors PynputBackend semantics)
@@ -181,6 +183,13 @@ class QuartzHotkeyBackend:
"""
if self._started:
return
+ if self._teardown_failed:
+ log.warning(
+ "Quartz hotkeys remain disabled after an event-tap teardown "
+ "failure; restart Jarvis to re-arm them safely. Voice still "
+ "works via the wake word."
+ )
+ return
granted = False
try:
@@ -263,40 +272,107 @@ class QuartzHotkeyBackend:
return
self._tap = tap
+ self._source = source
ready = threading.Event()
+ startup_failed = threading.Event()
def _run() -> None:
- loop = Quartz.CFRunLoopGetCurrent()
- self._runloop = loop
- Quartz.CFRunLoopAddSource(loop, source, Quartz.kCFRunLoopCommonModes)
- Quartz.CGEventTapEnable(tap, True)
- ready.set()
- Quartz.CFRunLoopRun()
+ try:
+ loop = Quartz.CFRunLoopGetCurrent()
+ self._runloop = loop
+ Quartz.CFRunLoopAddSource(
+ loop, source, Quartz.kCFRunLoopCommonModes
+ )
+ Quartz.CGEventTapEnable(tap, True)
+ ready.set()
+ Quartz.CFRunLoopRun()
+ except Exception: # noqa: BLE001 — native hook failure must degrade
+ startup_failed.set()
+ log.error("Quartz event tap thread failed", exc_info=True)
+ ready.set()
thread = threading.Thread(
target=_run, name="jarvis-hotkey-tap", daemon=True
)
- thread.start()
- ready.wait(timeout=5.0)
self._thread = thread
+ thread.start()
+ if (
+ not ready.wait(timeout=5.0)
+ or startup_failed.is_set()
+ or not thread.is_alive()
+ ):
+ log.error(
+ "Quartz event tap thread did not become ready — hotkeys "
+ "disabled for this session; voice still works via wake word."
+ )
+ self.stop()
+ return
self._started = True
def stop(self) -> None:
"""Stop the run loop and drop the tap. Idempotent, never raises."""
+ tap = self._tap
+ source = self._source
runloop = self._runloop
- if runloop is not None:
+ if tap is not None or runloop is not None:
try:
import Quartz # type: ignore[import-untyped]
-
- Quartz.CFRunLoopStop(runloop)
except Exception: # noqa: BLE001 — teardown must never propagate
- log.debug("CFRunLoopStop failed (non-fatal)", exc_info=True)
+ Quartz = None # type: ignore[assignment,misc]
+ log.debug("Quartz teardown import failed (non-fatal)", exc_info=True)
+ if Quartz is not None:
+ # Re-arm used to call only CFRunLoopStop. A sleeping run loop
+ # could survive the two-second join, leaving its event tap live;
+ # after three Settings saves one physical key-up therefore
+ # produced four PTT release callbacks. Run every cleanup step
+ # independently so one native failure cannot skip stop+wake.
+ teardown_steps = []
+ if tap is not None:
+ teardown_steps.append(
+ ("disable", lambda: Quartz.CGEventTapEnable(tap, False))
+ )
+ if runloop is not None and source is not None:
+ teardown_steps.append(
+ (
+ "remove source",
+ lambda: Quartz.CFRunLoopRemoveSource(
+ runloop, source, Quartz.kCFRunLoopCommonModes
+ ),
+ )
+ )
+ if tap is not None:
+ teardown_steps.append(
+ ("invalidate", lambda: Quartz.CFMachPortInvalidate(tap))
+ )
+ if runloop is not None:
+ teardown_steps.extend(
+ [
+ ("stop", lambda: Quartz.CFRunLoopStop(runloop)),
+ ("wake", lambda: Quartz.CFRunLoopWakeUp(runloop)),
+ ]
+ )
+ for step_name, step in teardown_steps:
+ try:
+ step()
+ except Exception: # noqa: BLE001 — continue remaining steps
+ log.debug(
+ "Quartz event tap %s failed (non-fatal)",
+ step_name,
+ exc_info=True,
+ )
thread = self._thread
if thread is not None:
thread.join(timeout=2.0)
+ if thread.is_alive():
+ self._teardown_failed = True
+ log.warning(
+ "Quartz hotkey listener did not stop within two seconds; "
+ "the replacement listener will not be started."
+ )
self._runloop = None
self._thread = None
self._tap = None
+ self._source = None
self._held.clear()
for combo in self._combos:
combo["down"] = False
diff --git a/tests/unit/speech/test_pipeline_push_to_talk.py b/tests/unit/speech/test_pipeline_push_to_talk.py
index e19d60ebff..0dab6dfcb7 100644
--- a/tests/unit/speech/test_pipeline_push_to_talk.py
+++ b/tests/unit/speech/test_pipeline_push_to_talk.py
@@ -18,16 +18,15 @@ exactly like a live mic between the last word and the key release.
from __future__ import annotations
import asyncio
+import threading
import time
from collections.abc import AsyncIterator
from types import SimpleNamespace
-import pytest
-
from jarvis.core.events import TranscriptionUpdate
from jarvis.core.protocols import AudioChunk
from jarvis.sessions.constants import HANGUP_HOTKEY, HANGUP_TURN_COMPLETE
-from jarvis.speech.pipeline import PipelineState, SpeechPipeline
+from jarvis.speech.pipeline import PipelineState, SpeechPipeline, TurnTakingState
class FakeTTS:
@@ -390,6 +389,193 @@ async def test_ptt_live_feed_disabled_when_interval_zero(monkeypatch):
assert pipe._utterance_stt.calls == 0, "interval=0 must not probe the STT"
+class _SerialProbeSTT:
+ """STT fake that exposes any overlap between partial and final calls."""
+
+ def __init__(self) -> None:
+ self.partial_started = asyncio.Event()
+ self.finish_partial = asyncio.Event()
+ self.calls = 0
+ self.active = 0
+ self.max_active = 0
+
+ async def transcribe_pcm(self, pcm: bytes): # noqa: ANN201
+ self.calls += 1
+ call = self.calls
+ self.active += 1
+ self.max_active = max(self.max_active, self.active)
+ try:
+ if call == 1:
+ self.partial_started.set()
+ await self.finish_partial.wait()
+ return SimpleNamespace(text="partial", language="en", confidence=0.9)
+ return SimpleNamespace(text="final", language="en", confidence=0.9)
+ finally:
+ self.active -= 1
+
+
+class _TrackedInputBuffer:
+ """Wake-handoff stand-in that records exactly when PTT releases capture."""
+
+ def __init__(self, chunks: list[bytes]) -> None:
+ self._chunks = chunks
+ self.closed = asyncio.Event()
+
+ async def stream(self) -> AsyncIterator[AudioChunk]:
+ for pcm in self._chunks:
+ yield AudioChunk(pcm=pcm, sample_rate=16_000, timestamp_ns=0, channels=1)
+ await asyncio.sleep(0)
+ await self.closed.wait()
+
+ async def close(self) -> None:
+ self.closed.set()
+
+
+async def test_ptt_release_closes_capture_then_waits_for_live_probe_before_final_stt():
+ """A native live probe must quiesce before final STT uses the same model."""
+ pipe = _make_pipeline()
+ _silence_side_effects(pipe)
+ pipe._ptt_mode = True
+ pipe._ptt_partial_interval_s = 0.01
+ pipe._stt_final_timeout_s = 0.5
+ stt = _SerialProbeSTT()
+ pipe._utterance_stt = stt # type: ignore[assignment]
+ input_buffer = _TrackedInputBuffer([_CHUNK_100MS] * 8)
+ states: list[TurnTakingState] = []
+
+ async def _track_state(state: TurnTakingState) -> None:
+ states.append(state)
+
+ pipe._set_turn_state = _track_state # type: ignore[method-assign]
+ captured: dict[str, object] = {}
+
+ async def _finalize(pcm: bytes, *, skip_completion: bool = False) -> bool:
+ captured["transcript"] = await pipe._transcribe_final(pcm)
+ return False
+
+ pipe._handle_utterance = _finalize # type: ignore[method-assign]
+ session = asyncio.create_task(pipe._ptt_session(input_buffer=input_buffer))
+ await asyncio.wait_for(stt.partial_started.wait(), timeout=1.0)
+
+ pipe._on_ptt_release()
+ await asyncio.wait_for(input_buffer.closed.wait(), timeout=0.2)
+ assert states[-1] is TurnTakingState.WAITING_FOR_FINAL_TRANSCRIPT
+ await asyncio.sleep(0.03)
+ assert stt.calls == 1, "final STT started while the partial still owned the model"
+
+ stt.finish_partial.set()
+ reason = await asyncio.wait_for(session, timeout=2.0)
+
+ assert reason == HANGUP_TURN_COMPLETE
+ assert stt.calls == 2
+ assert stt.max_active == 1
+ assert getattr(captured["transcript"], "text", "") == "final"
+
+
+class _RecoverableBlockingSTT:
+ """Models an un-cancellable native probe and its fresh-engine recovery."""
+
+ def __init__(self) -> None:
+ self.started = asyncio.Event()
+ self.recover_calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes): # noqa: ANN201
+ self.started.set()
+ await asyncio.Event().wait()
+
+ def recover(self) -> None:
+ self.recover_calls += 1
+
+
+class _RecoverableNativeSTT:
+ """Models a timed-out ``to_thread`` probe that survives task cancellation."""
+
+ def __init__(self) -> None:
+ self.partial_started = asyncio.Event()
+ self.release_native_call = threading.Event()
+ self.calls = 0
+ self.recover_calls = 0
+ self.final_started_after_recover = False
+
+ async def transcribe_pcm(self, pcm: bytes): # noqa: ANN201
+ self.calls += 1
+ if self.calls == 1:
+ self.partial_started.set()
+ await asyncio.to_thread(self.release_native_call.wait)
+ return SimpleNamespace(text="partial", language="en", confidence=0.9)
+ self.final_started_after_recover = self.recover_calls > 0
+ return SimpleNamespace(text="final", language="en", confidence=0.9)
+
+ def recover(self) -> None:
+ self.recover_calls += 1
+
+
+async def test_ptt_release_recovers_timed_out_native_probe_before_final_stt(
+ monkeypatch,
+):
+ """A wedged cosmetic probe is orphaned onto a fresh engine before submit."""
+ pipe = _make_pipeline()
+ _silence_side_effects(pipe)
+ pipe._ptt_mode = True
+ pipe._ptt_partial_interval_s = 0.01
+ pipe._stt_final_timeout_s = 0.05
+ stt = _RecoverableNativeSTT()
+ pipe._utterance_stt = stt # type: ignore[assignment]
+ monkeypatch.setattr(
+ "jarvis.speech.pipeline.MicrophoneCapture",
+ lambda device=None, **kwargs: _FakeMic(chunks=[_CHUNK_100MS] * 8),
+ )
+ captured: dict[str, object] = {}
+
+ async def _finalize(pcm: bytes, *, skip_completion: bool = False) -> bool:
+ captured["transcript"] = await pipe._transcribe_final(pcm)
+ return False
+
+ pipe._handle_utterance = _finalize # type: ignore[method-assign]
+ session = asyncio.create_task(pipe._ptt_session())
+ try:
+ await asyncio.wait_for(stt.partial_started.wait(), timeout=1.0)
+ pipe._on_ptt_release()
+ reason = await asyncio.wait_for(session, timeout=2.0)
+ finally:
+ # Let the deliberately orphaned executor call leave its old engine.
+ stt.release_native_call.set()
+ if not session.done():
+ session.cancel()
+ try:
+ await session
+ except asyncio.CancelledError: # noqa: S110 - test cleanup
+ pass
+
+ assert reason == HANGUP_TURN_COMPLETE
+ assert stt.recover_calls == 1
+ assert stt.calls == 2
+ assert stt.final_started_after_recover is True
+ assert getattr(captured["transcript"], "text", "") == "final"
+
+
+async def test_ptt_hangup_recovers_live_probe_before_wake_rearm(monkeypatch):
+ """A hard hangup never leaves a busy native STT engine for the wake path."""
+ pipe = _make_pipeline()
+ _silence_side_effects(pipe)
+ pipe._ptt_mode = True
+ pipe._ptt_partial_interval_s = 0.01
+ stt = _RecoverableBlockingSTT()
+ pipe._utterance_stt = stt # type: ignore[assignment]
+ monkeypatch.setattr(
+ "jarvis.speech.pipeline.MicrophoneCapture",
+ lambda device=None, **kwargs: _FakeMic(chunks=[_CHUNK_100MS] * 8),
+ )
+
+ session = asyncio.create_task(pipe._ptt_session())
+ await asyncio.wait_for(stt.started.wait(), timeout=1.0)
+ pipe._hangup_event.set()
+ reason = await asyncio.wait_for(session, timeout=2.0)
+
+ assert reason == HANGUP_HOTKEY
+ assert stt.recover_calls == 1
+
+
async def test_non_ptt_ack_plays_spoken_ack_and_dead_zone(monkeypatch):
"""The wake-word path keeps the spoken 'Ja?' + the 400 ms dead-zone."""
pipe = _make_pipeline()
diff --git a/tests/unit/trigger/test_hotkey.py b/tests/unit/trigger/test_hotkey.py
index a5aa12b758..f9f39d86ca 100644
--- a/tests/unit/trigger/test_hotkey.py
+++ b/tests/unit/trigger/test_hotkey.py
@@ -31,7 +31,7 @@ LIVE_BINDINGS = {"call": CALL_COMBOS, "hangup": HANGUP_COMBOS}
@pytest.fixture()
-def fake_gh():
+def fake_gh(monkeypatch):
"""Install a fresh FakeGlobalHotkeys into ``sys.modules`` for the test.
Also resets the module-level checker refcount so the single-checker
@@ -43,6 +43,12 @@ def fake_gh():
saved = sys.modules.get("global_hotkeys")
sys.modules["global_hotkeys"] = fake
hk._reset_checker_state_for_tests()
+ # This module verifies the Windows global-hotkeys contract. Pin the
+ # backend explicitly so the same tests remain valid on the macOS and Linux
+ # CI legs instead of silently selecting Quartz/pynput from the host OS.
+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
+
+ monkeypatch.setattr(hk, "make_hotkey_backend", GlobalHotkeysBackend)
try:
yield fake
finally:
diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.py
index 043ba89dcb..df4affc6f5 100644
--- a/tests/unit/trigger/test_hotkey_backends.py
+++ b/tests/unit/trigger/test_hotkey_backends.py
@@ -23,6 +23,8 @@ from __future__ import annotations
import inspect
import logging
import sys
+import threading
+import types
import pytest
@@ -180,6 +182,24 @@ def test_global_backend_two_instances_share_one_checker(fake_gh):
assert fake_gh.peak_live == 1
+def test_global_backend_delivers_one_ptt_press_release_pair(fake_gh):
+ """Windows keeps distinct down/up callbacks for a held PTT chord."""
+ from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
+
+ edges: list[str] = []
+ backend = GlobalHotkeysBackend()
+ backend.register(
+ [["control + alt + l", lambda: edges.append("down"), lambda: edges.append("up")]]
+ )
+ backend.start()
+ fake_gh.fire_press("control + alt + l")
+ fake_gh.fire_release("control + alt + l")
+ backend.stop()
+ backend.unregister()
+
+ assert edges == ["down", "up"]
+
+
def test_global_backend_unregister_removes_by_string(fake_gh):
"""REGRESSION: unregister must pass combo STRINGS, never the rows."""
from jarvis.trigger.backends.global_hotkeys import GlobalHotkeysBackend
@@ -335,6 +355,27 @@ def test_pynput_combo_translation_fkeys_passthrough():
assert _parse_combo_tokens("f3 + f4") == ("f3", "f4")
+def test_pynput_linux_right_alt_drives_one_ptt_edge_pair():
+ """Linux-X11 reports right Alt as ``alt_r``; generic Alt must match it."""
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ edges: list[str] = []
+ backend = PynputBackend()
+ backend.register(
+ [["alt + l", lambda: edges.append("down"), lambda: edges.append("up")]]
+ )
+ right_alt = types.SimpleNamespace(char=None, name="alt_r")
+ letter_l = types.SimpleNamespace(char="l", name=None)
+
+ backend._on_press_key(right_alt)
+ backend._on_press_key(letter_l)
+ backend._on_press_key(letter_l) # OS key repeat must not emit another edge
+ backend._on_release_key(letter_l)
+ backend._on_release_key(right_alt)
+
+ assert edges == ["down", "up"]
+
+
def test_pynput_backend_register_does_not_import_pynput():
"""register() only stashes rows — no pynput import, so it works here."""
from jarvis.trigger.backends.pynput import PynputBackend
@@ -345,6 +386,32 @@ def test_pynput_backend_register_does_not_import_pynput():
backend.unregister() # no raise
+def test_pynput_rearm_refuses_duplicate_when_old_listener_is_stuck(caplog):
+ """Linux keeps wake usable instead of stacking a second global hook."""
+ from jarvis.trigger.backends.pynput import PynputBackend
+
+ class _StuckListener:
+ def stop(self) -> None:
+ return None
+
+ def join(self, timeout=None) -> None: # noqa: ANN001
+ return None
+
+ def is_alive(self) -> bool:
+ return True
+
+ backend = PynputBackend()
+ backend._listener = _StuckListener()
+ backend._started = True
+ with caplog.at_level(logging.WARNING, logger="jarvis.trigger.backends.pynput"):
+ backend.stop()
+ backend.start()
+
+ assert backend._teardown_failed is True
+ assert backend._listener is None
+ assert "replacement listener" in caplog.text
+
+
def test_pynput_backend_start_degrades_without_pynput(caplog):
"""When pynput is absent, start() logs + degrades — never raises (AD-6)."""
from jarvis.trigger.backends.pynput import PynputBackend
@@ -407,6 +474,12 @@ def _install_fake_pynput(monkeypatch, built: list) -> None:
def stop(self) -> None: ...
+ def join(self, timeout=None) -> None: # noqa: ANN001
+ return None
+
+ def is_alive(self) -> bool:
+ return False
+
fake_pynput = types.ModuleType("pynput")
fake_pynput.keyboard = types.SimpleNamespace(Listener=_FakeListener)
monkeypatch.setitem(sys.modules, "pynput", fake_pynput)
@@ -547,3 +620,129 @@ def test_pynput_backend_revoked_permission_suppresses_live_callback(monkeypatch)
assert fired == []
assert backend._held == set()
+
+
+# ----------------------------------------------------------------------
+# QuartzHotkeyBackend — edge semantics + leak-free live re-arm (macOS).
+# ----------------------------------------------------------------------
+
+
+def test_quartz_backend_delivers_one_ptt_edge_pair() -> None:
+ """Key repeat and the later modifier release never duplicate PTT edges."""
+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+
+ edges: list[str] = []
+ backend = QuartzHotkeyBackend()
+ backend._permission_check = lambda: True
+ backend.register(
+ [["alt + l", lambda: edges.append("down"), lambda: edges.append("up")]]
+ )
+
+ backend._handle_flags(1 << 19) # Option/Alt down
+ backend._handle_key_down(0x25) # physical L
+ backend._handle_key_down(0x25) # key repeat
+ backend._handle_key_up(0x25)
+ backend._handle_flags(0) # Option/Alt up after L
+
+ assert edges == ["down", "up"]
+
+
+def _install_fake_quartz(monkeypatch):
+ """Install a Core Foundation event-loop fake for lifecycle tests."""
+ quartz = types.ModuleType("Quartz")
+ quartz.kCGEventKeyDown = 10
+ quartz.kCGEventKeyUp = 11
+ quartz.kCGEventFlagsChanged = 12
+ quartz.kCGEventTapDisabledByTimeout = 13
+ quartz.kCGEventTapDisabledByUserInput = 14
+ quartz.kCGKeyboardEventKeycode = 15
+ quartz.kCGSessionEventTap = 16
+ quartz.kCGHeadInsertEventTap = 17
+ quartz.kCGEventTapOptionListenOnly = 18
+ quartz.kCFRunLoopCommonModes = "common"
+ quartz._local = threading.local()
+ quartz.taps = []
+ quartz.removed_sources = []
+ quartz.wake_calls = 0
+
+ class _Tap:
+ def __init__(self, callback) -> None: # noqa: ANN001
+ self.callback = callback
+ self.enabled = False
+ self.invalidated = False
+
+ class _Loop:
+ def __init__(self) -> None:
+ self.stopped = False
+ self.wake = threading.Event()
+
+ def _tap_create(_location, _placement, _options, _mask, callback, _refcon):
+ tap = _Tap(callback)
+ quartz.taps.append(tap)
+ return tap
+
+ def _get_loop():
+ loop = _Loop()
+ quartz._local.loop = loop
+ return loop
+
+ def _run_loop():
+ loop = quartz._local.loop
+ while not loop.stopped:
+ loop.wake.wait()
+ loop.wake.clear()
+
+ def _stop_loop(loop): # noqa: ANN001
+ # Deliberately does not wake the waiter: the production fix must call
+ # CFRunLoopWakeUp as well as CFRunLoopStop before joining.
+ loop.stopped = True
+
+ def _wake_loop(loop): # noqa: ANN001
+ quartz.wake_calls += 1
+ loop.wake.set()
+
+ quartz.CGEventMaskBit = lambda value: 1 << value
+ quartz.CGEventTapCreate = _tap_create
+ quartz.CFMachPortCreateRunLoopSource = lambda _alloc, tap, _order: ("source", tap)
+ quartz.CFRunLoopGetCurrent = _get_loop
+ quartz.CFRunLoopAddSource = lambda _loop, _source, _mode: None
+ quartz.CFRunLoopRun = _run_loop
+ quartz.CFRunLoopStop = _stop_loop
+ quartz.CFRunLoopWakeUp = _wake_loop
+ quartz.CFRunLoopRemoveSource = (
+ lambda loop, source, mode: quartz.removed_sources.append((loop, source, mode))
+ )
+ quartz.CGEventTapEnable = lambda tap, enabled: setattr(tap, "enabled", enabled)
+ quartz.CFMachPortInvalidate = lambda tap: setattr(tap, "invalidated", True)
+ quartz.CGEventGetIntegerValueField = lambda _event, _field: 0
+ quartz.CGEventGetFlags = lambda _event: 0
+ monkeypatch.setitem(sys.modules, "Quartz", quartz)
+ return quartz
+
+
+def test_quartz_rearm_fully_retires_old_event_tap(monkeypatch) -> None:
+ """A Settings save cannot leave an older tap emitting duplicate edges."""
+ from jarvis.trigger.backends.quartz import QuartzHotkeyBackend
+
+ quartz = _install_fake_quartz(monkeypatch)
+ backend = QuartzHotkeyBackend()
+ backend._permission_check = lambda: True
+ backend.register([["alt + j", None, lambda: None]])
+ backend.start()
+ old_thread = backend._thread
+ old_tap = quartz.taps[-1]
+
+ backend.stop()
+ assert old_tap.enabled is False
+ assert old_tap.invalidated is True
+ assert quartz.removed_sources
+ assert quartz.wake_calls == 1
+ assert old_thread is not None and not old_thread.is_alive()
+
+ backend.unregister()
+ backend.register([["alt + l", lambda: None, lambda: None]])
+ backend.start()
+ assert len(quartz.taps) == 2
+ assert quartz.taps[-1].enabled is True
+ assert old_tap.enabled is False
+ backend.stop()