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.

@ feat(voice): add a hands-free dictation key alongside push-to-talk

Ruben Lütkefa59fee4a647
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index 6c5ba78f5d..cb038b6896 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -333,19 +333,28 @@ class TriggerConfig(BaseModel):
# Hangup key. Was hardcoded ("f1+f2",) at the SpeechPipeline call sites; now
# user-editable via /api/settings/keybinds. Read directly at bootstrap.
hotkey_hangup: str = "f1+f2"
- # Dictation key: hold (or toggle, see [dictation].mode) to speak; the
- # transcript is inserted into whatever text field currently has focus.
+ # Push-to-talk dictation key: HOLD to speak, release to insert. The
+ # transcript lands in whatever text field currently has focus.
#
- # Deliberately EMPTY by default. There is no combination that is free on
- # every machine and every OS — the well-known ones are refused by
- # ``validate_hotkey`` (Windows key, Ctrl+C, Alt+F4, the macOS Command
- # shortcuts), and silently claiming a chord the user needs elsewhere is the
- # worse failure. The setup wizard and Settings → Keybinds ask for it.
- # Unbound is a valid, fully usable state: dictation still starts from the
- # bar, from the UI, and from ``jarvis api dictation start`` — the last of
- # which is the documented Wayland path, where the compositor (not the app)
- # owns global shortcuts.
- hotkey_dictate: str = ""
+ # Ships BOUND (maintainer directive 2026-07-28). Dictation shipped unbound
+ # for a while on the theory that no chord is free on every machine; the
+ # result was a headline feature that did nothing on a fresh install unless
+ # the user happened to open the Shortcuts tab. The two combos below are
+ # curated instead: both pass ``validate_hotkey`` on win32, darwin AND linux,
+ # neither is an OS-reserved chord, and their key sets are neither subsets
+ # nor supersets of each other or of Call (``f3+f4``) / Hangup (``f1+f2``),
+ # so the keybind collision rule accepts all four at once. Clearing a row in
+ # the Voice → Shortcuts tab is one click, and an empty value remains a
+ # fully valid state: dictation still starts from the bar, from the UI, and
+ # from ``jarvis api dictation start`` — the last of which is the documented
+ # Wayland path, where the compositor (not the app) owns global shortcuts.
+ hotkey_dictate: str = "ctrl+right_alt+j"
+ # Hands-free dictation key: press once to start, press again to stop. Its
+ # own action (not ``[dictation].mode``) so a user can have BOTH a hold key
+ # and a toggle key armed at the same time; ``[dictation].mode = "toggle"``
+ # stays honoured for installs that configured it, and only changes how
+ # ``hotkey_dictate`` behaves.
+ hotkey_dictate_toggle: str = "ctrl+right_alt+space"
wake_word: WakeWordConfig = Field(default_factory=WakeWordConfig)
# When false (default), the pipeline keeps the mic open after the
# response (conversation mode) and only hangs up via HANGUP_RE, the idle
@@ -2464,6 +2473,14 @@ class SpeechConfig(BaseModel):
vad_silence_ms: int = Field(default=1500, ge=500, le=5000)
+#: The values ``[dictation].language`` accepts. ``auto`` (detect per utterance)
+#: plus every supported product locale — they are equal, never a German- or
+#: English-first list (CLAUDE.md §1, runtime output language). The REST layer's
+#: ``choices.language`` and the frontend's ``DictationLanguage`` union mirror
+#: this tuple; adding a locale means adding it here first.
+DICTATION_LANGUAGES: tuple[str, ...] = ("auto", "de", "en", "es")
+
+
class DictationConfig(BaseModel):
"""Dictation mode: speak into whatever text field currently has focus.
@@ -2545,6 +2562,43 @@ class DictationConfig(BaseModel):
history_max_entries: int = Field(default=200, ge=0, le=5000)
history_retention_days: int = Field(default=30, ge=0, le=3650)
+ #: Which language the dictation transcription is pinned to. ``auto`` (the
+ #: default, and the right answer for almost everyone) lets the provider
+ #: detect it per utterance. Pinning helps only when the provider keeps
+ #: guessing wrong; on a model that was not trained for the pinned language
+ #: it makes recognition WORSE, so the UI says so out loud.
+ #:
+ #: Deliberately independent of ``[stt].language`` (the voice-turn language)
+ #: and ``[wake].language`` — dictating in one language while talking to the
+ #: assistant in another is a normal thing to want.
+ language: str = "auto"
+
+ #: Keep the raw audio of a dictation that produced nothing usable
+ #: (``failed`` / ``cancelled`` / ``empty``) so the Restore button can
+ #: transcribe it again. NEVER kept for a successful dictation: audio is the
+ #: most sensitive thing this application stores, so it is only ever written
+ #: when it buys back something the user actually lost. Local-only, capped by
+ #: the two keys below, deleted with the history entry and purged when the
+ #: history is cleared. Its own key, not a rider on ``history_enabled``, so
+ #: it can be turned off on its own.
+ keep_failed_audio: bool = True
+ #: Delete kept audio older than this many days. ``0`` disables the age cap.
+ audio_retention_days: int = Field(default=7, ge=0, le=365)
+ #: Keep at most this many audio files. ``0`` disables the count cap (the
+ #: age cap still applies); it does not mean "delete everything".
+ audio_max_files: int = Field(default=20, ge=0, le=1000)
+
+ @field_validator("language", mode="before")
+ @classmethod
+ def _coerce_dictation_language(cls, value: object) -> str:
+ """Normalize only — an unknown value falls back to ``auto``.
+
+ A stale or hand-edited config must never fail validation (AP-16), and
+ ``auto`` is always a working answer.
+ """
+ text = str(value or "").strip().lower()
+ return text if text in DICTATION_LANGUAGES else "auto"
+
class MarketplaceConfig(BaseModel):
"""Plugin-marketplace connect settings (OAuth redirect mode).
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 1cb10a0a6f..f3b2849998 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -570,17 +570,21 @@ def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE)
# frontend (jarvis/ui/web/frontend/src/hooks/useHotkey.ts). Keep these layers in
# sync. The mapped value is BOTH the jarvis.toml key under [trigger] AND the
# TriggerConfig field name (they are intentionally identical).
-KEYBIND_ACTIONS = ("call", "hangup", "dictate")
+KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle")
KEYBIND_TOML_KEY = {
"call": "hotkey_call",
"hangup": "hotkey_hangup",
- # Dictation mode: hold (or toggle) to speak, the transcript is inserted into
- # whatever text field has focus. Ships UNBOUND — there is no combination
- # that is free on every machine, so the user picks one (setup wizard or
- # Settings). An empty value means "dictation has no shortcut", which is a
- # valid state, not a broken one: the bar, the UI and `jarvis api dictation
- # start` all still work (and are the documented Wayland path).
+ # Push-to-talk dictation: HOLD to speak, release to insert the transcript
+ # into whatever text field has focus. Ships bound to a curated combo (see
+ # TriggerConfig.hotkey_dictate for the reasoning and the collision proof).
+ # An empty value means "dictation has no shortcut", which stays a valid
+ # state, not a broken one: the bar, the UI and `jarvis api dictation start`
+ # all still work (and are the documented Wayland path).
"dictate": "hotkey_dictate",
+ # Hands-free dictation: press once to start, press again to stop. A
+ # separate action rather than a mode flag, so a user can arm a hold key and
+ # a toggle key at the same time.
+ "dictate_toggle": "hotkey_dictate_toggle",
}
@@ -620,6 +624,10 @@ DICTATION_SETTING_KEYS = (
"history_enabled",
"history_max_entries",
"history_retention_days",
+ "language",
+ "keep_failed_audio",
+ "audio_retention_days",
+ "audio_max_files",
)
diff --git a/jarvis/core/events.py b/jarvis/core/events.py
index a02892f8b8..dd2928ba3a 100644
--- a/jarvis/core/events.py
+++ b/jarvis/core/events.py
@@ -140,7 +140,10 @@ class DictationCompleted(Event):
text: str = ""
#: The transcript exactly as the STT returned it, before cleanup.
raw_text: str = ""
- #: ``inserted`` | ``clipboard_only`` | ``unavailable`` | ``chat`` | ``empty``.
+ #: One of ``jarvis.dictation.outcomes.DICTATION_OUTCOMES``. That tuple is
+ #: the single vocabulary for this value; it is imported rather than
+ #: restated here because listing it twice is exactly how the five layers
+ #: that carry an outcome drifted apart before (AP-4 / BUG-008).
outcome: str = ""
#: User-facing explanation; empty when nothing needs explaining.
detail: str = ""
@@ -149,6 +152,11 @@ class DictationCompleted(Event):
language: str = ""
duration_s: float = 0.0
removed_words: int = 0
+ #: Why transcription failed, when it did (a provider error, a missing key,
+ #: a wedged engine). ``None`` on every path that did not fail. This is what
+ #: makes ``outcome="failed"`` distinguishable from ``outcome="empty"``:
+ #: before it existed, a provider 401 and plain silence looked identical.
+ error: str | None = None
# ----------------------------------------------------------------------
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2537c03b5c..32ee0d2774 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -1289,6 +1289,11 @@ class SpeechPipeline:
# deprecated ptt slot: dictation never reaches the brain.
dictate_hotkeys: tuple[str, ...] = (),
dictate_mode: str = "hold",
+ # Hands-free dictation: press once to start, press again to stop. Its
+ # OWN binding, independent of ``dictate_mode`` — a user may have a hold
+ # key and a toggle key armed at the same time, and the legacy
+ # ``[dictation].mode = "toggle"`` still only governs ``dictate_hotkeys``.
+ dictate_toggle_hotkeys: tuple[str, ...] = (),
# Resolved DictationConfig (jarvis.core.config.DictationConfig) or None.
# None keeps every legacy call site and test on the built-in defaults.
dictation_config: Any = None,
@@ -1297,6 +1302,7 @@ class SpeechPipeline:
self._ptt_hotkeys = ptt_hotkeys
self._hangup_hotkeys = hangup_hotkeys
self._dictate_hotkeys = list(dictate_hotkeys)
+ self._dictate_toggle_hotkeys = list(dictate_toggle_hotkeys)
self._dictate_mode = "toggle" if str(dictate_mode).lower() == "toggle" else "hold"
self._dictation_cfg = dictation_config
# Push-to-talk runtime state. ``_ptt_mode`` arms the raw-recording path
@@ -2278,6 +2284,7 @@ class SpeechPipeline:
hangup: list[str] | None = None,
ptt: list[str] | None = None,
dictate: list[str] | None = None,
+ dictate_toggle: list[str] | None = None,
) -> None:
"""Live-apply changed voice keybinds — no app/pipeline restart.
@@ -2290,6 +2297,11 @@ class SpeechPipeline:
Mirrors the ``set_wake_plan`` live-apply contract: safe to call from the
FastAPI handler thread — it shares the pipeline's event loop. Only the
actions passed are changed; ``None`` leaves that action untouched.
+
+ Every keyword here is spelled exactly like its entry in
+ ``config_writer.KEYBIND_ACTIONS``: the settings route calls
+ ``set_keybinds(**{action: [...]})``, so a keyword that drifts from the
+ action string turns a successful save into a silent no-op.
"""
if call is not None:
self._call_hotkeys = list(call)
@@ -2299,12 +2311,16 @@ class SpeechPipeline:
self._ptt_hotkeys = list(ptt)
if dictate is not None:
self._dictate_hotkeys = list(dictate)
+ if dictate_toggle is not None:
+ self._dictate_toggle_hotkeys = list(dictate_toggle)
log.info(
- "Keybind-Live-Switch: CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s]",
+ "Keybind-Live-Switch: CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s] "
+ "DICTATE-TOGGLE=[%s]",
", ".join(self._call_hotkeys),
", ".join(self._ptt_hotkeys) or "off",
", ".join(self._hangup_hotkeys),
", ".join(self._dictate_hotkeys) or "off",
+ ", ".join(self._dictate_toggle_hotkeys) or "off",
)
self._hotkey_reload_event.set()
@@ -2345,6 +2361,14 @@ class SpeechPipeline:
# so holding the key does not start and stop repeatedly.
if self._dictate_mode == "hold":
edge_events.add("dictate")
+ # ``getattr`` default: unit tests build pipelines via ``__new__`` and set
+ # only the attributes they care about, a widely used pattern in this repo.
+ dictate_toggle = getattr(self, "_dictate_toggle_hotkeys", None) or []
+ if dictate_toggle:
+ bindings["dictate_toggle"] = list(dictate_toggle)
+ # Never an edge binding: the whole point of a toggle is one event
+ # per press. Asking for both edges would start on the down edge and
+ # stop again on the up edge, i.e. turn it back into push-to-talk.
return bindings, edge_events
# ------------------------------------------------------------------
@@ -4061,13 +4085,15 @@ class SpeechPipeline:
# single-fire-on-release contract. One producer for boot and live re-arm.
hotkey_bindings, ptt_events = self._build_hotkey_bindings()
log.info(
- "Pipeline ready. CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s/%s] OWW=%s "
+ "Pipeline ready. CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s/%s] "
+ "DICTATE-TOGGLE=[%s] OWW=%s "
"WAKE=%s (threshold=%.2f) WHISPER-WAKE=%s TURN-MODE=%s",
", ".join(self._call_hotkeys),
", ".join(self._ptt_hotkeys) or "off",
", ".join(self._hangup_hotkeys),
", ".join(self._dictate_hotkeys) or "off",
self._dictate_mode,
+ ", ".join(getattr(self, "_dictate_toggle_hotkeys", None) or []) or "off",
"on" if self._openwakeword_enabled else "off",
list(self._wake._keywords),
self._wake._threshold,
@@ -4569,7 +4595,11 @@ class SpeechPipeline:
elif event_name == "dictate_release":
self._on_dictate_release()
elif event_name == "dictate":
- # Toggle mode: one press starts, the next stops.
+ # 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 == "hangup":
log.info("📵 HANGUP via Hotkey")
@@ -7523,17 +7553,46 @@ class SpeechPipeline:
stop_event = asyncio.Event()
inference_active = asyncio.Event()
language = ""
+ # The last transcription error, or None. Resolved ONCE per session at
+ # the end: it is what separates "the provider rejected us" from "you
+ # said nothing", and without it a 401 arrives in the history looking
+ # exactly like silence — with no hint that a key needs fixing.
+ stt_error: str | None = None
+ # ``[dictation].language`` pinned by the user; None means "auto", i.e.
+ # let the provider detect it. Resolved here rather than inside the
+ # closure so the config is read once per session, not once per segment.
+ pinned_language = str(getattr(cfg, "language", "auto") or "auto").strip().lower()
+ forced_language = pinned_language if pinned_language not in ("", "auto") else None
async def _transcribe(pcm: bytes) -> tuple[str, str]:
- """One transcription. Returns ``(text, language)``; never raises."""
+ """One transcription. Returns ``(text, language)``; never raises.
+
+ Records the failure in ``stt_error`` instead of swallowing it. A
+ later successful call clears it again — a single flaky segment in an
+ otherwise working dictation is not a failed dictation.
+ """
+ nonlocal stt_error
inference_active.set()
try:
- transcript = await stt.transcribe_pcm(pcm)
+ if forced_language is None:
+ transcript = await stt.transcribe_pcm(pcm)
+ else:
+ try:
+ transcript = await stt.transcribe_pcm(
+ pcm, language=forced_language
+ )
+ except TypeError:
+ # Provider predates the keyword (contract allows a bare
+ # ``transcribe_pcm(pcm)``). Fall back rather than call
+ # the pin a failure — precedent: rolling_whisper_wake.
+ transcript = await stt.transcribe_pcm(pcm)
except Exception as exc: # noqa: BLE001 — one failed call is not fatal
log.debug("dictation transcribe failed: %s", exc)
+ stt_error = f"{type(exc).__name__}: {exc}".strip()
return "", ""
finally:
inference_active.clear()
+ stt_error = None
text = (getattr(transcript, "text", "") or "").strip()
lang = str(getattr(transcript, "language", "") or "")
return text, lang
@@ -7599,6 +7658,10 @@ class SpeechPipeline:
final_text = ""
raw_text = ""
hung_up = False
+ # True once the delivery half has been entered, so the crash handler
+ # below can tell "we never got to deliver" from "delivery itself blew
+ # up" and never runs the delivery twice.
+ finished = False
try:
async with MicrophoneCapture(
device=self._input_device, device_priority=self._input_priority
@@ -7666,31 +7729,57 @@ class SpeechPipeline:
final_text = raw_text
duration_s = max(0.0, time.monotonic() - started_at)
+ finished = True
result = await self._finish_dictation(
raw_text=raw_text,
language=language,
duration_s=duration_s,
target=target,
hung_up=hung_up,
+ stt_error=stt_error,
+ audio=bytes(buffer),
)
final_text = result
log.info(
- "🎙️ dictation ended (%d chars, %.1fs, target=%s%s).",
+ "🎙️ dictation ended (%d chars, %.1fs, target=%s%s%s).",
len(final_text),
duration_s,
target,
", hung up" if hung_up else "",
+ f", stt error: {stt_error}" if stt_error else "",
)
- except Exception: # noqa: BLE001 — dictation must never break voice
+ except Exception as exc: # noqa: BLE001 — dictation must never break voice
log.warning("dictation session crashed (non-fatal)", exc_info=True)
+ if finished:
+ # The crash happened after (or inside) the delivery half, which
+ # already published its own final transcript. Re-entering it
+ # would double-publish and could recurse into the same fault.
+ return
+ # Everything before delivery: route the failure THROUGH the normal
+ # finish path instead of returning silently. It publishes the same
+ # empty final transcript the old handler did, and additionally
+ # records a `failed` history row — the worst failure this feature
+ # has used to be its most invisible one.
try:
- await self._publish_event(
- DictationTranscript(
- source_layer="speech.dictation", text="", is_final=True
- )
+ await self._finish_dictation(
+ raw_text="",
+ language=language,
+ duration_s=max(0.0, time.monotonic() - started_at),
+ target=target,
+ hung_up=False,
+ stt_error=f"{type(exc).__name__}: {exc}".strip(),
+ audio=bytes(buffer),
)
- except Exception: # noqa: BLE001
- pass
+ except Exception: # noqa: BLE001 — the fallback must not raise either
+ log.debug("dictation failure record failed", exc_info=True)
+ try:
+ await self._publish_event(
+ DictationTranscript(
+ source_layer="speech.dictation", text="", is_final=True
+ )
+ )
+ except Exception: # noqa: BLE001
+ pass
async def _finish_dictation(
self,
@@ -7700,6 +7789,8 @@ class SpeechPipeline:
duration_s: float,
target: str,
hung_up: bool,
+ stt_error: str | None = None,
+ audio: bytes | None = None,
) -> str:
"""Clean, deliver and record one finished dictation. Returns the text.
@@ -7708,19 +7799,34 @@ class SpeechPipeline:
falls back to the raw transcript, a failed insertion falls back to "it
is on your clipboard", and a failed history write costs nothing but the
history entry.
+
+ ``stt_error`` is the transcription failure, if there was one. It is what
+ makes ``failed`` distinguishable from ``empty``, so it is carried into
+ the completion event and the history row rather than logged and dropped.
+ ``audio`` is the session's raw PCM; it is written to a local sidecar
+ only when the dictation produced nothing usable AND the user allows it
+ (``[dictation].keep_failed_audio``), which is what a later Restore
+ transcribes again.
"""
cleaned = raw_text
removed_words = 0
cleanup_reason = ""
cfg = getattr(self, "_dictation_cfg", None)
+ # A user-pinned ``[dictation].language`` outranks whatever the provider
+ # reported. Without this the cleanup rules see the provider's guess —
+ # and a provider that answers "unknown" leaves every dictation with
+ # reason="no_rules", i.e. no cleanup at all despite an explicit pin.
+ pinned = str(getattr(cfg, "language", "auto") or "auto").strip().lower()
+ effective_language = pinned if pinned not in ("", "auto") else language
+
if raw_text and not hung_up:
try:
from jarvis.dictation.cleanup import clean_transcript
outcome = clean_transcript(
raw_text,
- language=language,
+ language=effective_language,
remove_fillers=bool(getattr(cfg, "remove_fillers", True)),
max_removed_fraction=float(
getattr(cfg, "filler_max_removed_fraction", 0.25)
@@ -7766,7 +7872,10 @@ class SpeechPipeline:
if hung_up:
outcome_name = "cancelled"
elif not cleaned.strip():
- outcome_name = "empty"
+ # Nothing to deliver. WHY there is nothing is the whole point of
+ # this branch: a provider error is a "failed" the user can act on
+ # (fix the key, switch provider), silence is just an "empty".
+ outcome_name = "failed" if stt_error else "empty"
elif resolved_target == "insert":
insert_result = await asyncio.to_thread(self._insert_dictation, cleaned)
outcome_name = insert_result.status
@@ -7782,35 +7891,117 @@ class SpeechPipeline:
outcome=outcome_name,
detail=detail,
method=method,
- language=language,
+ language=effective_language,
duration_s=duration_s,
removed_words=removed_words,
+ error=stt_error,
)
)
except Exception as exc: # noqa: BLE001
log.debug("dictation completion publish failed: %s", exc)
- if raw_text and getattr(cfg, "history_enabled", True):
- try:
- from jarvis.dictation.history import DictationHistory
+ await self._record_dictation(
+ raw_text=raw_text,
+ cleaned=cleaned,
+ language=effective_language,
+ duration_s=duration_s,
+ outcome_name=outcome_name,
+ method=method,
+ removed_words=removed_words,
+ cleanup_reason=cleanup_reason,
+ stt_error=stt_error,
+ audio=audio,
+ )
+ return cleaned
+ async def _record_dictation(
+ self,
+ *,
+ raw_text: str,
+ cleaned: str,
+ language: str,
+ duration_s: float,
+ outcome_name: str,
+ method: str,
+ removed_words: int,
+ cleanup_reason: str,
+ stt_error: str | None,
+ audio: bytes | None,
+ ) -> None:
+ """Write the history row and, when warranted, the audio sidecar.
+
+ Split out of ``_finish_dictation`` because it is the only part that
+ touches the disk: the caller has already published everything the UI
+ needs, so nothing in here is allowed to change what the user sees. All
+ of it is best-effort — a failed history write costs the history entry
+ and nothing else.
+ """
+ from jarvis.dictation.outcomes import is_recoverable
+
+ cfg = getattr(self, "_dictation_cfg", None)
+ # A dictation that produced nothing is recorded too when its outcome
+ # says the user LOST something (failed / cancelled / empty): that row is
+ # the only place a later Restore can start from.
+ if not (raw_text or is_recoverable(outcome_name)):
+ return
+ if not getattr(cfg, "history_enabled", True):
+ return
+
+ entry = None
+ history = None
+ try:
+ from jarvis.dictation.history import DictationHistory
+
+ history = DictationHistory()
+ entry = await asyncio.to_thread(
+ history.add,
+ raw_text=raw_text,
+ text=cleaned,
+ language=language,
+ duration_s=duration_s,
+ outcome=outcome_name,
+ method=method,
+ removed_words=removed_words,
+ cleanup_reason=cleanup_reason,
+ error=stt_error,
+ max_entries=int(getattr(cfg, "history_max_entries", 200)),
+ retention_days=int(getattr(cfg, "history_retention_days", 30)),
+ )
+ except Exception: # noqa: BLE001 — history is never worth a failure
+ log.debug("dictation history write failed", exc_info=True)
+ return
+
+ # Audio is the most sensitive thing this application ever stores, so it
+ # is written on exactly one path: the user allowed it AND the dictation
+ # left them with nothing to show for it. Never on a success.
+ if (
+ entry is None
+ or history is None
+ or not audio
+ or not bool(getattr(cfg, "keep_failed_audio", True))
+ or not is_recoverable(outcome_name)
+ ):
+ return
+ try:
+ from jarvis.dictation.audio import prune_audio, save_dictation_audio
+
+ path = await asyncio.to_thread(
+ save_dictation_audio, entry.id, audio, directory=history.audio_dir
+ )
+ if path is not None:
await asyncio.to_thread(
- DictationHistory().add,
- raw_text=raw_text,
- text=cleaned,
- language=language,
- duration_s=duration_s,
- outcome=outcome_name,
- method=method,
- removed_words=removed_words,
- cleanup_reason=cleanup_reason,
- max_entries=int(getattr(cfg, "history_max_entries", 200)),
- retention_days=int(getattr(cfg, "history_retention_days", 30)),
+ history.update, entry.id, audio_path=str(path)
)
- except Exception: # noqa: BLE001 — history is never worth a failure
- log.debug("dictation history write failed", exc_info=True)
-
- return cleaned
+ # Retention runs after the write, off the delivery path: the
+ # transcript is already in front of the user by now.
+ await asyncio.to_thread(
+ prune_audio,
+ max_files=int(getattr(cfg, "audio_max_files", 20)),
+ retention_days=int(getattr(cfg, "audio_retention_days", 7)),
+ directory=history.audio_dir,
+ )
+ except Exception: # noqa: BLE001 — a lost recovery option, not a lost dictation
+ log.debug("dictation audio sidecar failed", exc_info=True)
def _insert_dictation(self, text: str):
"""Blocking insertion, run off the event loop. Never raises.
@@ -10932,6 +11123,11 @@ async def _main() -> None:
if config.trigger.hotkey_dictate.strip()
else ()
),
+ dictate_toggle_hotkeys=(
+ (config.trigger.hotkey_dictate_toggle,)
+ if config.trigger.hotkey_dictate_toggle.strip()
+ else ()
+ ),
dictate_mode=config.dictation.mode,
dictation_config=config.dictation,
hangup_hotkeys=(
diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.py
index 2fc1e63567..971ae5ee22 100644
--- a/jarvis/speech/watchdog.py
+++ b/jarvis/speech/watchdog.py
@@ -130,6 +130,14 @@ async def _main() -> None:
if config.trigger.hotkey_dictate.strip()
else ()
),
+ # Hands-free dictation. Wired here as well as in desktop_app: this is
+ # the pipeline the watchdog rebuilds after a voice restart, so a
+ # binding missing here works exactly once and then disappears.
+ dictate_toggle_hotkeys=(
+ (config.trigger.hotkey_dictate_toggle,)
+ if config.trigger.hotkey_dictate_toggle.strip()
+ else ()
+ ),
dictate_mode=config.dictation.mode,
dictation_config=config.dictation,
hangup_hotkeys=(
diff --git a/jarvis/trigger/backends/global_hotkeys.py b/jarvis/trigger/backends/global_hotkeys.py
index ba9df0a2fc..fe005f336b 100644
--- a/jarvis/trigger/backends/global_hotkeys.py
+++ b/jarvis/trigger/backends/global_hotkeys.py
@@ -40,6 +40,13 @@ _KEY_MAP = {
"left_alt": "alt",
"altgr": "alt",
"win": "window",
+ # Same physical key, other names: X11 and most Linux desktops call it
+ # Super, some configs spell it Meta. ``validate_hotkey`` refuses new
+ # bindings that use them, but a jarvis.toml written before that rule
+ # existed may still carry one — folding them here means such a config
+ # normalizes to a real token instead of arming a combo that never fires.
+ "super": "window",
+ "meta": "window",
"shift": "shift",
}
diff --git a/jarvis/trigger/backends/pynput.py b/jarvis/trigger/backends/pynput.py
index 4c112cf07f..cfe51f8f95 100644
--- a/jarvis/trigger/backends/pynput.py
+++ b/jarvis/trigger/backends/pynput.py
@@ -74,6 +74,11 @@ _MODIFIER_TO_KEY_ATTR = {
"alt": "alt",
"shift": "shift",
"window": "cmd",
+ # ``_normalize_combo`` already folds super/meta to ``window``, so these two
+ # only matter for a caller that hands us a raw combo. pynput reports the
+ # Super/Windows key as ``Key.cmd`` on every platform, hence the same target.
+ "super": "cmd",
+ "meta": "cmd",
}
# ``pynput`` reports the right-hand modifier keys with side-specific names
@@ -86,6 +91,12 @@ _GENERIC_MODIFIER_ALIASES: dict[str, frozenset[str]] = {
"alt": frozenset({"alt", "alt_l", "alt_r", "alt_gr"}),
"shift": frozenset({"shift", "shift_l", "shift_r"}),
"cmd": frozenset({"cmd", "cmd_l", "cmd_r"}),
+ # Super/Meta are the same key pynput calls ``cmd``. Reached only when a
+ # combo skipped ``_normalize_combo``; folding them here keeps a legacy
+ # config comparing against the right physical key instead of a token that
+ # matches nothing.
+ "super": frozenset({"cmd", "cmd_l", "cmd_r"}),
+ "meta": frozenset({"cmd", "cmd_l", "cmd_r"}),
}
# --------------------------------------------------------------------------
diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.py
index be9a06836e..f988416a64 100644
--- a/jarvis/trigger/hotkey.py
+++ b/jarvis/trigger/hotkey.py
@@ -167,8 +167,18 @@ def validate_hotkey(combo: str, *, platform: str | None = None) -> tuple[bool, s
"second key. (Function keys and navigation keys like F5 or Arrow Up "
"can be used on their own.)"
)
- if any(p in ("win", "window") for p in modifiers):
- return False, "Windows-key combos are reserved by the OS — pick Ctrl/Alt/Shift."
+ # ``super`` / ``meta`` are the same physical key as ``win`` under different
+ # names (X11 and most Linux desktops call it Super, pynput reports it as
+ # ``cmd``). Before they were listed here, ``ctrl+super+space`` passed
+ # validation and then registered a binding that could never fire: neither
+ # ``global_hotkeys._KEY_MAP`` nor ``pynput._MODIFIER_TO_KEY_ATTR`` knew the
+ # token, so the combo was armed and silently dead. Rejecting it is the
+ # honest answer — the OS owns that key on all three platforms.
+ if any(p in ("win", "window", "super", "meta") for p in modifiers):
+ return False, (
+ "Windows / Super key combos are reserved by the OS — pick "
+ "Ctrl/Alt/Shift."
+ )
reserved = sorted(set(non_modifiers) & _RESERVED_SOLO_KEYS)
if reserved:
@@ -179,6 +189,9 @@ def validate_hotkey(combo: str, *, platform: str | None = None) -> tuple[bool, s
_CTRL = ("ctrl", "control", "right_ctrl", "right_control")
_ALT = ("alt", "right_alt", "left_alt", "altgr")
+ # ``meta``/``super`` are listed for completeness only — the Windows/Super
+ # rule above already rejected any combo containing them, so they can never
+ # reach this branch. macOS Command is spelled ``cmd``/``command``.
_CMD = ("cmd", "command", "meta", "super")
alt_held = any(p in _ALT for p in modifiers)
# "X-only" means X-family modifiers and nothing else — so the exact OS
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index f4a65b34e2..0163f789bb 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -2899,13 +2899,19 @@ class DesktopApp:
pipeline = SpeechPipeline(
call_hotkeys=_call_hk,
ptt_hotkeys=_ptt_hk,
- # Dictation mode. Ships unbound; the user assigns the key in
- # Settings → Keybinds (or the wizard), and it live-re-arms.
+ # Dictation. Both keys ship bound to a curated combo (see
+ # TriggerConfig.hotkey_dictate); either can be cleared in the
+ # Voice → Shortcuts tab, and both live-re-arm without a restart.
dictate_hotkeys=(
(self.cfg.trigger.hotkey_dictate,)
if self.cfg.trigger.hotkey_dictate.strip()
else ()
),
+ dictate_toggle_hotkeys=(
+ (self.cfg.trigger.hotkey_dictate_toggle,)
+ if self.cfg.trigger.hotkey_dictate_toggle.strip()
+ else ()
+ ),
dictate_mode=self.cfg.dictation.mode,
dictation_config=self.cfg.dictation,
hangup_hotkeys=(
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index dcbe8258d9..568992f254 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -1247,20 +1247,52 @@ async def wake_mic_level(request: Request) -> dict[str, object]:
}
-# Curated safe combos for the voice-keybind UI quick-picks. They avoid
-# OS-critical shortcuts and work across the supported desktop platforms.
+# Curated safe combos for the voice-keybind UI quick-picks. Every entry passes
+# ``validate_hotkey`` on win32, darwin AND linux, and avoids the OS-critical
+# chords. ``f3+f4`` used to be in this list and was removed: it is the shipped
+# Call combo, so it collided with an existing binding every single time and the
+# quick-pick could never be saved.
_KEYBIND_SUGGESTIONS = [
"ctrl+right_alt+j",
"ctrl+right_alt+k",
"ctrl+right_alt+space",
"ctrl+shift+space",
- "f3+f4",
+ "ctrl+shift+d",
+ "ctrl+shift+j",
+ "ctrl+alt+d",
]
+def _combo_keys(combo: str) -> set[str]:
+ """The key SET of a combo — the unit the collision rule compares."""
+ return {p.strip() for p in str(combo or "").strip().lower().split("+") if p.strip()}
+
+
+def _available_suggestions(bound: dict[str, str]) -> list[str]:
+ """Quick-picks minus everything that would be rejected on save.
+
+ The collision rule refuses a combo whose key set is a subset or superset of
+ another action's. Offering such a chord as a one-click suggestion is a
+ guaranteed 400 the moment the user clicks it, so it is filtered out here
+ instead — the server owns the rule, so the server owns the list.
+ """
+ taken = [_combo_keys(c) for c in bound.values() if c and c.strip()]
+ out: list[str] = []
+ for suggestion in _KEYBIND_SUGGESTIONS:
+ keys = _combo_keys(suggestion)
+ if any(keys <= other or other <= keys for other in taken):
+ continue
+ out.append(suggestion)
+ return out
+
+
# ---------------------------------------------------------------------------
-# Voice keybinds (editable): Call / Hangup. GET both actions plus defaults;
-# PUT one action at a time. Persisted to jarvis.toml [trigger] AND live-applied
+# Voice keybinds (editable): every action in config_writer.KEYBIND_ACTIONS —
+# Call, Hangup, push-to-talk dictation and hands-free dictation. GET returns all
+# of them plus their defaults; PUT changes one action at a time. The action list
+# is never restated here; it is read from KEYBIND_ACTIONS / KEYBIND_TOML_KEY so
+# a new action reaches this route, the CLI and the UI in one edit.
+# Persisted to jarvis.toml [trigger] AND live-applied
# to the running voice pipeline (set_keybinds → HotkeyTrigger.rearm), so a
# change takes effect immediately without a restart; a headless/down pipeline
# falls back to "applies on next start".
@@ -1281,7 +1313,11 @@ def _keybind_values(trig: object) -> dict[str, str]:
class KeybindBody(BaseModel):
- action: str = Field(..., description="call | hangup | dictate")
+ action: str = Field(
+ ...,
+ description="One of config_writer.KEYBIND_ACTIONS "
+ "(call | hangup | dictate | dictate_toggle)",
+ )
hotkey: str = Field(..., max_length=64)
persist: bool = Field(default=True, description="Persist to jarvis.toml")
@@ -1289,6 +1325,7 @@ class KeybindBody(BaseModel):
@router.get("/keybinds")
async def get_keybinds(request: Request) -> dict[str, object]:
from jarvis.core.config import TriggerConfig
+ from jarvis.core.config_writer import KEYBIND_TOML_KEY
cfg = _config(request)
trig = getattr(cfg, "trigger", None) if cfg is not None else None
@@ -1297,15 +1334,17 @@ async def get_keybinds(request: Request) -> dict[str, object]:
# (headless / not yet started). With a running pipeline, saves apply live.
pipeline = getattr(request.app.state, "speech_pipeline", None)
restart_required = pipeline is None or not hasattr(pipeline, "set_keybinds")
+ current = _keybind_values(trig)
return {
- "keybinds": _keybind_values(trig),
+ "keybinds": current,
+ # DERIVED, never a hand-written dict. A literal map here is the AP-4
+ # trap in its purest form: a new action lands in KEYBIND_ACTIONS, the
+ # UI renders its row, and the row's "reset to default" reads undefined
+ # because one of the four layers was never told.
"defaults": {
- "call": d.hotkey_call,
- "hangup": d.hotkey_hangup,
- # Dictation ships unbound on purpose — see TriggerConfig.hotkey_dictate.
- "dictate": d.hotkey_dictate,
+ action: str(getattr(d, field, "")) for action, field in KEYBIND_TOML_KEY.items()
},
- "suggestions": list(_KEYBIND_SUGGESTIONS),
+ "suggestions": _available_suggestions(current),
"restart_required": restart_required,
}
diff --git a/tests/unit/core/test_config_writer_keybinds.py b/tests/unit/core/test_config_writer_keybinds.py
index 66ea5753a8..5bed6bd5af 100644
--- a/tests/unit/core/test_config_writer_keybinds.py
+++ b/tests/unit/core/test_config_writer_keybinds.py
@@ -26,6 +26,35 @@ def test_set_keybind_hangup_writes_hotkey_hangup(tmp_path) -> None:
assert 'hotkey_hangup = "ctrl+shift+h"' in _read(toml)
+def test_set_keybind_dictate_writes_hotkey_dictate(tmp_path) -> None:
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("[trigger]\n", encoding="utf-8")
+ config_writer.set_keybind("dictate", "ctrl+alt+d", path=toml)
+ assert 'hotkey_dictate = "ctrl+alt+d"' in _read(toml)
+
+
+def test_set_keybind_dictate_toggle_writes_its_own_key(tmp_path) -> None:
+ """Its own TOML key, not a rider on hotkey_dictate: a user may arm a hold
+ key and a hands-free key at the same time."""
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("[trigger]\n", encoding="utf-8")
+ config_writer.set_keybind("dictate_toggle", "ctrl+shift+d", path=toml)
+ written = _read(toml)
+ assert 'hotkey_dictate_toggle = "ctrl+shift+d"' in written
+ assert "\nhotkey_dictate =" not in written
+
+
+def test_every_registered_action_is_writable(tmp_path) -> None:
+ """A registry entry with no TOML key would save in memory and vanish on
+ restart — the failure mode this mapping exists to prevent."""
+ toml = tmp_path / "jarvis.toml"
+ toml.write_text("[trigger]\n", encoding="utf-8")
+ for action in config_writer.KEYBIND_ACTIONS:
+ assert action in config_writer.KEYBIND_TOML_KEY
+ config_writer.set_keybind(action, "f7+f8", path=toml)
+ assert f'{config_writer.KEYBIND_TOML_KEY[action]} = "f7+f8"' in _read(toml)
+
+
def test_set_keybind_rejects_retired_ptt_action(tmp_path) -> None:
toml = tmp_path / "jarvis.toml"
toml.write_text("[trigger]\n", encoding="utf-8")
diff --git a/tests/unit/core/test_trigger_keybinds.py b/tests/unit/core/test_trigger_keybinds.py
index e1c7b6083c..b26e63cc6e 100644
--- a/tests/unit/core/test_trigger_keybinds.py
+++ b/tests/unit/core/test_trigger_keybinds.py
@@ -4,7 +4,7 @@ from __future__ import annotations
from jarvis.core.config import TriggerConfig
-def test_defaults_expose_only_call_and_hangup_shortcuts() -> None:
+def test_defaults_expose_the_four_shipped_shortcuts() -> None:
t = TriggerConfig()
assert t.hotkey == ""
assert t.hotkey_call == "f3+f4"
@@ -12,6 +12,30 @@ def test_defaults_expose_only_call_and_hangup_shortcuts() -> None:
assert t.push_to_talk is False
+def test_both_dictation_shortcuts_ship_bound() -> None:
+ """Maintainer directive 2026-07-28: dictation is no longer invisible on a
+ fresh install. Curated combos, valid on all three platforms, no collisions
+ (proved in tests/unit/ui/test_keybinds_route.py)."""
+ t = TriggerConfig()
+ assert t.hotkey_dictate == "ctrl+right_alt+j"
+ assert t.hotkey_dictate_toggle == "ctrl+right_alt+space"
+
+
+def test_a_cleared_dictation_shortcut_is_still_a_valid_state() -> None:
+ """Clearing a row in the Shortcuts tab must not be rejected — dictation
+ still runs from the bar, the UI and `jarvis api dictation start`."""
+ t = TriggerConfig(hotkey_dictate="", hotkey_dictate_toggle="")
+ assert t.hotkey_dictate == ""
+ assert t.hotkey_dictate_toggle == ""
+
+
+def test_an_existing_install_keeps_its_own_dictation_keys() -> None:
+ """The new defaults must never overwrite a value the user already chose."""
+ t = TriggerConfig(hotkey_dictate="ctrl+shift+d", hotkey_dictate_toggle="")
+ assert t.hotkey_dictate == "ctrl+shift+d"
+ assert t.hotkey_dictate_toggle == ""
+
+
def test_resolve_hotkeys_ignores_legacy_push_to_talk_values() -> None:
t = TriggerConfig(push_to_talk=True, hotkey="ctrl+right_alt+j", hotkey_call="f7+f8")
call, ptt = t.resolve_hotkeys()
diff --git a/tests/unit/dictation/test_delivery_and_bar.py b/tests/unit/dictation/test_delivery_and_bar.py
index 4be795f806..eabad13059 100644
--- a/tests/unit/dictation/test_delivery_and_bar.py
+++ b/tests/unit/dictation/test_delivery_and_bar.py
@@ -10,6 +10,9 @@ a voice session.
"""
from __future__ import annotations
+from pathlib import Path
+from types import SimpleNamespace
+
import pytest
from jarvis.core.config import DictationConfig
@@ -163,6 +166,240 @@ async def test_auto_target_is_resolved_at_DELIVERY_time(
assert events[-1].outcome == "chat"
+# --------------------------------------------------------------------------
+# The failure signal — "the provider refused us" vs "you said nothing"
+# --------------------------------------------------------------------------
+
+
+async def test_a_transcription_failure_is_reported_as_failed_not_empty() -> None:
+ """Before this, a provider 401 and plain silence produced the identical
+ ``empty`` outcome, so the one failure a user can actually fix was the one
+ the app never mentioned."""
+ pipe, events = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="", language="", duration_s=1.0, target="insert", hung_up=False,
+ stt_error="AuthenticationError: 401 invalid api key",
+ )
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "failed"
+ assert "401" in (completed.error or "")
+
+
+async def test_silence_without_an_error_is_still_empty() -> None:
+ pipe, events = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="", language="en", duration_s=0.2, target="insert", hung_up=False,
+ stt_error=None,
+ )
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "empty"
+ assert completed.error is None
+
+
+async def test_a_hangup_outranks_a_late_transcription_error() -> None:
+ """The user cancelled; telling them it "failed" would be a lie."""
+ pipe, events = _pipeline()
+ await pipe._finish_dictation(
+ raw_text="", language="", duration_s=0.4, target="insert", hung_up=True,
+ stt_error="TimeoutError: provider timed out",
+ )
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "cancelled"
+
+
+async def test_text_that_did_arrive_is_still_delivered_after_a_flaky_segment() -> None:
+ """One failed segment in an otherwise working dictation is not a failed
+ dictation — the words the user got must still reach their text field."""
+ inserted: list[str] = []
+ pipe, events = _pipeline()
+ pipe._insert_dictation = lambda text: inserted.append(text) or InsertResult( # type: ignore[assignment]
+ status="inserted", detail="", clipboard_holds_text=False,
+ method="clipboard+ctrl_v",
+ )
+ await pipe._finish_dictation(
+ raw_text="the part that came through", language="en", duration_s=2.0,
+ target="insert", hung_up=False, stt_error="TimeoutError: one segment",
+ )
+ assert inserted == ["the part that came through"]
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "inserted"
+
+
+# --------------------------------------------------------------------------
+# The pinned dictation language
+# --------------------------------------------------------------------------
+
+
+async def test_a_pinned_language_outranks_the_provider_guess() -> None:
+ """A provider that reports nothing (or the wrong thing) leaves the cleanup
+ with reason="no_rules" — no cleanup at all — despite an explicit pin."""
+ pipe, events = _pipeline(
+ DictationConfig(language="de", history_enabled=False)
+ )
+ text = await pipe._finish_dictation(
+ raw_text="Ähm, das ist äh wirklich gut.", # i18n-allow: fixture (§1 #4)
+ language="", # the provider could not tell
+ duration_s=3.0,
+ target="chat",
+ hung_up=False,
+ )
+ assert text == "Das ist wirklich gut." # i18n-allow: German fixture under test (§1 list #4)
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.language == "de"
+
+
+async def test_auto_leaves_the_detected_language_alone() -> None:
+ pipe, events = _pipeline(DictationConfig(history_enabled=False))
+ await pipe._finish_dictation(
+ raw_text="hello there", language="en", duration_s=1.0,
+ target="chat", hung_up=False,
+ )
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.language == "en"
+
+
+# --------------------------------------------------------------------------
+# The audio sidecar — written only when it buys back something lost
+# --------------------------------------------------------------------------
+
+
+class _FakeHistory:
+ """Stands in for DictationHistory without touching the user's data dir."""
+
+ instances: list = []
+
+ def __init__(self, *_a, **_k) -> None:
+ self.added: list[dict] = []
+ self.updated: list[tuple[str, dict]] = []
+ _FakeHistory.instances.append(self)
+
+ @property
+ def audio_dir(self):
+ from pathlib import Path
+
+ return Path("audio-dir-sentinel")
+
+ def add(self, **fields):
+ self.added.append(fields)
+ return SimpleNamespace(id="entry-1")
+
+ def update(self, entry_id: str, **fields):
+ self.updated.append((entry_id, fields))
+ return SimpleNamespace(id=entry_id)
+
+
+def audio_spy(monkeypatch: pytest.MonkeyPatch):
+ """Capture every audio-sidecar call without writing a byte to disk."""
+ import jarvis.dictation.audio as audio_mod
+ import jarvis.dictation.history as history_mod
+
+ saved: list[tuple[str, int]] = []
+ pruned: list[dict] = []
+ _FakeHistory.instances.clear()
+
+ monkeypatch.setattr(history_mod, "DictationHistory", _FakeHistory)
+ monkeypatch.setattr(
+ audio_mod,
+ "save_dictation_audio",
+ lambda entry_id, pcm, **kw: (
+ saved.append((entry_id, len(pcm))) or Path("saved.wav")
+ ),
+ )
+ monkeypatch.setattr(
+ audio_mod, "prune_audio", lambda **kw: pruned.append(kw) or 0
+ )
+ return SimpleNamespace(saved=saved, pruned=pruned)
+
+
+async def test_failed_audio_is_kept_and_linked_to_its_entry(audio_spy) -> None:
+ pipe, _events = _pipeline(DictationConfig(keep_failed_audio=True))
+ await pipe._finish_dictation(
+ raw_text="", language="en", duration_s=2.0, target="insert", hung_up=False,
+ stt_error="AuthenticationError: 401", audio=b"\x01\x02" * 100,
+ )
+ assert audio_spy.saved == [("entry-1", 200)]
+ history = _FakeHistory.instances[-1]
+ assert history.updated == [("entry-1", {"audio_path": "saved.wav"})]
+ # Retention runs after the write, never before it.
+ assert audio_spy.pruned and audio_spy.pruned[0]["max_files"] == 20
+
+
+async def test_a_successful_dictation_never_leaves_audio_behind(audio_spy) -> None:
+ """Audio is the most sensitive thing this app stores. It is written on
+ exactly one path: the user lost something AND allowed it."""
+ pipe, _events = _pipeline(DictationConfig(keep_failed_audio=True))
+ await pipe._finish_dictation(
+ raw_text="this one worked", language="en", duration_s=2.0,
+ target="chat", hung_up=False, audio=b"\x01\x02" * 100,
+ )
+ assert audio_spy.saved == []
+
+
+async def test_keep_failed_audio_off_writes_nothing(audio_spy) -> None:
+ pipe, _events = _pipeline(DictationConfig(keep_failed_audio=False))
+ await pipe._finish_dictation(
+ raw_text="", language="en", duration_s=2.0, target="insert", hung_up=False,
+ stt_error="AuthenticationError: 401", audio=b"\x01\x02" * 100,
+ )
+ assert audio_spy.saved == []
+ # The history row is still written — that is what Restore needs a handle on.
+ assert _FakeHistory.instances[-1].added
+
+
+async def test_a_wordless_failure_is_still_recorded(audio_spy) -> None:
+ """The old guard skipped the history whenever there was no raw text, which
+ is precisely when the worst failures happen."""
+ pipe, _events = _pipeline(DictationConfig())
+ await pipe._finish_dictation(
+ raw_text="", language="en", duration_s=2.0, target="insert", hung_up=False,
+ stt_error="RuntimeError: engine wedged",
+ )
+ added = _FakeHistory.instances[-1].added
+ assert added and added[0]["outcome"] == "failed"
+ assert added[0]["error"] == "RuntimeError: engine wedged"
+
+
+async def test_history_disabled_writes_nothing_at_all(audio_spy) -> None:
+ pipe, _events = _pipeline(DictationConfig(history_enabled=False))
+ await pipe._finish_dictation(
+ raw_text="", language="en", duration_s=2.0, target="insert", hung_up=False,
+ stt_error="RuntimeError: engine wedged", audio=b"\x01\x02" * 100,
+ )
+ assert _FakeHistory.instances == []
+ assert audio_spy.saved == []
+
+
+async def test_a_broken_history_write_never_costs_the_transcript(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import jarvis.dictation.history as history_mod
+
+ class _BoomHistory:
+ def __init__(self, *_a, **_k) -> None:
+ raise RuntimeError("disk on fire")
+
+ monkeypatch.setattr(history_mod, "DictationHistory", _BoomHistory)
+ pipe, _events = _pipeline(DictationConfig())
+ text = await pipe._finish_dictation(
+ raw_text="the words survive", language="en", duration_s=1.0,
+ target="chat", hung_up=False,
+ )
+ assert text == "the words survive"
+
+
@pytest.mark.asyncio
async def test_a_broken_cleanup_never_loses_the_text(
monkeypatch: pytest.MonkeyPatch,
@@ -179,6 +416,213 @@ async def test_a_broken_cleanup_never_loses_the_text(
assert text == "the raw words"
+# --------------------------------------------------------------------------
+# The recording session — the half above the delivery contract
+# --------------------------------------------------------------------------
+
+
+class _FakeChunk:
+ def __init__(self, pcm: bytes) -> None:
+ self.pcm = pcm
+
+
+class _FakeMic:
+ """Yields one chunk and ends, which is what closes the session."""
+
+ def __init__(self, pcm: bytes) -> None:
+ self._pcm = pcm
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *_exc) -> bool:
+ return False
+
+ async def stream(self):
+ yield _FakeChunk(self._pcm)
+
+
+def _session_pipeline(stt, cfg: DictationConfig):
+ """A pipeline wired for ``_dictation_session`` and nothing else."""
+ import asyncio
+
+ pipe = SpeechPipeline.__new__(SpeechPipeline)
+ pipe._utterance_stt = stt
+ pipe._dictation_cfg = cfg
+ pipe._dictation_target = "chat"
+ pipe._ptt_partial_interval_s = 0.0
+ pipe._dictation_max_s = 5.0
+ pipe._input_device = None
+ pipe._input_priority = None
+ pipe._dictation_stop_event = asyncio.Event()
+ pipe._hangup_event = asyncio.Event()
+ events: list[object] = []
+
+ async def _publish(event: object) -> None:
+ events.append(event)
+
+ pipe._publish_event = _publish # type: ignore[assignment]
+ return pipe, events
+
+
+async def test_the_pinned_language_reaches_the_provider(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ import jarvis.speech.pipeline as pipeline_mod
+
+ seen: list[dict] = []
+
+ class _STT:
+ async def transcribe_pcm(self, pcm: bytes, **kw):
+ seen.append(kw)
+ return SimpleNamespace(text="hola mundo", language="es")
+
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)
+ )
+ pipe, _events = _session_pipeline(
+ _STT(), DictationConfig(language="es", partial_interval_s=0.0)
+ )
+ await pipe._dictation_session()
+ assert seen == [{"language": "es"}]
+
+
+async def test_auto_sends_no_language_at_all(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ """``auto`` means "provider, you decide" — pinning it to a detected value
+ would defeat per-utterance detection."""
+ import jarvis.speech.pipeline as pipeline_mod
+
+ seen: list[dict] = []
+
+ class _STT:
+ async def transcribe_pcm(self, pcm: bytes, **kw):
+ seen.append(kw)
+ return SimpleNamespace(text="hello", language="en")
+
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)
+ )
+ pipe, _events = _session_pipeline(
+ _STT(), DictationConfig(language="auto", partial_interval_s=0.0)
+ )
+ await pipe._dictation_session()
+ assert seen == [{}]
+
+
+async def test_a_provider_without_the_language_keyword_still_transcribes(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ """The STT contract allows a bare ``transcribe_pcm(pcm)``. A pin must
+ degrade to "no pin", never to a failed dictation."""
+ import jarvis.speech.pipeline as pipeline_mod
+
+ class _LegacySTT:
+ def __init__(self) -> None:
+ self.calls = 0
+
+ async def transcribe_pcm(self, pcm: bytes):
+ self.calls += 1
+ return SimpleNamespace(text="it still works", language="en")
+
+ stt = _LegacySTT()
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)
+ )
+ pipe, events = _session_pipeline(
+ stt, DictationConfig(language="de", partial_interval_s=0.0)
+ )
+ await pipe._dictation_session()
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "chat"
+ assert completed.text == "it still works"
+ assert stt.calls == 1
+
+
+async def test_a_provider_error_ends_the_session_as_failed(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ import jarvis.speech.pipeline as pipeline_mod
+
+ class _BrokenSTT:
+ async def transcribe_pcm(self, pcm: bytes, **_kw):
+ raise RuntimeError("401 invalid api key")
+
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)
+ )
+ pipe, events = _session_pipeline(
+ _BrokenSTT(), DictationConfig(partial_interval_s=0.0)
+ )
+ await pipe._dictation_session()
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "failed"
+ assert "401" in (completed.error or "")
+
+
+async def test_a_crashed_session_is_recorded_instead_of_vanishing(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ """The old handler logged a warning and returned. The worst failure this
+ feature has must not also be its most invisible one."""
+ import jarvis.speech.pipeline as pipeline_mod
+
+ class _BoomMic:
+ async def __aenter__(self):
+ raise OSError("no input device")
+
+ async def __aexit__(self, *_exc) -> bool:
+ return False
+
+ monkeypatch.setattr(pipeline_mod, "MicrophoneCapture", lambda **_kw: _BoomMic())
+
+ class _STT:
+ async def transcribe_pcm(self, pcm: bytes, **_kw): # pragma: no cover
+ raise AssertionError("never reached")
+
+ pipe, events = _session_pipeline(_STT(), DictationConfig())
+ await pipe._dictation_session()
+ completed = next(e for e in events if isinstance(e, DictationCompleted))
+ assert completed.outcome == "failed"
+ assert "no input device" in (completed.error or "")
+ added = _FakeHistory.instances[-1].added
+ assert added and added[0]["outcome"] == "failed"
+
+
+async def test_a_crash_inside_delivery_does_not_double_publish(
+ monkeypatch: pytest.MonkeyPatch, audio_spy
+) -> None:
+ """Re-entering the delivery half would publish a second final transcript
+ and could recurse straight back into the same fault."""
+ import jarvis.speech.pipeline as pipeline_mod
+
+ calls: list[int] = []
+
+ class _STT:
+ async def transcribe_pcm(self, pcm: bytes, **_kw):
+ return SimpleNamespace(text="hello", language="en")
+
+ monkeypatch.setattr(
+ pipeline_mod, "MicrophoneCapture", lambda **_kw: _FakeMic(b"\x00\x01" * 16_000)
+ )
+ pipe, _events = _session_pipeline(_STT(), DictationConfig(partial_interval_s=0.0))
+
+ async def _boom(**_kw):
+ calls.append(1)
+ raise RuntimeError("delivery exploded")
+
+ pipe._finish_dictation = _boom # type: ignore[assignment]
+ await pipe._dictation_session()
+ assert calls == [1]
+
+
# --------------------------------------------------------------------------
# The Jarvis Bar
# --------------------------------------------------------------------------
diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.py
index 8f1f7e9af2..6cd5218558 100644
--- a/tests/unit/dictation/test_dictate_keybind.py
+++ b/tests/unit/dictation/test_dictate_keybind.py
@@ -28,9 +28,28 @@ def test_dictate_is_a_first_class_keybind_action() -> None:
assert hasattr(TriggerConfig(), "hotkey_dictate")
-def test_dictation_ships_unbound() -> None:
- """No combination is free on every machine — the user picks one."""
- assert TriggerConfig().hotkey_dictate == ""
+def test_hands_free_dictation_is_its_own_keybind_action() -> None:
+ """Not a mode flag: a user may arm a hold key AND a toggle key at once."""
+ assert "dictate_toggle" in KEYBIND_ACTIONS
+ assert KEYBIND_TOML_KEY["dictate_toggle"] == "hotkey_dictate_toggle"
+ assert hasattr(TriggerConfig(), "hotkey_dictate_toggle")
+
+
+def test_dictation_ships_bound_on_both_rows() -> None:
+ """Maintainer directive 2026-07-28. Shipping unbound made the headline
+ feature do nothing on a fresh install; these two combos are curated
+ instead (valid on all three platforms, mutually disjoint)."""
+ trig = TriggerConfig()
+ assert trig.hotkey_dictate == "ctrl+right_alt+j"
+ assert trig.hotkey_dictate_toggle == "ctrl+right_alt+space"
+
+
[email protected]("platform", ["win32", "darwin", "linux"])
+def test_the_shipped_dictation_combos_validate_everywhere(platform: str) -> None:
+ trig = TriggerConfig()
+ for combo in (trig.hotkey_dictate, trig.hotkey_dictate_toggle):
+ ok, reason = validate_hotkey(combo, platform=platform)
+ assert ok is True, f"{combo} on {platform}: {reason}"
# --------------------------------------------------------------------------
@@ -92,12 +111,15 @@ def test_existing_rules_are_unchanged(combo: str, expected: bool) -> None:
# --------------------------------------------------------------------------
-def _pipeline(*, dictate: list[str], mode: str = "hold") -> SpeechPipeline:
+def _pipeline(
+ *, dictate: list[str], mode: str = "hold", dictate_toggle: list[str] | None = None
+) -> SpeechPipeline:
pipe = SpeechPipeline.__new__(SpeechPipeline)
pipe._call_hotkeys = ["f3+f4"]
pipe._hangup_hotkeys = ["f1+f2"]
pipe._ptt_hotkeys = []
pipe._dictate_hotkeys = dictate
+ pipe._dictate_toggle_hotkeys = dictate_toggle or []
pipe._dictate_mode = mode
return pipe
@@ -119,12 +141,39 @@ def test_toggle_mode_fires_once_on_release() -> None:
def test_unbound_dictation_arms_nothing_but_leaves_voice_intact() -> None:
bindings, edges = _pipeline(dictate=[])._build_hotkey_bindings()
assert "dictate" not in bindings
+ assert "dictate_toggle" not in bindings
assert edges == set()
# The existing voice shortcuts must be untouched by this feature.
assert bindings["call"] == ["f3+f4"]
assert bindings["hangup"] == ["f1+f2"]
+def test_hands_free_fires_once_per_press() -> None:
+ """Never an edge binding — both edges would make a toggle behave like
+ push-to-talk (start on key-down, stop again on key-up)."""
+ bindings, edges = _pipeline(
+ dictate=[], dictate_toggle=["ctrl+right_alt+space"]
+ )._build_hotkey_bindings()
+ assert bindings["dictate_toggle"] == ["ctrl+right_alt+space"]
+ assert "dictate_toggle" not in edges
+
+
+def test_both_dictation_rows_can_be_armed_at_the_same_time() -> None:
+ bindings, edges = _pipeline(
+ dictate=["ctrl+right_alt+j"], dictate_toggle=["ctrl+right_alt+space"]
+ )._build_hotkey_bindings()
+ assert bindings["dictate"] == ["ctrl+right_alt+j"]
+ assert bindings["dictate_toggle"] == ["ctrl+right_alt+space"]
+ assert edges == {"dictate"}
+
+
+def test_an_unbound_hands_free_row_arms_nothing() -> None:
+ bindings, _edges = _pipeline(
+ dictate=["ctrl+right_alt+j"], dictate_toggle=[]
+ )._build_hotkey_bindings()
+ assert "dictate_toggle" not in bindings
+
+
# --------------------------------------------------------------------------
# Hotkey edges
# --------------------------------------------------------------------------
@@ -203,6 +252,48 @@ def test_toggle_starts_then_stops() -> None:
assert pipe.stopped == 1
+class _ScriptedTrigger:
+ """Replays a fixed list of hotkey event names, then ends the stream."""
+
+ def __init__(self, names: list[str]) -> None:
+ self._names = names
+
+ async def events(self):
+ for name in self._names:
+ yield name
+
+
+async def test_the_hands_free_event_reaches_the_toggle_handler() -> None:
+ """The binding is only half the wiring — without this dispatch arm the key
+ registers with the OS, fires, and nothing happens."""
+ pipe = _RecordingPipeline()
+ await pipe._hotkey_loop(_ScriptedTrigger(["dictate_toggle"]))
+ assert pipe.started == ["auto"]
+
+
+async def test_the_hands_free_key_stops_a_running_dictation() -> None:
+ pipe = _RecordingPipeline()
+
+ class _RunningTask:
+ def done(self) -> bool:
+ return False
+
+ pipe._dictation_task = _RunningTask() # type: ignore[assignment]
+ await pipe._hotkey_loop(_ScriptedTrigger(["dictate_toggle"]))
+ assert pipe.stopped == 1
+ assert pipe.started == []
+
+
+async def test_the_hold_key_edges_still_dispatch_unchanged() -> None:
+ pipe = _RecordingPipeline()
+ await pipe._hotkey_loop(_ScriptedTrigger(["dictate_press", "dictate_release"]))
+ assert pipe.started == ["auto"]
+ assert pipe.stopped == 1
+
+
# --------------------------------------------------------------------------
# start_dictation target
# --------------------------------------------------------------------------
diff --git a/tests/unit/speech/test_pipeline_keybind_reload.py b/tests/unit/speech/test_pipeline_keybind_reload.py
index d136b7189b..5dbca35ed4 100644
--- a/tests/unit/speech/test_pipeline_keybind_reload.py
+++ b/tests/unit/speech/test_pipeline_keybind_reload.py
@@ -99,3 +99,50 @@ async def test_reload_loop_omits_ptt_binding_when_unset():
bindings, ptt = trigger.calls[0]
assert "ptt" not in bindings
assert ptt == set()
+
+
+def test_set_keybinds_updates_the_hands_free_dictation_key():
+ """The kwarg is spelled like the action id, because the settings route
+ calls ``set_keybinds(**{action: [...]})`` — a rename there turns a
+ successful save into a silent no-op."""
+ pipe = _pipe()
+ pipe.set_keybinds(dictate_toggle=["ctrl+shift+d"])
+ assert pipe._dictate_toggle_hotkeys == ["ctrl+shift+d"]
+ assert pipe._dictate_hotkeys == [] # untouched
+ assert pipe._hotkey_reload_event.is_set()
+
+
+async def test_reload_loop_arms_hands_free_without_asking_for_both_edges():
+ """A toggle must fire once per press. Registering it as an edge binding
+ would start on key-down and stop again on key-up — push-to-talk by
+ accident."""
+ pipe = _pipe()
+ pipe._call_hotkeys = ["f3+f4"]
+ pipe._hangup_hotkeys = ["f1+f2"]
+ pipe._ptt_hotkeys = []
+ pipe._dictate_hotkeys = ["ctrl+right_alt+j"]
+ pipe._dictate_toggle_hotkeys = ["ctrl+right_alt+space"]
+ trigger = _FakeTrigger()
+ pipe._hotkey_reload_event.set()
+
+ await _run_reload_once(pipe, trigger)
+
+ bindings, edges = trigger.calls[0]
+ assert bindings["dictate"] == ["ctrl+right_alt+j"]
+ assert bindings["dictate_toggle"] == ["ctrl+right_alt+space"]
+ assert edges == {"dictate"}
+
+
+async def test_reload_loop_omits_hands_free_binding_when_cleared():
+ pipe = _pipe()
+ pipe._call_hotkeys = ["f3+f4"]
+ pipe._hangup_hotkeys = ["f1+f2"]
+ pipe._ptt_hotkeys = []
+ pipe._dictate_toggle_hotkeys = []
+ trigger = _FakeTrigger()
+ pipe._hotkey_reload_event.set()
+
+ await _run_reload_once(pipe, trigger)
+
+ bindings, _edges = trigger.calls[0]
+ assert "dictate_toggle" not in bindings
diff --git a/tests/unit/trigger/test_hotkey.py b/tests/unit/trigger/test_hotkey.py
index f9f39d86ca..a161c87991 100644
--- a/tests/unit/trigger/test_hotkey.py
+++ b/tests/unit/trigger/test_hotkey.py
@@ -145,6 +145,41 @@ def test_validate_hotkey_allows_ctrl_c_when_part_of_larger_combo():
assert ok
+@_pytest.mark.parametrize(
+ "combo",
+ ["super+d", "meta+d", "ctrl+super+space", "ctrl+meta+j", "shift+super+k"],
+)
+@_pytest.mark.parametrize("platform", ["win32", "darwin", "linux"])
+def test_validate_hotkey_rejects_the_super_and_meta_aliases(combo, platform):
+ """The hole this closes: ``super``/``meta`` are the SAME physical key as
+ ``win``, but they were checked by neither the Windows rule nor the Command
+ rule. A combo using them passed validation and then registered a binding no
+ backend could ever match — armed, and permanently dead."""
+ from jarvis.trigger.hotkey import validate_hotkey
+
+ ok, reason = validate_hotkey(combo, platform=platform)
+ assert not ok, f"{combo!r} should be rejected on {platform}"
+ assert "Super" in reason or "Windows" in reason
+
+
+def test_legacy_super_combos_still_normalize_to_a_real_key():
+ """A jarvis.toml written before the rule above must not arm a token no
+ backend understands: super/meta fold to the same key ``win`` does."""
+ from jarvis.trigger.hotkey import _normalize_combo
+
+ assert _normalize_combo("ctrl+super+space") == "control + window + space"
+ assert _normalize_combo("ctrl+meta+space") == "control + window + space"
+ assert _normalize_combo("ctrl+win+space") == "control + window + space"
+
+
+def test_command_chords_stay_valid_on_macos():
+ """Closing the Super hole must not take macOS Command with it."""
+ from jarvis.trigger.hotkey import validate_hotkey
+
+ ok, reason = validate_hotkey("cmd+d", platform="darwin")
+ assert ok, reason
+
+
# ----------------------------------------------------------------------
# Registration
# ----------------------------------------------------------------------
diff --git a/tests/unit/ui/test_keybinds_route.py b/tests/unit/ui/test_keybinds_route.py
index fe4d62d8ac..060b4eafed 100644
--- a/tests/unit/ui/test_keybinds_route.py
+++ b/tests/unit/ui/test_keybinds_route.py
@@ -1,4 +1,10 @@
-"""GET/PUT /api/settings/keybinds — editable Call/Hangup keybinds."""
+"""GET/PUT /api/settings/keybinds — the editable voice keybinds.
+
+The exact-dict assertions below are a deliberate tripwire, not an oversight: a
+keybind action that reaches ``KEYBIND_ACTIONS`` but not this route is the AP-4
+drift class (the UI renders a row whose value and default are both undefined).
+Extend them when an action is added; never relax them to a subset check.
+"""
from __future__ import annotations
from types import SimpleNamespace
@@ -6,6 +12,9 @@ from types import SimpleNamespace
from fastapi import FastAPI
from fastapi.testclient import TestClient
+from jarvis.core.config import TriggerConfig
+from jarvis.core.config_writer import KEYBIND_ACTIONS, KEYBIND_TOML_KEY
+from jarvis.trigger.hotkey import validate_hotkey
from jarvis.ui.web.settings_routes import router
@@ -23,25 +32,136 @@ def _client(**trig) -> TestClient:
return TestClient(app)
-def test_get_returns_call_and_hangup_plus_defaults() -> None:
+def test_get_returns_every_action_plus_defaults() -> None:
body = _client().get("/api/settings/keybinds").json()
+ # The namespace above carries no dictation fields, so both dictation values
+ # fall back to the TriggerConfig defaults — which is exactly the fresh
+ # install a downloader gets.
assert body["keybinds"] == {
"call": "f3+f4",
"hangup": "f1+f2",
- # Dictation ships UNBOUND on purpose: no combination is free on every
- # machine, so the user assigns one (TriggerConfig.hotkey_dictate).
- "dictate": "",
+ "dictate": "ctrl+right_alt+j",
+ "dictate_toggle": "ctrl+right_alt+space",
}
assert body["defaults"] == {
"call": "f3+f4",
"hangup": "f1+f2",
- "dictate": "",
+ "dictate": "ctrl+right_alt+j",
+ "dictate_toggle": "ctrl+right_alt+space",
}
assert "push_to_talk" not in body
assert body["restart_required"] is True
assert len(body["suggestions"]) >= 3
+def test_get_covers_exactly_the_registered_actions() -> None:
+ """No action may exist in the registry without a value AND a default."""
+ body = _client().get("/api/settings/keybinds").json()
+ assert set(body["keybinds"]) == set(KEYBIND_ACTIONS)
+ assert set(body["defaults"]) == set(KEYBIND_ACTIONS)
+
+
+def test_defaults_are_derived_from_the_config_model() -> None:
+ """A hardcoded defaults dict is the AP-4 trap this route used to carry."""
+ body = _client().get("/api/settings/keybinds").json()
+ model = TriggerConfig()
+ assert body["defaults"] == {
+ action: getattr(model, field) for action, field in KEYBIND_TOML_KEY.items()
+ }
+
+
+def test_shipped_defaults_are_valid_on_every_supported_platform() -> None:
+ """A default that fails validation is a shortcut nobody can re-save."""
+ model = TriggerConfig()
+ for field in KEYBIND_TOML_KEY.values():
+ combo = getattr(model, field)
+ if not combo:
+ continue
+ for platform in ("win32", "darwin", "linux"):
+ ok, reason = validate_hotkey(combo, platform=platform)
+ assert ok is True, f"{field}={combo} rejected on {platform}: {reason}"
+
+
+def test_shipped_defaults_do_not_collide_with_each_other() -> None:
+ """The polling backend matches subsets, so any subset/superset pair fires
+ two actions at once. All four shipped combos must be mutually disjoint."""
+ model = TriggerConfig()
+ sets = {
+ action: {p for p in getattr(model, field).split("+") if p}
+ for action, field in KEYBIND_TOML_KEY.items()
+ if getattr(model, field)
+ }
+ for left, left_keys in sets.items():
+ for right, right_keys in sets.items():
+ if left >= right:
+ continue
+ assert not (left_keys <= right_keys or right_keys <= left_keys), (
+ f"{left} and {right} overlap"
+ )
+
+
+def test_suggestions_exclude_combos_that_would_be_rejected() -> None:
+ """A quick-pick that collides with a bound action is a guaranteed 400."""
+ body = _client().get("/api/settings/keybinds").json()
+ bound = [
+ {p for p in combo.split("+") if p}
+ for combo in body["keybinds"].values()
+ if combo
+ ]
+ for suggestion in body["suggestions"]:
+ keys = {p for p in suggestion.split("+") if p}
+ assert not any(keys <= other or other <= keys for other in bound), suggestion
+
+
+def test_suggestions_are_valid_on_every_supported_platform() -> None:
+ from jarvis.ui.web.settings_routes import _KEYBIND_SUGGESTIONS
+
+ assert len(_KEYBIND_SUGGESTIONS) >= 6
+ for suggestion in _KEYBIND_SUGGESTIONS:
+ for platform in ("win32", "darwin", "linux"):
+ ok, reason = validate_hotkey(suggestion, platform=platform)
+ assert ok is True, f"{suggestion} rejected on {platform}: {reason}"
+
+
+def test_put_dictate_toggle_is_accepted() -> None:
+ body = _client().put(
+ "/api/settings/keybinds",
+ json={"action": "dictate_toggle", "hotkey": "CTRL+SHIFT+D", "persist": False},
+ ).json()
+ assert body["ok"] is True
+ assert body["action"] == "dictate_toggle"
+ assert body["hotkey"] == "ctrl+shift+d"
+
+
+def test_put_dictate_toggle_live_applies_under_its_action_name() -> None:
+ """The pipeline kwarg must be spelled exactly like the action, or a
+ successful save silently re-arms nothing."""
+ calls: list[dict] = []
+
+ class _FakePipeline:
+ def set_keybinds(self, **kw): # noqa: ANN003
+ calls.append(kw)
+
+ client = _client()
+ client.app.state.speech_pipeline = _FakePipeline()
+ resp = client.put(
+ "/api/settings/keybinds",
+ json={"action": "dictate_toggle", "hotkey": "ctrl+shift+d", "persist": False},
+ )
+ assert resp.json()["applied_live"] is True
+ assert calls == [{"dictate_toggle": ["ctrl+shift+d"]}]
+
+
+def test_put_rejects_a_dictation_combo_that_collides_with_the_other_one() -> None:
+ """Both dictation rows are bound by default, so they must guard each other."""
+ resp = _client().put(
+ "/api/settings/keybinds",
+ json={"action": "dictate", "hotkey": "ctrl+right_alt+space", "persist": False},
+ )
+ assert resp.status_code == 400
+ assert "dictate_toggle" in resp.json()["detail"]
+
+
def test_retired_ptt_hotkey_route_is_not_mounted() -> None:
assert _client().get("/api/settings/ptt-hotkey").status_code == 404