Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(dictation): hold a key, speak, the text lands where you type
Ruben Lütke88d927ffcd14
diff --git a/docs/commands-reference.md b/docs/commands-reference.mdindex 47da720ee9..d97bb0410a 100644--- a/docs/commands-reference.md+++ b/docs/commands-reference.md@@ -181,6 +181,26 @@ Return the effective live Brain tool surface, including native, connected CLI, M- **Desktop UI section:** `settings`- **Voice example (EN):** "list the connected tools mcps and clis"+## `dictation-start` — Start dictation++Start dictation: speak, and the transcribed text is inserted into whatever text field currently has focus. Stops with dictation-stop or the dictation shortcut.++- **Endpoint:** `POST /api/dictation/start`+- **Arguments:** `target` (one of: insert, chat; optional)+- **Requires confirmation:** no+- **Desktop UI section:** `dictation`+- **Voice example (EN):** "start dictation"++## `dictation-stop` — Stop dictation++Finish the running dictation and deliver the text.++- **Endpoint:** `POST /api/dictation/stop`+- **Arguments:** none+- **Requires confirmation:** no+- **Desktop UI section:** `dictation`+- **Voice example (EN):** "stop dictation"+## `app-restart` — Restart JarvisRestart the Jarvis desktop app (voice + UI restart too).@@ -263,7 +283,7 @@ Read what the coding agent in a named terminal is doing — its status and its r## `agentic-ide-prompt` — Prompt an Agentic-IDE terminal-Send an instruction to the coding agent in ONE named terminal. Use this whenever the user tells a terminal to do something ('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') — that work belongs to that agent, never to a background worker. For SEVERAL terminals ('Kai and Mika both ...', 'let the two of them ...') call 'agentic-ide-fanout' instead, with every call-sign in 'terminals': it briefs them at once and reports which ones really got the work. Calling this command twice for a pair leaves the second agent idle whenever the second call is forgotten, which is the failure mode fanout exists to remove. Pass the instruction in the USER's words: everything they asked for, every constraint and file they named, nothing invented and nothing summarised away. Do NOT write the brief yourself — a prompt writer that has read this repository turns what you pass into a briefed task with the relevant files attached, and a headline you composed instead arrives at the agent as its whole assignment. Only ever names a terminal that is ALREADY running: if the call fails with 'no terminal called …', opening a pane will not create that name — use 'agentic-ide-fanout' with spawn to open and brief one in a single step, and never repeat the spawn. CHECK THE REPLY: it carries a 'submitted' flag. True means the agent accepted the prompt and started. False means the text is only sitting in that terminal's input box — say so plainly and name the terminal, never report it as done.+Send an instruction to the coding agent in ONE terminal. Terminals are called T plus their place in the grid (T1, T2, T3, left to right). Use this whenever the user tells a terminal to do something ('tell T1 to ...', 'T2 soll ...', 'let terminal three refactor ...', 'prompt the second terminal') — that work belongs to that agent, never to a background worker. For SEVERAL terminals ('T1 and T2 both ...', 'let the two of them ...') call 'agentic-ide-fanout' instead, with every call-sign in 'terminals': it briefs them at once and reports which ones really got the work. Calling this command twice for a pair leaves the second agent idle whenever the second call is forgotten, which is the failure mode fanout exists to remove. Pass the instruction in the USER's words: everything they asked for, every constraint and file they named, nothing invented and nothing summarised away. Do NOT write the brief yourself — a prompt writer that has read this repository turns what you pass into a briefed task with the relevant files attached, and a headline you composed instead arrives at the agent as its whole assignment. Only ever names a terminal that is ALREADY running: if the call fails with 'no terminal called …', opening a pane will not create that name — use 'agentic-ide-fanout' with spawn to open and brief one in a single step, and never repeat the spawn. CHECK THE REPLY: it carries a 'submitted' flag. True means the agent accepted the prompt and started. False means the text is only sitting in that terminal's input box — say so plainly and name the terminal, never report it as done.- **Endpoint:** `POST /api/agentic-ide/terminals/{name}/prompt`- **Arguments:** `name` (string; required); `prompt` (string; required); `compose` (boolean; optional)@@ -273,7 +293,7 @@ Send an instruction to the coding agent in ONE named terminal. Use this whenever## `agentic-ide-fanout` — Open and brief Agentic-IDE terminals in one step-Give ONE task to coding terminals — existing ones, brand-new ones, or both — in a single call. This is the ONLY correct way to handle 'if no terminal is called that, open one and prompt it' and 'spawn N terminals and let them do X': pass the work as 'instruction', the panes to brief as 'terminals', and the panes to open first as 'spawn'. Never emulate it by opening panes and then prompting — call-signs are assigned automatically, so a pane you open is NOT called the name you had in mind, and re-spawning after a failed prompt just leaves blank panes behind. Set 'split' true only when the user asked for the work to be DIVIDED between the agents. CHECK THE REPLY: 'delivered' names the agents that really got the task and 'undelivered' those that did not — report both, and use the call-signs the reply gives you.+Give ONE task to coding terminals — existing ones, brand-new ones, or both — in a single call. This is the ONLY correct way to handle 'if no terminal is called that, open one and prompt it' and 'spawn N terminals and let them do X': pass the work as 'instruction', the panes to brief as 'terminals', and the panes to open first as 'spawn'. Never emulate it by opening panes and then prompting — call-signs are the panes' positions (T1, T2, …) and are assigned by the workspace, so a pane you open is NOT called the name you had in mind, and re-spawning after a failed prompt just leaves blank panes behind. Set 'split' true only when the user asked for the work to be DIVIDED between the agents. CHECK THE REPLY: 'delivered' names the agents that really got the task and 'undelivered' those that did not — report both, and use the call-signs the reply gives you.- **Endpoint:** `POST /api/agentic-ide/fanout`- **Arguments:** `instruction` (string; required); `terminals` (array; optional); `spawn` (array; optional); `split` (boolean; optional)@@ -283,7 +303,7 @@ Give ONE task to coding terminals — existing ones, brand-new ones, or both —## `agentic-ide-spawn-terminals` — Open more Agentic-IDE terminals-Open one or more additional coding terminals in the open workspace, WITHOUT giving them work. Use this only when the user asks for bare panes ('spawn five new Claude Code terminals', 'open two more Codex terminals') — that is a request for workspace panes, never for a background worker. When the new panes are also meant to DO something, use 'agentic-ide-fanout' instead, which opens and briefs them in one step. Pass count, and agent only when the user named one — the accepted ids are listed on the parameter itself, and it is the only list that is right for this install. Omitted, the new panes run whatever the last pane runs. Their call-signs are assigned automatically — the reply's names are the only way to address them, and calling this again never produces a name you picked. CHECK THE REPLY: 'capped' true means the workspace maximum cut the request short — say how many actually opened and name them, never report the full number as done.+Open one or more additional coding terminals in the open workspace, WITHOUT giving them work. Use this only when the user asks for bare panes ('spawn five new Claude Code terminals', 'open two more Codex terminals') — that is a request for workspace panes, never for a background worker. When the new panes are also meant to DO something, use 'agentic-ide-fanout' instead, which opens and briefs them in one step. Pass count, and agent only when the user named one — the accepted ids are listed on the parameter itself, and it is the only list that is right for this install. Omitted, the new panes run whatever the last pane runs. Their call-signs are their positions in the grid (T1, T2, …), assigned by the workspace — the reply's names are the only way to address them, and calling this again never produces a name you picked. CHECK THE REPLY: 'capped' true means the workspace maximum cut the request short — say how many actually opened and name them, never report the full number as done.- **Endpoint:** `POST /api/agentic-ide/terminals/batch`- **Arguments:** `count` (integer; required); `agent` (one of: claude, codex, glm, kimi, opencode; optional)diff --git a/docs/os-parity.md b/docs/os-parity.mdindex 30b60ae43a..f07848b8ee 100644--- a/docs/os-parity.md+++ b/docs/os-parity.md@@ -48,6 +48,8 @@ experiences today.| # | Impact | Area | Gap | Evidence | Behavior off-Windows ||---|---|---|---|---|---|+| P-24 | Medium | Dictation shortcut | The global dictation/call shortcut needs `pynput` on Linux/X11, and `pynput` hard-requires `evdev` — which is published **source-only** (verified on PyPI 2026-07-28: evdev 1.9.3 ships an sdist and no wheels) and compiles against the kernel headers. Putting it in `[full]` would break the one advertised install path on a stock `python:3.11-slim`, so it is the opt-in `[desktop-linux]` extra instead. Wayland is a separate, unfixable-by-install case: the compositor owns global shortcuts by design (the XDG `GlobalShortcuts` portal lets the *compositor* assign the keys, and no wlroots compositor implements it at all) | `pyproject.toml` (`desktop-linux`), `jarvis/platform/probes.py::has_hotkey`, `jarvis/trigger/backends/noop.py::explain_unavailable` | X11 without the extra: no global shortcut, and the log/UI now names the actual cause and the exact `pip install` that fixes it (it used to blame Wayland unconditionally). Wayland: no global shortcut at all — bind a compositor shortcut to `jarvis api dictation start`. On both, dictation still works from the Jarvis Bar, the Dictation view and the CLI, and voice still works via the wake word |+| P-25 | Medium | Dictation insertion | Pasting the transcript into another application is blocked, silently, in three OS-specific situations: Windows UIPI when the foreground window is elevated and Jarvis is not (`SendInput` reports success and the input is discarded), macOS Secure Input while a password field is focused, and Wayland outright (no synthetic input). Detection exists for the first two; Wayland is refused up front | `jarvis/dictation/insert.py::describe_target`, `jarvis/platform/input_isolation.py::windows_foreground_window_is_elevated`, `macos_secure_input_enabled` | All three degrade to the SAME honest outcome instead of silence: the transcript is left on the clipboard, the result is reported as `clipboard_only`, and the bar plus the Dictation view say why and that Ctrl+V will paste it. macOS Secure Input detection is implemented but has not been verified on real hardware from this machine || P-02 | Low | Awareness | Idle detection has no Wayland backend (Windows GetLastInputInfo, macOS Quartz, Linux X11 `xprintidle` all exist since 2026-07-16); Wayland exposes no global idle time without portal support | `jarvis/awareness/watchers/idle.py` | Wayland: one honest log line, watcher does not start || P-03 | Low | Awareness | Window-focus watcher has no Wayland backend (Windows event hook, macOS NSWorkspace, Linux X11 polling all exist since 2026-07-16); Wayland hides the foreground window by design | `jarvis/awareness/watchers/window.py` | Wayland: one honest log line, watcher does not start || P-04 | Medium | CU typing | Linux desktop Unicode text input needs the system `xdotool` binary (pip cannot install it); the pyautogui fallback used on Linux drops non-ASCII chars (umlauts, CJK, emoji) without it | `jarvis/cu/actuate/posix.py::type_text`, `jarvis/plugins/tool/type_text.py` | With `xdotool` (installer provisions it since 2026-07-15): fine. Without, the drop is now reported HONESTLY (2026-07-23): an all-non-ASCII text fails with an actionable "install xdotool" error, and a mixed text types its ASCII portion and warns that the rest was dropped — no more silent success |diff --git a/docs/research/dictation-feature-matrix.md b/docs/research/dictation-feature-matrix.mdindex 549bbd5324..d615dd2096 100644--- a/docs/research/dictation-feature-matrix.md+++ b/docs/research/dictation-feature-matrix.md@@ -1,7 +1,15 @@# Dictation Feature Matrix — established tools vs. our current state-**Date:** 2026-07-28 · **Status:** research only, no code changed ·-**Companion:** [`docs/plans/dictation-mode-plan.md`](../plans/dictation-mode-plan.md)+**Date:** 2026-07-28 · **Status:** research snapshot taken BEFORE the feature+was built — the "our state" column is the starting point, not today's state.++> **Dictation mode shipped the same day.** The rows below marked *partial* or+> *missing* were the work list; they are now implemented (`jarvis/dictation/`,+> the `dictate` keybind, `/api/dictation/*`, the Dictation view, the bar's+> `dictate` mode). This document is kept as-is because it is the evidence the+> design rests on — what the established tools actually do, and where our own+> gaps were. For what was built and why, read the module docstrings under+> `jarvis/dictation/`.A "dictation mode" (hold a key, speak, release, the text lands in whatever textfield currently has focus) is not a new subsystem for Personal Jarvis. It is adiff --git a/jarvis/commands/registry.py b/jarvis/commands/registry.pyindex 25da8ebc46..b0ecac7a70 100644--- a/jarvis/commands/registry.py+++ b/jarvis/commands/registry.py@@ -505,6 +505,50 @@ def _build_registry() -> tuple[AppCommand, ...]:"es": ("lista las herramientas mcps y clis conectadas",), # i18n-allow: input vocab},),+ # -------------------------------------------------------- dictation+ AppCommand(+ id="dictation-start",+ title="Start dictation",+ description=(+ "Start dictation: speak, and the transcribed text is inserted "+ "into whatever text field currently has focus. Stops with "+ "dictation-stop or the dictation shortcut."+ ),+ method="POST",+ path="/api/dictation/start",+ params={+ "type": "object",+ "properties": {+ "target": {+ "type": "string",+ "enum": ["insert", "chat"],+ "description": (+ "insert = paste into the app in front; "+ "chat = fill the chat input only"+ ),+ }+ },+ },+ ui_section="dictation",+ voice_aliases={+ "de": ("starte das diktat", "diktier-modus an"), # i18n-allow: input vocab+ "en": ("start dictation", "turn on dictation mode"),+ "es": ("inicia el dictado", "activa el modo dictado"), # i18n-allow: input vocab+ },+ ),+ AppCommand(+ id="dictation-stop",+ title="Stop dictation",+ description="Finish the running dictation and deliver the text.",+ method="POST",+ path="/api/dictation/stop",+ ui_section="dictation",+ voice_aliases={+ "de": ("stopp das diktat", "diktier-modus aus"), # i18n-allow: input vocab+ "en": ("stop dictation", "turn off dictation mode"),+ "es": ("detén el dictado", "desactiva el modo dictado"), # i18n-allow: input vocab+ },+ ),# ----------------------------------------------------------- systemAppCommand(id="app-restart",@@ -693,11 +737,14 @@ def _build_registry() -> tuple[AppCommand, ...]:id="agentic-ide-prompt",title="Prompt an Agentic-IDE terminal",description=(- "Send an instruction to the coding agent in ONE named terminal. "- "Use this whenever the user tells a terminal to do something "- "('tell Kai to ...', 'Mika soll ...', 'let Nova refactor ...') " # i18n-allow: quoted addressing examples the router must match+ "Send an instruction to the coding agent in ONE terminal. "+ "Terminals are called T plus their place in the grid (T1, T2, "+ "T3, left to right). Use this whenever the user tells a "+ "terminal to do something "+ "('tell T1 to ...', 'T2 soll ...', 'let terminal three " # i18n-allow: quoted addressing examples the router must match+ "refactor ...', 'prompt the second terminal') ""— that work belongs to that agent, never to a background "- "worker. For SEVERAL terminals ('Kai and Mika both ...', 'let "+ "worker. For SEVERAL terminals ('T1 and T2 both ...', 'let ""the two of them ...') call 'agentic-ide-fanout' instead, with ""every call-sign in 'terminals': it briefs them at once and ""reports which ones really got the work. Calling this command "@@ -767,7 +814,8 @@ def _build_registry() -> tuple[AppCommand, ...]:"it' and 'spawn N terminals and let them do X': pass the work as ""'instruction', the panes to brief as 'terminals', and the panes ""to open first as 'spawn'. Never emulate it by opening panes and "- "then prompting — call-signs are assigned automatically, so a "+ "then prompting — call-signs are the panes' positions (T1, T2, "+ "…) and are assigned by the workspace, so a ""pane you open is NOT called the name you had in mind, and ""re-spawning after a failed prompt just leaves blank panes ""behind. Set 'split' true only when the user asked for the work "@@ -854,7 +902,8 @@ def _build_registry() -> tuple[AppCommand, ...]:"the accepted ids are listed on the parameter itself, and it is ""the only list that is right for this install. Omitted, the new ""panes run whatever the "- "last pane runs. Their call-signs are assigned automatically — "+ "last pane runs. Their call-signs are their positions in the "+ "grid (T1, T2, …), assigned by the workspace — ""the reply's names are the only way to address them, and calling ""this again never produces a name you picked. ""CHECK THE REPLY: 'capped' true means the workspace maximum cut "diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.pyindex 4b8c3e5b8a..1cb10a0a6f 100644--- a/jarvis/core/config_writer.py+++ b/jarvis/core/config_writer.py@@ -570,10 +570,17 @@ 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")+KEYBIND_ACTIONS = ("call", "hangup", "dictate")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).+ "dictate": "hotkey_dictate",}@@ -594,6 +601,47 @@ def set_keybind(action: str, hotkey: str, *, path: Path = DEFAULT_CONFIG_FILE) -_patch_table(path, "trigger", key, hotkey)+#: Dictation settings that may be changed through the API. The value is both+#: the ``[dictation]`` TOML key and the ``DictationConfig`` field name; keep in+#: sync with the model and with the TS type in the frontend's dictation hook.+DICTATION_SETTING_KEYS = (+ "mode",+ "target",+ "insert_method",+ "paste_chord",+ "paste_delay_ms",+ "paste_delay_after_ms",+ "restore_clipboard",+ "remove_fillers",+ "filler_max_removed_fraction",+ "max_seconds",+ "partial_interval_s",+ "segment_seconds",+ "history_enabled",+ "history_max_entries",+ "history_retention_days",+)+++def set_dictation_setting(+ key: str,+ value: str | bool | int | float,+ *,+ path: Path = DEFAULT_CONFIG_FILE,+) -> None:+ """Persist one ``[dictation]`` key in jarvis.toml.++ Toml-only, like the other ``[trigger]``/``[dictation]`` writers: these keys+ are not part of the drift-guard's reference snapshot, so a plain atomic+ write is enough and the BUG-010 three-layer rule does not apply. The+ caller validates the value against ``DictationConfig`` first — this writer+ only refuses unknown KEYS, so a typo can never invent a config field.+ """+ if key not in DICTATION_SETTING_KEYS:+ raise ValueError(f"unknown dictation setting: {key!r}")+ _patch_table(path, "dictation", key, value)++def set_reply_language(name: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:"""Persist the user-facing reply-language pin in ``[brain] reply_language``.@@ -1622,14 +1670,17 @@ def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONF_atomic_write(path, out)-def _patch_table(path: Path, table: str, key: str, value: str | bool | list[str]) -> None:+def _patch_table(+ path: Path, table: str, key: str, value: str | bool | int | float | list[str]+) -> None:"""Set ``[table] key = value`` in the TOML file.Creates the table if it is absent. Preserves comments and formatting viatomlkit, including the optional BOM (see module docstring). ``value`` may bea ``str``, a ``bool`` (serialised as ``true``/``false`` — used by the- autostart toggle), or a ``list[str]`` (serialised as a TOML array — used by- ``[team_proxy] local_providers``).+ autostart toggle), an ``int``/``float`` (the dictation delays and caps), or+ a ``list[str]`` (serialised as a TOML array — used by ``[team_proxy]+ local_providers``)."""path = _ensure_writable_config_path(path)diff --git a/jarvis/core/events.py b/jarvis/core/events.pyindex 41d6de0eb7..a02892f8b8 100644--- a/jarvis/core/events.py+++ b/jarvis/core/events.py@@ -124,6 +124,33 @@ class DictationTranscript(Event):is_final: bool = False+@dataclass(frozen=True, slots=True)+class DictationCompleted(Event):+ """A dictation finished — what was produced and where it ended up.++ Separate from ``DictationTranscript`` (which is the live text feed) because+ this carries the OUTCOME, and the outcome is the part the user must not be+ left guessing about: ``inserted`` means it is in their text field,+ ``clipboard_only`` means the OS blocked the paste and the text is one+ Ctrl+V away, ``unavailable`` means neither worked. The UI and the Jarvis Bar+ both surface ``detail`` verbatim, so it is a complete, user-facing sentence.+ """++ #: What was inserted (after cleanup).+ text: str = ""+ #: The transcript exactly as the STT returned it, before cleanup.+ raw_text: str = ""+ #: ``inserted`` | ``clipboard_only`` | ``unavailable`` | ``chat`` | ``empty``.+ outcome: str = ""+ #: User-facing explanation; empty when nothing needs explaining.+ detail: str = ""+ #: e.g. ``clipboard+ctrl_v`` / ``type`` — empty when nothing was inserted.+ method: str = ""+ language: str = ""+ duration_s: float = 0.0+ removed_words: int = 0++# ----------------------------------------------------------------------# Intent & Routing# ----------------------------------------------------------------------diff --git a/jarvis/dictation/__init__.py b/jarvis/dictation/__init__.pynew file mode 100644index 0000000000..60da902db6--- /dev/null+++ b/jarvis/dictation/__init__.py@@ -0,0 +1,24 @@+"""Dictation mode — speak into whatever text field currently has focus.++Three small, independently testable pieces:++* :mod:`jarvis.dictation.cleanup` — deterministic, per-language filler-sound+ removal. Regex only; no model call ever happens in here.+* :mod:`jarvis.dictation.insert` — put text into the focused field of the+ foreground application: clipboard first, paste chord, restore. Reports+ honestly instead of failing silently.+* :mod:`jarvis.dictation.history` — the local record of what was dictated+ (raw and cleaned), so a cleanup can always be audited after the fact.++The capture itself is NOT here: it reuses the dictation lane that already lives+in :mod:`jarvis.speech.pipeline` (``start_dictation`` / ``_dictation_session``),+which in turn reuses the microphone and the configured STT provider. Nothing in+this package imports the speech pipeline — the dependency runs one way only.++Import-cleanliness: nothing here imports a platform-only package at module+scope, so ``import jarvis.dictation`` stays clean on a headless server.+"""++from __future__ import annotations++__all__ = ["cleanup", "history", "insert"]diff --git a/jarvis/dictation/cleanup.py b/jarvis/dictation/cleanup.pynew file mode 100644index 0000000000..69de4c7c7f--- /dev/null+++ b/jarvis/dictation/cleanup.py@@ -0,0 +1,278 @@+"""Deterministic filler-sound removal for dictated text.++Why deterministic and not a model pass+--------------------------------------+A dictation feature's whole promise is "these are my words". A second model+pass can rewrite, shorten and "improve" — and when it does, the user has no way+to tell. Rules can also be wrong, but they are wrong in a way you can read,+predict and correct. So the default path is regex only: **no LLM call ever+happens in this module** (same discipline as ``scrub_for_voice``, AP-11).++Three guards keep content words safe+------------------------------------+1. **Whole-word matches from a curated list, nothing else.** No stemming, no+ fuzzy matching, no "drop short words". A sound is removed only because it is+ explicitly listed as a filler for that language.+2. **A destruction ceiling.** If the rules would drop more than+ ``max_removed_fraction`` of the words, the RAW text is returned untouched.+ A cleanup that eats a quarter of a sentence is a bug, not a cleanup.+3. **An unknown language is a no-op.** Applying English rules to Spanish speech+ is how "esto" becomes a filler. No rules for the detected language means the+ text is passed through unchanged.++The lists are deliberately SHORT. Only unambiguous hesitation sounds qualify.+Words that carry meaning in ordinary speech are excluded on purpose even when+every style guide calls them filler — English "like", "actually", "basically";+German "also", "halt", "eben"; Spanish "este", "pues". Removing those changes+what was said.+"""++from __future__ import annotations++import re+from dataclasses import dataclass++# i18n-allow: the tables below are speech-recognition vocabulary — the literal+# German/Spanish tokens a matcher must contain to recognise a German or Spanish+# hesitation sound. Matching data, not prose (CLAUDE.md §1, category 3).++#: Hesitation sounds per language. Keys are lowercase two-letter codes.+#: Multi-word entries are matched as a phrase.+FILLER_WORDS: dict[str, tuple[str, ...]] = {+ "en": (+ "uh", "uhh", "uhhh", "um", "umm", "ummm",+ "er", "erm", "ah", "ahh", "eh",+ "hm", "hmm", "hmmm", "mhm", "mm", "mmm",+ ),+ "de": ( # i18n-allow: speech-recognition input vocabulary (§1 list #3)+ "äh", "ähh", "ähhh", "ähm", "ähem", "hä", # i18n-allow: input vocab+ "öh", "öhm", "em", # i18n-allow: input vocab+ "hm", "hmm", "hmmm", "mhm", "mmh", "mm",+ ),+ "es": (+ "eh", "ehh", "ehhh", "em", "emm",+ "mm", "mmm", "ajá", "aja",+ ),+}++#: Languages we have curated rules for. Anything else is a documented no-op.+SUPPORTED_LANGUAGES: frozenset[str] = frozenset(FILLER_WORDS)++# STT providers do NOT agree on how they name a language. faster-whisper returns+# an ISO code ("de"), while a Whisper cloud endpoint returns the English NAME+# ("German" / "english") — a live dictation on 2026-07-28 came back as+# ``language="English"``, which meant every cleanup silently resolved to+# "no rules for this language" and never ran. Accepting both spellings is what+# makes the feature work with whichever provider the user happens to have+# (AP-21: gate on capability, never on a provider's conventions).+_LANGUAGE_NAME_TO_CODE: dict[str, str] = {+ "english": "en",+ "german": "de",+ "deutsch": "de",+ "spanish": "es",+ "castilian": "es",+ "español": "es",+ "espanol": "es",+}++# The ceiling exists to catch BROKEN RULES (a content word that slipped into a+# filler list would eat half a sentence), not to punish someone who hesitates a+# lot. A percentage alone cannot do that job at both ends: one filler in a+# three-word sentence is already 33 %, while 25 % of a 100-word dictation would+# be twenty-five hesitation sounds — far past "broken". So the test is staged.+#+#: Under this word count no proportional test runs at all; the "nothing+#: survived" check is the only guard ("Ähm ja" -> "ja" must work). # i18n-allow: quoted input+_SHORT_TEXT_WORDS = 4+#: Up to this word count an ABSOLUTE cap applies instead of a proportion.+_ABSOLUTE_CAP_WORDS = 12+#: The absolute cap itself. Three hesitation sounds in a short sentence is+#: plausible speech; a fourth means the rules are matching something else.+_ABSOLUTE_MAX_REMOVED = 3++_WORD_RE = re.compile(r"\w+", re.UNICODE)+# A filler is only ever removed as a WHOLE word. \b does not behave for tokens+# containing non-ASCII letters on some patterns, so the boundaries are spelled+# out as "not preceded/followed by a word character".+_BOUNDARY_PREFIX = r"(?<![^\W\d_])"+_BOUNDARY_SUFFIX = r"(?![^\W\d_])"+++@dataclass(frozen=True, slots=True)+class CleanupResult:+ """Outcome of one cleanup pass.++ ``text`` is what should be inserted; ``raw`` is always the untouched+ transcript, so the caller can store both and show what changed.+ """++ text: str+ raw: str+ removed_words: int+ total_words: int+ applied: bool+ #: "" when applied, otherwise why it was not: ``disabled`` | ``no_rules``+ #: | ``ceiling`` | ``empty``.+ reason: str = ""++ @property+ def changed(self) -> bool:+ return self.applied and self.text != self.raw+++def normalize_language(language: str | None) -> str | None:+ """``"de-DE"`` / ``"DE"`` / ``"German"`` -> ``"de"``; unknown -> ``None``.++ Accepts BOTH spellings providers use — an ISO code and the English language+ name — because they genuinely differ per provider (see+ ``_LANGUAGE_NAME_TO_CODE``). ``auto`` and ``unknown`` (what the providers+ return when they could not tell) map to ``None`` on purpose: guessing here+ would apply one language's filler list to another's speech.+ """+ if not language:+ return None+ value = str(language).strip().lower().replace("_", "-")+ if not value or value in ("auto", "unknown", "und"):+ return None+ named = _LANGUAGE_NAME_TO_CODE.get(value)+ if named is not None:+ return named+ code = value.split("-", 1)[0]+ return code if code in SUPPORTED_LANGUAGES else None+++def _count_words(text: str) -> int:+ return len(_WORD_RE.findall(text))+++def _compile_patterns(language: str) -> list[re.Pattern[str]]:+ """Whole-word patterns for one language, longest phrase first.++ Longest-first matters for multi-word entries: a short rule must never+ shadow a longer phrase that contains it.+ """+ words = sorted(FILLER_WORDS[language], key=len, reverse=True)+ patterns: list[re.Pattern[str]] = []+ for word in words:+ escaped = r"\s+".join(re.escape(part) for part in word.split())+ patterns.append(+ re.compile(+ _BOUNDARY_PREFIX + escaped + _BOUNDARY_SUFFIX,+ re.IGNORECASE | re.UNICODE,+ )+ )+ return patterns+++# Compiled once per language at import; the tables are constant.+_PATTERN_CACHE: dict[str, list[re.Pattern[str]]] = {+ lang: _compile_patterns(lang) for lang in FILLER_WORDS+}+++def _tidy(text: str, *, raw: str) -> str:+ """Repair the punctuation and spacing a removal leaves behind.++ Strictly repair, never restyle: collapse the whitespace a removed word left,+ drop punctuation that now has nothing in front of it, and restore a leading+ capital ONLY when the raw text had one (so a German example that starts on a+ filler keeps its capital instead of turning into a lowercase sentence).+ """+ out = text+ # A removal can leave " , " or " ." — pull the mark back onto the previous word.+ out = re.sub(r"\s+([,.;:!?])", r"\1", out)+ # Two marks that ended up adjacent ("..,") collapse to the first.+ out = re.sub(r"([,;:])\s*([,.;:!?])", r"\2", out)+ out = re.sub(r"[ \t]{2,}", " ", out)+ # Leading punctuation left by a filler at the start of the text.+ out = re.sub(r"^[\s,;:.!?\-–—]+", "", out)+ out = out.strip()+ if out and raw[:1].isupper() and out[:1].islower():+ out = out[:1].upper() + out[1:]+ return out+++def clean_transcript(+ text: str,+ *,+ language: str | None = None,+ remove_fillers: bool = True,+ max_removed_fraction: float = 0.25,+) -> CleanupResult:+ """Remove hesitation sounds from ``text``. Never raises.++ Returns a :class:`CleanupResult` whose ``text`` is safe to insert. When the+ cleanup is refused (disabled, unknown language, or the destruction ceiling),+ ``text`` is the raw transcript and ``reason`` says why.+ """+ raw = text or ""+ stripped = raw.strip()+ if not stripped:+ return CleanupResult(+ text=raw, raw=raw, removed_words=0, total_words=0,+ applied=False, reason="empty",+ )+ if not remove_fillers:+ return CleanupResult(+ text=raw, raw=raw, removed_words=0, total_words=_count_words(raw),+ applied=False, reason="disabled",+ )++ lang = normalize_language(language)+ if lang is None:+ # Honest no-op: we would rather leave a filler in than damage a+ # sentence in a language whose rules we do not have.+ return CleanupResult(+ text=raw, raw=raw, removed_words=0, total_words=_count_words(raw),+ applied=False, reason="no_rules",+ )++ total = _count_words(raw)+ cleaned = raw+ try:+ for pattern in _PATTERN_CACHE[lang]:+ cleaned = pattern.sub(" ", cleaned)+ cleaned = _tidy(cleaned, raw=raw)+ except Exception: # noqa: BLE001 — a broken rule must never eat the dictation+ return CleanupResult(+ text=raw, raw=raw, removed_words=0, total_words=total,+ applied=False, reason="error",+ )++ remaining = _count_words(cleaned)+ removed = max(0, total - remaining)++ # Nothing survived — always a defect in the rules, never a valid result.+ if not cleaned.strip():+ return CleanupResult(+ text=raw, raw=raw, removed_words=0, total_words=total,+ applied=False, reason="ceiling",+ )++ if _SHORT_TEXT_WORDS <= total <= _ABSOLUTE_CAP_WORDS:+ if removed > _ABSOLUTE_MAX_REMOVED:+ return CleanupResult(+ text=raw, raw=raw, removed_words=removed, total_words=total,+ applied=False, reason="ceiling",+ )+ elif total > _ABSOLUTE_CAP_WORDS:+ fraction = removed / total if total else 0.0+ if fraction > max_removed_fraction:+ return CleanupResult(+ text=raw, raw=raw, removed_words=removed, total_words=total,+ applied=False, reason="ceiling",+ )++ return CleanupResult(+ text=cleaned, raw=raw, removed_words=removed, total_words=total,+ applied=True, reason="",+ )+++__all__ = [+ "FILLER_WORDS",+ "SUPPORTED_LANGUAGES",+ "CleanupResult",+ "clean_transcript",+ "normalize_language",+]diff --git a/jarvis/dictation/history.py b/jarvis/dictation/history.pynew file mode 100644index 0000000000..c2720d284b--- /dev/null+++ b/jarvis/dictation/history.py@@ -0,0 +1,265 @@+"""Local record of what was dictated — raw text, cleaned text, and outcome.++Two reasons this exists, and one reason it is careful:++* **Auditability.** The filler cleanup is deterministic, but "deterministic"+ only helps if you can see what it did. Storing raw *and* cleaned side by side+ is what makes a wrong rule findable instead of merely suspected.+* **Recovery.** When insertion degrades to "it is on your clipboard" and the+ user copies something else before pasting, the transcript is otherwise gone.++The care: dictated text is among the most sensitive data this application ever+holds — it is, by definition, whatever the user is writing. So the store is+local-only (a JSON sidecar under ``user_data_dir()/data/``, never synced,+never sent anywhere), capped in size, aged out on a user-set retention, and+purgeable with one call. It can be switched off entirely+(``[dictation].history_enabled = false``), in which case nothing is written.++Storage pattern mirrors ``jarvis.speech.stt_dictionary.DictionaryStore``:+atomic tempfile + ``os.replace`` so a crash mid-write never leaves a torn file.+"""++from __future__ import annotations++import json+import logging+import os+import tempfile+import threading+import uuid+from dataclasses import asdict, dataclass, field+from datetime import UTC, datetime, timedelta+from pathlib import Path+from typing import Any++log = logging.getLogger(__name__)++#: Hard ceiling regardless of configuration — an abuse guard, not a product limit.+MAX_ENTRIES_CEILING = 5_000+#: Longest single transcript kept. Longer ones are stored truncated with a marker.+MAX_TEXT_LEN = 20_000+++@dataclass(frozen=True, slots=True)+class DictationEntry:+ """One completed dictation."""++ id: str+ created_at: str+ #: The transcript exactly as the STT returned it.+ raw_text: str+ #: What was actually inserted (equals ``raw_text`` when no cleanup applied).+ text: str+ #: BCP-47-ish language the STT reported, or "" when unknown.+ language: str = ""+ #: Seconds of audio.+ duration_s: float = 0.0+ #: ``inserted`` | ``clipboard_only`` | ``unavailable`` | ``chat``.+ outcome: str = ""+ #: How it got there, e.g. ``clipboard+ctrl_v``.+ method: str = ""+ #: Words the cleanup removed (0 when it did not run or was refused).+ removed_words: int = 0+ #: Why a cleanup did not apply — ``""`` when it did.+ cleanup_reason: str = ""+ metadata: dict[str, Any] = field(default_factory=dict)++ def to_dict(self) -> dict[str, Any]:+ return asdict(self)+++def default_history_path() -> Path:+ """``<user data>/data/dictation_history.json``."""+ from jarvis.core.paths import user_data_dir++ return Path(user_data_dir()) / "data" / "dictation_history.json"+++class DictationHistory:+ """Append-only-ish store of recent dictations. Never raises to the caller.++ Every public method is wrapped: a broken or unreadable history file must+ never cost the user their dictation. Failures are logged and degrade to+ "no history", which is a cosmetic loss.+ """++ def __init__(self, path: Path | str | None = None) -> None:+ self._path = Path(path) if path is not None else default_history_path()+ self._lock = threading.Lock()++ @property+ def path(self) -> Path:+ return self._path++ # -- reading ---------------------------------------------------------++ def list_all(self) -> list[DictationEntry]:+ """Newest first. An unreadable file reads as an empty history."""+ try:+ raw = self._path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return []+ except OSError as exc:+ log.warning("dictation history unreadable: %s", exc)+ return []+ try:+ payload = json.loads(raw)+ except (ValueError, TypeError) as exc:+ log.warning("dictation history is corrupt, ignoring it: %s", exc)+ return []+ entries: list[DictationEntry] = []+ for item in payload.get("entries", []) or []:+ if not isinstance(item, dict):+ continue+ try:+ entries.append(+ DictationEntry(+ id=str(item.get("id") or uuid.uuid4().hex),+ created_at=str(item.get("created_at") or ""),+ raw_text=str(item.get("raw_text") or ""),+ text=str(item.get("text") or ""),+ language=str(item.get("language") or ""),+ duration_s=float(item.get("duration_s") or 0.0),+ outcome=str(item.get("outcome") or ""),+ method=str(item.get("method") or ""),+ removed_words=int(item.get("removed_words") or 0),+ cleanup_reason=str(item.get("cleanup_reason") or ""),+ metadata=dict(item.get("metadata") or {}),+ )+ )+ except (TypeError, ValueError):+ continue # one bad row never invalidates the rest+ return entries++ # -- writing ---------------------------------------------------------++ def add(+ self,+ *,+ raw_text: str,+ text: str,+ language: str = "",+ duration_s: float = 0.0,+ outcome: str = "",+ method: str = "",+ removed_words: int = 0,+ cleanup_reason: str = "",+ max_entries: int = 200,+ retention_days: int = 30,+ ) -> DictationEntry | None:+ """Record one dictation and prune. ``None`` when nothing was stored."""+ if not (raw_text or text):+ return None+ entry = DictationEntry(+ id=uuid.uuid4().hex,+ created_at=datetime.now(UTC).isoformat(),+ raw_text=_clip(raw_text),+ text=_clip(text),+ language=str(language or ""),+ duration_s=max(0.0, float(duration_s or 0.0)),+ outcome=str(outcome or ""),+ method=str(method or ""),+ removed_words=max(0, int(removed_words or 0)),+ cleanup_reason=str(cleanup_reason or ""),+ )+ try:+ with self._lock:+ entries = [entry, *self.list_all()]+ entries = _prune(+ entries,+ max_entries=max_entries,+ retention_days=retention_days,+ )+ self._write(entries)+ except Exception: # noqa: BLE001 — history is never worth a failed dictation+ log.warning("could not record the dictation history entry", exc_info=True)+ return None+ return entry++ def delete(self, entry_id: str) -> bool:+ try:+ with self._lock:+ entries = self.list_all()+ kept = [e for e in entries if e.id != entry_id]+ if len(kept) == len(entries):+ return False+ self._write(kept)+ return True+ except Exception: # noqa: BLE001+ log.warning("could not delete a dictation history entry", exc_info=True)+ return False++ def clear(self) -> bool:+ """Purge everything. The user-facing "delete my dictation history"."""+ try:+ with self._lock:+ self._write([])+ return True+ except Exception: # noqa: BLE001+ log.warning("could not clear the dictation history", exc_info=True)+ return False++ def _write(self, entries: list[DictationEntry]) -> None:+ payload = {"version": 1, "entries": [e.to_dict() for e in entries]}+ self._path.parent.mkdir(parents=True, exist_ok=True)+ # Atomic tempfile + os.replace: a crash mid-write never leaves a torn+ # sidecar (same discipline as the config writer, AP-7).+ fd, tmp_name = tempfile.mkstemp(+ dir=str(self._path.parent), prefix=".dictation_history_", suffix=".tmp"+ )+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as fh:+ json.dump(payload, fh, ensure_ascii=False, indent=2)+ os.replace(tmp_name, self._path)+ except Exception:+ try:+ os.unlink(tmp_name)+ except OSError:+ pass+ raise+++def _clip(text: str) -> str:+ value = str(text or "")+ if len(value) <= MAX_TEXT_LEN:+ return value+ return value[:MAX_TEXT_LEN] + " […truncated]"+++def _prune(+ entries: list[DictationEntry],+ *,+ max_entries: int,+ retention_days: int,+) -> list[DictationEntry]:+ """Drop entries past the count cap or the retention window.++ ``retention_days = 0`` means "keep until the count cap"; an unparseable+ timestamp is kept rather than silently discarded.+ """+ cap = max(0, min(int(max_entries or 0), MAX_ENTRIES_CEILING))+ kept = entries+ if retention_days and retention_days > 0:+ cutoff = datetime.now(UTC) - timedelta(days=int(retention_days))+ fresh: list[DictationEntry] = []+ for entry in kept:+ try:+ created = datetime.fromisoformat(entry.created_at)+ except (TypeError, ValueError):+ fresh.append(entry)+ continue+ if created.tzinfo is None:+ created = created.replace(tzinfo=UTC)+ if created >= cutoff:+ fresh.append(entry)+ kept = fresh+ return kept[:cap] if cap else []+++__all__ = [+ "MAX_ENTRIES_CEILING",+ "MAX_TEXT_LEN",+ "DictationEntry",+ "DictationHistory",+ "default_history_path",+]diff --git a/jarvis/dictation/insert.py b/jarvis/dictation/insert.pynew file mode 100644index 0000000000..1645089b77--- /dev/null+++ b/jarvis/dictation/insert.py@@ -0,0 +1,408 @@+"""Put dictated text into the focused field of the foreground application.++The one rule this module exists to enforce+------------------------------------------+**The text is on the clipboard before the first keystroke is emitted, and it+stays there if the paste fails.**++Insertion — not speech recognition — is where a dictation feature actually+breaks, and it breaks *silently* in at least three independent ways:++* **Windows UIPI.** A non-elevated process cannot send synthetic input to a+ window owned by a higher-integrity process. Microsoft documents that a+ ``SendInput`` blocked this way reports failure through neither its return+ value nor ``GetLastError`` — so the paste vanishes and the call reports+ success (measured on a live desktop, 2026-07-02).+* **macOS Secure Input.** A password field calls ``EnableSecureEventInput``;+ while it is on, keyboard events stop reaching other processes.+* **Wayland.** Synthetic input is blocked by design; there is no in-process+ route at all.++None of these produce an error we could catch after the fact, and verifying by+reading the target field back needs the accessibility tree — which is blocked in+exactly the cases that fail. So the design does not try to detect failure+afterwards: it checks what it can beforehand, always leaves the transcript on+the clipboard, and tells the truth about which of the two happened.++Everything here composes existing platform code — ``jarvis.platform.clipboard``,+``jarvis.cu.actuate.get_actuator``, ``jarvis.platform.probes`` — and adds no new+dependency. Nothing is imported at module scope that a headless host lacks.+"""++from __future__ import annotations++import logging+import sys+import time+from dataclasses import dataclass+from typing import Literal++log = logging.getLogger(__name__)++#: Paste chords by name. ``auto`` resolves per platform at call time.+#: Ctrl+V is wrong in many terminals (it is an interrupt or a literal there),+#: which is why the two alternatives exist as an explicit user choice.+PASTE_CHORDS: dict[str, list[str]] = {+ "ctrl_v": ["ctrl", "v"],+ "ctrl_shift_v": ["ctrl", "shift", "v"],+ "shift_insert": ["shift", "insert"],+ "cmd_v": ["cmd", "v"],+}++InsertStatus = Literal["inserted", "clipboard_only", "unavailable"]+++@dataclass(frozen=True, slots=True)+class TargetReport:+ """Whether synthetic input can reach the foreground window right now."""++ can_insert: bool+ #: "" when fine, else one of: ``wayland`` | ``headless`` | ``elevated`` |+ #: ``secure_input`` | ``no_backend``.+ reason: str+ #: English, user-facing sentence. Empty when ``can_insert`` is True.+ detail: str+++@dataclass(frozen=True, slots=True)+class InsertResult:+ """What actually happened to the dictated text.++ ``clipboard_only`` is a SUCCESS state, not a failure: the text is one+ Ctrl+V away and the user was told so. Only ``unavailable`` means the text+ could not even be parked.+ """++ status: InsertStatus+ detail: str+ #: True when the transcript is sitting on the clipboard right now.+ clipboard_holds_text: bool+ #: e.g. ``"clipboard+ctrl_v"`` / ``"type"`` / ``""``.+ method: str = ""+ #: True when the previous clipboard content was put back.+ clipboard_restored: bool = False++ @property+ def ok(self) -> bool:+ """The text reached the user one way or another."""+ return self.status in ("inserted", "clipboard_only")+++def resolve_paste_chord(name: str = "auto") -> tuple[str, list[str]]:+ """``("ctrl_v", ["ctrl", "v"])`` — the chord to send and its label.++ ``auto`` picks Command+V on macOS and Ctrl+V everywhere else. An unknown+ name falls back to ``auto`` rather than raising: a bad config value must+ not stop a dictation.+ """+ key = (name or "auto").strip().lower()+ if key == "auto" or key not in PASTE_CHORDS:+ key = "cmd_v" if sys.platform == "darwin" else "ctrl_v"+ return key, list(PASTE_CHORDS[key])+++def foreground_is_this_app() -> bool | None:+ """Is the window in front owned by THIS process (or its children)?++ Used to resolve ``[dictation].target = "auto"``: when Jarvis itself is in+ front, the transcript belongs in the app's own input box, because inserting+ into the window the user just left is both surprising and unrecoverable.++ ``None`` when it cannot be determined — the caller then treats it as "not+ us" and inserts, which is the behaviour people expect from a dictation key.+ Never raises.+ """+ if sys.platform != "win32":+ # The equivalent probe on macOS (NSWorkspace frontmostApplication) and+ # X11 (_NET_ACTIVE_WINDOW -> _NET_WM_PID) is a follow-up; until then+ # "auto" behaves like "insert" there, which is the safe default and is+ # recorded in docs/os-parity.md.+ return None+ try:+ import ctypes # noqa: PLC0415 — lazy (HN-7)+ import os # noqa: PLC0415+ from ctypes import wintypes # noqa: PLC0415++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ user32.GetForegroundWindow.argtypes = []+ user32.GetForegroundWindow.restype = wintypes.HWND+ user32.GetWindowThreadProcessId.argtypes = [+ wintypes.HWND,+ ctypes.POINTER(wintypes.DWORD),+ ]+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD++ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return None+ pid = wintypes.DWORD()+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))+ if not pid.value:+ return None+ return pid.value == os.getpid()+ except Exception: # noqa: BLE001 — an unreadable foreground is "unknown"+ log.debug("could not read the foreground window's owner", exc_info=True)+ return None+++def resolve_target(configured: str) -> str:+ """``"auto"`` -> ``"chat"`` or ``"insert"``; anything else passes through."""+ value = (configured or "auto").strip().lower()+ if value in ("chat", "insert"):+ return value+ return "chat" if foreground_is_this_app() is True else "insert"+++def describe_target() -> TargetReport:+ """Can we type into whatever is in front right now? Never raises.++ Fail-OPEN on an unreadable probe (report "can insert"), because refusing on+ a guess would send every dictation to the clipboard on hosts where pasting+ works fine. A real block is always a positive measurement.+ """+ try:+ from jarvis.platform.probes import display_present, is_wayland+ except Exception: # noqa: BLE001 — probe import must never break dictation+ return TargetReport(can_insert=True, reason="", detail="")++ try:+ if sys.platform not in ("win32", "darwin"):+ if is_wayland():+ return TargetReport(+ can_insert=False,+ reason="wayland",+ detail=(+ "Wayland blocks one program from typing into another, so "+ "the text cannot be inserted automatically. It is on your "+ "clipboard — press Ctrl+V where you want it."+ ),+ )+ if not display_present():+ return TargetReport(+ can_insert=False,+ reason="headless",+ detail=(+ "There is no desktop session on this host, so there is no "+ "window to type into."+ ),+ )+ except Exception: # noqa: BLE001 — an unreadable probe is not a block+ log.debug("display/wayland probe failed", exc_info=True)++ try:+ from jarvis.platform.input_isolation import (+ macos_secure_input_enabled,+ windows_foreground_window_is_elevated,+ )++ if sys.platform == "win32" and windows_foreground_window_is_elevated() is True:+ # Only a problem when WE are not elevated — same-or-higher integrity+ # may inject downward. Reading our own token is cheap and exact.+ from jarvis.platform.input_isolation import windows_process_is_elevated++ if windows_process_is_elevated() is not True:+ return TargetReport(+ can_insert=False,+ reason="elevated",+ detail=(+ "The window in front is running as administrator, and "+ "Windows blocks normal programs from typing into it. The "+ "text is on your clipboard — press Ctrl+V there."+ ),+ )+ if sys.platform == "darwin" and macos_secure_input_enabled() is True:+ return TargetReport(+ can_insert=False,+ reason="secure_input",+ detail=(+ "A password field is active, so macOS is blocking keystrokes "+ "from other apps. The text is on your clipboard — press "+ "Command+V once you are somewhere safe to paste it."+ ),+ )+ except Exception: # noqa: BLE001 — a failed probe never blocks the paste+ log.debug("input-isolation probe failed", exc_info=True)++ return TargetReport(can_insert=True, reason="", detail="")+++def insert_text(+ text: str,+ *,+ method: str = "clipboard",+ paste_chord: str = "auto",+ delay_ms: int = 120,+ delay_after_ms: int = 120,+ restore_clipboard: bool = True,+) -> InsertResult:+ """Insert ``text`` into the focused field. Never raises.++ The clipboard route (default) writes the text, sends the paste chord and+ puts the previous clipboard content back. The ``type`` route synthesises+ the characters instead — correct for the rare control that ignores paste,+ but slow and easily mangled by editor autocomplete, so it is opt-in.++ Either way the text is written to the clipboard FIRST, so every failure+ path below degrades to "it is one Ctrl+V away" rather than to silence.+ """+ if not text or not text.strip():+ return InsertResult(+ status="unavailable",+ detail="Nothing was dictated.",+ clipboard_holds_text=False,+ )++ from jarvis.platform import clipboard++ # 1. Remember what was there. ``None`` means the clipboard is unreachable+ # (not that it was empty) — restoring on that would CLEAR it, so the+ # two cases must stay apart.+ previous: str | None = None+ if restore_clipboard:+ try:+ previous = clipboard.read_text()+ except Exception: # noqa: BLE001 — a failed read only costs the restore+ log.debug("clipboard read failed; will not restore", exc_info=True)+ previous = None++ # 2. Park the text. This happens before ANY keystroke, so it is the one+ # guarantee that survives every silent-failure path below.+ parked = False+ try:+ parked = bool(clipboard.write_text(text))+ except Exception: # noqa: BLE001+ log.warning("clipboard write failed", exc_info=True)+ parked = False++ if not parked and method != "type":+ return InsertResult(+ status="unavailable",+ detail=(+ "The text could not be placed on the clipboard, so it cannot be "+ "inserted here. It is still in the dictation history."+ ),+ clipboard_holds_text=False,+ )++ # 3. Can synthetic input reach the foreground window at all?+ report = describe_target()+ if not report.can_insert:+ # Deliberately NOT restoring the clipboard: the transcript is the only+ # copy the user can reach, and putting the old content back here would+ # destroy the very fallback this whole design rests on.+ return InsertResult(+ status="clipboard_only" if parked else "unavailable",+ detail=report.detail,+ clipboard_holds_text=parked,+ )++ # 4. Actually insert.+ try:+ from jarvis.cu.actuate import get_actuator+ except Exception as exc: # noqa: BLE001 — optional desktop extra+ return InsertResult(+ status="clipboard_only" if parked else "unavailable",+ detail=(+ "No keyboard-control backend is available on this host "+ f"({exc}). The text is on your clipboard — paste it where you "+ "want it."+ ),+ clipboard_holds_text=parked,+ )++ try:+ actuator = get_actuator()+ except Exception as exc: # noqa: BLE001 — ActuationUnavailable + anything else+ return InsertResult(+ status="clipboard_only" if parked else "unavailable",+ detail=(+ f"{exc} The text is on your clipboard — paste it where you want it."+ ),+ clipboard_holds_text=parked,+ )++ if method == "type":+ try:+ actuator.type_text(text)+ except Exception as exc: # noqa: BLE001+ log.warning("synthetic typing failed: %s", exc)+ return InsertResult(+ status="clipboard_only" if parked else "unavailable",+ detail=(+ "Typing the text directly did not work. It is on your "+ "clipboard — press Ctrl+V (Command+V on a Mac)."+ ),+ clipboard_holds_text=parked,+ )+ restored = _restore(clipboard, previous) if restore_clipboard else False+ return InsertResult(+ status="inserted",+ detail="",+ clipboard_holds_text=not restored,+ method="type",+ clipboard_restored=restored,+ )++ chord_name, chord = resolve_paste_chord(paste_chord)+ if delay_ms > 0:+ # Load-bearing: without it the target app can still be holding the+ # PREVIOUS clipboard content when the chord arrives, and pastes that.+ time.sleep(delay_ms / 1000.0)+ try:+ actuator.key_combo(chord)+ except Exception as exc: # noqa: BLE001+ log.warning("paste chord %s failed: %s", chord_name, exc)+ return InsertResult(+ status="clipboard_only" if parked else "unavailable",+ detail=(+ "The paste shortcut could not be sent. The text is on your "+ "clipboard — press Ctrl+V (Command+V on a Mac)."+ ),+ clipboard_holds_text=parked,+ )+ if delay_after_ms > 0:+ # Equally load-bearing in the other direction: restoring too early+ # snatches the text away before the target app has read it.+ time.sleep(delay_after_ms / 1000.0)++ restored = _restore(clipboard, previous) if restore_clipboard else False+ return InsertResult(+ status="inserted",+ detail="",+ clipboard_holds_text=not restored,+ method=f"clipboard+{chord_name}",+ clipboard_restored=restored,+ )+++def _restore(clipboard_module: object, previous: str | None) -> bool:+ """Put the previous clipboard text back. Best-effort, never raises.++ ``previous is None`` means "we could not read it", NOT "it was empty" —+ writing an empty string then would clear a clipboard we never owned. An+ empty string does mean genuinely empty, and is restored as such.++ Known limitation, documented rather than hidden: the platform clipboard+ layer is text-only, so an IMAGE that was on the clipboard cannot be+ restored. Dictating over a copied image loses it.+ """+ if previous is None:+ return False+ try:+ return bool(clipboard_module.write_text(previous)) # type: ignore[attr-defined]+ except Exception: # noqa: BLE001 — a failed restore is not a failed dictation+ log.debug("clipboard restore failed", exc_info=True)+ return False+++__all__ = [+ "PASTE_CHORDS",+ "InsertResult",+ "InsertStatus",+ "TargetReport",+ "describe_target",+ "foreground_is_this_app",+ "insert_text",+ "resolve_paste_chord",+ "resolve_target",+]diff --git a/jarvis/dictation/segment.py b/jarvis/dictation/segment.pynew file mode 100644index 0000000000..29dadea16e--- /dev/null+++ b/jarvis/dictation/segment.py@@ -0,0 +1,95 @@+"""Where to cut a dictation recording into transcribable segments.++Why segmenting matters at all: transcribing the whole growing buffer on every+tick costs O(n²) in audio seconds and, on a metered API, real money — a+two-minute dictation re-sends the entire recording roughly a hundred times.+Closing segments as they finish turns that into one pass over the audio.++Why cutting is not trivial: a cut in the middle of a word produces two wrong+transcriptions instead of one right one, and the damage is permanent because a+closed segment is never re-transcribed. So the cut point is not "exactly at N+seconds" but "at the quietest moment near N seconds" — which, in dictated+speech, is a pause between words far more often than not.++Pure functions over raw PCM: no model, no VAD state machine, no I/O. The VAD+proper is deliberately not reused here — it is a stateful component on the+voice hot path, and dictation must never contend with it.+"""++from __future__ import annotations++import numpy as np++#: Samples are 16-bit little-endian mono.+BYTES_PER_SAMPLE = 2++#: How far back from the nominal cut we are willing to look for a quiet spot.+#: Wide enough to reach the previous pause in normal speech, narrow enough that+#: segments stay roughly the requested length.+_SEARCH_BACK_S = 1.5++#: Width of the loudness window scored while searching. Roughly the length of a+#: natural inter-word pause.+_PROBE_WINDOW_S = 0.2++#: Step between scored positions. Finer than this buys no accuracy for the cost.+_PROBE_STEP_S = 0.02+++def _align(offset: int) -> int:+ """Round an offset down to a whole int16 sample boundary."""+ return max(0, offset - (offset % BYTES_PER_SAMPLE))+++def quietest_cut(+ pcm: bytes,+ nominal_bytes: int,+ bytes_per_second: int = 16_000 * BYTES_PER_SAMPLE,+) -> int:+ """Byte offset at which to close a segment of ``pcm``.++ Looks in ``[nominal - 1.5 s, nominal]`` for the quietest short window and+ returns its centre; falls back to ``nominal_bytes`` when the buffer is too+ short to search or anything about the scan goes wrong. The result is always+ sample-aligned and never past the end of ``pcm``.+ """+ if nominal_bytes <= 0:+ return 0+ limit = min(len(pcm), nominal_bytes)+ if limit <= 0:+ return 0++ window = int(_PROBE_WINDOW_S * bytes_per_second)+ step = max(BYTES_PER_SAMPLE, int(_PROBE_STEP_S * bytes_per_second))+ search_start = max(0, limit - int(_SEARCH_BACK_S * bytes_per_second))+ if window <= 0 or limit - search_start < window * 2:+ # Too little audio to make a meaningful choice — the nominal cut is as+ # good as any, and pretending otherwise would just add jitter.+ return _align(limit)++ try:+ samples = np.frombuffer(pcm[:limit], dtype=np.int16).astype(np.float32)+ except (ValueError, TypeError):+ return _align(limit)+ if samples.size == 0:+ return _align(limit)++ window_samples = max(1, window // BYTES_PER_SAMPLE)+ step_samples = max(1, step // BYTES_PER_SAMPLE)+ first = search_start // BYTES_PER_SAMPLE++ best_energy: float | None = None+ best_centre = samples.size+ for start in range(first, samples.size - window_samples + 1, step_samples):+ chunk = samples[start : start + window_samples]+ energy = float(np.mean(np.abs(chunk)))+ if best_energy is None or energy < best_energy:+ best_energy = energy+ best_centre = start + window_samples // 2++ if best_energy is None:+ return _align(limit)+ return _align(min(limit, best_centre * BYTES_PER_SAMPLE))+++__all__ = ["BYTES_PER_SAMPLE", "quietest_cut"]diff --git a/jarvis/platform/input_isolation.py b/jarvis/platform/input_isolation.pyindex 47beb4b5d4..119a998437 100644--- a/jarvis/platform/input_isolation.py+++ b/jarvis/platform/input_isolation.py@@ -36,6 +36,7 @@ from __future__ import annotationsimport loggingimport os+import sysfrom dataclasses import dataclassfrom enum import StrEnumfrom typing import Any@@ -170,6 +171,141 @@ def windows_process_is_elevated() -> bool | None:return None+def windows_foreground_window_is_elevated() -> bool | None:+ """Is the window currently in the FOREGROUND owned by an elevated process?++ The mirror image of :func:`windows_process_is_elevated`: that one asks+ "can other software type into us", this one asks "can we type into what the+ user is looking at". Same UIPI rule, opposite direction — and the same+ silence: a ``SendInput`` blocked by UIPI reports failure through neither its+ return value nor ``GetLastError``, so dictation would paste into the void+ and report success. Measured on a live desktop 2026-07-02.++ ``None`` when the answer cannot be determined — including on every+ non-Windows host, where the question does not apply. Never raises: a+ diagnostic that can crash the caller is worse than no diagnostic.+ """+ if os.name != "nt":+ return None+ try:+ import ctypes # noqa: PLC0415 — lazy: keeps this module import-clean (HN-7)+ from ctypes import wintypes # noqa: PLC0415++ TOKEN_QUERY = 0x0008+ TokenElevation = 20+ PROCESS_QUERY_LIMITED_INFORMATION = 0x1000++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ # Declaring these is load-bearing, not decoration — see the sibling+ # function: an undeclared 64-bit HANDLE is silently truncated to int.+ user32.GetForegroundWindow.argtypes = []+ user32.GetForegroundWindow.restype = wintypes.HWND+ user32.GetWindowThreadProcessId.argtypes = [+ wintypes.HWND,+ ctypes.POINTER(wintypes.DWORD),+ ]+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD+ kernel32.OpenProcess.argtypes = [+ wintypes.DWORD,+ wintypes.BOOL,+ wintypes.DWORD,+ ]+ kernel32.OpenProcess.restype = wintypes.HANDLE+ kernel32.CloseHandle.argtypes = [wintypes.HANDLE]+ kernel32.CloseHandle.restype = wintypes.BOOL+ advapi32.OpenProcessToken.argtypes = [+ wintypes.HANDLE,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.HANDLE),+ ]+ advapi32.OpenProcessToken.restype = wintypes.BOOL+ advapi32.GetTokenInformation.argtypes = [+ wintypes.HANDLE,+ ctypes.c_int,+ wintypes.LPVOID,+ wintypes.DWORD,+ ctypes.POINTER(wintypes.DWORD),+ ]+ advapi32.GetTokenInformation.restype = wintypes.BOOL++ hwnd = user32.GetForegroundWindow()+ if not hwnd:+ return None+ pid = wintypes.DWORD()+ user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))+ if not pid.value:+ return None++ process = kernel32.OpenProcess(+ PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value+ )+ if not process:+ # Access denied reading a higher-integrity process is itself a+ # strong hint that it IS elevated — but it is not proof (the+ # handle can fail for other reasons), and this probe must not+ # invent findings. "Unknown" is the honest answer.+ return None+ try:+ token = wintypes.HANDLE()+ if not advapi32.OpenProcessToken(+ process, TOKEN_QUERY, ctypes.byref(token)+ ):+ return None+ try:+ elevated = wintypes.DWORD()+ returned = wintypes.DWORD()+ ok = advapi32.GetTokenInformation(+ token,+ TokenElevation,+ ctypes.cast(ctypes.byref(elevated), wintypes.LPVOID),+ ctypes.sizeof(elevated),+ ctypes.byref(returned),+ )+ if not ok:+ return None+ return bool(elevated.value)+ finally:+ kernel32.CloseHandle(token)+ finally:+ kernel32.CloseHandle(process)+ except Exception: # noqa: BLE001 — an unreadable token is "unknown", not fatal+ log.debug("Could not read the foreground window's elevation", exc_info=True)+ return None+++def macos_secure_input_enabled() -> bool | None:+ """Is macOS Secure Input active right now?++ A password field turns it on (``EnableSecureEventInput``), and while it is+ on, keyboard events stop reaching every other process. Synthetic keystrokes+ are therefore unsafe: the paste chord may simply not arrive.++ ``None`` on non-macOS hosts or when the API cannot be reached. Never raises.+ """+ if sys.platform != "darwin":+ return None+ try:+ import ctypes # noqa: PLC0415 — lazy (HN-7)+ import ctypes.util # noqa: PLC0415++ path = ctypes.util.find_library("Carbon")+ if not path:+ return None+ carbon = ctypes.cdll.LoadLibrary(path)+ probe = getattr(carbon, "IsSecureEventInputEnabled", None)+ if probe is None:+ return None+ probe.argtypes = []+ probe.restype = ctypes.c_bool+ return bool(probe())+ except Exception: # noqa: BLE001 — an unreadable state is "unknown", not fatal+ log.debug("Could not read the macOS Secure Input state", exc_info=True)+ return None++def _euid() -> int | None:"""Effective user id, or ``None`` on platforms without one (Windows)."""getter = getattr(os, "geteuid", None)@@ -251,5 +387,7 @@ __all__ = ["InputIsolationReason","InputIsolationReport","describe_input_isolation",+ "macos_secure_input_enabled",+ "windows_foreground_window_is_elevated","windows_process_is_elevated",]diff --git a/jarvis/plugins/tool/navigate.py b/jarvis/plugins/tool/navigate.pyindex 336cb614c9..bca0bec32d 100644--- a/jarvis/plugins/tool/navigate.py+++ b/jarvis/plugins/tool/navigate.py@@ -48,6 +48,7 @@ KNOWN: frozenset[str] = frozenset("feedback","agent-instructions","dictionary",+ "dictation","agentic-ide",})diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex bdddfc42e5..2537c03b5c 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -48,6 +48,7 @@ from jarvis.core.events import (AnnouncementRequested,AudioOutFirst,BrainTTFT,+ DictationCompleted,DictationTranscript,JarvisAgentAnnouncement,JarvisAgentBackgroundCompleted,@@ -1281,10 +1282,23 @@ class SpeechPipeline:# it overrides the OWW model + threshold, the prefix-verifier matcher,# and the rolling-whisper pattern from the plan.wake_plan: Any = None,+ # Dictation mode: hold (or toggle) to speak, the transcript is inserted+ # into whatever text field has focus. Empty (the default) means no+ # shortcut is armed — dictation is then started from the bar, the UI or+ # the CLI. Deliberately its OWN binding rather than a revival of the+ # deprecated ptt slot: dictation never reaches the brain.+ dictate_hotkeys: tuple[str, ...] = (),+ dictate_mode: str = "hold",+ # 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,) -> None:self._call_hotkeys = call_hotkeysself._ptt_hotkeys = ptt_hotkeysself._hangup_hotkeys = hangup_hotkeys+ self._dictate_hotkeys = list(dictate_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# in ``_active_session``; ``_ptt_release_event`` is the up-edge signal# that ends the recording. A held key never auto-ends via the VAD — the@@ -1305,7 +1319,18 @@ class SpeechPipeline:# task so it can never touch ``_handle_utterance`` / the wake loop.self._dictation_stop_event = asyncio.Event()self._dictation_task: asyncio.Task[None] | None = None- self._dictation_max_s = 300.0+ self._dictation_max_s = float(+ getattr(self._dictation_cfg, "max_seconds", 300.0) or 300.0+ )+ # Where the finished transcript goes for the CURRENT dictation run:+ # "chat" only publishes the transcript event (the chat composer's mic+ # button), "insert" additionally pastes it into the focused field of+ # whatever app is in front. Set per start_dictation call, never global.+ self._dictation_target = "chat"+ # True while a hold-mode dictation key is physically down. Mirrors+ # ``_ptt_mode`` for the dictation lane so a repeated press edge (the+ # Windows backend polls and re-fires on_press while held) is idempotent.+ self._dictate_key_down = False# ``self._stt`` is the LOCAL FasterWhisperProvider used by the wake# backstop + VAD endpoint-probe (many calls/sec, a cloud round-trip# would be too slow). In the cloud-first lightweight path it is None:@@ -2252,6 +2277,7 @@ class SpeechPipeline:call: list[str] | None = None,hangup: list[str] | None = None,ptt: list[str] | None = None,+ dictate: list[str] | None = None,) -> None:"""Live-apply changed voice keybinds — no app/pipeline restart.@@ -2271,11 +2297,14 @@ class SpeechPipeline:self._hangup_hotkeys = list(hangup)if ptt is not None:self._ptt_hotkeys = list(ptt)+ if dictate is not None:+ self._dictate_hotkeys = list(dictate)log.info(- "Keybind-Live-Switch: CALL=[%s] PTT=[%s] HANGUP=[%s]",+ "Keybind-Live-Switch: CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s]",", ".join(self._call_hotkeys),", ".join(self._ptt_hotkeys) or "off",", ".join(self._hangup_hotkeys),+ ", ".join(self._dictate_hotkeys) or "off",)self._hotkey_reload_event.set()@@ -2290,15 +2319,33 @@ class SpeechPipeline:while True:await self._hotkey_reload_event.wait()self._hotkey_reload_event.clear()- bindings: dict[str, list[str]] = {- "call": list(self._call_hotkeys),- "hangup": list(self._hangup_hotkeys),- }- ptt_events: set[str] = set()- if self._ptt_hotkeys:- bindings["ptt"] = list(self._ptt_hotkeys)- ptt_events.add("ptt")- await trigger.rearm(bindings, push_to_talk=ptt_events)+ bindings, edge_events = self._build_hotkey_bindings()+ await trigger.rearm(bindings, push_to_talk=edge_events)++ def _build_hotkey_bindings(self) -> tuple[dict[str, list[str]], set[str]]:+ """The live binding table + the set of bindings wanting BOTH key edges.++ One producer for both arming sites (``run`` at start, ``_hotkey_reload_loop``+ on a live keybind change). They used to build this dict twice; a third+ action made that duplication a drift bug waiting to happen — a shortcut+ that works at boot but not after a Settings save, or the reverse.+ """+ bindings: dict[str, list[str]] = {+ "call": list(self._call_hotkeys),+ "hangup": list(self._hangup_hotkeys),+ }+ edge_events: set[str] = set()+ if self._ptt_hotkeys:+ bindings["ptt"] = list(self._ptt_hotkeys)+ edge_events.add("ptt")+ if self._dictate_hotkeys:+ bindings["dictate"] = list(self._dictate_hotkeys)+ # Hold mode needs the release edge to know when to submit; toggle+ # mode deliberately gets the legacy single-fire-on-release contract+ # so holding the key does not start and stop repeatedly.+ if self._dictate_mode == "hold":+ edge_events.add("dictate")+ return bindings, edge_events# ------------------------------------------------------------------# Bus / Supervisor Helper — no-op wenn nicht konfiguriert@@ -4010,23 +4057,17 @@ class SpeechPipeline:exc,exc_info=True,)- hotkey_bindings = {- "call": list(self._call_hotkeys),- "hangup": list(self._hangup_hotkeys),- }- # Push-to-talk binding (both key edges) — only when configured. Kept as- # its own event so the configured wake hotkey can be true PTT while- # F3+F4 stays a quick toggle (a two-F-key chord is awkward to hold).- ptt_events: set[str] = set()- if self._ptt_hotkeys:- hotkey_bindings["ptt"] = list(self._ptt_hotkeys)- ptt_events.add("ptt")+ # Push-to-talk and dictation want BOTH key edges; call/hangup keep the+ # 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] OWW=%s WAKE=%s (threshold=%.2f) "- "WHISPER-WAKE=%s TURN-MODE=%s",+ "Pipeline ready. CALL=[%s] PTT=[%s] HANGUP=[%s] DICTATE=[%s/%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,"on" if self._openwakeword_enabled else "off",list(self._wake._keywords),self._wake._threshold,@@ -4523,10 +4564,57 @@ class SpeechPipeline:self._on_ptt_press()elif event_name == "ptt_release":self._on_ptt_release()+ elif event_name == "dictate_press":+ self._on_dictate_press()+ elif event_name == "dictate_release":+ self._on_dictate_release()+ elif event_name == "dictate":+ # Toggle mode: one press starts, the next stops.+ self._on_dictate_toggle()elif event_name == "hangup":log.info("📵 HANGUP via Hotkey")self._trigger_voice_hangup()+ # ------------------------------------------------------------------+ # Dictation hotkey edges+ # ------------------------------------------------------------------++ def _on_dictate_press(self) -> None:+ """Dictation key DOWN — start recording into the focused text field.++ Idempotent by design: the Windows backend polls, so ``on_press`` fires+ again on every poll while the chord is held. Only the first edge from+ "key up" starts anything.+ """+ if self._dictate_key_down:+ return+ self._dictate_key_down = True+ if not self.start_dictation(target=self._configured_dictation_target()):+ # Could not start (mic busy, a voice session is live, no STT). Drop+ # the latch immediately so the NEXT press is a fresh attempt rather+ # than being swallowed as a repeat.+ self._dictate_key_down = False++ def _on_dictate_release(self) -> None:+ """Dictation key UP — stop recording and submit what was held."""+ if not self._dictate_key_down:+ return+ self._dictate_key_down = False+ self.stop_dictation()++ def _on_dictate_toggle(self) -> None:+ """Toggle mode: start if idle, stop if running."""+ task = self._dictation_task+ if task is not None and not task.done():+ self.stop_dictation()+ return+ self.start_dictation(target=self._configured_dictation_target())++ def _configured_dictation_target(self) -> str:+ """``[dictation].target`` — ``auto`` by default, resolved at start."""+ cfg = getattr(self, "_dictation_cfg", None)+ return str(getattr(cfg, "target", "auto") or "auto")+def _on_ptt_press(self) -> None:"""Push-to-talk DOWN edge — arm raw recording and open the session.@@ -7304,16 +7392,23 @@ class SpeechPipeline:and self._capture_permission_allowed())- def start_dictation(self) -> bool:+ def start_dictation(self, *, target: str = "chat") -> bool:"""Begin a transcribe-only dictation session (idempotent-safe).+ ``target`` decides where the finished transcript goes:++ * ``"chat"`` — publish the transcript only. This is the chat composer's+ mic button: the text lands in the app's own input box.+ * ``"insert"`` — additionally paste it into the focused text field of+ whatever application is in front. This is dictation mode proper.+Returns ``False`` when it cannot start — a voice/PTT session is active,the pipeline is busy, dictation is already running, or no STT is wired.- The caller (WS handler) turns ``False`` into an honest UI message rather- than silently doing nothing.+ The caller (hotkey edge, WS handler, REST route) turns ``False`` into an+ honest message rather than silently doing nothing.This NEVER routes to the brain: it spawns ``_dictation_session`` which- only publishes ``DictationTranscript`` events.+ only publishes ``DictationTranscript`` / ``DictationCompleted`` events."""if not self._capture_permission_allowed():log.info("start_dictation ignored: microphone access is not ready.")@@ -7342,13 +7437,27 @@ class SpeechPipeline:hangup = getattr(self, "_hangup_event", None)if hangup is not None:hangup.clear()+ # Stored RAW ("auto" / "insert" / "chat"). ``auto`` is resolved when the+ # recording ENDS, not here: the window that matters is the one in front+ # when the text is delivered. Clicking "Start dictating" in the app and+ # then switching to the target application is a normal flow, and+ # resolving at start would have sent that text to the chat box.+ self._dictation_target = target if target in ("insert", "chat") else "auto"self._dictation_stop_event = asyncio.Event()self._dictation_task = loop.create_task(- self._dictation_session(), name="chat-dictation"+ self._dictation_session(), name="dictation"+ )+ log.info(+ "🎙️ dictation started (transcribe-only, target=%s).",+ self._dictation_target,)- log.info("🎙️ dictation started (transcribe-only → chat input).")return True+ def dictation_active(self) -> bool:+ """Is a dictation running right now? (REST/UI status, cheap.)"""+ task = self._dictation_task+ return task is not None and not task.done()+def stop_dictation(self) -> bool:"""Signal the active dictation session to finish (best-effort)."""if self._dictation_task is None or self._dictation_task.done():@@ -7357,49 +7466,128 @@ class SpeechPipeline:return Trueasync def _dictation_session(self) -> None:- """Capture mic audio and stream live transcripts to the chat input.+ """Capture mic audio, transcribe it in segments, deliver the result.A stripped-down ``_ptt_session``: open the mic, drain into a buffer,- transcribe the held-so-far buffer every ``_ptt_partial_interval_s`` and- publish a non-final ``DictationTranscript``; on the stop event (or the- max-duration cap) transcribe once more and publish the final one. It- deliberately does NOT use the VAD, the brain, TTS, or the turn-state- machine — the whole thing is wrapped fail-open so a dictation error can- never break a later real voice turn (BUG-020 discipline).+ publish a live ``DictationTranscript`` while speaking, and on the stop+ event (or the max-duration cap) produce the final text, clean it, and —+ when the target is ``insert`` — paste it into the focused field of+ whatever application is in front. It deliberately does NOT use the VAD+ endpointing, the brain, TTS, or the turn-state machine, and the whole+ thing is wrapped fail-open so a dictation error can never break a later+ real voice turn (BUG-020 discipline).++ **Segmented transcription.** The previous version re-transcribed the+ ENTIRE growing buffer on every tick. That is O(n²) in audio seconds: a+ two-minute dictation re-sent the whole recording ~100 times, and on a+ paid API every one of those was billed. Now a segment is closed roughly+ every ``segment_seconds`` — at the quietest point nearby, so words are+ not cut in half — transcribed exactly once, and never re-sent. Only the+ open tail is re-transcribed for the live preview, so on release only+ that tail remains to be finalized.++ **AP-24.** The live probe and the final transcription must never run+ concurrently on one native engine. ``inference_active`` + the shared+ ``_stop_ptt_live_transcription`` handshake are what keep them apart —+ cancelling an ``asyncio.to_thread`` would only cancel the wrapper, not+ the native call, and the next transcribe would then raise TranscribeBusy."""stt = self._utterance_sttif stt is None:return+ # ``getattr`` defaults keep pipelines built via ``__new__`` working —+ # a widely used pattern in this repo's unit tests, which bypass+ # ``__init__`` entirely.+ cfg = getattr(self, "_dictation_cfg", None)+ target = getattr(self, "_dictation_target", "chat")buffer = bytearray()- interval = self._ptt_partial_interval_s if self._ptt_partial_interval_s > 0 else 1.2+ started_at = time.monotonic()+ interval = float(+ getattr(cfg, "partial_interval_s", None)+ if getattr(cfg, "partial_interval_s", None) is not None+ else self._ptt_partial_interval_s+ )+ segment_seconds = float(getattr(cfg, "segment_seconds", 8.0) or 0.0)+ # 16 kHz mono int16 -> 32000 bytes per second.+ bytes_per_second = 16_000 * 2+ segment_bytes = int(segment_seconds * bytes_per_second)# Sub-0.4s of audio is almost always a near-silence Whisper# hallucination; wait until enough has accumulated before transcribing.- min_bytes = int(0.4 * 16_000 * 2)+ min_bytes = int(0.4 * bytes_per_second)++ # Text of segments already closed and transcribed — never re-sent.+ closed_parts: list[str] = []+ # How many bytes of ``buffer`` the closed segments cover.+ closed_bytes = 0last_published = ""+ stop_event = asyncio.Event()+ inference_active = asyncio.Event()+ language = ""++ async def _transcribe(pcm: bytes) -> tuple[str, str]:+ """One transcription. Returns ``(text, language)``; never raises."""+ inference_active.set()+ try:+ 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)+ return "", ""+ finally:+ inference_active.clear()+ text = (getattr(transcript, "text", "") or "").strip()+ lang = str(getattr(transcript, "language", "") or "")+ return text, langasync def _probe() -> None:- """Periodic non-final transcript of the held-so-far buffer."""- nonlocal last_published+ """Close finished segments and publish the live transcript."""+ nonlocal closed_bytes, last_published, languagetry:- while True:- await asyncio.sleep(interval)- pcm = bytes(buffer)- if len(pcm) < min_bytes:- continue+ while not stop_event.is_set():try:- transcript = await stt.transcribe_pcm(pcm)- except Exception as exc: # noqa: BLE001 — cosmetic, keep going- log.debug("dictation probe failed: %s", exc)+ await asyncio.wait_for(stop_event.wait(), timeout=interval)+ except TimeoutError:+ pass+ if stop_event.is_set():+ return+ tail = bytes(buffer[closed_bytes:])+ if len(tail) < min_bytes:continue- text = (getattr(transcript, "text", "") or "").strip()- if not text or text == last_published:++ # Close a segment once the tail is long enough. Cutting at+ # the quietest point in the last stretch keeps the cut off+ # the middle of a word in the overwhelming majority of cases.+ if segment_bytes and len(tail) >= segment_bytes:+ from jarvis.dictation.segment import quietest_cut++ cut = quietest_cut(tail, segment_bytes, bytes_per_second)+ if cut >= min_bytes:+ text, lang = await _transcribe(tail[:cut])+ if stop_event.is_set():+ return+ if text:+ closed_parts.append(text)+ language = lang or language+ # Advance regardless: a segment that transcribed to+ # nothing was silence, and re-sending it forever+ # would rebuild the very O(n²) loop this replaces.+ closed_bytes += cut+ tail = bytes(buffer[closed_bytes:])++ tail_text = ""+ if len(tail) >= min_bytes:+ tail_text, lang = await _transcribe(tail)+ language = lang or language+ if stop_event.is_set():+ return+ live = " ".join([*closed_parts, tail_text]).strip()+ if not live or live == last_published:continue- last_published = text+ last_published = livetry:await self._publish_event(DictationTranscript(source_layer="speech.dictation",- text=text,+ text=live,is_final=False,))@@ -7408,6 +7596,9 @@ class SpeechPipeline:except asyncio.CancelledError:pass+ final_text = ""+ raw_text = ""+ hung_up = Falsetry:async with MicrophoneCapture(device=self._input_device, device_priority=self._input_priority@@ -7416,48 +7607,80 @@ class SpeechPipeline:async def _drain() -> None:async for chunk in mic.stream():buffer.extend(chunk.pcm)+ # Feed the live loudness so the bar's equalizer moves+ # while dictating — same normalized RMS as the VAD and+ # PTT sites, zero cost when no overlay is subscribed.+ if mic_level.has_subscribers():+ samples = pcm_bytes_to_np(chunk.pcm)+ if samples.size:+ mic_level.feed(+ float(np.sqrt(np.mean(np.square(samples))))+ )drain_task = asyncio.create_task(_drain(), name="dictation-drain")- probe_task = asyncio.create_task(_probe(), name="dictation-probe")+ probe_task = (+ asyncio.create_task(_probe(), name="dictation-probe")+ if interval > 0+ else None+ )stop_task = asyncio.create_task(self._dictation_stop_event.wait())hangup_task = asyncio.create_task(self._hangup_event.wait())wait_set = {stop_task, hangup_task, drain_task}- all_tasks = [drain_task, probe_task, stop_task, hangup_task]try:- await asyncio.wait(+ done, _pending = await asyncio.wait(wait_set,timeout=self._dictation_max_s,return_when=asyncio.FIRST_COMPLETED,)+ hung_up = hangup_task in done or self._hangup_event.is_set()finally:- for t in all_tasks:+ # Freeze the probe BEFORE tearing anything else down so a+ # stop edge cannot race one more transcription into flight.+ stop_event.set()+ for t in (drain_task, stop_task, hangup_task):t.cancel()- for t in all_tasks:+ for t in (drain_task, stop_task, hangup_task):try:await texcept (asyncio.CancelledError, Exception): # noqa: BLE001pass- # One final transcription of the whole capture.- pcm = bytes(buffer)- final_text = ""- if len(pcm) >= min_bytes:- try:- transcript = await stt.transcribe_pcm(pcm)- final_text = (getattr(transcript, "text", "") or "").strip()- except Exception as exc: # noqa: BLE001- log.debug("dictation final transcribe failed: %s", exc)- try:- await self._publish_event(- DictationTranscript(- source_layer="speech.dictation",- text=final_text,- is_final=True,- )+ # The mic lease is closed before waiting on the probe, so releasing+ # the key always ends the recording even if a probe call is slow.+ if probe_task is not None:+ await self._stop_ptt_live_transcription(+ probe_task,+ stop_event=stop_event,+ inference_active=inference_active,+ wait_for_inference=not hung_up,)- except Exception as exc: # noqa: BLE001- log.debug("dictation final publish failed: %s", exc)- log.info("🎙️ dictation ended (%d chars).", len(final_text))++ if not hung_up:+ # Finalize ONLY the open tail — every closed segment is done.+ tail = bytes(buffer[closed_bytes:])+ tail_text = ""+ if len(tail) >= min_bytes:+ tail_text, lang = await _transcribe(tail)+ language = lang or language+ raw_text = " ".join([*closed_parts, tail_text]).strip()+ final_text = raw_text++ duration_s = max(0.0, time.monotonic() - started_at)+ result = await self._finish_dictation(+ raw_text=raw_text,+ language=language,+ duration_s=duration_s,+ target=target,+ hung_up=hung_up,+ )+ final_text = result+ log.info(+ "🎙️ dictation ended (%d chars, %.1fs, target=%s%s).",+ len(final_text),+ duration_s,+ target,+ ", hung up" if hung_up else "",+ )except Exception: # noqa: BLE001 — dictation must never break voicelog.warning("dictation session crashed (non-fatal)", exc_info=True)try:@@ -7469,6 +7692,156 @@ class SpeechPipeline:except Exception: # noqa: BLE001pass+ async def _finish_dictation(+ self,+ *,+ raw_text: str,+ language: str,+ duration_s: float,+ target: str,+ hung_up: bool,+ ) -> str:+ """Clean, deliver and record one finished dictation. Returns the text.++ Split out of ``_dictation_session`` so the delivery half is testable+ without a microphone. Every step degrades on its own: a failed cleanup+ 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.+ """+ cleaned = raw_text+ removed_words = 0+ cleanup_reason = ""+ cfg = getattr(self, "_dictation_cfg", None)++ if raw_text and not hung_up:+ try:+ from jarvis.dictation.cleanup import clean_transcript++ outcome = clean_transcript(+ raw_text,+ language=language,+ remove_fillers=bool(getattr(cfg, "remove_fillers", True)),+ max_removed_fraction=float(+ getattr(cfg, "filler_max_removed_fraction", 0.25)+ ),+ )+ cleaned = outcome.text+ removed_words = outcome.removed_words+ cleanup_reason = outcome.reason+ except Exception: # noqa: BLE001 — never lose the text to a cleanup bug+ log.warning("dictation cleanup failed; using the raw transcript",+ exc_info=True)+ cleaned = raw_text++ # Publish the final transcript first: the chat composer and the bar+ # both listen for it, and they should update even if insertion fails.+ try:+ await self._publish_event(+ DictationTranscript(+ source_layer="speech.dictation",+ text=cleaned,+ is_final=True,+ )+ )+ except Exception as exc: # noqa: BLE001+ log.debug("dictation final publish failed: %s", exc)++ # Resolve ``auto`` now: the foreground window at DELIVERY time is the+ # one the user means, not the one that happened to be in front when+ # recording started.+ resolved_target = target+ if target not in ("insert", "chat"):+ try:+ from jarvis.dictation.insert import resolve_target++ resolved_target = resolve_target(target)+ except Exception: # noqa: BLE001 — an unreadable foreground is not fatal+ log.debug("dictation target resolution failed", exc_info=True)+ resolved_target = "insert"++ outcome_name = "chat"+ detail = ""+ method = ""+ if hung_up:+ outcome_name = "cancelled"+ elif not cleaned.strip():+ outcome_name = "empty"+ elif resolved_target == "insert":+ insert_result = await asyncio.to_thread(self._insert_dictation, cleaned)+ outcome_name = insert_result.status+ detail = insert_result.detail+ method = insert_result.method++ try:+ await self._publish_event(+ DictationCompleted(+ source_layer="speech.dictation",+ text=cleaned,+ raw_text=raw_text,+ outcome=outcome_name,+ detail=detail,+ method=method,+ language=language,+ duration_s=duration_s,+ removed_words=removed_words,+ )+ )+ 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 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)),+ )+ except Exception: # noqa: BLE001 — history is never worth a failure+ log.debug("dictation history write failed", exc_info=True)++ return cleaned++ def _insert_dictation(self, text: str):+ """Blocking insertion, run off the event loop. Never raises.++ ``insert_text`` sleeps around the paste chord and talks to the OS+ clipboard, so it must not run on the pipeline's loop — a 250 ms block+ there is a stutter in the voice path.+ """+ from jarvis.dictation.insert import InsertResult, insert_text++ cfg = getattr(self, "_dictation_cfg", None)+ try:+ return insert_text(+ text,+ method=str(getattr(cfg, "insert_method", "clipboard")),+ paste_chord=str(getattr(cfg, "paste_chord", "auto")),+ delay_ms=int(getattr(cfg, "paste_delay_ms", 120)),+ delay_after_ms=int(getattr(cfg, "paste_delay_after_ms", 120)),+ restore_clipboard=bool(getattr(cfg, "restore_clipboard", True)),+ )+ except Exception as exc: # noqa: BLE001 — degrade to an honest report+ log.warning("dictation insertion failed: %s", exc, exc_info=True)+ return InsertResult(+ status="unavailable",+ detail=(+ "The text could not be inserted here. It is kept in the "+ "dictation history."+ ),+ clipboard_holds_text=False,+ )+async def _session_input_stream(self, chunks: AsyncIterator[AudioChunk]) -> AsyncIterator[AudioChunk]:@@ -10554,6 +10927,13 @@ async def _main() -> None:pipeline = SpeechPipeline(call_hotkeys=_call_hk,ptt_hotkeys=_ptt_hk,+ dictate_hotkeys=(+ (config.trigger.hotkey_dictate,)+ if config.trigger.hotkey_dictate.strip()+ else ()+ ),+ dictate_mode=config.dictation.mode,+ dictation_config=config.dictation,hangup_hotkeys=((config.trigger.hotkey_hangup,)if config.trigger.hotkey_hangup.strip()diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.pyindex a57c24d520..2fc1e63567 100644--- a/jarvis/speech/watchdog.py+++ b/jarvis/speech/watchdog.py@@ -125,6 +125,13 @@ async def _main() -> None:pipeline = SpeechPipeline(call_hotkeys=_call_hk,ptt_hotkeys=_ptt_hk,+ dictate_hotkeys=(+ (config.trigger.hotkey_dictate,)+ if config.trigger.hotkey_dictate.strip()+ else ()+ ),+ dictate_mode=config.dictation.mode,+ dictation_config=config.dictation,hangup_hotkeys=((config.trigger.hotkey_hangup,)if config.trigger.hotkey_hangup.strip()diff --git a/jarvis/trigger/backends/noop.py b/jarvis/trigger/backends/noop.pyindex a6c916d702..a700615d30 100644--- a/jarvis/trigger/backends/noop.py+++ b/jarvis/trigger/backends/noop.py@@ -1,12 +1,22 @@"""No-op hotkey backend for hosts where global hotkeys are unavailable (AD-8).Returned by ``make_hotkey_backend()`` when ``capabilities.has_hotkey`` is-``False`` — most importantly on a Linux **Wayland** session, where a process-cannot install a global keyboard grab by OS design (the compositor owns input-routing; there is no portable global-hotkey API). Rather than crash or silently-do nothing (the "said it worked, nothing happened" class — AD-OE6), this backend-logs one clear English message explaining the situation and then no-ops every-call. The voice path is unaffected: the user leans on the wake word.+``False``. Two quite different situations land here and they need different+answers, which is why :func:`explain_unavailable` measures rather than assumes:++* **Wayland** — a process cannot install a global keyboard grab by OS design+ (the compositor owns input routing). Nothing the user installs changes that;+ the fix is a compositor-level shortcut pointing at the CLI.+* **X11 without ``pynput``** — the far more common case, and entirely fixable:+ ``pip install 'personal-jarvis[desktop-linux]'``. It is a separate opt-in+ extra because pynput hard-requires ``evdev``, which is source-only and+ compiles against the kernel headers — pulling it into ``[full]`` would break+ the advertised install on a stock slim image.++Rather than crash or silently do nothing (the "said it worked, nothing+happened" class — AD-OE6), this backend logs one clear English message+explaining the actual situation and then no-ops every call. The voice path is+unaffected: the user leans on the wake word.The message is emitted at most once per process (a module-level flag), so arestart-heavy session does not spam the log.@@ -28,6 +38,63 @@ def _reset_noop_log_flag_for_tests() -> None:_LOGGED_ONCE = False+def explain_unavailable() -> str:+ """Why global hotkeys do not work here, and what (if anything) fixes it.++ The message used to say "Wayland" unconditionally, which was wrong on the+ far more common case: an X11 desktop where ``pynput`` simply is not+ installed. Telling a user their session is the problem when the fix is one+ ``pip install`` away is the "said it worked, nothing happened" class of+ dishonesty applied to a diagnostic — so the reason is now measured.++ English, user-facing, and safe to surface in the UI as well as the log.+ """+ try:+ from jarvis.platform import detect_platform+ from jarvis.platform.probes import is_wayland++ platform = detect_platform()+ except Exception: # noqa: BLE001 — a probe failure must not break the message+ return (+ "this host cannot register a global keyboard shortcut. Voice still "+ "works via the wake word, and dictation can be started from the "+ "Jarvis Bar, the Dictation view, or `jarvis api dictation start`."+ )++ if platform == "linux":+ try:+ wayland = is_wayland()+ except Exception: # noqa: BLE001+ wayland = False+ if wayland:+ return (+ "Wayland does not let an application grab a global shortcut — "+ "the compositor owns them by design. Bind a shortcut in your "+ "desktop settings to `jarvis api dictation start` instead; "+ "voice also still works via the wake word."+ )+ return (+ "the pynput package is not installed. On an X11 desktop, "+ "`pip install 'personal-jarvis[desktop-linux]'` enables global "+ "shortcuts (it builds evdev, so a C compiler and the kernel "+ "headers are required). Until then, use the wake word, the Jarvis "+ "Bar, or `jarvis api dictation start`."+ )++ if platform == "darwin":+ return (+ "macOS needs both the Accessibility and Input Monitoring "+ "permissions, and the pyobjc Quartz package. Grant them under "+ "Settings > Permissions, then restart Jarvis."+ )++ return (+ "the global-hotkeys package is not installed. `pip install "+ "'personal-jarvis[desktop]'` enables the shortcuts; voice still works "+ "via the wake word."+ )++class NoopBackend:"""A ``HotkeyBackend`` that explains itself once, then does nothing.@@ -44,11 +111,7 @@ class NoopBackend:if _LOGGED_ONCE:return_LOGGED_ONCE = True- log.info(- "Global hotkey unavailable on Wayland by OS design — leaning on the "- "wake word instead. Voice and the mascot click still work; on an X11 "- "session install the [desktop] extra to enable global hotkeys."- )+ log.info("Global hotkeys are unavailable here: %s", explain_unavailable())def register(self, bindings, on_event=None) -> None:return None@@ -66,4 +129,4 @@ class NoopBackend:return False-__all__ = ["NoopBackend", "_reset_noop_log_flag_for_tests"]+__all__ = ["NoopBackend", "_reset_noop_log_flag_for_tests", "explain_unavailable"]diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.pyindex 46209f9335..be9a06836e 100644--- a/jarvis/trigger/hotkey.py+++ b/jarvis/trigger/hotkey.py@@ -85,6 +85,14 @@ _MODIFIER_TOKENS = frozenset("ctrl", "control", "right_ctrl", "right_control","alt", "right_alt", "left_alt", "altgr","shift", "win", "window",+ # macOS Command. The Quartz backend has always decoded it+ # (``_FLAG_MASK_TO_TOKEN`` maps ``kCGEventFlagMaskCommand`` -> ``cmd``),+ # but it was missing here, so the validator treated Command as an+ # ordinary KEY. Consequence: every macOS-critical chord passed —+ # ``cmd+q``, ``cmd+w``, ``cmd+c``, ``cmd+space`` were all accepted while+ # their Windows equivalents were refused, and a user could bind "quit+ # the focused app" as their dictation key.+ "cmd", "command", "meta", "super",})@@ -102,21 +110,41 @@ _SOLO_SAFE_KEYS = frozenset({f"f{i}" for i in range(1, 25)}) | frozenset()-def validate_hotkey(combo: str) -> tuple[bool, str]:- """Validate a user-supplied push-to-talk hotkey string.+# Keys the OS keeps for itself no matter what the user wants.+# * F12 is permanently reserved for the debugger — Microsoft documents that it+# must not be registered as a hot key even when nothing is being debugged.+_RESERVED_SOLO_KEYS = frozenset({"f12"})++# Command-modified chords macOS assigns to universal system actions. Binding one+# as a trigger means the user loses that action (Cmd+Q quits the focused app,+# Cmd+W closes its window, Cmd+Space is Spotlight) — the exact class of mistake+# the Windows list below already prevented. These were all ACCEPTED before+# ``cmd`` became a recognised modifier.+_MACOS_CRITICAL_KEYS = frozenset({"c", "v", "x", "z", "q", "w", "a", "s", "space", "tab"})+++def validate_hotkey(combo: str, *, platform: str | None = None) -> tuple[bool, str]:+ """Validate a user-supplied hotkey string (call / hangup / dictate).Returns ``(ok, reason)``. ``reason`` is an English, user-facing sentencewhen ``ok`` is False (the UI surfaces it). The rules encode the CLAUDE.mdhotkey guidance so a bad combo can never reach the hotkey backend (where an- invalid registration would silently disable EVERY hotkey):+ invalid registration would silently disable that shortcut):* non-empty and parseable (``mod+mod+key`` syntax),* at least one non-modifier key (a combo of only Ctrl/Alt/Shift is dead),* a modifier OR a second key — a single bare key (``j``) as a globalhotkey fires on every keystroke while typing,* no Windows-key combos (reserved by the OS),- * not an OS-critical shortcut (Alt+F4 closes windows, Ctrl+C is- copy/interrupt).+ * not an OS-critical shortcut — Alt+F4 closes windows, Ctrl+C is+ copy/interrupt, and on the macOS side Cmd+Q/W/C/V/Space and friends,+ * not a permanently reserved key (F12 belongs to the debugger).++ ``platform`` (``"win32"`` / ``"darwin"`` / ``"linux"``) is only used to warn+ about a Command-based chord on a host that has no Command key; it defaults+ to the live platform and exists so tests are deterministic. The combo+ vocabulary itself stays platform-neutral: a config file may legitimately+ travel between a Mac and a PC."""if not combo or not combo.strip():return False, "Hotkey is empty."@@ -142,21 +170,58 @@ def validate_hotkey(combo: str) -> tuple[bool, str]:if any(p in ("win", "window") for p in modifiers):return False, "Windows-key combos are reserved by the OS — pick Ctrl/Alt/Shift."+ reserved = sorted(set(non_modifiers) & _RESERVED_SOLO_KEYS)+ if reserved:+ return False, (+ f"{reserved[0].upper()} is permanently reserved by the operating "+ "system (the debugger claims it) — choose another key."+ )+_CTRL = ("ctrl", "control", "right_ctrl", "right_control")_ALT = ("alt", "right_alt", "left_alt", "altgr")+ _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# shortcut is blocked while a richer combo that merely contains it (e.g.# Ctrl+Shift+C) stays allowed.ctrl_only = bool(modifiers) and all(p in _CTRL for p in modifiers)+ cmd_only = bool(modifiers) and all(p in _CMD for p in modifiers)if alt_held and "f4" in non_modifiers:return False, "Alt+F4 closes the active window — choose another combo."if ctrl_only and non_modifiers == ["c"]:return False, "Ctrl+C is the copy / interrupt shortcut — choose another combo."+ if cmd_only and len(non_modifiers) == 1 and non_modifiers[0] in _MACOS_CRITICAL_KEYS:+ return False, (+ f"Command+{non_modifiers[0].upper()} is a system shortcut on macOS "+ "(copy, quit, close, Spotlight and friends) — add Shift/Alt or "+ "choose another key."+ )++ if any(p in ("cmd", "command") for p in modifiers):+ host = platform if platform is not None else _detect_platform()+ if host not in (None, "darwin"):+ return False, (+ "There is no Command key on this computer — use Ctrl, Alt or "+ "Shift instead. (Command shortcuts work on macOS.)"+ )return True, ""+def _detect_platform() -> str | None:+ """The live platform id, or ``None`` when it cannot be determined.++ Lazy + fail-open: a hotkey the validator cannot place is better accepted+ (the backend then degrades honestly, per-combo) than rejected on a guess.+ """+ try:+ from jarvis.platform import detect_platform++ return detect_platform()+ except Exception: # noqa: BLE001 — validation must never depend on a probe+ return None++class HotkeyTrigger:"""Manages several named hotkey bindings at once.diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex 43cd1a41c6..f4a65b34e2 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2899,6 +2899,15 @@ 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.+ dictate_hotkeys=(+ (self.cfg.trigger.hotkey_dictate,)+ if self.cfg.trigger.hotkey_dictate.strip()+ else ()+ ),+ dictate_mode=self.cfg.dictation.mode,+ dictation_config=self.cfg.dictation,hangup_hotkeys=((self.cfg.trigger.hotkey_hangup,)if self.cfg.trigger.hotkey_hangup.strip()diff --git a/jarvis/ui/jarvisbar/interaction.py b/jarvis/ui/jarvisbar/interaction.pyindex b74009e04d..eea032c35b 100644--- a/jarvis/ui/jarvisbar/interaction.py+++ b/jarvis/ui/jarvisbar/interaction.py@@ -67,8 +67,17 @@ def resolve_click(instead of silently hanging up. This closes the "Jarvis hangs up by itself"trap (live bug 2026-06-19): the old code hung up on ANY click in the left40% of the bar, decoupled from the visible affordance.++ ``dictate`` (a dictation is recording) is inert on purpose: without this+ branch it would fall through to "not active" and a stray click would START+ A VOICE SESSION in the middle of dictating. There is always another way to+ stop — release the key, press it again in toggle mode, the Dictation view,+ or ``jarvis api dictation stop`` — so an inert bar costs nothing and cannot+ misfire."""frac = x / max(1, width)+ if mode == "dictate":+ return "none"active = mode in ("listen", "think", "speak")if frac >= 0.60: # right zone → the mic mute toggle (non-destructive)return "mute"diff --git a/jarvis/ui/jarvisbar/renderer.py b/jarvis/ui/jarvisbar/renderer.pyindex be1fdf758d..3e78e80317 100644--- a/jarvis/ui/jarvisbar/renderer.py+++ b/jarvis/ui/jarvisbar/renderer.py@@ -542,9 +542,18 @@ def visual_mode(``hold_s`` bridges the short gaps between words/sentences so the bars don'tflap back on every micro-pause.++ ``dictate`` is the fifth coarse mode (dictation runs outside the voice+ state machine entirely). It always renders as the equalizer: dictation is+ the user talking, the mic level is being fed, and there is nothing for a+ thinking indicator to represent. Handled BEFORE the audio-activity branches+ so a silent pause mid-dictation shows still bars rather than falling+ through to the thinking core."""if coarse_mode == "idle":return "idle"+ if coarse_mode == "dictate":+ return "speak"if playback_active or seconds_since_audible < hold_s:return "speak"if coarse_mode == "think":diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.pynew file mode 100644index 0000000000..f6aba09e8f--- /dev/null+++ b/jarvis/ui/web/dictation_routes.py@@ -0,0 +1,348 @@+"""REST API for dictation mode — hold a key, speak, text lands where you type.++Endpoints (mounted by the WebServer in ``_build_app()``):++ GET /api/dictation/status → capability + live state + the shortcut.+ POST /api/dictation/start → begin a dictation ({"target": ...}).+ POST /api/dictation/stop → finish the running one.+ GET /api/dictation/history → recent dictations (raw + cleaned).+ DELETE /api/dictation/history → purge everything (destructive).+ DELETE /api/dictation/history/{id} → drop one entry.+ GET /api/dictation/settings → the [dictation] block.+ PUT /api/dictation/settings → change one or more keys.++Why REST and not only the WebSocket command the chat mic button uses: under the+CLI-first contract (CLAUDE.md §5) a capability that exists only in the UI is not+finished. Mounting this router also makes every action a+``jarvis api dictation <op>`` command for free — and *that* is the documented+fallback on Wayland, where the compositor owns global shortcuts and the app+cannot bind one itself.++No Brain dependency, so it works headless and with a MockBrain; on a host with+no microphone the status endpoint answers honestly instead of 500-ing.+"""+from __future__ import annotations++import logging+from typing import Any++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, Field++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/dictation", tags=["dictation"])+++# ----------------------------------------------------------------------+# Helpers+# ----------------------------------------------------------------------+++def _config(request: Request) -> Any:+ return getattr(request.app.state, "config", None)+++def _pipeline() -> Any:+ """The live SpeechPipeline, or ``None`` (headless / voice disabled)."""+ try:+ from jarvis.core.runtime_refs import get_speech_pipeline++ return get_speech_pipeline()+ except Exception: # noqa: BLE001 — a missing runtime ref is "no pipeline"+ return None+++def _dictation_cfg(request: Request) -> Any:+ cfg = _config(request)+ dictation = getattr(cfg, "dictation", None) if cfg is not None else None+ if dictation is not None:+ return dictation+ from jarvis.core.config import DictationConfig++ return DictationConfig()+++# ----------------------------------------------------------------------+# Request models+# ----------------------------------------------------------------------+++class StartBody(BaseModel):+ target: str = Field(+ default="auto",+ description=(+ "auto = follow [dictation].target (insert, unless Jarvis itself is "+ "the window in front); insert = always paste into the app in front; "+ "chat = only publish the transcript (fills the chat composer)"+ ),+ )+++class SettingsBody(BaseModel):+ """Partial update — only the keys present are changed."""++ mode: str | None = None+ target: str | None = None+ insert_method: str | None = None+ paste_chord: str | None = None+ paste_delay_ms: int | None = None+ paste_delay_after_ms: int | None = None+ restore_clipboard: bool | None = None+ remove_fillers: bool | None = None+ filler_max_removed_fraction: float | None = None+ max_seconds: float | None = None+ partial_interval_s: float | None = None+ segment_seconds: float | None = None+ history_enabled: bool | None = None+ history_max_entries: int | None = None+ history_retention_days: int | None = None+ persist: bool = Field(+ default=True, description="Also write the change to jarvis.toml"+ )+++# ----------------------------------------------------------------------+# Status + control+# ----------------------------------------------------------------------++[email protected]("/status")+async def get_status(request: Request) -> dict[str, Any]:+ """Can dictation run here, is it running, and where would text go?++ Answers honestly on a host that cannot do it rather than hiding the+ feature: ``available`` false plus a ``reason`` the UI can show.+ """+ pipeline = _pipeline()+ cfg = _config(request)+ trigger = getattr(cfg, "trigger", None) if cfg is not None else None+ dictation = _dictation_cfg(request)++ available = False+ active = False+ reason = ""+ if pipeline is None:+ reason = "No speech pipeline is running (headless, or voice is disabled)."+ else:+ try:+ available = bool(pipeline.dictation_available())+ active = bool(pipeline.dictation_active())+ if not available:+ reason = "No microphone or no speech-to-text provider is configured."+ except Exception as exc: # noqa: BLE001 — never 500 a status probe+ log.debug("dictation availability probe failed: %s", exc)+ reason = "Dictation status could not be read."++ # Whether the transcript could actually be pasted into another app. This is+ # the honest part: on Wayland, on a headless host, or in front of an+ # elevated window it cannot, and saying so up front beats a silent no-op.+ insertion: dict[str, Any] = {"can_insert": False, "reason": "", "detail": ""}+ try:+ from jarvis.dictation.insert import describe_target++ report = describe_target()+ insertion = {+ "can_insert": report.can_insert,+ "reason": report.reason,+ "detail": report.detail,+ }+ except Exception as exc: # noqa: BLE001+ log.debug("insertion probe failed: %s", exc)++ return {+ "available": available,+ "active": active,+ "reason": reason,+ "hotkey": str(getattr(trigger, "hotkey_dictate", "") or ""),+ "mode": str(getattr(dictation, "mode", "hold")),+ "target": str(getattr(dictation, "target", "auto")),+ "insertion": insertion,+ }++[email protected]("/start")+async def start(body: StartBody, request: Request) -> dict[str, Any]:+ """Begin a dictation. 409 when the mic is busy, 503 when there is none."""+ pipeline = _pipeline()+ if pipeline is None:+ raise HTTPException(+ status_code=503,+ detail=(+ "Dictation needs a running speech pipeline with a microphone; "+ "this host has none."+ ),+ )+ # "auto" defers to the configured target, which the pipeline resolves+ # against the live foreground window at the moment recording starts.+ target = body.target if body.target in ("chat", "insert") else str(+ getattr(_dictation_cfg(request), "target", "auto") or "auto"+ )+ try:+ started = bool(pipeline.start_dictation(target=target))+ except Exception as exc: # noqa: BLE001+ log.warning("dictation start failed: %s", exc, exc_info=True)+ raise HTTPException(status_code=500, detail="Dictation could not start.") from exc+ if not started:+ raise HTTPException(+ status_code=409,+ detail=(+ "Dictation could not start — a voice session is running, "+ "dictation is already active, or the microphone is not ready."+ ),+ )+ return {"ok": True, "active": True, "target": target}++[email protected]("/stop")+async def stop() -> dict[str, Any]:+ """Finish the running dictation. Idempotent: stopping nothing is not an error."""+ pipeline = _pipeline()+ if pipeline is None:+ return {"ok": True, "stopped": False, "active": False}+ try:+ stopped = bool(pipeline.stop_dictation())+ except Exception as exc: # noqa: BLE001+ log.warning("dictation stop failed: %s", exc, exc_info=True)+ stopped = False+ return {"ok": True, "stopped": stopped, "active": False}+++# ----------------------------------------------------------------------+# History+# ----------------------------------------------------------------------++[email protected]("/history")+async def get_history(limit: int = 50) -> dict[str, Any]:+ """Recent dictations, newest first — raw text alongside the cleaned text.++ Local-only data. It exists so a filler-cleanup can be audited after the+ fact ("did it drop a word I actually said?") and so a transcript survives+ an insertion that had to fall back to the clipboard.+ """+ from jarvis.dictation.history import DictationHistory++ capped = max(1, min(int(limit or 50), 500))+ entries = DictationHistory().list_all()[:capped]+ return {"entries": [e.to_dict() for e in entries], "count": len(entries)}+++ "/history",+ openapi_extra={"x-jarvis-dangerous": True},+)+async def clear_history() -> dict[str, Any]:+ """Purge the whole dictation history. Irreversible."""+ from jarvis.dictation.history import DictationHistory++ return {"ok": bool(DictationHistory().clear())}++[email protected]("/history/{entry_id}")+async def delete_history_entry(entry_id: str) -> dict[str, Any]:+ """Drop one entry (idempotent — removing an absent id is not an error)."""+ from jarvis.dictation.history import DictationHistory++ return {"removed": bool(DictationHistory().delete(entry_id))}+++# ----------------------------------------------------------------------+# Settings+# ----------------------------------------------------------------------++[email protected]("/settings")+async def get_settings(request: Request) -> dict[str, Any]:+ """The live ``[dictation]`` block plus the accepted values per key."""+ from jarvis.core.config_writer import DICTATION_SETTING_KEYS++ dictation = _dictation_cfg(request)+ values = {key: getattr(dictation, key, None) for key in DICTATION_SETTING_KEYS}+ return {+ "settings": values,+ "choices": {+ "mode": ["hold", "toggle"],+ "target": ["auto", "insert", "chat"],+ "insert_method": ["clipboard", "type"],+ "paste_chord": ["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"],+ },+ }++[email protected]("/settings")+async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:+ """Change one or more ``[dictation]`` keys.++ Validated against ``DictationConfig`` BEFORE anything is written, so an+ out-of-range delay or an unknown mode is a 400 rather than a config file+ the app then refuses to boot from. Applies live to the running pipeline;+ ``max_seconds`` and the shortcut itself take effect immediately, and the+ rest are read per dictation anyway.+ """+ from jarvis.core.config import DictationConfig++ updates = {+ key: value+ for key, value in body.model_dump(exclude={"persist"}).items()+ if value is not None+ }+ if not updates:+ raise HTTPException(status_code=400, detail="No settings were provided.")++ dictation = _dictation_cfg(request)+ current = {+ key: getattr(dictation, key)+ for key in DictationConfig.model_fields+ if hasattr(dictation, key)+ }+ try:+ validated = DictationConfig(**{**current, **updates})+ except Exception as exc: # noqa: BLE001 — pydantic ValidationError and friends+ raise HTTPException(status_code=400, detail=f"Invalid setting: {exc}") from exc++ # In-memory first so a running pipeline sees the change even if the write+ # fails (a read-only config file must not silently drop the setting).+ for key in updates:+ try:+ setattr(dictation, key, getattr(validated, key))+ except Exception as exc: # noqa: BLE001 — frozen model is not an error+ log.debug("in-memory dictation.%s update skipped: %s", key, exc)++ persisted = False+ if body.persist:+ from jarvis.core import config_writer++ try:+ for key in updates:+ config_writer.set_dictation_setting(key, getattr(validated, key))+ persisted = True+ except Exception as exc: # noqa: BLE001+ log.warning("dictation settings persist failed: %s", exc)++ # Live-apply what the running pipeline caches at construction time.+ applied_live = False+ pipeline = _pipeline()+ if pipeline is not None:+ try:+ pipeline._dictation_cfg = dictation+ pipeline._dictation_max_s = float(validated.max_seconds)+ if "mode" in updates:+ pipeline._dictate_mode = validated.mode+ # The mode decides whether the binding wants both key edges,+ # so the trigger has to re-arm for a hold<->toggle switch.+ if hasattr(pipeline, "set_keybinds"):+ pipeline.set_keybinds()+ applied_live = True+ except Exception as exc: # noqa: BLE001 — never fail a save on live-apply+ log.warning("dictation settings live-apply failed: %s", exc)++ return {+ "ok": True,+ "settings": {+ key: getattr(validated, key)+ for key in DictationConfig.model_fields+ },+ "persisted": persisted,+ "applied_live": applied_live,+ }diff --git a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx b/jarvis/ui/web/frontend/src/components/layout/MainView.tsxindex c097cc13a7..6d5c3c21fe 100644--- a/jarvis/ui/web/frontend/src/components/layout/MainView.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/MainView.tsx@@ -89,6 +89,9 @@ const RunInspectorView = lazyView(() =>const DictionaryView = lazyView(() =>import("@/views/DictionaryView").then((m) => ({ default: m.DictionaryView })),);+const DictationView = lazyView(() =>+ import("@/views/DictationView").then((m) => ({ default: m.DictationView })),+);const AgentInstructionsView = lazyView(() =>import("@/views/AgentInstructionsView").then((m) => ({default: m.AgentInstructionsView,@@ -266,6 +269,8 @@ function SwitchOnActiveSection({ active }: { active: string }) {return <SettingsView />;case "dictionary":return <DictionaryView />;+ case "dictation":+ return <DictationView />;case "outputs":return <OutputsView />;case "socials":diff --git a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsxindex 79524063bd..143b4b55b9 100644--- a/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx+++ b/jarvis/ui/web/frontend/src/components/layout/Sidebar.tsx@@ -125,6 +125,12 @@ const NAV_GROUPS: NavItem[][] = [icon: BookA,fallbackLabel: "Dictionary",},+ {+ id: "dictation",+ labelKey: "nav.dictation",+ icon: Mic,+ fallbackLabel: "Dictation",+ },{ id: "outputs", labelKey: "nav.outputs", icon: FolderOpen },],// 4) Social links + in-app feedback.diff --git a/jarvis/ui/web/frontend/src/hooks/useDictation.ts b/jarvis/ui/web/frontend/src/hooks/useDictation.tsnew file mode 100644index 0000000000..5ec7eae718--- /dev/null+++ b/jarvis/ui/web/frontend/src/hooks/useDictation.ts@@ -0,0 +1,192 @@+import { useCallback, useEffect, useState } from "react";++/**+ * Live state of dictation mode from GET /api/dictation/status.+ *+ * `insertion` is the honest part: on Wayland, on a headless host, or in front+ * of an elevated window the transcript cannot be pasted into another app, and+ * the UI says so up front instead of letting the user discover it by dictating+ * into nothing.+ */+export interface DictationStatus {+ available: boolean;+ active: boolean;+ reason: string;+ hotkey: string;+ mode: string;+ target: string;+ insertion: {+ can_insert: boolean;+ reason: string;+ detail: string;+ };+}++/** One recorded dictation — raw transcript alongside what was inserted. */+export interface DictationEntry {+ id: string;+ created_at: string;+ raw_text: string;+ text: string;+ language: string;+ duration_s: number;+ outcome: string;+ method: string;+ removed_words: number;+ cleanup_reason: string;+}++export interface DictationSettings {+ mode: string;+ target: string;+ insert_method: string;+ paste_chord: string;+ paste_delay_ms: number;+ paste_delay_after_ms: number;+ restore_clipboard: boolean;+ remove_fillers: boolean;+ filler_max_removed_fraction: number;+ max_seconds: number;+ partial_interval_s: number;+ segment_seconds: number;+ history_enabled: boolean;+ history_max_entries: number;+ history_retention_days: number;+}++export interface DictationChoices {+ mode: string[];+ target: string[];+ insert_method: string[];+ paste_chord: string[];+}++async function unwrap<T>(res: Response): Promise<T> {+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error((body as { detail?: string }).detail ?? `HTTP ${res.status}`);+ }+ return body as T;+}++/**+ * Loads dictation status, settings and history, and exposes start/stop plus a+ * partial settings save. Mirrors useDictionary's fetch/error/loading shape.+ */+export function useDictation() {+ const [status, setStatus] = useState<DictationStatus | null>(null);+ const [settings, setSettings] = useState<DictationSettings | null>(null);+ const [choices, setChoices] = useState<DictationChoices | null>(null);+ const [entries, setEntries] = useState<DictationEntry[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string | null>(null);++ const refetchStatus = useCallback(async () => {+ try {+ const data = await unwrap<DictationStatus>(+ await fetch("/api/dictation/status"),+ );+ setStatus(data);+ } catch (e) {+ setError((e as Error).message);+ }+ }, []);++ const refetchHistory = useCallback(async () => {+ try {+ const data = await unwrap<{ entries: DictationEntry[] }>(+ await fetch("/api/dictation/history?limit=50"),+ );+ setEntries(data.entries ?? []);+ } catch (e) {+ setError((e as Error).message);+ }+ }, []);++ const refetch = useCallback(async () => {+ setError(null);+ try {+ const data = await unwrap<{+ settings: DictationSettings;+ choices: DictationChoices;+ }>(await fetch("/api/dictation/settings"));+ setSettings(data.settings);+ setChoices(data.choices);+ await Promise.all([refetchStatus(), refetchHistory()]);+ } catch (e) {+ setError((e as Error).message);+ } finally {+ setLoading(false);+ }+ }, [refetchStatus, refetchHistory]);++ useEffect(() => {+ void refetch();+ }, [refetch]);++ const start = useCallback(+ async (target: "auto" | "insert" | "chat" = "auto") => {+ await unwrap(+ await fetch("/api/dictation/start", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ target }),+ }),+ );+ await refetchStatus();+ },+ [refetchStatus],+ );++ const stop = useCallback(async () => {+ await unwrap(await fetch("/api/dictation/stop", { method: "POST" }));+ await refetchStatus();+ await refetchHistory();+ }, [refetchStatus, refetchHistory]);++ const saveSettings = useCallback(+ async (patch: Partial<DictationSettings>) => {+ const data = await unwrap<{ settings: DictationSettings }>(+ await fetch("/api/dictation/settings", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ ...patch, persist: true }),+ }),+ );+ setSettings(data.settings);+ await refetchStatus();+ },+ [refetchStatus],+ );++ const deleteEntry = useCallback(async (id: string) => {+ await unwrap(+ await fetch(`/api/dictation/history/${encodeURIComponent(id)}`, {+ method: "DELETE",+ }),+ );+ setEntries((prev) => prev.filter((e) => e.id !== id));+ }, []);++ const clearHistory = useCallback(async () => {+ await unwrap(await fetch("/api/dictation/history", { method: "DELETE" }));+ setEntries([]);+ }, []);++ return {+ status,+ settings,+ choices,+ entries,+ loading,+ error,+ start,+ stop,+ saveSettings,+ deleteEntry,+ clearHistory,+ refetch,+ refetchStatus,+ refetchHistory,+ };+}diff --git a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts b/jarvis/ui/web/frontend/src/hooks/useHotkey.tsindex 672e5f18a0..847ca87614 100644--- a/jarvis/ui/web/frontend/src/hooks/useHotkey.ts+++ b/jarvis/ui/web/frontend/src/hooks/useHotkey.ts@@ -296,7 +296,8 @@ export function validateCombo(return { status: "ok" };}-export type KeybindAction = "call" | "hangup";+// Mirrors KEYBIND_ACTIONS in jarvis/core/config_writer.py — keep in sync.+export type KeybindAction = "call" | "hangup" | "dictate";/** Response of GET /api/settings/keybinds. */export interface KeybindsConfig {diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 29121b6352..bef96b0aaa 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -83,6 +83,7 @@"apikeys": "API-Keys","settings": "Einstellungen","dictionary": "Wörterbuch",+ "dictation": "Diktat","telephony": "Telefonie","outputs": "Outputs","socials": "Socials",@@ -230,6 +231,43 @@"add_confirm": "Wort hinzufügen","research_preview": "Research Preview"},+ "dictation": {+ "title": "Diktat",+ "description": "Diktiertaste halten, sprechen — der Text erscheint dort, wo du gerade getippt hast. In jeder App, nicht nur in dieser.",+ "loading": "Diktat wird geprüft…",+ "state_active": "Nimmt auf",+ "state_ready": "Bereit",+ "state_unavailable": "Auf diesem Computer nicht verfügbar",+ "shortcut_set": "Halte {0}, um zu diktieren.",+ "shortcut_unset": "Noch keine Taste zugewiesen — Diktat geht auch über den Knopf unten.",+ "assign_hint": "Weise unter Einstellungen → Sprach-Tastenkürzel eine Taste zu, um überall zu diktieren.",+ "start": "Diktat starten",+ "stop": "Stopp",+ "saved": "Einstellung gespeichert",+ "cannot_insert_title": "Text kann gerade nicht in andere Apps geschrieben werden",+ "cannot_insert_generic": "Dein System blockiert, dass ein Programm in ein anderes tippt. Diktat funktioniert trotzdem — der Text landet in der Zwischenablage, du kannst ihn einfügen.",+ "settings_title": "So verhält sich das Diktat",+ "mode_label": "Tastenverhalten",+ "mode_hint": "hold = aufnehmen, solange die Taste gedrückt ist. toggle = einmal drücken startet, nochmal drücken stoppt.",+ "paste_chord_label": "Einfüge-Kürzel",+ "paste_chord_hint": "auto passt sich deinem System an. Terminals brauchen oft shift_insert.",+ "insert_method_label": "Wie der Text ankommt",+ "insert_method_hint": "clipboard fügt in einem Schritt ein. type tippt Zeichen für Zeichen — langsamer, funktioniert aber in Feldern, die Einfügen ignorieren.",+ "target_label": "Wohin der Text geht",+ "target_hint": "auto nutzt die App im Vordergrund, außer diese App ist vorne. chat füllt nur das Chatfeld.",+ "remove_fillers_label": "Füllwörter entfernen",+ "remove_fillers_hint": "Entfernt „äh“, „ähm“ und Ähnliches. Nur feste Regeln — nichts wird umformuliert, und eine Bereinigung, die zu viel entfernen würde, wird verworfen.",+ "restore_clipboard_label": "Zwischenablage zurücksetzen",+ "restore_clipboard_hint": "Stellt wieder her, was du vor dem Diktat kopiert hattest. Nur Text — ein kopiertes Bild lässt sich nicht wiederherstellen.",+ "history_label": "Verlauf speichern",+ "history_hint": "Bleibt nur auf diesem Computer, damit du nachsehen kannst, was die Bereinigung geändert hat, und Text rettest, den ein fehlgeschlagenes Einfügen verloren hat.",+ "history_title": "Letzte Diktate",+ "history_empty": "Noch nichts diktiert.",+ "clear_history": "Alle löschen",+ "raw_prefix": "Gehört:",+ "removed_words": "{0} Füllwort/-wörter entfernt",+ "delete_entry": "Diesen Eintrag löschen"+ },"voice_state": {"idle": "Bereit","listening": "Hört zu",@@ -1399,9 +1437,10 @@},"keybinds": {"title": "Sprach-Tastenkürzel",- "description": "Lege die Tasten für Anruf und Auflegen fest. Klick auf Aufnehmen und drücke deine Kombination — oder klick die Tasten auf der Bildschirm-Tastatur an. Änderungen greifen sofort.",+ "description": "Lege die Tasten für Anruf, Auflegen und Diktat fest. Klick auf Aufnehmen und drücke deine Kombination — oder klick die Tasten auf der Bildschirm-Tastatur an. Änderungen greifen sofort.","call_label": "Anruf (annehmen / Sprechen starten)","hangup_label": "Auflegen",+ "dictate_label": "Diktat (halten und sprechen, Text landet dort, wo du tippst)","record": "Aufnehmen","stop": "Stopp","recording": "Drücke deine Tasten…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 59604c4400..47ac417f32 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -83,6 +83,7 @@"apikeys": "API Keys","settings": "Settings","dictionary": "Dictionary",+ "dictation": "Dictation","telephony": "Telephony","outputs": "Outputs","socials": "Socials",@@ -230,6 +231,43 @@"add_confirm": "Add word","research_preview": "Research Preview"},+ "dictation": {+ "title": "Dictation",+ "description": "Hold your dictation key, speak, and the text appears in whatever field you were typing in — any app, not just this one.",+ "loading": "Checking dictation…",+ "state_active": "Recording",+ "state_ready": "Ready",+ "state_unavailable": "Not available on this computer",+ "shortcut_set": "Hold {0} to dictate.",+ "shortcut_unset": "No key assigned yet — dictation still works from the button below.",+ "assign_hint": "Assign a key in Settings → Voice Keybinds to dictate from anywhere.",+ "start": "Start dictating",+ "stop": "Stop",+ "saved": "Setting saved",+ "cannot_insert_title": "Text cannot be typed into other apps right now",+ "cannot_insert_generic": "Your system is blocking one program from typing into another. Dictation still works — the text is placed on your clipboard so you can paste it.",+ "settings_title": "How dictation behaves",+ "mode_label": "Key behaviour",+ "mode_hint": "hold = record while the key is down. toggle = press once to start, again to stop.",+ "paste_chord_label": "Paste shortcut",+ "paste_chord_hint": "auto fits your system. Terminals often need shift_insert.",+ "insert_method_label": "How the text is delivered",+ "insert_method_hint": "clipboard pastes in one step. type writes it character by character — slower, but works in fields that ignore paste.",+ "target_label": "Where the text goes",+ "target_hint": "auto uses the app in front, except when this app is in front. chat only fills the chat box.",+ "remove_fillers_label": "Remove filler sounds",+ "remove_fillers_hint": "Drops “um”, “uh” and their equivalents. Fixed rules only — nothing is reworded, and a cleanup that would remove too much is discarded.",+ "restore_clipboard_label": "Put my clipboard back",+ "restore_clipboard_hint": "Restores what you had copied before dictating. Text only — a copied image cannot be restored.",+ "history_label": "Keep a history",+ "history_hint": "Stored on this computer only, so you can check what the cleanup changed and recover text a failed paste lost.",+ "history_title": "Recent dictations",+ "history_empty": "Nothing dictated yet.",+ "clear_history": "Delete all",+ "raw_prefix": "Heard:",+ "removed_words": "{0} filler word(s) removed",+ "delete_entry": "Delete this entry"+ },"voice_state": {"idle": "Ready","listening": "Listening",@@ -1400,9 +1438,10 @@},"keybinds": {"title": "Voice Keybinds",- "description": "Set the keys for Call and Hangup. Click Record and press your combination — or click keys on the on-screen keyboard. Changes apply instantly.",+ "description": "Set the keys for Call, Hangup and Dictation. Click Record and press your combination — or click keys on the on-screen keyboard. Changes apply instantly.","call_label": "Call (answer / start talking)","hangup_label": "Hangup",+ "dictate_label": "Dictation (hold to speak, text lands where you type)","record": "Record","stop": "Stop","recording": "Press your keys…",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex cd2916dc6e..275453b162 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -83,6 +83,7 @@"apikeys": "Claves API","settings": "Ajustes","dictionary": "Diccionario",+ "dictation": "Dictado","telephony": "Telefonía","outputs": "Salidas","socials": "Redes",@@ -230,6 +231,43 @@"add_confirm": "Añadir palabra","research_preview": "Research Preview"},+ "dictation": {+ "title": "Dictado",+ "description": "Mantén pulsada tu tecla de dictado, habla, y el texto aparece donde estabas escribiendo — en cualquier app, no solo en esta.",+ "loading": "Comprobando el dictado…",+ "state_active": "Grabando",+ "state_ready": "Listo",+ "state_unavailable": "No disponible en este ordenador",+ "shortcut_set": "Mantén {0} para dictar.",+ "shortcut_unset": "Aún no hay tecla asignada — el dictado también funciona con el botón de abajo.",+ "assign_hint": "Asigna una tecla en Ajustes → Atajos de voz para dictar desde cualquier sitio.",+ "start": "Empezar a dictar",+ "stop": "Detener",+ "saved": "Ajuste guardado",+ "cannot_insert_title": "Ahora mismo no se puede escribir en otras apps",+ "cannot_insert_generic": "Tu sistema impide que un programa escriba en otro. El dictado sigue funcionando — el texto queda en el portapapeles para que lo pegues.",+ "settings_title": "Cómo se comporta el dictado",+ "mode_label": "Comportamiento de la tecla",+ "mode_hint": "hold = graba mientras la tecla está pulsada. toggle = una pulsación empieza, otra detiene.",+ "paste_chord_label": "Atajo de pegado",+ "paste_chord_hint": "auto se adapta a tu sistema. Las terminales suelen necesitar shift_insert.",+ "insert_method_label": "Cómo llega el texto",+ "insert_method_hint": "clipboard pega de una vez. type lo escribe carácter a carácter — más lento, pero funciona en campos que ignoran el pegado.",+ "target_label": "Adónde va el texto",+ "target_hint": "auto usa la app en primer plano, salvo cuando esta app lo está. chat solo rellena el cuadro de chat.",+ "remove_fillers_label": "Quitar muletillas",+ "remove_fillers_hint": "Elimina “eh”, “em” y similares. Solo reglas fijas — nada se reformula, y una limpieza que quitaría demasiado se descarta.",+ "restore_clipboard_label": "Restaurar mi portapapeles",+ "restore_clipboard_hint": "Devuelve lo que habías copiado antes de dictar. Solo texto — una imagen copiada no se puede restaurar.",+ "history_label": "Guardar historial",+ "history_hint": "Se queda solo en este ordenador, para que veas qué cambió la limpieza y recuperes texto que un pegado fallido perdió.",+ "history_title": "Dictados recientes",+ "history_empty": "Todavía no has dictado nada.",+ "clear_history": "Borrar todo",+ "raw_prefix": "Se oyó:",+ "removed_words": "{0} muletilla(s) eliminada(s)",+ "delete_entry": "Eliminar esta entrada"+ },"voice_state": {"idle": "Listo","listening": "Escuchando",@@ -1399,9 +1437,10 @@},"keybinds": {"title": "Atajos de voz",- "description": "Configura las teclas para Llamar y Colgar. Pulsa Grabar y presiona tu combinación — o haz clic en las teclas del teclado en pantalla. Los cambios se aplican al instante.",+ "description": "Configura las teclas para Llamar, Colgar y Dictado. Pulsa Grabar y presiona tu combinación — o haz clic en las teclas del teclado en pantalla. Los cambios se aplican al instante.","call_label": "Llamar (responder / empezar a hablar)","hangup_label": "Colgar",+ "dictate_label": "Dictado (mantén pulsado y habla, el texto va donde escribes)","record": "Grabar","stop": "Detener","recording": "Presiona tus teclas…",diff --git a/jarvis/ui/web/frontend/src/store/events.ts b/jarvis/ui/web/frontend/src/store/events.tsindex 34da56f581..fdbe9780b3 100644--- a/jarvis/ui/web/frontend/src/store/events.ts+++ b/jarvis/ui/web/frontend/src/store/events.ts@@ -37,6 +37,7 @@ export type SectionId =| "feedback"| "agent-instructions"| "dictionary"+ | "dictation"| "agentic-ide";export const SECTION_IDS = [@@ -66,6 +67,7 @@ export const SECTION_IDS = ["feedback","agent-instructions","dictionary",+ "dictation","agentic-ide",] as const satisfies readonly SectionId[];@@ -104,6 +106,7 @@ export const SECTION_LABELS: Record<SectionId, string> = {feedback: "Feedback","agent-instructions": "Agent Instructions",dictionary: "Dictionary",+ dictation: "Dictation","agentic-ide": "Agentic IDE",};diff --git a/jarvis/ui/web/frontend/src/views/DictationView.tsx b/jarvis/ui/web/frontend/src/views/DictationView.tsxnew file mode 100644index 0000000000..63641b5e81--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/DictationView.tsx@@ -0,0 +1,393 @@+import { useState } from "react";+import {+ AlertTriangle,+ Keyboard,+ Loader2,+ Mic,+ Square,+ Trash2,+} from "lucide-react";+import { ViewHeader } from "@/views/ChatsView";+import { Button } from "@/components/ui/button";+import { Switch } from "@/components/ui/switch";+import { useDictation, type DictationEntry } from "@/hooks/useDictation";+import { useEventStore } from "@/store/events";+import { useT } from "@/i18n";++/**+ * "Dictation" section — hold a key, speak, and the text lands in whatever text+ * field currently has focus.+ *+ * Two things this view deliberately makes visible rather than hiding:+ *+ * 1. **Whether insertion can work at all.** On Wayland, on a headless host, or+ * while an elevated window is in front, the OS blocks one program from+ * typing into another — and does so silently. The banner says it up front so+ * "nothing happened" is never a mystery.+ * 2. **What the filler cleanup changed.** Every entry keeps the raw transcript+ * next to the inserted one, so a wrong rule is findable instead of merely+ * suspected.+ *+ * Backed by /api/dictation (status/start/stop/settings/history) via useDictation.+ */+export function DictationView() {+ const t = useT();+ const {+ status,+ settings,+ choices,+ entries,+ loading,+ error,+ start,+ stop,+ saveSettings,+ deleteEntry,+ clearHistory,+ } = useDictation();+ const pushToast = useEventStore((s) => s.pushToast);+ const [busy, setBusy] = useState(false);++ async function onToggle() {+ setBusy(true);+ try {+ if (status?.active) {+ await stop();+ } else {+ // "auto" — the backend decides at delivery time whether the text goes+ // into the app in front or into this app's own input box, so starting+ // here and then switching to the target application works.+ await start("auto");+ }+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setBusy(false);+ }+ }++ async function onSave(patch: Record<string, unknown>) {+ try {+ await saveSettings(patch);+ pushToast("success", t("dictation.saved"));+ } catch (e) {+ pushToast("error", (e as Error).message);+ }+ }++ const blocked = status?.insertion && !status.insertion.can_insert;++ return (+ <div className="flex h-full flex-col">+ <ViewHeader+ icon={<Mic className="h-4 w-4 text-primary" />}+ title={t("dictation.title")}+ subtitle={t("dictation.description")}+ />+ <div className="flex-1 overflow-y-auto scrollbar-jarvis p-6">+ <div className="mx-auto flex max-w-3xl flex-col gap-4">+ {error && <p className="text-xs text-destructive">{error}</p>}++ {/* --- Insertion warning: the silent-failure paths, made loud. --- */}+ {blocked && (+ <div+ className="flex items-start gap-3 rounded-lg border border-amber-500/40 bg-amber-500/10 p-4"+ data-testid="dictation-insert-warning"+ >+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0 text-amber-500" />+ <div className="min-w-0">+ <h4 className="font-display text-sm font-semibold">+ {t("dictation.cannot_insert_title")}+ </h4>+ <p className="mt-1 text-xs text-muted-foreground">+ {status?.insertion.detail || t("dictation.cannot_insert_generic")}+ </p>+ </div>+ </div>+ )}++ {/* --- Status + the big button. --- */}+ <div className="rounded-lg border border-border bg-card/60 p-4">+ {loading ? (+ <div className="flex items-center gap-2 text-xs text-muted-foreground">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ {t("dictation.loading")}+ </div>+ ) : (+ <div className="flex flex-wrap items-center justify-between gap-3">+ <div className="min-w-0">+ <div className="flex items-center gap-2">+ <span+ className={`h-2 w-2 shrink-0 rounded-full ${+ status?.active+ ? "animate-pulse bg-primary"+ : status?.available+ ? "bg-emerald-500"+ : "bg-muted-foreground/50"+ }`}+ />+ <span className="text-sm font-medium">+ {status?.active+ ? t("dictation.state_active")+ : status?.available+ ? t("dictation.state_ready")+ : t("dictation.state_unavailable")}+ </span>+ </div>+ <p className="mt-1 text-xs text-muted-foreground">+ {status?.available+ ? status.hotkey+ ? t("dictation.shortcut_set").replace("{0}", status.hotkey)+ : t("dictation.shortcut_unset")+ : status?.reason || t("dictation.state_unavailable")}+ </p>+ </div>+ <Button+ size="sm"+ className="gap-1.5"+ disabled={busy || !status?.available}+ data-testid="dictation-toggle"+ onClick={() => void onToggle()}+ >+ {busy ? (+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ ) : status?.active ? (+ <Square className="h-3.5 w-3.5" />+ ) : (+ <Mic className="h-3.5 w-3.5" />+ )}+ {status?.active ? t("dictation.stop") : t("dictation.start")}+ </Button>+ </div>+ )}+ {!status?.hotkey && status?.available && (+ <p className="mt-3 flex items-center gap-1.5 text-xs text-muted-foreground">+ <Keyboard className="h-3.5 w-3.5" />+ {t("dictation.assign_hint")}+ </p>+ )}+ </div>++ {/* --- Settings. --- */}+ {settings && choices && (+ <div className="rounded-lg border border-border bg-card/60 p-4">+ <h4 className="font-display text-sm font-semibold">+ {t("dictation.settings_title")}+ </h4>+ <div className="mt-3 grid gap-3 sm:grid-cols-2">+ <SelectRow+ label={t("dictation.mode_label")}+ hint={t("dictation.mode_hint")}+ value={settings.mode}+ options={choices.mode}+ testId="dictation-mode"+ onChange={(v) => void onSave({ mode: v })}+ />+ <SelectRow+ label={t("dictation.paste_chord_label")}+ hint={t("dictation.paste_chord_hint")}+ value={settings.paste_chord}+ options={choices.paste_chord}+ testId="dictation-paste-chord"+ onChange={(v) => void onSave({ paste_chord: v })}+ />+ <SelectRow+ label={t("dictation.insert_method_label")}+ hint={t("dictation.insert_method_hint")}+ value={settings.insert_method}+ options={choices.insert_method}+ testId="dictation-insert-method"+ onChange={(v) => void onSave({ insert_method: v })}+ />+ <SelectRow+ label={t("dictation.target_label")}+ hint={t("dictation.target_hint")}+ value={settings.target}+ options={choices.target}+ testId="dictation-target"+ onChange={(v) => void onSave({ target: v })}+ />+ </div>+ <div className="mt-4 flex flex-col gap-3">+ <SwitchRow+ label={t("dictation.remove_fillers_label")}+ hint={t("dictation.remove_fillers_hint")}+ checked={settings.remove_fillers}+ testId="dictation-remove-fillers"+ onChange={(v) => void onSave({ remove_fillers: v })}+ />+ <SwitchRow+ label={t("dictation.restore_clipboard_label")}+ hint={t("dictation.restore_clipboard_hint")}+ checked={settings.restore_clipboard}+ testId="dictation-restore-clipboard"+ onChange={(v) => void onSave({ restore_clipboard: v })}+ />+ <SwitchRow+ label={t("dictation.history_label")}+ hint={t("dictation.history_hint")}+ checked={settings.history_enabled}+ testId="dictation-history-enabled"+ onChange={(v) => void onSave({ history_enabled: v })}+ />+ </div>+ </div>+ )}++ {/* --- History. --- */}+ <div className="rounded-lg border border-border bg-card/60 p-4">+ <div className="flex items-center justify-between gap-3">+ <h4 className="font-display text-sm font-semibold">+ {t("dictation.history_title")}+ </h4>+ {entries.length > 0 && (+ <Button+ size="sm"+ variant="ghost"+ className="gap-1.5 text-xs"+ data-testid="dictation-clear-history"+ onClick={() => {+ void clearHistory().catch((e) =>+ pushToast("error", (e as Error).message),+ );+ }}+ >+ <Trash2 className="h-3.5 w-3.5" />+ {t("dictation.clear_history")}+ </Button>+ )}+ </div>+ {entries.length === 0 ? (+ <p className="mt-3 text-xs text-muted-foreground">+ {t("dictation.history_empty")}+ </p>+ ) : (+ <ul+ className="mt-3 divide-y divide-border/60"+ data-testid="dictation-history"+ >+ {entries.map((entry) => (+ <HistoryRow+ key={entry.id}+ entry={entry}+ onDelete={() => {+ void deleteEntry(entry.id).catch((e) =>+ pushToast("error", (e as Error).message),+ );+ }}+ />+ ))}+ </ul>+ )}+ </div>+ </div>+ </div>+ </div>+ );+}++function SelectRow({+ label,+ hint,+ value,+ options,+ testId,+ onChange,+}: {+ label: string;+ hint: string;+ value: string;+ options: string[];+ testId: string;+ onChange: (value: string) => void;+}) {+ return (+ <label className="flex flex-col gap-1">+ <span className="text-xs font-medium">{label}</span>+ <select+ value={value}+ data-testid={testId}+ onChange={(e) => onChange(e.target.value)}+ className="rounded-md border border-input bg-background px-2 py-1.5 text-sm focus:outline-none focus:ring-1 focus:ring-primary"+ >+ {options.map((option) => (+ <option key={option} value={option}>+ {option}+ </option>+ ))}+ </select>+ <span className="text-[11px] text-muted-foreground">{hint}</span>+ </label>+ );+}++function SwitchRow({+ label,+ hint,+ checked,+ testId,+ onChange,+}: {+ label: string;+ hint: string;+ checked: boolean;+ testId: string;+ onChange: (checked: boolean) => void;+}) {+ return (+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0">+ <p className="text-xs font-medium">{label}</p>+ <p className="text-[11px] text-muted-foreground">{hint}</p>+ </div>+ <Switch checked={checked} onCheckedChange={onChange} data-testid={testId} />+ </div>+ );+}++function HistoryRow({+ entry,+ onDelete,+}: {+ entry: DictationEntry;+ onDelete: () => void;+}) {+ const t = useT();+ const cleaned = entry.text !== entry.raw_text;+ return (+ <li className="group flex items-start gap-2 py-2.5">+ <div className="min-w-0 flex-1">+ <p className="break-words text-sm">{entry.text || entry.raw_text}</p>+ {cleaned && (+ <p className="mt-0.5 break-words text-[11px] text-muted-foreground">+ {t("dictation.raw_prefix")} {entry.raw_text}+ </p>+ )}+ <div className="mt-1 flex flex-wrap items-center gap-2 text-[10px] text-muted-foreground">+ <span>{new Date(entry.created_at).toLocaleString()}</span>+ {entry.outcome && (+ <span className="rounded-full border border-border bg-muted/60 px-1.5 py-0.5">+ {entry.outcome}+ </span>+ )}+ {entry.removed_words > 0 && (+ <span>+ {t("dictation.removed_words").replace(+ "{0}",+ String(entry.removed_words),+ )}+ </span>+ )}+ </div>+ </div>+ <button+ type="button"+ onClick={onDelete}+ aria-label={t("dictation.delete_entry")}+ className="rounded p-1 text-muted-foreground opacity-0 transition group-hover:opacity-100 hover:text-destructive"+ >+ <Trash2 className="h-3.5 w-3.5" />+ </button>+ </li>+ );+}diff --git a/jarvis/ui/web/frontend/src/views/SettingsView.tsx b/jarvis/ui/web/frontend/src/views/SettingsView.tsxindex 33f709767f..6262e2df6e 100644--- a/jarvis/ui/web/frontend/src/views/SettingsView.tsx+++ b/jarvis/ui/web/frontend/src/views/SettingsView.tsx@@ -774,6 +774,7 @@ function formatCombo(combo: string): string {const _KEYBIND_ROWS: { action: KeybindAction; labelKey: string }[] = [{ action: "call", labelKey: "settings_view.keybinds.call_label" },{ action: "hangup", labelKey: "settings_view.keybinds.hangup_label" },+ { action: "dictate", labelKey: "settings_view.keybinds.dictate_label" },];/**@@ -824,6 +825,7 @@ const _KB_PLATFORM = detectKeyboardPlatform();const _ACTION_LABEL_KEY: Record<KeybindAction, string> = {call: "settings_view.keybinds.call_label",hangup: "settings_view.keybinds.hangup_label",+ dictate: "settings_view.keybinds.dictate_label",};/** The combo rendered as keycap chips ("Ctrl + F5" → [Ctrl] + [F5]). */diff --git a/jarvis/ui/web/schema.py b/jarvis/ui/web/schema.pyindex eec48ae6c9..a2b2388796 100644--- a/jarvis/ui/web/schema.py+++ b/jarvis/ui/web/schema.py@@ -75,8 +75,10 @@ class WSCommand(BaseModel):"terminal.input","terminal.resize","terminal.close",- # Chat mic-dictation: payload {"mode": "start" | "stop"}. Transcribe-only- # into the chat input — never reaches the brain.+ # Mic-dictation: payload {"mode": "start" | "stop", "target": "chat" |+ # "insert"}. Transcribe-only — never reaches the brain. "chat" (the+ # default) fills the composer; "insert" pastes into the focused field+ # of whatever application is in front."stt_dictate",# Drag-drop a mission/output card onto the Jarvis dock: payload# {slug, utterance, status, summary?, error?, mission_id?, thread_id?}.diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex c591c2a5a3..d694e5ee25 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -316,6 +316,7 @@ class WebServer:from .contacts_routes import router as contacts_routerfrom .control_routes import router as control_routerfrom .diagnostics_routes import router as diagnostics_router+ from .dictation_routes import router as dictation_routerfrom .dictionary_routes import router as dictionary_routerfrom .docs_routes import router as docs_routerfrom .downloads_routes import router as downloads_router@@ -442,6 +443,10 @@ class WebServer:# Contacts section — user-curated address book (pure file store, no Brain dep).app.include_router(contacts_router)app.include_router(dictionary_router)+ # Dictation mode — hold to speak, text lands in the focused field.+ # Mounted so every action is also `jarvis api dictation <op>`, which is+ # the documented Wayland path (no app-owned global shortcuts there).+ app.include_router(dictation_router)app.include_router(workflows_router)if conductor_router is not None:app.include_router(conductor_router)@@ -1583,6 +1588,10 @@ class WebServer:from jarvis.core.runtime_refs import get_speech_pipelinemode = str(payload.get("mode", "start"))+ # "chat" (default) fills the composer; "insert" is dictation mode —+ # the transcript is pasted into the focused field of whatever app is in+ # front. The chat mic button never sends "insert".+ target = "insert" if str(payload.get("target", "chat")) == "insert" else "chat"pipeline = get_speech_pipeline()if pipeline is None:# Headless / voice disabled — no server mic. Recoverable, not fatal:@@ -1602,7 +1611,7 @@ class WebServer:if mode == "stop":pipeline.stop_dictation()else:- started = pipeline.start_dictation()+ started = pipeline.start_dictation(target=target)if not started:await self.bus.publish(ErrorOccurred(diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex a05b9882a4..dcbe8258d9 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -1281,7 +1281,7 @@ def _keybind_values(trig: object) -> dict[str, str]:class KeybindBody(BaseModel):- action: str = Field(..., description="call | hangup")+ action: str = Field(..., description="call | hangup | dictate")hotkey: str = Field(..., max_length=64)persist: bool = Field(default=True, description="Persist to jarvis.toml")@@ -1299,7 +1299,12 @@ async def get_keybinds(request: Request) -> dict[str, object]:restart_required = pipeline is None or not hasattr(pipeline, "set_keybinds")return {"keybinds": _keybind_values(trig),- "defaults": {"call": d.hotkey_call, "hangup": d.hotkey_hangup},+ "defaults": {+ "call": d.hotkey_call,+ "hangup": d.hotkey_hangup,+ # Dictation ships unbound on purpose — see TriggerConfig.hotkey_dictate.+ "dictate": d.hotkey_dictate,+ },"suggestions": list(_KEYBIND_SUGGESTIONS),"restart_required": restart_required,}diff --git a/pyproject.toml b/pyproject.tomlindex 958cbeb9a7..c933ad45d5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -344,6 +344,23 @@ desktop = [# base install never pulls them in. Linux's AT-SPI uses distro-packaged pyatspi# (``apt install python3-pyatspi gir1.2-atspi-2.0``), surfaced via the# ``capabilities.has_ax_tree`` runtime probe — it is NEVER a pip dependency.+# Linux DESKTOP input extras — deliberately opt-in and NOT part of [full].+#+# Global hotkeys on Linux/X11 need pynput, and pynput hard-requires ``evdev``,+# which ships source-only and compiles against the kernel headers. Pulling that+# into [full] would break the one advertised install path on a stock+# python:3.11-slim image — exactly what the cloud-first rule forbids. So it+# lives here: a Linux desktop user who wants a global dictation/call shortcut+# installs ``personal-jarvis[desktop-linux]`` (needs a C compiler and+# linux-headers), and everyone else gets the honest, logged no-op instead of a+# failed install.+#+# Wayland is a separate matter and this extra does NOT fix it: Wayland blocks+# global key grabs by design, so shortcuts there belong to the compositor.+# See docs/os-parity.md.+desktop-linux = [+ "pynput>=1.7; sys_platform == 'linux'",+]desktop-macos = [# The managed-install app bundle keeps a native Mach-O launcher: a shell# CFBundleExecutable that execs external Python has no stable TCCdiff --git a/tests/unit/dictation/__init__.py b/tests/unit/dictation/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/tests/unit/dictation/test_cleanup.py b/tests/unit/dictation/test_cleanup.pynew file mode 100644index 0000000000..d1da3014da--- /dev/null+++ b/tests/unit/dictation/test_cleanup.py@@ -0,0 +1,228 @@+"""Filler-word cleanup: remove hesitation sounds, never content words.++The value of a dictation feature is "these are my words", so the tests that+matter most here are the NEGATIVE ones: words that look like filler to a style+guide but carry meaning must survive, an unknown language must be a no-op, and+a cleanup that would eat too much must be refused outright.+"""+from __future__ import annotations++import pytest++from jarvis.dictation.cleanup import (+ FILLER_WORDS,+ SUPPORTED_LANGUAGES,+ clean_transcript,+ normalize_language,+)++# --------------------------------------------------------------------------+# Removal actually happens, in every supported language+# --------------------------------------------------------------------------+++ ("text", "language", "expected"),+ [+ (+ "Uh, I think we should um ship it tomorrow.",+ "en",+ "I think we should ship it tomorrow.",+ ),+ (+ "Ähm, das ist äh wirklich gut geworden.", # i18n-allow: German fixture under test (§1 list #4)+ "de",+ "Das ist wirklich gut geworden.", # i18n-allow: German fixture under test (§1 list #4)+ ),+ (+ "Eh, creo que em deberíamos enviarlo.",+ "es",+ "Creo que deberíamos enviarlo.",+ ),+ ],+)+def test_removes_hesitation_sounds(text: str, language: str, expected: str) -> None:+ result = clean_transcript(text, language=language)+ assert result.applied is True+ assert result.text == expected+ assert result.raw == text # the raw transcript is always preserved+ assert result.removed_words == 2+++def test_every_supported_language_has_rules() -> None:+ """A language in the set must actually have a non-empty table."""+ for language in SUPPORTED_LANGUAGES:+ assert FILLER_WORDS[language], language+++# --------------------------------------------------------------------------+# Content words must survive — the failure mode that matters+# --------------------------------------------------------------------------+++ ("text", "language"),+ [+ # English words every style guide calls filler, but which change meaning.+ ("I like this, actually it is basically fine.", "en"),+ ("So right, well then, you know the answer.", "en"),+ # German particles that are ordinary vocabulary.+ ("Also halt eben das Thema.", "de"),+ ("Ja nun gut, das machen wir so.", "de"),+ # Spanish words that are demonstratives / connectives, not fillers.+ ("Este informe es bueno, pues claro.", "es"),+ ("O sea que vale, entonces seguimos.", "es"),+ ],+)+def test_content_words_are_never_removed(text: str, language: str) -> None:+ result = clean_transcript(text, language=language)+ assert result.removed_words == 0+ assert result.text == text+++def test_filler_inside_a_word_is_not_touched() -> None:+ """Whole-word matching only — "umbrella" must not lose its "um"."""+ text = "The umbrella and the ehrenamt are fine."+ assert clean_transcript(text, language="en").text == text+++# --------------------------------------------------------------------------+# The destruction ceiling+# --------------------------------------------------------------------------+++def test_all_filler_input_is_refused_rather_than_emptied() -> None:+ result = clean_transcript("um uh er", language="en")+ assert result.applied is False+ assert result.reason == "ceiling"+ assert result.text == "um uh er"+++def test_absolute_cap_refuses_a_short_sentence_losing_too_many_words() -> None:+ # 8 words, 4 of them filler -> past the absolute cap for short texts.+ text = "um uh er ah the plan is ready"+ result = clean_transcript(text, language="en")+ assert result.applied is False+ assert result.reason == "ceiling"+ assert result.text == text+++def test_short_sentence_with_two_fillers_is_still_cleaned() -> None:+ """The ceiling catches broken rules, not someone who hesitates twice."""+ result = clean_transcript("Ähm, das ist äh gut.", language="de") # i18n-allow: German fixture under test (§1 list #4)+ assert result.applied is True+ assert result.text == "Das ist gut." # i18n-allow: German fixture under test (§1 list #4)+++def test_long_text_uses_the_proportional_ceiling() -> None:+ body = " ".join(["word"] * 40)+ result = clean_transcript(f"um {body}", language="en")+ assert result.applied is True+ assert result.removed_words == 1+++def test_ceiling_is_configurable() -> None:+ text = " ".join(["um"] * 5 + ["word"] * 15) # 25 % filler in 20 words+ lenient = clean_transcript(text, language="en", max_removed_fraction=0.9)+ strict = clean_transcript(text, language="en", max_removed_fraction=0.01)+ assert lenient.applied is True+ assert strict.applied is False+ assert strict.reason == "ceiling"+++# --------------------------------------------------------------------------+# Language handling+# --------------------------------------------------------------------------+++ ("value", "expected"),+ [+ ("de", "de"),+ ("de-DE", "de"),+ ("DE_de", "de"),+ ("en-US", "en"),+ ("auto", None),+ ("unknown", None),+ ("", None),+ (None, None),+ ("fr", None),+ ("ja", None),+ ],+)+def test_normalize_language(value: str | None, expected: str | None) -> None:+ assert normalize_language(value) == expected+++ ("value", "expected"),+ [+ ("English", "en"),+ ("english", "en"),+ ("German", "de"),+ ("Deutsch", "de"),+ ("Spanish", "es"),+ ("español", "es"),+ ("French", None), # a name we have no rules for is still a no-op+ ],+)+def test_language_NAMES_are_accepted_not_just_codes(+ value: str, expected: str | None+) -> None:+ """Providers disagree: faster-whisper says "de", a cloud Whisper says "German".++ Found live on 2026-07-28: a real dictation came back with+ ``language="English"``, so every cleanup resolved to "no rules for this+ language" and silently never ran. Accepting both spellings is what makes+ the feature provider-agnostic (AP-21).+ """+ assert normalize_language(value) == expected+++def test_cleanup_runs_when_the_provider_reports_a_language_name() -> None:+ result = clean_transcript("Uh, I think we should um ship it.", language="English")+ assert result.applied is True+ assert result.text == "I think we should ship it."+++def test_unknown_language_is_a_no_op_not_an_english_guess() -> None:+ """Applying English rules to French speech is how content gets eaten."""+ text = "Euh, je pense que um c'est bien."+ result = clean_transcript(text, language="fr")+ assert result.applied is False+ assert result.reason == "no_rules"+ assert result.text == text+++def test_disabled_returns_the_raw_text() -> None:+ result = clean_transcript("um hello", language="en", remove_fillers=False)+ assert result.applied is False+ assert result.reason == "disabled"+ assert result.text == "um hello"+++def test_empty_input() -> None:+ result = clean_transcript(" ", language="en")+ assert result.applied is False+ assert result.reason == "empty"+++# --------------------------------------------------------------------------+# Tidying after a removal+# --------------------------------------------------------------------------+++def test_leading_capital_is_restored_after_removing_the_first_word() -> None:+ result = clean_transcript("Um, the meeting is at four.", language="en")+ assert result.text == "The meeting is at four."+++def test_lowercase_stays_lowercase() -> None:+ result = clean_transcript("um the meeting is at four", language="en")+ assert result.text == "the meeting is at four"+++def test_punctuation_is_pulled_back_onto_the_previous_word() -> None:+ result = clean_transcript("We should go um, tomorrow please.", language="en")+ assert " " not in result.text+ assert " ," not in result.textdiff --git a/tests/unit/dictation/test_delivery_and_bar.py b/tests/unit/dictation/test_delivery_and_bar.pynew file mode 100644index 0000000000..4be795f806--- /dev/null+++ b/tests/unit/dictation/test_delivery_and_bar.py@@ -0,0 +1,227 @@+"""Delivery of a finished dictation, and the bar's new coarse mode.++``_finish_dictation`` is the half of the dictation session that has nothing to+do with a microphone: clean, publish, insert, record. Testing it directly is+what makes the delivery contract verifiable without audio hardware.++The bar tests pin the promise made when the mode was added: the four existing+voice modes behave EXACTLY as before, and a click during dictation cannot start+a voice session.+"""+from __future__ import annotations++import pytest++from jarvis.core.config import DictationConfig+from jarvis.core.events import DictationCompleted, DictationTranscript+from jarvis.dictation.insert import InsertResult+from jarvis.speech.pipeline import SpeechPipeline+from jarvis.ui.jarvisbar import interaction, renderer++# --------------------------------------------------------------------------+# Delivery+# --------------------------------------------------------------------------+++def _pipeline(cfg: DictationConfig | None = None, *, insert: InsertResult | None = None):+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._dictation_cfg = cfg or DictationConfig(history_enabled=False)+ events: list[object] = []++ async def _publish(event: object) -> None:+ events.append(event)++ pipe._publish_event = _publish # type: ignore[assignment]+ pipe._insert_dictation = lambda text: insert or InsertResult( # type: ignore[assignment]+ status="inserted", detail="", clipboard_holds_text=False,+ method="clipboard+ctrl_v",+ )+ return pipe, events+++async def test_cleans_then_inserts() -> None:+ pipe, events = _pipeline()+ text = await pipe._finish_dictation(+ raw_text="Ähm, das ist äh wirklich gut.", # i18n-allow: German fixture under test (§1 list #4)+ language="de",+ duration_s=3.0,+ target="insert",+ hung_up=False,+ )+ assert text == "Das ist wirklich gut." # i18n-allow: German fixture under test (§1 list #4)++ transcript = next(e for e in events if isinstance(e, DictationTranscript))+ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert transcript.is_final is True+ assert transcript.text == "Das ist wirklich gut." # i18n-allow: German fixture under test (§1 list #4)+ assert completed.outcome == "inserted"+ assert completed.raw_text == "Ähm, das ist äh wirklich gut." # i18n-allow: German fixture under test (§1 list #4)+ assert completed.removed_words == 2+++async def test_chat_target_never_inserts() -> None:+ """The chat composer's mic button must not type into other apps."""+ inserted: list[str] = []+ pipe, events = _pipeline()+ pipe._insert_dictation = lambda text: inserted.append(text) # type: ignore[assignment]++ await pipe._finish_dictation(+ raw_text="hello there", language="en", duration_s=1.0,+ target="chat", hung_up=False,+ )+ assert inserted == []+ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert completed.outcome == "chat"+++async def test_blocked_insertion_surfaces_the_reason() -> None:+ blocked = InsertResult(+ status="clipboard_only",+ detail="The window in front is running as administrator.",+ clipboard_holds_text=True,+ )+ pipe, events = _pipeline(insert=blocked)+ await pipe._finish_dictation(+ raw_text="hello there", language="en", duration_s=1.0,+ target="insert", hung_up=False,+ )+ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert completed.outcome == "clipboard_only"+ assert "administrator" in completed.detail+++async def test_hangup_cancels_without_inserting() -> None:+ inserted: list[str] = []+ pipe, events = _pipeline()+ pipe._insert_dictation = lambda text: inserted.append(text) # type: ignore[assignment]++ await pipe._finish_dictation(+ raw_text="", language="", duration_s=0.4, target="insert", hung_up=True,+ )+ assert inserted == []+ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert completed.outcome == "cancelled"+++async def test_empty_transcript_is_reported_as_empty() -> None:+ pipe, events = _pipeline()+ await pipe._finish_dictation(+ raw_text="", language="en", duration_s=0.2, target="insert", hung_up=False,+ )+ completed = next(e for e in events if isinstance(e, DictationCompleted))+ assert completed.outcome == "empty"+++async def test_cleanup_can_be_switched_off() -> None:+ pipe, _events = _pipeline(+ DictationConfig(remove_fillers=False, history_enabled=False)+ )+ text = await pipe._finish_dictation(+ raw_text="Um, hello there friend.", language="en", duration_s=1.0,+ target="chat", hung_up=False,+ )+ assert text == "Um, hello there friend."+++async def test_auto_target_is_resolved_at_DELIVERY_time(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Start in the app, switch to the target, speak — the switch must count.++ Resolving "auto" when recording STARTS would send that text to the chat box,+ because Jarvis was in front at the moment the button was clicked.+ """+ import jarvis.dictation.insert as insert_mod++ 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",+ )++ monkeypatch.setattr(insert_mod, "foreground_is_this_app", lambda: False)+ await pipe._finish_dictation(+ raw_text="into the other app", language="en", duration_s=1.0,+ target="auto", hung_up=False,+ )+ assert inserted == ["into the other app"]++ inserted.clear()+ monkeypatch.setattr(insert_mod, "foreground_is_this_app", lambda: True)+ await pipe._finish_dictation(+ raw_text="into our own box", language="en", duration_s=1.0,+ target="auto", hung_up=False,+ )+ assert inserted == []+ assert events[-1].outcome == "chat"+++async def test_a_broken_cleanup_never_loses_the_text(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ def _boom(*_a, **_k):+ raise RuntimeError("rule exploded")++ monkeypatch.setattr("jarvis.dictation.cleanup.clean_transcript", _boom)+ pipe, _events = _pipeline()+ text = await pipe._finish_dictation(+ raw_text="the raw words", language="en", duration_s=1.0,+ target="chat", hung_up=False,+ )+ assert text == "the raw words"+++# --------------------------------------------------------------------------+# The Jarvis Bar+# --------------------------------------------------------------------------+++def test_dictate_renders_as_the_equalizer() -> None:+ """Dictation is the user talking — never the thinking indicator."""+ assert renderer.visual_mode("dictate", 99.0, hold_s=0.4) == "speak"+ assert renderer.visual_mode("dictate", 0.0, hold_s=0.4) == "speak"+++ ("mode", "seconds_since_audible", "playback", "expected"),+ [+ ("idle", 99.0, False, "idle"),+ ("listen", 99.0, False, "speak"),+ ("listen", 0.0, False, "speak"),+ ("think", 99.0, False, "think"),+ ("think", 0.0, False, "speak"),+ ("speak", 99.0, False, "speak"),+ ("speak", 0.0, True, "speak"),+ ],+)+def test_existing_visual_modes_are_unchanged(+ mode: str, seconds_since_audible: float, playback: bool, expected: str+) -> None:+ assert (+ renderer.visual_mode(+ mode, seconds_since_audible, hold_s=0.4, playback_active=playback+ )+ == expected+ )++[email protected]("x", [10, 100, 400, 700])+def test_clicking_the_bar_during_dictation_does_nothing(x: int) -> None:+ """Without this, a stray click would start a voice session mid-dictation."""+ assert interaction.resolve_click(x, 800, "dictate", hovered=True, pill_w=400) == "none"+ assert interaction.resolve_click(x, 800, "dictate", hovered=False) == "none"+++def test_existing_click_zones_are_unchanged() -> None:+ assert interaction.resolve_click(100, 800, "idle") == "talk"+ assert interaction.resolve_click(700, 800, "idle") == "mute"+ assert interaction.resolve_click(700, 800, "listen") == "mute"+ assert interaction.resolve_click(400, 800, "listen", hovered=True, pill_w=400) == "none"diff --git a/tests/unit/dictation/test_dictate_keybind.py b/tests/unit/dictation/test_dictate_keybind.pynew file mode 100644index 0000000000..8f1f7e9af2--- /dev/null+++ b/tests/unit/dictation/test_dictate_keybind.py@@ -0,0 +1,238 @@+"""The dictate keybind: validator rules, binding table, and hotkey edges.++Two of these tests pin defects that were found by CALLING the validator rather+than reading it: ``cmd`` was not in the modifier vocabulary, so every+macOS-critical chord (Cmd+Q, Cmd+W, Cmd+C, Cmd+Space) passed validation while+the Windows equivalents were refused; and F12, which the OS reserves for the+debugger, was accepted.+"""+from __future__ import annotations++import asyncio++import pytest++from jarvis.core.config import DictationConfig, TriggerConfig+from jarvis.core.config_writer import KEYBIND_ACTIONS, KEYBIND_TOML_KEY+from jarvis.speech.pipeline import PipelineState, SpeechPipeline+from jarvis.trigger.hotkey import validate_hotkey++# --------------------------------------------------------------------------+# Registry wiring+# --------------------------------------------------------------------------+++def test_dictate_is_a_first_class_keybind_action() -> None:+ assert "dictate" in KEYBIND_ACTIONS+ assert KEYBIND_TOML_KEY["dictate"] == "hotkey_dictate"+ 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 == ""+++# --------------------------------------------------------------------------+# Validator — the macOS gap+# --------------------------------------------------------------------------++[email protected]("combo", ["cmd+c", "cmd+v", "cmd+q", "cmd+w", "cmd+space"])+def test_macos_system_shortcuts_are_refused(combo: str) -> None:+ ok, reason = validate_hotkey(combo, platform="darwin")+ assert ok is False+ assert "macOS" in reason++[email protected]("combo", ["cmd+d", "cmd+shift+d", "cmd+alt+space"])+def test_usable_command_chords_are_accepted_on_macos(combo: str) -> None:+ ok, reason = validate_hotkey(combo, platform="darwin")+ assert ok is True, reason+++def test_command_chord_is_refused_where_there_is_no_command_key() -> None:+ ok, reason = validate_hotkey("cmd+d", platform="win32")+ assert ok is False+ assert "Command key" in reason+++# --------------------------------------------------------------------------+# Validator — reserved keys and the pre-existing rules+# --------------------------------------------------------------------------+++def test_f12_is_refused_as_reserved() -> None:+ ok, reason = validate_hotkey("f12", platform="win32")+ assert ok is False+ assert "reserved" in reason.lower()+++ ("combo", "expected"),+ [+ ("ctrl+alt+d", True),+ ("f5", True),+ ("f3+f4", True),+ ("win+d", False),+ ("alt+f4", False),+ ("ctrl+c", False),+ ("j", False),+ ("ctrl", False),+ ("", False),+ ],+)+def test_existing_rules_are_unchanged(combo: str, expected: bool) -> None:+ ok, _reason = validate_hotkey(combo, platform="win32")+ assert ok is expected+++# --------------------------------------------------------------------------+# Binding table+# --------------------------------------------------------------------------+++def _pipeline(*, dictate: list[str], mode: str = "hold") -> SpeechPipeline:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._call_hotkeys = ["f3+f4"]+ pipe._hangup_hotkeys = ["f1+f2"]+ pipe._ptt_hotkeys = []+ pipe._dictate_hotkeys = dictate+ pipe._dictate_mode = mode+ return pipe+++def test_hold_mode_asks_for_both_key_edges() -> None:+ bindings, edges = _pipeline(dictate=["ctrl+alt+d"])._build_hotkey_bindings()+ assert bindings["dictate"] == ["ctrl+alt+d"]+ assert "dictate" in edges+++def test_toggle_mode_fires_once_on_release() -> None:+ bindings, edges = _pipeline(+ dictate=["ctrl+alt+d"], mode="toggle"+ )._build_hotkey_bindings()+ assert bindings["dictate"] == ["ctrl+alt+d"]+ assert "dictate" not in edges+++def test_unbound_dictation_arms_nothing_but_leaves_voice_intact() -> None:+ bindings, edges = _pipeline(dictate=[])._build_hotkey_bindings()+ assert "dictate" 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"]+++# --------------------------------------------------------------------------+# Hotkey edges+# --------------------------------------------------------------------------+++class _RecordingPipeline(SpeechPipeline):+ """Counts start/stop calls without touching a microphone."""++ def __init__(self) -> None: # noqa: D107 — deliberately bypasses the real ctor+ self.started: list[str] = []+ self.stopped = 0+ self._dictate_key_down = False+ self._dictation_task = None++ def start_dictation(self, *, target: str = "chat") -> bool: # type: ignore[override]+ self.started.append(target)+ return True++ def stop_dictation(self) -> bool: # type: ignore[override]+ self.stopped += 1+ return True+++def test_press_starts_once_even_though_the_backend_polls() -> None:+ """The Windows backend re-fires on_press while the chord is held."""+ pipe = _RecordingPipeline()+ pipe._on_dictate_press()+ pipe._on_dictate_press()+ pipe._on_dictate_press()+ # "auto" is the shipped [dictation].target; it is resolved against the live+ # foreground window when the recording ENDS, not here.+ assert pipe.started == ["auto"]+++def test_the_key_follows_the_configured_target() -> None:+ pipe = _RecordingPipeline()+ pipe._dictation_cfg = DictationConfig(target="chat")+ pipe._on_dictate_press()+ assert pipe.started == ["chat"]+++def test_release_submits_once() -> None:+ pipe = _RecordingPipeline()+ pipe._on_dictate_press()+ pipe._on_dictate_release()+ pipe._on_dictate_release() # stray second edge+ assert pipe.stopped == 1+++def test_a_refused_start_does_not_swallow_the_next_press() -> None:+ pipe = _RecordingPipeline()++ def _refuse(*, target: str = "chat") -> bool:+ return False++ pipe.start_dictation = _refuse # type: ignore[assignment]+ pipe._on_dictate_press()+ assert pipe._dictate_key_down is False++ pipe.start_dictation = lambda *, target="chat": pipe.started.append(target) or True # type: ignore[assignment]+ pipe._on_dictate_press()+ assert pipe.started == ["auto"]+++def test_toggle_starts_then_stops() -> None:+ pipe = _RecordingPipeline()+ pipe._on_dictate_toggle()+ assert pipe.started == ["auto"]++ class _RunningTask:+ def done(self) -> bool:+ return False++ pipe._dictation_task = _RunningTask() # type: ignore[assignment]+ pipe._on_dictate_toggle()+ assert pipe.stopped == 1+++# --------------------------------------------------------------------------+# start_dictation target+# --------------------------------------------------------------------------+++class _StubSTT:+ async def transcribe_pcm(self, pcm: bytes): # pragma: no cover+ raise AssertionError("no transcription in this unit test")+++async def test_start_dictation_records_the_requested_target() -> None:+ pipe = SpeechPipeline.__new__(SpeechPipeline)+ pipe._utterance_stt = _StubSTT()+ pipe._dictation_task = None+ pipe._dictation_stop_event = asyncio.Event()+ pipe._ptt_mode = False+ pipe._state = PipelineState.IDLE+ pipe._input_device = "default"+ pipe._hangup_event = asyncio.Event()+ pipe._dictation_cfg = DictationConfig()++ assert pipe.start_dictation(target="insert") is True+ assert pipe._dictation_target == "insert"+ assert pipe.dictation_active() is True++ task = pipe._dictation_task+ if task is not None:+ task.cancel()+ try:+ await task+ except (asyncio.CancelledError, Exception): # noqa: BLE001, S110+ pass # teardown only — the session body never runs in this testdiff --git a/tests/unit/dictation/test_insert.py b/tests/unit/dictation/test_insert.pynew file mode 100644index 0000000000..3b70391554--- /dev/null+++ b/tests/unit/dictation/test_insert.py@@ -0,0 +1,281 @@+"""Insertion layer: the transcript must never vanish silently.++Insertion is where a dictation feature actually breaks, and it breaks without+an error on three OS paths (Windows UIPI, macOS Secure Input, Wayland). These+tests pin the one guarantee that makes all three survivable: **the text is on+the clipboard before any keystroke, and it stays there when the paste fails.**+"""+from __future__ import annotations++import sys++import pytest++from jarvis.dictation import insert as insert_mod+from jarvis.dictation.insert import (+ TargetReport,+ insert_text,+ resolve_paste_chord,+)+++class FakeClipboard:+ """In-memory stand-in for jarvis.platform.clipboard."""++ def __init__(self, initial: str | None = "previous contents") -> None:+ self.content = initial+ self.writes: list[str] = []+ self.fail_write = False++ def read_text(self) -> str | None:+ return self.content++ def write_text(self, text: str) -> bool:+ if self.fail_write:+ return False+ self.writes.append(text)+ self.content = text+ return True+++class FakeActuator:+ """Records the chords/typing it was asked to emit."""++ def __init__(self, *, fail: bool = False) -> None:+ self.combos: list[list[str]] = []+ self.typed: list[str] = []+ self.fail = fail++ def key_combo(self, keys: list[str]) -> None:+ if self.fail:+ raise RuntimeError("UIPI ate it")+ self.combos.append(list(keys))++ def type_text(self, text: str, *, delay_s: float = 0.02) -> None:+ if self.fail:+ raise RuntimeError("no backend")+ self.typed.append(text)+++def wired(monkeypatch: pytest.MonkeyPatch):+ """insert_text wired to fakes, with insertion permitted and no sleeping."""+ clipboard = FakeClipboard()+ actuator = FakeActuator()++ import jarvis.platform.clipboard as real_clipboard++ monkeypatch.setattr(real_clipboard, "read_text", clipboard.read_text)+ monkeypatch.setattr(real_clipboard, "write_text", clipboard.write_text)+ monkeypatch.setattr(+ insert_mod, "describe_target", lambda: TargetReport(True, "", "")+ )+ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", lambda: actuator)+ monkeypatch.setattr(insert_mod.time, "sleep", lambda _s: None)+ return clipboard, actuator+++# --------------------------------------------------------------------------+# Chord resolution+# --------------------------------------------------------------------------+++def test_named_chords() -> None:+ assert resolve_paste_chord("ctrl_v") == ("ctrl_v", ["ctrl", "v"])+ assert resolve_paste_chord("ctrl_shift_v") == ("ctrl_shift_v", ["ctrl", "shift", "v"])+ assert resolve_paste_chord("shift_insert") == ("shift_insert", ["shift", "insert"])+++def test_auto_follows_the_platform() -> None:+ name, keys = resolve_paste_chord("auto")+ if sys.platform == "darwin":+ assert (name, keys) == ("cmd_v", ["cmd", "v"])+ else:+ assert (name, keys) == ("ctrl_v", ["ctrl", "v"])+++def test_unknown_chord_falls_back_instead_of_raising() -> None:+ """A bad config value must not stop a dictation."""+ assert resolve_paste_chord("nonsense") == resolve_paste_chord("auto")+++# --------------------------------------------------------------------------+# The happy path+# --------------------------------------------------------------------------+++def test_pastes_and_restores_the_previous_clipboard(wired) -> None:+ clipboard, actuator = wired+ result = insert_text("dictated text", paste_chord="ctrl_v")++ assert result.status == "inserted"+ assert result.method == "clipboard+ctrl_v"+ assert actuator.combos == [["ctrl", "v"]]+ # The transcript was written BEFORE the chord, and the old content restored.+ assert clipboard.writes == ["dictated text", "previous contents"]+ assert clipboard.content == "previous contents"+ assert result.clipboard_restored is True+++def test_restore_can_be_switched_off(wired) -> None:+ clipboard, _actuator = wired+ result = insert_text("dictated text", restore_clipboard=False)+ assert result.status == "inserted"+ assert clipboard.content == "dictated text"+ assert result.clipboard_restored is False+++def test_unreadable_clipboard_is_not_restored_as_empty(+ monkeypatch: pytest.MonkeyPatch, wired+) -> None:+ """``None`` means "could not read", not "was empty" — clearing would be a bug."""+ clipboard, _actuator = wired+ clipboard.content = None+ result = insert_text("dictated text")+ assert result.status == "inserted"+ assert clipboard.writes == ["dictated text"] # no restore write+ assert result.clipboard_restored is False+++def test_genuinely_empty_clipboard_is_restored_as_empty(wired) -> None:+ clipboard, _actuator = wired+ clipboard.content = ""+ insert_text("dictated text")+ assert clipboard.writes == ["dictated text", ""]+++def test_type_method_uses_the_actuator_not_a_chord(wired) -> None:+ _clipboard, actuator = wired+ result = insert_text("dictated text", method="type")+ assert result.status == "inserted"+ assert result.method == "type"+ assert actuator.typed == ["dictated text"]+ assert actuator.combos == []+++# --------------------------------------------------------------------------+# The failure paths — all must leave the text reachable+# --------------------------------------------------------------------------+++def test_blocked_target_leaves_the_text_on_the_clipboard(+ monkeypatch: pytest.MonkeyPatch, wired+) -> None:+ clipboard, actuator = wired+ monkeypatch.setattr(+ insert_mod,+ "describe_target",+ lambda: TargetReport(False, "elevated", "The window in front is elevated."),+ )+ result = insert_text("dictated text")++ assert result.status == "clipboard_only"+ assert result.ok is True # reachable = success, just not automatic+ assert result.clipboard_holds_text is True+ assert "elevated" in result.detail+ # Crucially: no keystroke was attempted and the transcript was NOT replaced+ # by the previous clipboard content.+ assert actuator.combos == []+ assert clipboard.content == "dictated text"+++def test_failed_paste_chord_leaves_the_text_on_the_clipboard(+ monkeypatch: pytest.MonkeyPatch, wired+) -> None:+ clipboard, actuator = wired+ actuator.fail = True+ result = insert_text("dictated text")++ assert result.status == "clipboard_only"+ assert result.clipboard_holds_text is True+ assert clipboard.content == "dictated text"+ assert "clipboard" in result.detail.lower()+++def test_missing_actuator_backend_degrades(monkeypatch: pytest.MonkeyPatch, wired) -> None:+ clipboard, _actuator = wired++ def _boom():+ raise RuntimeError("Wayland blocks synthetic input for security.")++ monkeypatch.setattr("jarvis.cu.actuate.get_actuator", _boom)+ result = insert_text("dictated text")++ assert result.status == "clipboard_only"+ assert clipboard.content == "dictated text"+ assert "Wayland" in result.detail+++def test_clipboard_write_failure_is_reported_as_unavailable(+ monkeypatch: pytest.MonkeyPatch, wired+) -> None:+ clipboard, _actuator = wired+ clipboard.fail_write = True+ result = insert_text("dictated text")+ assert result.status == "unavailable"+ assert result.ok is False+ assert result.clipboard_holds_text is False+++def test_empty_text_is_rejected_before_anything_happens(wired) -> None:+ clipboard, actuator = wired+ result = insert_text(" ")+ assert result.status == "unavailable"+ assert clipboard.writes == []+ assert actuator.combos == []+++# --------------------------------------------------------------------------+# Target resolution ("auto")+# --------------------------------------------------------------------------+++def test_explicit_targets_pass_through(monkeypatch: pytest.MonkeyPatch) -> None:+ called: list[int] = []+ monkeypatch.setattr(+ insert_mod, "foreground_is_this_app", lambda: called.append(1) or True+ )+ assert insert_mod.resolve_target("insert") == "insert"+ assert insert_mod.resolve_target("chat") == "chat"+ assert called == [] # an explicit choice must not probe anything+++def test_auto_goes_to_chat_when_our_own_window_is_in_front(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Otherwise the text is typed into the window the user just left."""+ monkeypatch.setattr(insert_mod, "foreground_is_this_app", lambda: True)+ assert insert_mod.resolve_target("auto") == "chat"+++def test_auto_inserts_when_another_app_is_in_front(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(insert_mod, "foreground_is_this_app", lambda: False)+ assert insert_mod.resolve_target("auto") == "insert"+++def test_auto_inserts_when_the_foreground_is_unknown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Unknown must behave like "another app" — that is what a dictation key is for."""+ monkeypatch.setattr(insert_mod, "foreground_is_this_app", lambda: None)+ assert insert_mod.resolve_target("auto") == "insert"+ assert insert_mod.resolve_target("") == "insert"+++def test_foreground_probe_never_raises() -> None:+ assert insert_mod.foreground_is_this_app() in (True, False, None)+++def test_describe_target_never_raises(monkeypatch: pytest.MonkeyPatch) -> None:+ """A failing probe must report "can insert", not block every dictation."""++ def _boom(*_a, **_k):+ raise OSError("probe exploded")++ monkeypatch.setattr("jarvis.platform.probes.is_wayland", _boom)+ monkeypatch.setattr("jarvis.platform.probes.display_present", _boom)+ report = insert_mod.describe_target()+ assert isinstance(report, TargetReport)+ assert report.can_insert is Truediff --git a/tests/unit/dictation/test_segment_and_history.py b/tests/unit/dictation/test_segment_and_history.pynew file mode 100644index 0000000000..dd8f3c95d2--- /dev/null+++ b/tests/unit/dictation/test_segment_and_history.py@@ -0,0 +1,176 @@+"""Segment cutting and the local dictation history.++The cut matters because a closed segment is transcribed ONCE and never+revisited — a cut through the middle of a word is permanent damage, which is+why it lands at the quietest point near the nominal length rather than exactly+on it.+"""+from __future__ import annotations++from datetime import UTC, datetime, timedelta+from pathlib import Path++import numpy as np+import pytest++from jarvis.dictation.history import DictationHistory, _prune+from jarvis.dictation.segment import quietest_cut++SR = 16_000+BPS = SR * 2 # 16 kHz mono int16+++def _tone(seconds: float, amplitude: int = 3000) -> np.ndarray:+ t = np.arange(int(seconds * SR))+ return (amplitude * np.sin(2 * np.pi * 220 * t / SR)).astype(np.int16)+++# --------------------------------------------------------------------------+# quietest_cut+# --------------------------------------------------------------------------+++def test_cut_lands_in_the_silent_gap() -> None:+ audio = _tone(10.0)+ audio[int(6.8 * SR) : int(7.3 * SR)] = 0 # a clear pause+ cut = quietest_cut(audio.tobytes(), int(8 * BPS), BPS)+ assert 6.8 * BPS <= cut <= 7.3 * BPS+++def test_cut_is_sample_aligned() -> None:+ audio = _tone(10.0)+ audio[int(7.0 * SR) : int(7.4 * SR)] = 0+ assert quietest_cut(audio.tobytes(), int(8 * BPS), BPS) % 2 == 0+++def test_cut_never_exceeds_the_buffer() -> None:+ audio = _tone(3.0)+ cut = quietest_cut(audio.tobytes(), int(8 * BPS), BPS)+ assert cut <= len(audio.tobytes())+++def test_short_buffer_falls_back_to_the_nominal_cut() -> None:+ pcm = b"\x00" * 1000+ assert quietest_cut(pcm, 8 * BPS, BPS) == 1000+++def test_zero_nominal_is_zero() -> None:+ assert quietest_cut(_tone(2.0).tobytes(), 0, BPS) == 0+++def test_uniformly_loud_audio_still_returns_a_usable_cut() -> None:+ """No pause anywhere — the cut must still be inside the search window."""+ audio = _tone(10.0)+ cut = quietest_cut(audio.tobytes(), int(8 * BPS), BPS)+ assert 6.4 * BPS <= cut <= 8 * BPS+++# --------------------------------------------------------------------------+# History+# --------------------------------------------------------------------------+++def history(tmp_path: Path) -> DictationHistory:+ return DictationHistory(tmp_path / "dictation_history.json")+++def test_empty_history_reads_as_empty_list(history: DictationHistory) -> None:+ assert history.list_all() == []+++def test_add_stores_raw_and_cleaned(history: DictationHistory) -> None:+ entry = history.add(+ raw_text="Ähm das ist gut", # i18n-allow: German fixture under test (§1 list #4)+ text="Das ist gut", # i18n-allow: German fixture under test (§1 list #4)+ language="de",+ outcome="inserted",+ removed_words=1,+ )+ assert entry is not None+ stored = history.list_all()+ assert len(stored) == 1+ assert stored[0].raw_text == "Ähm das ist gut" # i18n-allow: German fixture under test (§1 list #4)+ assert stored[0].text == "Das ist gut" # i18n-allow: German fixture under test (§1 list #4)+ assert stored[0].removed_words == 1+++def test_newest_first_and_capped(history: DictationHistory) -> None:+ for i in range(6):+ history.add(raw_text=f"x{i}", text=f"x{i}", max_entries=3)+ assert [e.text for e in history.list_all()] == ["x5", "x4", "x3"]+++def test_delete_and_clear(history: DictationHistory) -> None:+ history.add(raw_text="a", text="a")+ history.add(raw_text="b", text="b")+ target = history.list_all()[0].id+ assert history.delete(target) is True+ assert history.delete(target) is False # idempotent+ assert len(history.list_all()) == 1+ assert history.clear() is True+ assert history.list_all() == []+++def test_corrupt_file_reads_as_empty_instead_of_raising(tmp_path: Path) -> None:+ path = tmp_path / "broken.json"+ path.write_text("{not json at all", encoding="utf-8")+ assert DictationHistory(path).list_all() == []+++def test_a_single_bad_row_does_not_invalidate_the_rest(tmp_path: Path) -> None:+ path = tmp_path / "mixed.json"+ path.write_text(+ '{"version": 1, "entries": ['+ '"not-an-object",'+ '{"id": "a", "created_at": "2026-07-28T00:00:00+00:00", "text": "kept"}'+ "]}",+ encoding="utf-8",+ )+ entries = DictationHistory(path).list_all()+ assert [e.text for e in entries] == ["kept"]+++def test_empty_add_is_a_no_op(history: DictationHistory) -> None:+ assert history.add(raw_text="", text="") is None+ assert history.list_all() == []+++# --------------------------------------------------------------------------+# Pruning+# --------------------------------------------------------------------------+++def _entry(days_old: float, text: str = "x"):+ from jarvis.dictation.history import DictationEntry++ created = datetime.now(UTC) - timedelta(days=days_old)+ return DictationEntry(+ id=text, created_at=created.isoformat(), raw_text=text, text=text+ )+++def test_retention_drops_old_entries() -> None:+ kept = _prune(+ [_entry(1, "fresh"), _entry(40, "old")], max_entries=100, retention_days=30+ )+ assert [e.text for e in kept] == ["fresh"]+++def test_retention_zero_keeps_everything_up_to_the_cap() -> None:+ kept = _prune(+ [_entry(1, "a"), _entry(400, "b")], max_entries=100, retention_days=0+ )+ assert len(kept) == 2+++def test_unparseable_timestamp_is_kept_not_silently_discarded() -> None:+ from jarvis.dictation.history import DictationEntry++ broken = DictationEntry(id="b", created_at="not-a-date", raw_text="b", text="b")+ kept = _prune([broken], max_entries=100, retention_days=30)+ assert [e.text for e in kept] == ["b"]+++def test_zero_cap_keeps_nothing() -> None:+ assert _prune([_entry(1)], max_entries=0, retention_days=0) == []diff --git a/tests/unit/trigger/test_hotkey_backends.py b/tests/unit/trigger/test_hotkey_backends.pyindex df4affc6f5..0b6ad7bbab 100644--- a/tests/unit/trigger/test_hotkey_backends.py+++ b/tests/unit/trigger/test_hotkey_backends.py@@ -311,8 +311,48 @@ def test_noop_backend_logs_once_then_no_ops(caplog):with caplog.at_level(logging.INFO, logger="jarvis.trigger.backends.noop"):NoopBackend()NoopBackend() # second construction must NOT log again- wayland_logs = [r for r in caplog.records if "Wayland" in r.getMessage()]- assert len(wayland_logs) == 1, "the Wayland message must log exactly once"+ explained = [+ r for r in caplog.records if "Global hotkeys are unavailable" in r.getMessage()+ ]+ assert len(explained) == 1, "the explanation must log exactly once"+++def test_noop_backend_explains_the_ACTUAL_reason(monkeypatch):+ """The message used to say "Wayland" on every host, including Windows.++ Telling users their session type is the problem when the real fix is one+ ``pip install`` away is the "said it worked, nothing happened" class applied+ to a diagnostic. The reason is measured now, so each host gets the remedy+ that actually applies to it.+ """+ from jarvis.trigger.backends.noop import explain_unavailable++ monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "linux")+ monkeypatch.setattr("jarvis.platform.probes.is_wayland", lambda: True)+ wayland = explain_unavailable()+ assert "Wayland" in wayland+ assert "pip install" not in wayland # nothing to install fixes Wayland++ monkeypatch.setattr("jarvis.platform.probes.is_wayland", lambda: False)+ x11 = explain_unavailable()+ assert "desktop-linux" in x11 # the extra that actually fixes X11+ assert "Wayland" not in x11++ monkeypatch.setattr("jarvis.platform.detect_platform", lambda: "darwin")+ macos = explain_unavailable()+ assert "Accessibility" in macos and "Input Monitoring" in macos+++def test_noop_backend_reason_never_raises(monkeypatch):+ """A failing probe must still yield a usable sentence."""+ from jarvis.trigger.backends.noop import explain_unavailable++ def _boom():+ raise OSError("probe exploded")++ monkeypatch.setattr("jarvis.platform.detect_platform", _boom)+ message = explain_unavailable()+ assert message and "wake word" in messagedef test_noop_backend_methods_never_raise():@@ -332,7 +372,7 @@ def test_noop_backend_message_is_english():import jarvis.trigger.backends.noop as noop_mod# Inspect the source so the assertion does not depend on log capture timing.- src = inspect.getsource(noop_mod.NoopBackend._explain_once)+ src = inspect.getsource(noop_mod.explain_unavailable)assert "wake word" in srcassert "Wayland" in srcdiff --git a/tests/unit/ui/test_keybinds_route.py b/tests/unit/ui/test_keybinds_route.pyindex aa1d8785fb..fe4d62d8ac 100644--- a/tests/unit/ui/test_keybinds_route.py+++ b/tests/unit/ui/test_keybinds_route.py@@ -28,8 +28,15 @@ def test_get_returns_call_and_hangup_plus_defaults() -> None: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": "",+ }+ assert body["defaults"] == {+ "call": "f3+f4",+ "hangup": "f1+f2",+ "dictate": "",}- assert body["defaults"] == {"call": "f3+f4", "hangup": "f1+f2"}assert "push_to_talk" not in bodyassert body["restart_required"] is Trueassert len(body["suggestions"]) >= 3diff --git a/ui/orb/bus_bridge.py b/ui/orb/bus_bridge.pyindex 95485b4514..0a34a8e7e7 100644--- a/ui/orb/bus_bridge.py+++ b/ui/orb/bus_bridge.py@@ -37,6 +37,8 @@ from typing import TYPE_CHECKING, Anyfrom jarvis.core.events import (AudioOutFirst,+ DictationCompleted,+ DictationTranscript,JarvisAgentBackgroundCompleted,ListeningStarted,OrbResetRequested,@@ -189,6 +191,10 @@ class OrbBusBridge:self._hide_on_idle = hide_on_idleself._hangup_task: asyncio.Task | None = Noneself._completion_task: asyncio.Task | None = None+ # Dictation lane (separate from every voice state — see+ # _on_dictation_transcript): True while a dictation is painting the bar.+ self._dictation_active = False+ self._dictation_standdown_task: asyncio.Task | None = Noneself._rng = random.Random()self._listening_transcript_text = ""# True while the pipeline is mid-completion-buffer (paused on an@@ -292,6 +298,13 @@ class OrbBusBridge:self._bus.subscribe(ResponseGenerated, self._on_response_generated)self._bus.subscribe(JarvisAgentBackgroundCompleted, self._on_background_completed)self._bus.subscribe(AudioOutFirst, self._on_audio_out_first)+ # Dictation is a SEPARATE lane from the voice states: it raises no+ # SystemStateChanged, so the four voice modes stay exactly as they+ # are and dictation gets its own coarse mode instead of borrowing+ # one. Without these two the bar showed nothing at all while+ # dictating.+ self._bus.subscribe(DictationTranscript, self._on_dictation_transcript)+ self._bus.subscribe(DictationCompleted, self._on_dictation_completed)# Boot visibility gate: a genuine voice-ready signal releases the# hidden Jarvis Bar. Degraded UI-only ready signals do not.self._bus.subscribe(VoiceBootStatus, self._on_voice_boot_status)@@ -881,6 +894,84 @@ class OrbBusBridge:elif state in ("THINKING", "SPEAKING"):self._show_listening_transcript(self._last_response_text or THINKING_BUBBLE_TEXT)+ async def _on_dictation_transcript(self, event: DictationTranscript) -> None:+ """Show the live dictation text on the bar.++ Dictation runs in its own lane — it never raises SystemStateChanged, so+ none of the voice-state handling above sees it and none of the four+ voice modes change meaning. It gets its own coarse mode, ``dictate``,+ which the renderer paints as the equalizer (the mic level is being fed,+ so the bars actually move) with no thinking indicator.++ A live voice session ALWAYS wins: dictation cannot start while one is+ running, but a race at the boundary must not repaint a real turn.+ """+ if self._voice_session_active or self._last_state != "IDLE":+ return+ if getattr(event, "is_final", False):+ # The completion handler owns the end of a dictation — it knows the+ # outcome and whether anything needs saying.+ return+ text = (event.text or "").strip()+ try:+ self._orb.show(mode="dictate")+ except Exception as exc: # noqa: BLE001 — a surface hiccup is cosmetic+ log.debug("OrbBridge dictation show suppressed: %s", exc)+ self._dictation_active = True+ self._show_listening_transcript(text)++ async def _on_dictation_completed(self, event: DictationCompleted) -> None:+ """Dictation finished — show the outcome briefly, then stand down.++ ``detail`` is only non-empty when something the user must know happened+ (the OS blocked the paste and the text is on the clipboard). Showing it+ on the bar is the difference between "nothing happened" and "here is+ why, and here is what to do".+ """+ if not getattr(self, "_dictation_active", False):+ return+ self._dictation_active = False+ message = (event.detail or "").strip() or (event.text or "").strip()+ self._show_listening_transcript(message)+ if self._voice_session_active or self._last_state != "IDLE":+ return+ # Give the user a moment to read it, then return the bar to standby.+ # A longer dwell for a message that needs acting on than for the plain+ # "here is what you dictated" echo.+ delay = 4.0 if (event.detail or "").strip() else 1.5+ try:+ self._schedule_dictation_standdown(delay)+ except Exception as exc: # noqa: BLE001+ log.debug("OrbBridge dictation stand-down suppressed: %s", exc)++ def _schedule_dictation_standdown(self, delay_s: float) -> None:+ """Return the bar to its resting look after a dictation."""+ task = getattr(self, "_dictation_standdown_task", None)+ if task is not None and not task.done():+ task.cancel()++ async def _standdown() -> None:+ try:+ await asyncio.sleep(delay_s)+ except asyncio.CancelledError:+ return+ if self._dictation_active or self._voice_session_active:+ return+ if self._last_state != "IDLE":+ return+ self._show_listening_transcript("")+ try:+ if self._hide_on_idle:+ self._orb.hide()+ else:+ self._orb.show(mode="idle")+ except Exception as exc: # noqa: BLE001+ log.debug("OrbBridge dictation idle repaint suppressed: %s", exc)++ self._dictation_standdown_task = asyncio.create_task(+ _standdown(), name="orb-dictation-standdown"+ )+def _show_listening_transcript(self, text: str) -> None:show_transcript = getattr(self._orb, "show_listening_transcript", None)if not callable(show_transcript):