Skip to content

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

feat(dictation): heal the shortcut drift, add repeat-paste, allow a custom paste chord

Ruben Lütke213e6e3197f0
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index cb038b6896..a9fa0108bd 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -355,6 +355,23 @@ class TriggerConfig(BaseModel):
# stays honoured for installs that configured it, and only changes how
# ``hotkey_dictate`` behaves.
hotkey_dictate_toggle: str = "ctrl+right_alt+space"
+ # Insert the most recent dictation into the focused field AGAIN — the
+ # recovery key for a paste that landed nowhere. It exists because the
+ # clipboard is not a fallback here: a successful paste deliberately puts
+ # the previous clipboard content back, so the transcript is gone from the
+ # clipboard a second later and the local history is the only durable copy.
+ #
+ # Ships bound for the same reason the two dictation keys do (a recovery
+ # action nobody can find is not a recovery action). Ctrl+Alt+V is the
+ # documented suggestion; it does overlap with "Paste Special" in some
+ # office suites, and because the hotkey backend POLLS key state rather than
+ # registering with the OS, the key is not swallowed — both would fire.
+ # Clearing the row is one click, and an empty value stays fully valid: the
+ # action is also `jarvis api dictation paste-last`, which is the documented
+ # Wayland path (there the compositor, not the app, owns global shortcuts).
+ # A macOS user can record a Command-based combination instead; the
+ # validator accepts `cmd+...` on darwin.
+ hotkey_paste_last: str = "ctrl+alt+v"
wake_word: WakeWordConfig = Field(default_factory=WakeWordConfig)
# When false (default), the pipeline keeps the mic open after the
# response (conversation mode) and only hangs up via HANGUP_RE, the idle
@@ -2514,9 +2531,19 @@ class DictationConfig(BaseModel):
insert_method: Literal["clipboard", "type"] = "clipboard"
#: Which paste chord to send. ``auto`` = Cmd+V on macOS, Ctrl+V elsewhere.
- #: Many terminals do not paste on Ctrl+V, which is why the two explicit
- #: alternatives exist.
- paste_chord: Literal["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"] = "auto"
+ #: Many terminals do not paste on Ctrl+V, which is why the curated
+ #: alternatives exist (``ctrl_v`` | ``ctrl_shift_v`` | ``shift_insert`` |
+ #: ``cmd_v``, all in ``jarvis.dictation.insert.PASTE_CHORDS``).
+ #:
+ #: A recorded combination is also accepted, written with ``+``
+ #: (``"ctrl+shift+insert"``) — the paste shortcut of whatever application
+ #: you dictate into. It is a plain ``str`` rather than a ``Literal`` for
+ #: exactly that reason; the validator below normalizes it and falls back to
+ #: ``auto`` on anything it cannot send, because a hand-edited config must
+ #: never fail validation (AP-16). A custom chord is reported honestly at
+ #: delivery time: Jarvis cannot know whether the target app pasted, so the
+ #: outcome is ``paste_sent``, not ``inserted``.
+ paste_chord: str = "auto"
#: Pause after writing the clipboard, before sending the chord. Too short
#: and the target app pastes the PREVIOUS clipboard content.
@@ -2588,6 +2615,21 @@ class DictationConfig(BaseModel):
#: age cap still applies); it does not mean "delete everything".
audio_max_files: int = Field(default=20, ge=0, le=1000)
+ @field_validator("paste_chord", mode="before")
+ @classmethod
+ def _coerce_paste_chord(cls, value: object) -> str:
+ """Normalize only — an unusable value falls back to ``auto``.
+
+ The rejection message is thrown away here on purpose: this validator
+ runs on every config load, including one triggered by the self-mod
+ pipeline, and an exception there costs a boot (AP-16). The REST layer
+ calls ``normalize_paste_chord`` directly so a user who types a bad
+ chord gets the sentence instead of a silent fallback.
+ """
+ from jarvis.dictation.insert import normalize_paste_chord
+
+ return normalize_paste_chord(str(value or ""))[0]
+
@field_validator("language", mode="before")
@classmethod
def _coerce_dictation_language(cls, value: object) -> str:
@@ -3198,6 +3240,30 @@ def _migrate_worker_env_vars() -> None:
os.environ[new_name] = old_val # process-local only, no setx
+#: Paths whose dictation-shortcut backfill has already been attempted in THIS
+#: process. The on-disk marker is the durable guard; this only keeps a hot
+#: ``load_config`` loop from re-reading the file for a migration that is done.
+_DICTATION_HOTKEY_HEALED: set[Path] = set()
+
+
+def _heal_dictation_hotkeys_once(path: Path) -> None:
+ """Run the one-time dictation-shortcut backfill. Never raises, never blocks.
+
+ Kept to one cheap file read per process: the writer itself short-circuits
+ on a string probe once the marker is in the file, and this set stops even
+ that read from repeating.
+ """
+ if path in _DICTATION_HOTKEY_HEALED:
+ return
+ _DICTATION_HOTKEY_HEALED.add(path)
+ try:
+ from jarvis.core.config_writer import migrate_dictation_hotkey_defaults
+
+ migrate_dictation_hotkey_defaults(path=path)
+ except Exception: # noqa: BLE001, S110 — a boot heal must never block a load
+ pass
+
+
def load_config(
config_file: Path | None = None,
profile: str | None = None,
@@ -3215,6 +3281,13 @@ def load_config(
"""
if config_file is None:
config_file = resolve_config_path()
+ # One-time dictation-shortcut backfill BEFORE the file is read, so the
+ # very first boot after the update already sees the healed values
+ # (BUG-010 config drift; see config_writer for why a marker and not an
+ # empty-means-default rule). Only for the RESOLVED path: a caller that
+ # names a file explicitly — a test, a doctor script — gets it read, not
+ # rewritten. Process-local guard so repeated loads cost nothing.
+ _heal_dictation_hotkeys_once(config_file)
if not config_file.exists():
# No config file → pure defaults (useful for tests)
data: dict[str, Any] = {}
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index f3b2849998..4218724c79 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -570,7 +570,7 @@ def set_codex_binary_path(binary_path: str, *, path: Path = DEFAULT_CONFIG_FILE)
# frontend (jarvis/ui/web/frontend/src/hooks/useHotkey.ts). Keep these layers in
# sync. The mapped value is BOTH the jarvis.toml key under [trigger] AND the
# TriggerConfig field name (they are intentionally identical).
-KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle")
+KEYBIND_ACTIONS = ("call", "hangup", "dictate", "dictate_toggle", "paste_last")
KEYBIND_TOML_KEY = {
"call": "hotkey_call",
"hangup": "hotkey_hangup",
@@ -585,8 +585,148 @@ KEYBIND_TOML_KEY = {
# separate action rather than a mode flag, so a user can arm a hold key and
# a toggle key at the same time.
"dictate_toggle": "hotkey_dictate_toggle",
+ # Insert the most recent dictation again — the recovery key for a paste
+ # that landed nowhere. Needs no microphone and no speech-to-text; it reads
+ # the local history, because a successful paste restores the previous
+ # clipboard content and therefore takes the transcript back off the
+ # clipboard within a second.
+ "paste_last": "hotkey_paste_last",
}
+#: One-time marker under ``[trigger]`` recording that the dictation-shortcut
+#: backfill below has already run on this install. It is deliberately NOT a
+#: user setting; see :func:`migrate_dictation_hotkey_defaults`.
+DICTATION_HOTKEY_MIGRATION_KEY = "dictation_hotkeys_migrated"
+
+#: The keys the backfill may touch, in the order it reports them.
+_DICTATION_HOTKEY_FIELDS = ("hotkey_dictate", "hotkey_dictate_toggle")
+
+
+def _combo_key_set(combo: object) -> set[str]:
+ """Key SET of a combo — the unit the keybind collision rule compares."""
+ return {p.strip() for p in str(combo or "").strip().lower().split("+") if p.strip()}
+
+
+def migrate_dictation_hotkey_defaults(*, path: Path = DEFAULT_CONFIG_FILE) -> bool:
+ """One-time backfill of the dictation shortcuts. Runs exactly once, ever.
+
+ The problem it fixes (BUG-010 config drift). ``hotkey_dictate`` shipped as
+ ``""`` for a while, so every install from that period has ``hotkey_dictate
+ = ""`` written into its ``jarvis.toml``. A persisted empty string beats the
+ code default, so when the default became a real combo those installs kept
+ reading "no key assigned" — while ``hotkey_dictate_toggle``, which was
+ never persisted because it did not exist yet, WAS armed from the new
+ default. Same feature, two different answers, decided by which key happened
+ to be in the file.
+
+ Why ``""`` is not simply treated as "use the default": that would make the
+ Clear button impossible. An unbound shortcut is a state the user is
+ entitled to, and it has to survive restarts. So the two cases are told
+ apart by a MARKER rather than by the value:
+
+ * marker absent -> this install has never been through the migration, so
+ an empty value is stale rather than chosen: write the current default.
+ * marker present -> every empty value from here on was chosen by the user
+ and is left alone forever.
+
+ The marker is written the first time the migration has a stale value to
+ consider, and never otherwise: this function is reached from
+ ``load_config``, so a config file that has nothing to heal must come back
+ from a load byte-identical. The OTHER writer of the marker is
+ :func:`set_keybind` — an explicit save of a dictation shortcut, empty or
+ not, is proof the user has seen the value and chosen it, so it stamps the
+ marker too. Between them, an install where the keys are simply ABSENT is
+ never rewritten by a boot, and a Clear performed there is still permanent.
+
+ A default is skipped (while the marker is still written) when its key set
+ is a subset or superset of another shortcut already in the file: the
+ polling hotkey backend fires on subsets, so backfilling there would hand
+ the user two shortcuts that trigger each other. Better an unbound row the
+ user can fill in than a config the keybind route itself would refuse to
+ save.
+
+ Returns True when the file was rewritten. Best-effort by design: a missing
+ file, unparsable TOML or a failed write degrades to a logged no-op — a boot
+ heal must never break a boot.
+ """
+ try:
+ if path == DEFAULT_CONFIG_FILE:
+ from jarvis.core.config import resolve_config_path # noqa: PLC0415
+
+ path = resolve_config_path()
+ if not path.exists():
+ # Nothing persisted yet, so nothing can be stale: a fresh install
+ # gets the code defaults, and the marker is written the first time
+ # anything else touches the file.
+ return False
+ with _WRITE_LOCK:
+ raw = path.read_text(encoding="utf-8")
+ had_bom = raw.startswith(_BOM)
+ if had_bom:
+ raw = raw[len(_BOM) :]
+ # Fast path: healed installs pay one file read, never a TOML parse.
+ if DICTATION_HOTKEY_MIGRATION_KEY in raw:
+ return False
+
+ from jarvis.core.config import TriggerConfig # noqa: PLC0415
+
+ shipped = TriggerConfig()
+ doc: TOMLDocument = tomlkit.parse(raw)
+ trigger = doc.get("trigger")
+ if trigger is None:
+ # Nothing under [trigger] is persisted, so nothing can be
+ # stale: the code defaults already apply and there is nothing
+ # to heal. Returning without a write is what keeps a plain
+ # ``load_config`` from mutating a file it only had to read.
+ return False
+
+ backfilled: list[str] = []
+ considered = False
+ for field in _DICTATION_HOTKEY_FIELDS:
+ default = str(getattr(shipped, field, "") or "")
+ if not default:
+ continue
+ current = trigger.get(field)
+ if current is None or str(current).strip():
+ # Absent (the code default already applies) or already set
+ # by the user — either way, not this migration's business.
+ continue
+ considered = True
+ keys = _combo_key_set(default)
+ taken = [
+ _combo_key_set(trigger.get(other))
+ for other in KEYBIND_TOML_KEY.values()
+ if other != field and trigger.get(other) is not None
+ ]
+ if any(other and (keys <= other or other <= keys) for other in taken):
+ log.info(
+ "Dictation shortcut %s left unbound: the shipped default "
+ "%r overlaps a shortcut this install already uses.",
+ field,
+ default,
+ )
+ continue
+ trigger[field] = default
+ backfilled.append(field)
+
+ if not considered:
+ return False
+
+ trigger[DICTATION_HOTKEY_MIGRATION_KEY] = True
+ out = tomlkit.dumps(doc)
+ if had_bom:
+ out = _BOM + out
+ _atomic_write(path, out)
+ log.info(
+ "Dictation shortcut migration applied to %s (backfilled: %s).",
+ path,
+ ", ".join(backfilled) or "nothing",
+ )
+ return True
+ except Exception as exc: # noqa: BLE001 — a boot heal must never raise
+ log.warning("Dictation shortcut migration skipped: %s", exc)
+ return False
+
def set_keybind(action: str, hotkey: str, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
"""Persist a voice keybind (call / hangup) to ``[trigger]`` in jarvis.toml.
@@ -597,11 +737,26 @@ def set_keybind(action: str, hotkey: str, *, path: Path = DEFAULT_CONFIG_FILE) -
apply). Takes effect on the next SpeechPipeline bootstrap (a Jarvis restart):
bindings are armed once at pipeline start via ``TriggerConfig.resolve_hotkeys``
plus the ``hotkey_hangup`` read at the call sites.
+
+ Saving a DICTATION shortcut also stamps the one-time migration marker (see
+ :func:`migrate_dictation_hotkey_defaults`). An explicit save — including
+ clearing the row — is proof the user has seen this shortcut and chosen its
+ value, so the backfill must never reach it afterwards. Without the stamp,
+ Clear would work until the next restart and then quietly undo itself.
"""
try:
key = KEYBIND_TOML_KEY[action]
except KeyError:
raise ValueError(f"unknown keybind action: {action!r}") from None
+ if key in _DICTATION_HOTKEY_FIELDS:
+ _patch_table(
+ path,
+ "trigger",
+ key,
+ hotkey,
+ extra={DICTATION_HOTKEY_MIGRATION_KEY: True},
+ )
+ return
_patch_table(path, "trigger", key, hotkey)
@@ -1679,7 +1834,12 @@ def set_telephony_config(values: dict[str, object], *, path: Path = DEFAULT_CONF
def _patch_table(
- path: Path, table: str, key: str, value: str | bool | int | float | list[str]
+ path: Path,
+ table: str,
+ key: str,
+ value: str | bool | int | float | list[str],
+ *,
+ extra: dict[str, str | bool | int | float | list[str]] | None = None,
) -> None:
"""Set ``[table] key = value`` in the TOML file.
@@ -1689,6 +1849,12 @@ def _patch_table(
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``).
+
+ ``extra`` writes further keys into the SAME table in the SAME atomic write.
+ It exists for values that must land together or not at all — the dictation
+ migration marker beside the shortcut it vouches for; two separate writes
+ could be interrupted between them and leave a shortcut the backfill would
+ then overwrite again.
"""
path = _ensure_writable_config_path(path)
@@ -1703,6 +1869,8 @@ def _patch_table(
section = tomlkit.table()
doc[table] = section
section[key] = value
+ for extra_key, extra_value in (extra or {}).items():
+ section[extra_key] = extra_value
out = tomlkit.dumps(doc)
if had_bom:
out = _BOM + out
diff --git a/jarvis/dictation/insert.py b/jarvis/dictation/insert.py
index 1645089b77..89eaa4a6a7 100644
--- a/jarvis/dictation/insert.py
+++ b/jarvis/dictation/insert.py
@@ -42,6 +42,11 @@ 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.
+#:
+#: These four are the CURATED set: every one of them is a chord that means
+#: "paste" somewhere real, so when it is sent and no error comes back, calling
+#: the result ``inserted`` is a claim we are entitled to make. A user-recorded
+#: chord carries no such warrant — see :data:`CUSTOM_CHORD_KEYS` below.
PASTE_CHORDS: dict[str, list[str]] = {
"ctrl_v": ["ctrl", "v"],
"ctrl_shift_v": ["ctrl", "shift", "v"],
@@ -49,7 +54,76 @@ PASTE_CHORDS: dict[str, list[str]] = {
"cmd_v": ["cmd", "v"],
}
-InsertStatus = Literal["inserted", "clipboard_only", "unavailable"]
+#: Modifier tokens a custom paste chord may use, mapped to their canonical
+#: spelling. ``cmd`` and ``win`` stay apart on purpose: both resolve on both
+#: actuator backends, and folding one into the other would make the UI show a
+#: Mac user "Win" (or a Windows user "Cmd") for the key they actually pressed.
+CUSTOM_CHORD_MODIFIERS: dict[str, str] = {
+ "ctrl": "ctrl",
+ "control": "ctrl",
+ "alt": "alt",
+ "option": "alt",
+ "menu": "alt",
+ "shift": "shift",
+ "win": "win",
+ "windows": "win",
+ "lwin": "win",
+ "cmd": "cmd",
+ "command": "cmd",
+ "meta": "cmd",
+ "super": "cmd",
+}
+
+#: Canonical modifier order, so ``v+shift+ctrl`` and ``ctrl+shift+v`` are the
+#: same stored value rather than two configs that behave identically and look
+#: different in the UI.
+_MODIFIER_ORDER: tuple[str, ...] = ("ctrl", "alt", "shift", "win", "cmd")
+
+#: Non-modifier tokens a custom paste chord may use, mapped to their canonical
+#: spelling. Deliberately the INTERSECTION of what both actuator backends can
+#: send (``jarvis/cu/actuate/windows.py::_VK_TABLE`` and
+#: ``jarvis/cu/actuate/posix.py::_pynput_key_table``): a chord accepted here
+#: cannot be one that works on Windows and raises ``Unknown key`` on Linux —
+#: which would turn every paste on that host into a clipboard fallback. The
+#: numpad / add / subtract / decimal keys exist only in the Windows table, so
+#: they are refused rather than accepted-and-broken.
+CUSTOM_CHORD_KEYS: dict[str, str] = {
+ **{letter: letter for letter in "abcdefghijklmnopqrstuvwxyz"},
+ **{digit: digit for digit in "0123456789"},
+ **{f"f{i}": f"f{i}" for i in range(1, 13)},
+ "esc": "esc",
+ "escape": "esc",
+ "enter": "enter",
+ "return": "enter",
+ "tab": "tab",
+ "space": "space",
+ "spacebar": "space",
+ "backspace": "backspace",
+ "back": "backspace",
+ "delete": "delete",
+ "del": "delete",
+ "insert": "insert",
+ "ins": "insert",
+ "home": "home",
+ "end": "end",
+ "pageup": "pageup",
+ "pgup": "pageup",
+ "pagedown": "pagedown",
+ "pgdn": "pagedown",
+ "left": "left",
+ "up": "up",
+ "right": "right",
+ "down": "down",
+}
+
+#: ``paste_sent`` exists because Jarvis does not paste — it asks the foreground
+#: application to paste by sending a synthetic chord, and an application that
+#: does not bind that chord simply ignores it. There is no error and nothing to
+#: read back (see the module docstring), so for a chord we did not curate the
+#: only true statement is "the keystroke went out; what the app did with it is
+#: unknown". Reporting ``inserted`` there would be the exact lie this module
+#: exists to avoid.
+InsertStatus = Literal["inserted", "paste_sent", "clipboard_only", "unavailable"]
@dataclass(frozen=True, slots=True)
@@ -69,35 +143,124 @@ 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.
+ Ctrl+V away and the user was told so. ``paste_sent`` is the honest middle
+ ground for a user-recorded chord (the keystroke went out, the outcome is
+ unknown, so the transcript is left on the clipboard). 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"`` / ``""``.
+ #: e.g. ``"clipboard+ctrl_v"`` / ``"clipboard+ctrl+shift+insert"`` /
+ #: ``"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")
+ """The text reached the user one way or another.
+
+ ``paste_sent`` counts: the transcript is deliberately still on the
+ clipboard in that case, so the user has their words either way.
+ """
+ return self.status in ("inserted", "paste_sent", "clipboard_only")
+
+
+def normalize_paste_chord(value: str) -> tuple[str, str]:
+ """``(canonical_value, problem)`` for one configured paste chord.
+
+ ``problem`` is ``""`` when the value was understood, otherwise a
+ user-facing English sentence explaining what is wrong with it. The
+ canonical value is always usable — an unusable input degrades to ``auto``
+ rather than raising, because a hand-edited config must never fail
+ validation (AP-16) and a bad value must never cost someone a dictation.
+
+ Three shapes are accepted:
+
+ * ``auto`` (and empty) — resolved per platform at paste time;
+ * one of the curated :data:`PASTE_CHORDS` names (``ctrl_shift_v``, …);
+ * a recorded combo written with ``+`` (``ctrl+shift+insert``). It is
+ canonicalized — aliases folded, modifiers ordered — and, when it happens
+ to spell out a curated chord, reported under the curated NAME so the two
+ spellings cannot behave differently.
+ """
+ text = str(value or "").strip().lower()
+ if not text or text == "auto":
+ return "auto", ""
+ if text in PASTE_CHORDS:
+ return text, ""
+ if "+" not in text:
+ return "auto", (
+ f"'{value}' is not a paste shortcut. Pick one of the offered "
+ "shortcuts, or record a combination such as Ctrl+Shift+V."
+ )
+
+ modifiers: list[str] = []
+ keys: list[str] = []
+ for raw in text.split("+"):
+ token = raw.strip()
+ if not token:
+ continue
+ if token in CUSTOM_CHORD_MODIFIERS:
+ canonical = CUSTOM_CHORD_MODIFIERS[token]
+ if canonical not in modifiers:
+ modifiers.append(canonical)
+ continue
+ if token in CUSTOM_CHORD_KEYS:
+ canonical = CUSTOM_CHORD_KEYS[token]
+ if canonical not in keys:
+ keys.append(canonical)
+ continue
+ return "auto", (
+ f"'{token}' is not a key this computer can send. Use letters, "
+ "digits, F1–F12, the arrow keys, or Enter / Tab / Space / "
+ "Insert / Delete / Home / End / Page Up / Page Down."
+ )
+
+ if not keys:
+ return "auto", (
+ "A paste shortcut needs a real key, not only Ctrl / Alt / Shift."
+ )
+
+ ordered = [m for m in _MODIFIER_ORDER if m in modifiers] + keys
+ for name, chord in PASTE_CHORDS.items():
+ if chord == ordered:
+ # Recorded by hand but identical to a curated chord: store it under
+ # the curated name so it also gets the curated chord's honesty.
+ return name, ""
+ return "+".join(ordered), ""
+
+
+def paste_chord_is_curated(label: str) -> bool:
+ """Is this the label of a chord we know actually means "paste"?
+
+ The curated names (and ``auto``, which resolves to one of them) are chords
+ that paste in real applications, so a sent-without-error chord may honestly
+ be reported as ``inserted``. A recorded combo carries no such warrant.
+ """
+ return str(label or "").strip().lower() in PASTE_CHORDS
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.
+ ``auto`` picks Command+V on macOS and Ctrl+V everywhere else. A recorded
+ combo (``"ctrl+shift+insert"``) comes back under its own canonical label
+ and its own key list. 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"
+ if key not in PASTE_CHORDS:
+ canonical, problem = normalize_paste_chord(key)
+ if problem or canonical == "auto":
+ key = "cmd_v" if sys.platform == "darwin" else "ctrl_v"
+ elif canonical in PASTE_CHORDS:
+ key = canonical
+ else:
+ return canonical, canonical.split("+")
return key, list(PASTE_CHORDS[key])
@@ -365,6 +528,25 @@ def insert_text(
# snatches the text away before the target app has read it.
time.sleep(delay_after_ms / 1000.0)
+ if not paste_chord_is_curated(chord_name):
+ # A recorded chord. It was sent without error, but "sent" is not
+ # "pasted": an application that does not bind this combination simply
+ # ignores it, and there is nothing to read back (module docstring).
+ # So the clipboard is deliberately NOT restored — putting the previous
+ # content back here would delete the one copy the user can still reach
+ # if the chord landed nowhere.
+ return InsertResult(
+ status="paste_sent",
+ detail=(
+ f"The shortcut {chord_name.replace('+', ' + ')} was sent. If "
+ "the app it went to does not paste on that shortcut, nothing "
+ "happened there — the text is still on your clipboard."
+ ),
+ clipboard_holds_text=parked,
+ method=f"clipboard+{chord_name}",
+ clipboard_restored=False,
+ )
+
restored = _restore(clipboard, previous) if restore_clipboard else False
return InsertResult(
status="inserted",
@@ -375,6 +557,122 @@ def insert_text(
)
+@dataclass(frozen=True, slots=True)
+class RepeatResult:
+ """What happened when the last dictation was inserted a second time.
+
+ ``reason`` is the machine-readable half and is ``""`` on success; the REST
+ layer turns it into a status code and the voice layer speaks ``detail``.
+ """
+
+ ok: bool
+ #: ``""`` | ``history_disabled`` | ``not_found`` | ``insert``.
+ reason: str
+ #: English, user-facing sentence. Empty only when nothing needs saying.
+ detail: str
+ #: The history entry that was re-inserted, when there was one.
+ entry_id: str = ""
+ text: str = ""
+ #: The delivery report, when insertion was actually attempted.
+ insert: InsertResult | None = None
+
+
+def insert_last_dictation(
+ *,
+ entry_id: str | None = None,
+ settings: object | None = None,
+) -> RepeatResult:
+ """Insert the most recent dictation into the focused field again. Never raises.
+
+ This exists because a paste can land nowhere and the user only notices a
+ second later, by which time the clipboard is no help: on a successful paste
+ :func:`insert_text` puts the PREVIOUS clipboard content back on purpose, so
+ the transcript is gone from there within a second. The local history is the
+ only durable copy, which is why this reads from it rather than from the
+ clipboard — and why it refuses honestly when the history is switched off
+ instead of quietly keeping a hidden copy behind the user's privacy setting.
+
+ No microphone, no speech-to-text and no speech pipeline are involved: it is
+ a history read plus the SAME delivery path a fresh dictation uses, so a
+ fix to one can never leave the other behind.
+
+ ``settings`` is a ``DictationConfig``-shaped object (the live one from the
+ app config); every value is read with a fallback, so a partial stand-in or
+ ``None`` still works. ``entry_id`` picks one specific entry; the default is
+ the newest one that still has text and has not been discarded.
+ """
+
+ def _get(key: str, fallback: object) -> object:
+ return getattr(settings, key, fallback) if settings is not None else fallback
+
+ def _get_int(key: str, fallback: int) -> int:
+ """A hand-edited config can hold anything; a delay is never worth a crash."""
+ try:
+ return int(_get(key, fallback)) # type: ignore[call-overload]
+ except (TypeError, ValueError):
+ return fallback
+
+ if not bool(_get("history_enabled", True)):
+ return RepeatResult(
+ ok=False,
+ reason="history_disabled",
+ detail=(
+ "The dictation history is switched off, so there is no saved "
+ "text to paste again. Turn the history on in the dictation "
+ "settings if you want this shortcut to work."
+ ),
+ )
+
+ try:
+ from jarvis.dictation.history import DictationHistory
+
+ entries = DictationHistory().list_all(include_discarded=entry_id is not None)
+ except Exception as exc: # noqa: BLE001 — an unreadable history is "nothing to paste"
+ log.warning("dictation history unreadable for a repeat paste: %s", exc)
+ entries = []
+
+ chosen = None
+ for entry in entries:
+ if entry_id is not None:
+ if entry.id == entry_id:
+ chosen = entry
+ break
+ continue
+ if str(getattr(entry, "text", "") or "").strip():
+ chosen = entry
+ break
+
+ text = str(getattr(chosen, "text", "") or "").strip() if chosen is not None else ""
+ if chosen is None or not text:
+ return RepeatResult(
+ ok=False,
+ reason="not_found",
+ detail=(
+ "There is no saved dictation to paste again."
+ if entry_id is None
+ else "That dictation is not in the history, or it has no text."
+ ),
+ entry_id=str(getattr(chosen, "id", "") or "") if chosen is not None else "",
+ )
+
+ result = insert_text(
+ text,
+ method=str(_get("insert_method", "clipboard")),
+ paste_chord=str(_get("paste_chord", "auto")),
+ delay_ms=_get_int("paste_delay_ms", 120),
+ delay_after_ms=_get_int("paste_delay_after_ms", 120),
+ restore_clipboard=bool(_get("restore_clipboard", True)),
+ )
+ return RepeatResult(
+ ok=result.ok,
+ reason="" if result.ok else "insert",
+ detail=result.detail,
+ entry_id=str(chosen.id),
+ text=text,
+ insert=result,
+ )
+
+
def _restore(clipboard_module: object, previous: str | None) -> bool:
"""Put the previous clipboard text back. Best-effort, never raises.
@@ -396,13 +694,19 @@ def _restore(clipboard_module: object, previous: str | None) -> bool:
__all__ = [
+ "CUSTOM_CHORD_KEYS",
+ "CUSTOM_CHORD_MODIFIERS",
"PASTE_CHORDS",
"InsertResult",
"InsertStatus",
+ "RepeatResult",
"TargetReport",
"describe_target",
"foreground_is_this_app",
+ "insert_last_dictation",
"insert_text",
+ "normalize_paste_chord",
+ "paste_chord_is_curated",
"resolve_paste_chord",
"resolve_target",
]
diff --git a/jarvis/dictation/outcomes.py b/jarvis/dictation/outcomes.py
index 51d92bf502..35b364555a 100644
--- a/jarvis/dictation/outcomes.py
+++ b/jarvis/dictation/outcomes.py
@@ -16,6 +16,14 @@ What each value means
---------------------
``inserted``
The text was typed or pasted into the focused window. The happy path.
+``paste_sent``
+ A user-recorded paste shortcut was sent to the focused window and no error
+ came back — but Jarvis does not paste, it asks the application in front to
+ paste, and an application that does not bind that shortcut simply ignores
+ it. There is nothing to read back, so this is as far as honesty reaches:
+ the keystroke went out, the result is unknown, and the text is left on the
+ clipboard instead of being restored away. Only ever produced for a custom
+ chord; the curated ones report ``inserted``.
``clipboard_only``
Insertion was not possible, so the text was left on the clipboard. The
user still has their words; they just have to paste them.
@@ -48,6 +56,7 @@ from typing import Final
#: Mirrored in TypeScript as ``DICTATION_OUTCOMES`` and pinned by a parity test.
DICTATION_OUTCOMES: Final[tuple[str, ...]] = (
"inserted",
+ "paste_sent",
"clipboard_only",
"unavailable",
"chat",
diff --git a/jarvis/ui/web/dictation_routes.py b/jarvis/ui/web/dictation_routes.py
index 5324fc56cd..500e7da702 100644
--- a/jarvis/ui/web/dictation_routes.py
+++ b/jarvis/ui/web/dictation_routes.py
@@ -5,6 +5,7 @@ Endpoints (mounted by the WebServer in ``_build_app()``):
GET /api/dictation/status → capability + live state + the shortcuts.
POST /api/dictation/start → begin a dictation ({"target": ...}).
POST /api/dictation/stop → finish the running one.
+ POST /api/dictation/paste-last → insert the last dictation again.
GET /api/dictation/history → recent dictations (raw + cleaned).
GET /api/dictation/stats → lifetime totals, today, day streak.
DELETE /api/dictation/history → purge everything (destructive).
@@ -218,6 +219,18 @@ class StartBody(BaseModel):
)
+class PasteLastBody(BaseModel):
+ """Which saved dictation to insert again. Empty body = the newest one."""
+
+ entry_id: str | None = Field(
+ default=None,
+ description=(
+ "Id of a history entry to insert. Omit for the most recent "
+ "dictation that still has text."
+ ),
+ )
+
+
class SettingsBody(BaseModel):
"""Partial update — only the keys present are changed."""
@@ -314,6 +327,10 @@ async def get_status(request: Request) -> dict[str, Any]:
# both can be armed at once. Reported separately for the same reason:
# a UI that had to infer it from ``mode`` could not show the two rows.
"hotkey_toggle": str(getattr(trigger, "hotkey_dictate_toggle", "") or ""),
+ # "Insert the last dictation again" — its own action and its own row,
+ # because it needs neither a microphone nor a provider and therefore
+ # stays useful on a host where dictation itself cannot run.
+ "hotkey_paste_last": str(getattr(trigger, "hotkey_paste_last", "") or ""),
"mode": str(getattr(dictation, "mode", "hold")),
"target": str(getattr(dictation, "target", "auto")),
"insertion": insertion,
@@ -376,6 +393,59 @@ async def stop() -> dict[str, Any]:
return {"ok": True, "stopped": stopped, "active": False}
[email protected]("/paste-last")
+def paste_last(body: PasteLastBody, request: Request) -> dict[str, Any]:
+ """Insert the most recent dictation into the focused field again.
+
+ The recovery action for a paste that landed nowhere. It reads the local
+ history rather than the clipboard, and that is not an implementation
+ detail: a successful paste deliberately puts the PREVIOUS clipboard
+ content back, so the transcript is off the clipboard within a second. The
+ history is the only durable copy — which is also why this refuses honestly
+ when the history is switched off instead of keeping a hidden copy behind
+ the user's privacy setting.
+
+ Needs no microphone, no speech-to-text and no speech pipeline, so it works
+ on a host where dictation itself cannot run. It goes through the SAME
+ delivery path a fresh dictation uses, so the two can never drift apart.
+
+ Where insertion is impossible — Wayland, a headless host, an elevated
+ window in front, macOS secure input — this is still a 200: the text goes
+ to the clipboard and the answer carries the plain-English sentence
+ explaining what happened, exactly as a normal dictation would. 409 means
+ the history is off, 404 means there is nothing saved to paste.
+
+ Plain ``def`` on purpose: it parses the whole history file and sleeps
+ around the paste chord, which is blocking work FastAPI absorbs in its
+ threadpool but which must never sit on the loop a live voice turn shares.
+ """
+ from jarvis.dictation.insert import insert_last_dictation
+
+ result = insert_last_dictation(
+ entry_id=body.entry_id, settings=_dictation_cfg(request)
+ )
+ if result.reason == "history_disabled":
+ raise HTTPException(status_code=409, detail=result.detail)
+ if result.reason == "not_found":
+ raise HTTPException(status_code=404, detail=result.detail)
+
+ insertion = result.insert
+ return {
+ "ok": result.ok,
+ "entry_id": result.entry_id,
+ # The text travels in the body so a CLI or SSH user still gets their
+ # words on a host where nothing can be typed into anything.
+ "text": result.text,
+ "status": getattr(insertion, "status", "unavailable"),
+ "detail": result.detail,
+ "method": getattr(insertion, "method", ""),
+ "clipboard_holds_text": bool(
+ getattr(insertion, "clipboard_holds_text", False)
+ ),
+ "clipboard_restored": bool(getattr(insertion, "clipboard_restored", False)),
+ }
+
+
# ----------------------------------------------------------------------
# History
# ----------------------------------------------------------------------
@@ -593,11 +663,23 @@ async def get_settings(request: Request) -> dict[str, Any]:
``choices`` is what every dropdown in the UI is built from, and it is
hand-maintained: a key added to ``DICTATION_SETTING_KEYS`` without an entry
here renders an empty list the user cannot pick anything out of. The
- language list is the one exception — it is derived from
- ``DICTATION_LANGUAGES`` so adding a locale means touching one place.
+ language and paste-chord lists are the exceptions — they are derived from
+ ``DICTATION_LANGUAGES`` and ``PASTE_CHORDS`` so adding one means touching
+ one place.
+
+ ``custom`` describes the keys that also accept a RECORDED value, and it
+ carries the accepted token vocabulary rather than expecting the frontend to
+ keep its own copy — a hand-mirrored key list is the AP-4 drift trap, and
+ the cost of getting it wrong here is a recorder that happily captures a key
+ the actuator cannot send, which then fails silently at paste time.
"""
from jarvis.core.config import DICTATION_LANGUAGES
from jarvis.core.config_writer import DICTATION_SETTING_KEYS
+ from jarvis.dictation.insert import (
+ CUSTOM_CHORD_KEYS,
+ CUSTOM_CHORD_MODIFIERS,
+ PASTE_CHORDS,
+ )
dictation = _dictation_cfg(request)
values = {key: getattr(dictation, key, None) for key in DICTATION_SETTING_KEYS}
@@ -607,9 +689,27 @@ async def get_settings(request: Request) -> dict[str, Any]:
"mode": ["hold", "toggle"],
"target": ["auto", "insert", "chat"],
"insert_method": ["clipboard", "type"],
- "paste_chord": ["auto", "ctrl_v", "ctrl_shift_v", "shift_insert"],
+ "paste_chord": ["auto", *PASTE_CHORDS],
"language": list(DICTATION_LANGUAGES),
},
+ "custom": {
+ "paste_chord": {
+ "allowed": True,
+ "separator": "+",
+ "modifiers": sorted(set(CUSTOM_CHORD_MODIFIERS.values())),
+ "keys": sorted(set(CUSTOM_CHORD_KEYS.values())),
+ # The honest label for the feature. Jarvis does not paste — it
+ # asks the app in front to paste by sending this combination,
+ # so a combination that app does not bind does nothing, and the
+ # result is reported as "paste_sent", never as "inserted".
+ "detail": (
+ "The paste shortcut of the app you dictate into. A "
+ "shortcut that app does not use does nothing, and there is "
+ "no way to tell from here — so the text is left on your "
+ "clipboard instead of being cleaned up afterwards."
+ ),
+ }
+ },
}
@@ -638,6 +738,19 @@ async def put_settings(body: SettingsBody, request: Request) -> dict[str, Any]:
if not updates:
raise HTTPException(status_code=400, detail="No settings were provided.")
+ if "paste_chord" in updates:
+ # The model validator falls back to "auto" instead of raising, because
+ # a hand-edited config must never fail to load (AP-16). That is the
+ # wrong answer for someone who just recorded a shortcut, though: they
+ # would see the setting silently revert. So the same normalizer runs
+ # here, where its rejection sentence can actually reach the user.
+ from jarvis.dictation.insert import normalize_paste_chord
+
+ canonical, problem = normalize_paste_chord(str(updates["paste_chord"]))
+ if problem:
+ raise HTTPException(status_code=400, detail=problem)
+ updates["paste_chord"] = canonical
+
dictation = _dictation_cfg(request)
current = {
key: getattr(dictation, key)
diff --git a/tests/unit/core/test_dictation_hotkey_migration.py b/tests/unit/core/test_dictation_hotkey_migration.py
new file mode 100644
index 0000000000..05d756cae8
--- /dev/null
+++ b/tests/unit/core/test_dictation_hotkey_migration.py
@@ -0,0 +1,270 @@
+"""One-time backfill of the dictation shortcuts (BUG-010 config drift).
+
+``hotkey_dictate`` shipped as ``""`` for a while, so every install from that
+period persisted an empty value — and a persisted empty value beats a code
+default. When the default became a real combo, those installs kept reading "no
+key assigned" while ``hotkey_dictate_toggle``, which was never persisted, WAS
+armed from its new default. Same feature, two answers, decided by which key
+happened to be in the file.
+
+The fix cannot be "treat empty as use-the-default": that would make the Clear
+button impossible, and an unbound shortcut is a state the user is entitled to.
+So the two cases are told apart by a marker, and the tests below pin both
+halves of that contract — the backfill happens exactly once, and a deliberate
+Clear survives every restart afterwards.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import tomlkit
+
+from jarvis.core import config_writer
+from jarvis.core.config import TriggerConfig
+from jarvis.core.config_writer import (
+ DICTATION_HOTKEY_MIGRATION_KEY,
+ migrate_dictation_hotkey_defaults,
+)
+
+
+def _trigger(path: Path) -> dict:
+ doc = tomlkit.parse(path.read_text(encoding="utf-8"))
+ return dict(doc.get("trigger") or {})
+
+
+def _write(path: Path, body: str) -> Path:
+ path.write_text(body, encoding="utf-8")
+ return path
+
+
+# ----------------------------------------------------------------------
+# The drift it exists to heal
+# ----------------------------------------------------------------------
+
+
+def test_a_stale_empty_shortcut_gets_the_shipped_default(tmp_path: Path) -> None:
+ """The live case: an install that predates the default reads "unbound"."""
+ path = _write(tmp_path / "jarvis.toml", '[trigger]\nhotkey_dictate = ""\n')
+
+ assert migrate_dictation_hotkey_defaults(path=path) is True
+
+ trigger = _trigger(path)
+ assert trigger["hotkey_dictate"] == TriggerConfig().hotkey_dictate
+ assert trigger[DICTATION_HOTKEY_MIGRATION_KEY] is True
+
+
+def test_the_hands_free_shortcut_is_healed_the_same_way(tmp_path: Path) -> None:
+ path = _write(tmp_path / "jarvis.toml", '[trigger]\nhotkey_dictate_toggle = ""\n')
+
+ assert migrate_dictation_hotkey_defaults(path=path) is True
+
+ healed = _trigger(path)["hotkey_dictate_toggle"]
+ assert healed == TriggerConfig().hotkey_dictate_toggle
+
+
+def test_it_never_touches_a_shortcut_the_user_already_chose(tmp_path: Path) -> None:
+ path = _write(
+ tmp_path / "jarvis.toml",
+ '[trigger]\nhotkey_dictate = "ctrl+shift+d"\nhotkey_dictate_toggle = ""\n',
+ )
+
+ migrate_dictation_hotkey_defaults(path=path)
+
+ assert _trigger(path)["hotkey_dictate"] == "ctrl+shift+d"
+
+
+def test_it_leaves_the_other_keybinds_alone(tmp_path: Path) -> None:
+ path = _write(
+ tmp_path / "jarvis.toml",
+ '[trigger]\nhotkey_call = "j+n"\nhotkey_hangup = ""\nhotkey_dictate = ""\n',
+ )
+
+ migrate_dictation_hotkey_defaults(path=path)
+
+ trigger = _trigger(path)
+ assert trigger["hotkey_call"] == "j+n"
+ # A cleared HANGUP is not this migration's business — only the two
+ # dictation rows carry the shipped-empty drift.
+ assert trigger["hotkey_hangup"] == ""
+
+
+# ----------------------------------------------------------------------
+# Exactly once, and a Clear is forever
+# ----------------------------------------------------------------------
+
+
+def test_it_runs_exactly_once(tmp_path: Path) -> None:
+ path = _write(tmp_path / "jarvis.toml", '[trigger]\nhotkey_dictate = ""\n')
+ assert migrate_dictation_hotkey_defaults(path=path) is True
+
+ # The user clears the row again, deliberately.
+ _write(
+ tmp_path / "jarvis.toml",
+ f'[trigger]\nhotkey_dictate = ""\n{DICTATION_HOTKEY_MIGRATION_KEY} = true\n',
+ )
+
+ assert migrate_dictation_hotkey_defaults(path=path) is False
+ assert _trigger(path)["hotkey_dictate"] == ""
+
+
+def test_clearing_a_shortcut_stamps_the_marker_so_it_stays_cleared(
+ tmp_path: Path,
+) -> None:
+ """The half a marker in the file alone cannot cover.
+
+ On an install where the keys were never persisted the migration has nothing
+ to consider and writes nothing — so a Clear performed there would be
+ re-armed by the next boot unless the SAVE itself stamps the marker.
+ """
+ path = _write(tmp_path / "jarvis.toml", '[trigger]\nhotkey_call = "f3+f4"\n')
+
+ config_writer.set_keybind("dictate", "", path=path)
+
+ trigger = _trigger(path)
+ assert trigger["hotkey_dictate"] == ""
+ assert trigger[DICTATION_HOTKEY_MIGRATION_KEY] is True
+
+ assert migrate_dictation_hotkey_defaults(path=path) is False
+ assert _trigger(path)["hotkey_dictate"] == ""
+
+
+def test_saving_a_non_dictation_keybind_does_not_stamp_the_marker(
+ tmp_path: Path,
+) -> None:
+ """Saving Call says nothing about whether the dictation rows were seen."""
+ path = _write(tmp_path / "jarvis.toml", "[trigger]\n")
+
+ config_writer.set_keybind("call", "f7+f8", path=path)
+
+ assert DICTATION_HOTKEY_MIGRATION_KEY not in _trigger(path)
+
+
+# ----------------------------------------------------------------------
+# It must never rewrite a file that has nothing to heal
+# ----------------------------------------------------------------------
+
+
+def test_a_config_with_nothing_to_heal_is_left_byte_identical(
+ tmp_path: Path,
+) -> None:
+ """``load_config`` reaches this. A plain read must not mutate the file."""
+ body = '[trigger]\nhotkey_call = "f3+f4"\n\n[brain]\nprimary = "gemini"\n'
+ path = _write(tmp_path / "jarvis.toml", body)
+
+ assert migrate_dictation_hotkey_defaults(path=path) is False
+ assert path.read_text(encoding="utf-8") == body
+
+
+def test_a_config_without_a_trigger_table_is_left_alone(tmp_path: Path) -> None:
+ body = '[brain]\nprimary = "gemini"\n'
+ path = _write(tmp_path / "jarvis.toml", body)
+
+ assert migrate_dictation_hotkey_defaults(path=path) is False
+ assert path.read_text(encoding="utf-8") == body
+
+
+def test_a_missing_file_is_a_quiet_no_op(tmp_path: Path) -> None:
+ assert migrate_dictation_hotkey_defaults(path=tmp_path / "absent.toml") is False
+
+
+def test_unparsable_toml_never_raises(tmp_path: Path) -> None:
+ """A boot heal that can raise is a boot that can fail."""
+ path = _write(tmp_path / "jarvis.toml", "[trigger\nhotkey_dictate = ")
+
+ assert migrate_dictation_hotkey_defaults(path=path) is False
+
+
+def test_a_bom_survives_the_rewrite(tmp_path: Path) -> None:
+ """AP-7: a stripped BOM is a config the backend will not boot from."""
+ path = tmp_path / "jarvis.toml"
+ path.write_text('[trigger]\nhotkey_dictate = ""\n', encoding="utf-8")
+
+ assert migrate_dictation_hotkey_defaults(path=path) is True
+ assert path.read_text(encoding="utf-8").startswith("")
+
+
+def test_comments_and_unrelated_sections_survive(tmp_path: Path) -> None:
+ path = _write(
+ tmp_path / "jarvis.toml",
+ '# keep me\n[trigger]\nhotkey_dictate = ""\n\n[brain]\nprimary = "gemini"\n',
+ )
+
+ migrate_dictation_hotkey_defaults(path=path)
+
+ written = path.read_text(encoding="utf-8")
+ assert "# keep me" in written
+ assert 'primary = "gemini"' in written
+
+
+# ----------------------------------------------------------------------
+# It must not create a collision the keybind route would refuse
+# ----------------------------------------------------------------------
+
+
+def test_a_default_that_would_collide_is_skipped_not_forced(tmp_path: Path) -> None:
+ """The polling backend fires on subsets, so a backfilled default that
+ overlaps an existing shortcut would arm two actions on one press — and the
+ keybind route would refuse to save the same pair by hand."""
+ collides = TriggerConfig().hotkey_dictate
+ path = _write(
+ tmp_path / "jarvis.toml",
+ f'[trigger]\nhotkey_call = "{collides}"\nhotkey_dictate = ""\n',
+ )
+
+ assert migrate_dictation_hotkey_defaults(path=path) is True
+
+ trigger = _trigger(path)
+ assert trigger["hotkey_dictate"] == ""
+ # Still marked done: retrying it every boot would only re-skip it.
+ assert trigger[DICTATION_HOTKEY_MIGRATION_KEY] is True
+
+
+def test_an_unbound_other_action_is_not_treated_as_a_collision(
+ tmp_path: Path,
+) -> None:
+ """An empty key set is a subset of everything — the same false positive the
+ keybind route had to be fixed for."""
+ path = _write(
+ tmp_path / "jarvis.toml",
+ '[trigger]\nhotkey_call = ""\nhotkey_hangup = ""\nhotkey_dictate = ""\n',
+ )
+
+ migrate_dictation_hotkey_defaults(path=path)
+
+ assert _trigger(path)["hotkey_dictate"] == TriggerConfig().hotkey_dictate
+
+
+# ----------------------------------------------------------------------
+# The boot hook
+# ----------------------------------------------------------------------
+
+
+def test_load_config_heals_the_resolved_path(
+ tmp_path: Path, monkeypatch
+) -> None:
+ from jarvis.core import config as config_module
+
+ path = _write(tmp_path / "jarvis.toml", '[trigger]\nhotkey_dictate = ""\n')
+ monkeypatch.setenv("JARVIS_CONFIG", str(path))
+ monkeypatch.setattr(config_module, "_DICTATION_HOTKEY_HEALED", set())
+
+ cfg = config_module.load_config()
+
+ assert cfg.trigger.hotkey_dictate == TriggerConfig().hotkey_dictate
+ assert _trigger(path)[DICTATION_HOTKEY_MIGRATION_KEY] is True
+
+
+def test_load_config_never_rewrites_an_explicitly_named_file(
+ tmp_path: Path, monkeypatch
+) -> None:
+ """A doctor script or a test that names a file gets it READ, not healed."""
+ from jarvis.core import config as config_module
+
+ body = '[trigger]\nhotkey_dictate = ""\n'
+ path = _write(tmp_path / "jarvis.toml", body)
+ monkeypatch.setattr(config_module, "_DICTATION_HOTKEY_HEALED", set())
+
+ config_module.load_config(config_file=path)
+
+ assert path.read_text(encoding="utf-8") == body
diff --git a/tests/unit/core/test_dictation_paste_chord_custom.py b/tests/unit/core/test_dictation_paste_chord_custom.py
new file mode 100644
index 0000000000..d826c05ba5
--- /dev/null
+++ b/tests/unit/core/test_dictation_paste_chord_custom.py
@@ -0,0 +1,211 @@
+"""``[dictation].paste_chord`` accepts a recorded combination, honestly.
+
+Jarvis does not paste. It asks whatever application is in front to paste, by
+sending a synthetic chord — and an application that does not bind that chord
+ignores it silently. That is fine for the curated chords (they mean "paste"
+somewhere real), and it is the whole problem for a chord the user recorded:
+there is no error and nothing to read back, so reporting ``inserted`` would be
+a lie in the one module whose entire docstring is about not lying.
+
+So the vocabulary widened in two directions at once and both are pinned here:
+the config field accepts a combo, and the delivery report gains ``paste_sent``
+for the case where the keystroke went out and the result is unknown.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from jarvis.core.config import DictationConfig
+from jarvis.dictation.insert import (
+ CUSTOM_CHORD_KEYS,
+ CUSTOM_CHORD_MODIFIERS,
+ PASTE_CHORDS,
+ normalize_paste_chord,
+ paste_chord_is_curated,
+ resolve_paste_chord,
+)
+from jarvis.dictation.outcomes import DICTATION_OUTCOMES
+
+# ----------------------------------------------------------------------
+# What the field accepts
+# ----------------------------------------------------------------------
+
+
[email protected]("name", ["auto", *PASTE_CHORDS])
+def test_every_curated_chord_is_still_accepted(name: str) -> None:
+ """Widening the field must not cost the values people already have."""
+ assert DictationConfig(paste_chord=name).paste_chord == name
+
+
+def test_a_recorded_combination_is_accepted_and_canonicalized() -> None:
+ cfg = DictationConfig(paste_chord="SHIFT + Ctrl + Insert")
+ assert cfg.paste_chord == "ctrl+shift+insert"
+
+
+def test_a_recorded_combination_that_spells_a_curated_chord_folds_into_it() -> None:
+ """Otherwise two spellings of Ctrl+V would report different outcomes."""
+ assert DictationConfig(paste_chord="ctrl+v").paste_chord == "ctrl_v"
+ assert DictationConfig(paste_chord="v+ctrl+shift").paste_chord == "ctrl_shift_v"
+
+
+def test_an_unusable_value_falls_back_to_auto_instead_of_raising() -> None:
+ """AP-16: a hand-edited config must never fail to load."""
+ assert DictationConfig(paste_chord="nonsense").paste_chord == "auto"
+ assert DictationConfig(paste_chord="ctrl+dragon").paste_chord == "auto"
+ assert DictationConfig(paste_chord="").paste_chord == "auto"
+
+
+def test_a_modifier_only_combination_is_refused() -> None:
+ """Ctrl+Shift cannot paste anything — there is no key to send."""
+ value, problem = normalize_paste_chord("ctrl+shift")
+ assert value == "auto"
+ assert problem
+
+
+def test_the_rejection_is_a_sentence_a_person_can_act_on() -> None:
+ _, problem = normalize_paste_chord("ctrl+dragon")
+ assert "dragon" in problem
+ assert problem.endswith(".")
+
+
+def test_a_key_only_one_platform_can_send_is_refused() -> None:
+ """The token vocabulary is the INTERSECTION of the two actuator backends.
+
+ ``numpad3`` resolves on Windows and raises ``Unknown key`` on Linux/macOS,
+ which would turn every paste on those hosts into a clipboard fallback —
+ accepted here it would be a shortcut that works on one machine only.
+ """
+ assert "numpad3" not in CUSTOM_CHORD_KEYS
+ assert DictationConfig(paste_chord="ctrl+numpad3").paste_chord == "auto"
+
+
+def test_the_token_vocabulary_has_no_overlap_between_keys_and_modifiers() -> None:
+ """A token that is both would parse differently depending on lookup order."""
+ assert not set(CUSTOM_CHORD_MODIFIERS) & set(CUSTOM_CHORD_KEYS)
+
+
+# ----------------------------------------------------------------------
+# What gets sent
+# ----------------------------------------------------------------------
+
+
+def test_a_custom_chord_resolves_to_its_own_key_list() -> None:
+ label, keys = resolve_paste_chord("ctrl+shift+insert")
+ assert label == "ctrl+shift+insert"
+ assert keys == ["ctrl", "shift", "insert"]
+
+
+def test_an_unknown_chord_still_falls_back_to_the_platform_default() -> None:
+ assert resolve_paste_chord("nonsense") == resolve_paste_chord("auto")
+
+
+def test_only_the_curated_chords_are_treated_as_known_to_mean_paste() -> None:
+ for name in PASTE_CHORDS:
+ assert paste_chord_is_curated(name) is True
+ assert paste_chord_is_curated("ctrl+shift+insert") is False
+
+
+# ----------------------------------------------------------------------
+# The honest report
+# ----------------------------------------------------------------------
+
+
+def test_paste_sent_is_part_of_the_outcome_vocabulary() -> None:
+ """It reaches the history entry and the UI, so it is a five-layer value."""
+ assert "paste_sent" in DICTATION_OUTCOMES
+
+
+def test_a_custom_chord_reports_paste_sent_and_keeps_the_clipboard(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from jarvis.dictation import insert as insert_mod
+
+ class _Clipboard:
+ def __init__(self) -> None:
+ self.content = "something the user had copied"
+
+ def read_text(self) -> str:
+ return self.content
+
+ def write_text(self, text: str) -> bool:
+ self.content = text
+ return True
+
+ class _Actuator:
+ def __init__(self) -> None:
+ self.combos: list[list[str]] = []
+
+ def key_combo(self, keys: list[str]) -> None:
+ self.combos.append(list(keys))
+
+ clipboard = _Clipboard()
+ actuator = _Actuator()
+ monkeypatch.setitem(
+ __import__("sys").modules, "jarvis.platform.clipboard", clipboard
+ )
+ monkeypatch.setattr(
+ insert_mod, "describe_target", lambda: insert_mod.TargetReport(True, "", "")
+ )
+ monkeypatch.setattr(
+ "jarvis.cu.actuate.get_actuator", lambda *a, **k: actuator, raising=False
+ )
+
+ result = insert_mod.insert_text(
+ "dictated text",
+ paste_chord="ctrl+shift+insert",
+ delay_ms=0,
+ delay_after_ms=0,
+ )
+
+ assert result.status == "paste_sent"
+ assert actuator.combos == [["ctrl", "shift", "insert"]]
+ # The transcript is deliberately LEFT on the clipboard: if the chord landed
+ # nowhere, restoring the old content would delete the only copy the user
+ # can still reach.
+ assert result.clipboard_holds_text is True
+ assert result.clipboard_restored is False
+ assert clipboard.content == "dictated text"
+ assert result.ok is True
+ assert result.detail
+
+
+def test_a_curated_chord_still_reports_inserted_and_restores(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The honesty change must not cost the normal path its clean report."""
+ from jarvis.dictation import insert as insert_mod
+
+ class _Clipboard:
+ def __init__(self) -> None:
+ self.content = "previous"
+
+ def read_text(self) -> str:
+ return self.content
+
+ def write_text(self, text: str) -> bool:
+ self.content = text
+ return True
+
+ class _Actuator:
+ def key_combo(self, keys: list[str]) -> None:
+ return None
+
+ clipboard = _Clipboard()
+ monkeypatch.setitem(
+ __import__("sys").modules, "jarvis.platform.clipboard", clipboard
+ )
+ monkeypatch.setattr(
+ insert_mod, "describe_target", lambda: insert_mod.TargetReport(True, "", "")
+ )
+ monkeypatch.setattr(
+ "jarvis.cu.actuate.get_actuator", lambda *a, **k: _Actuator(), raising=False
+ )
+
+ result = insert_mod.insert_text(
+ "dictated text", paste_chord="ctrl_v", delay_ms=0, delay_after_ms=0
+ )
+
+ assert result.status == "inserted"
+ assert result.clipboard_restored is True
+ assert clipboard.content == "previous"
diff --git a/tests/unit/ui/test_keybinds_route.py b/tests/unit/ui/test_keybinds_route.py
index 060b4eafed..da9c533fd5 100644
--- a/tests/unit/ui/test_keybinds_route.py
+++ b/tests/unit/ui/test_keybinds_route.py
@@ -4,6 +4,13 @@ The exact-dict assertions below are a deliberate tripwire, not an oversight: a
keybind action that reaches ``KEYBIND_ACTIONS`` but not this route is the AP-4
drift class (the UI renders a row whose value and default are both undefined).
Extend them when an action is added; never relax them to a subset check.
+
+The route serves the FULL action set on purpose, and must keep doing so even
+though the Settings panel now renders only Call and Hangup. The two surfaces
+show different ROWS; they must not be given different DATA. A Settings panel
+that could not see the dictation combos would lose collision detection against
+them, and the user could bind Call onto a dictation chord with no warning until
+the server rejected the save.
"""
from __future__ import annotations
@@ -42,12 +49,14 @@ def test_get_returns_every_action_plus_defaults() -> None:
"hangup": "f1+f2",
"dictate": "ctrl+right_alt+j",
"dictate_toggle": "ctrl+right_alt+space",
+ "paste_last": "ctrl+alt+v",
}
assert body["defaults"] == {
"call": "f3+f4",
"hangup": "f1+f2",
"dictate": "ctrl+right_alt+j",
"dictate_toggle": "ctrl+right_alt+space",
+ "paste_last": "ctrl+alt+v",
}
assert "push_to_talk" not in body
assert body["restart_required"] is True
@@ -162,6 +171,63 @@ def test_put_rejects_a_dictation_combo_that_collides_with_the_other_one() -> Non
assert "dictate_toggle" in resp.json()["detail"]
+def test_put_paste_last_is_accepted_and_live_applies_under_its_action_name() -> None:
+ """"Insert the last dictation again" is a first-class action, not a rider
+ on the dictation keys: it needs no microphone and no provider, so it stays
+ useful on a host where dictation itself cannot run."""
+ calls: list[dict] = []
+
+ class _FakePipeline:
+ def set_keybinds(self, **kw): # noqa: ANN003
+ calls.append(kw)
+
+ client = _client()
+ client.app.state.speech_pipeline = _FakePipeline()
+ resp = client.put(
+ "/api/settings/keybinds",
+ json={"action": "paste_last", "hotkey": "CTRL+SHIFT+B", "persist": False},
+ )
+ body = resp.json()
+ assert body["ok"] is True
+ assert body["action"] == "paste_last"
+ assert body["hotkey"] == "ctrl+shift+b"
+ assert calls == [{"paste_last": ["ctrl+shift+b"]}]
+
+
+def test_put_paste_last_guards_against_colliding_with_dictation() -> None:
+ """All five ship bound, so every pair has to guard every other pair."""
+ resp = _client().put(
+ "/api/settings/keybinds",
+ json={"action": "paste_last", "hotkey": "ctrl+right_alt+j", "persist": False},
+ )
+ assert resp.status_code == 400
+ assert "dictate" in resp.json()["detail"]
+
+
+def test_paste_last_can_be_cleared_like_any_other_action() -> None:
+ """Unbound is a valid state: the action is also
+ ``jarvis api dictation paste-last``, which is the Wayland path."""
+ client = _client()
+ resp = client.put(
+ "/api/settings/keybinds",
+ json={"action": "paste_last", "hotkey": "", "persist": False},
+ )
+ assert resp.status_code == 200
+ assert client.get("/api/settings/keybinds").json()["keybinds"]["paste_last"] == ""
+
+
+def test_the_route_serves_every_action_even_though_settings_shows_two() -> None:
+ """The Settings panel renders Call + Hangup only; the PAYLOAD stays whole.
+
+ Trimming it there would strip Call/Hangup of collision detection against
+ the dictation combos — the surfaces differ in rows, never in data.
+ """
+ body = _client().get("/api/settings/keybinds").json()
+ for action in ("dictate", "dictate_toggle", "paste_last"):
+ assert action in body["keybinds"], action
+ assert action in body["defaults"], action
+
+
def test_retired_ptt_hotkey_route_is_not_mounted() -> None:
assert _client().get("/api/settings/ptt-hotkey").status_code == 404
diff --git a/tests/unit/ui/web/test_dictation_routes.py b/tests/unit/ui/web/test_dictation_routes.py
index 8248b0ee46..602869d849 100644
--- a/tests/unit/ui/web/test_dictation_routes.py
+++ b/tests/unit/ui/web/test_dictation_routes.py
@@ -227,6 +227,50 @@ def test_put_settings_rejects_an_unknown_language(client: TestClient) -> None:
assert body["settings"]["language"] == "auto"
+def test_settings_offer_the_curated_paste_chords_plus_a_custom_option(
+ client: TestClient,
+) -> None:
+ """The dropdown keeps its known-good chords; the recorder is the extra."""
+ from jarvis.dictation.insert import PASTE_CHORDS
+
+ body = client.get("/api/dictation/settings").json()
+
+ assert body["choices"]["paste_chord"] == ["auto", *PASTE_CHORDS]
+ custom = body["custom"]["paste_chord"]
+ assert custom["allowed"] is True
+ assert custom["separator"] == "+"
+ # The accepted vocabulary is SERVED, not mirrored by hand in the frontend:
+ # a recorder that captures a key the actuator cannot send fails silently at
+ # paste time, which is the exact AP-4 trap a hand-copied list sets.
+ assert "ctrl" in custom["modifiers"]
+ assert "insert" in custom["keys"]
+ assert custom["detail"]
+
+
+def test_put_settings_accepts_a_recorded_paste_chord(client: TestClient) -> None:
+ body = client.put(
+ "/api/dictation/settings",
+ json={"paste_chord": "Shift + Ctrl + Insert", "persist": False},
+ ).json()
+
+ assert body["settings"]["paste_chord"] == "ctrl+shift+insert"
+
+
+def test_put_settings_400s_on_a_paste_chord_it_cannot_send(
+ client: TestClient,
+) -> None:
+ """The model falls back to ``auto`` so a hand-edited file still loads
+ (AP-16) — but someone who just recorded a shortcut has to be TOLD, or the
+ setting appears to revert on its own."""
+ resp = client.put(
+ "/api/dictation/settings",
+ json={"paste_chord": "ctrl+dragon", "persist": False},
+ )
+
+ assert resp.status_code == 400
+ assert "dragon" in resp.json()["detail"]
+
+
# ----------------------------------------------------------------------
# Status
# ----------------------------------------------------------------------
@@ -249,6 +293,151 @@ def test_status_reports_an_unbound_hands_free_key_as_empty(client: TestClient) -
assert isinstance(body["hotkey_toggle"], str)
+def test_status_reports_the_paste_last_shortcut(app: FastAPI) -> None:
+ """Its own row: it needs no microphone, so it stays useful where dictation
+ itself cannot run."""
+ app.state.config.trigger.hotkey_paste_last = "ctrl+shift+b"
+
+ body = TestClient(app).get("/api/dictation/status").json()
+
+ assert body["hotkey_paste_last"] == "ctrl+shift+b"
+
+
+# ----------------------------------------------------------------------
+# Paste the last dictation again
+# ----------------------------------------------------------------------
+
+
+def _delivers(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ """Make ``insert_text`` succeed and record what it was handed."""
+ from jarvis.dictation import insert as insert_mod
+
+ delivered: list[str] = []
+
+ def _fake_insert(text: str, **kwargs: Any) -> Any:
+ delivered.append(text)
+ return insert_mod.InsertResult(
+ status="inserted",
+ detail="",
+ clipboard_holds_text=False,
+ method="clipboard+ctrl_v",
+ clipboard_restored=True,
+ )
+
+ monkeypatch.setattr(insert_mod, "insert_text", _fake_insert)
+ return delivered
+
+
+def test_paste_last_inserts_the_newest_dictation(
+ client: TestClient, _delivers: list[str]
+) -> None:
+ _add(text="the first one")
+ _add(text="the most recent one")
+
+ body = client.post("/api/dictation/paste-last", json={}).json()
+
+ assert body["ok"] is True
+ assert body["text"] == "the most recent one"
+ assert body["status"] == "inserted"
+ assert _delivers == ["the most recent one"]
+
+
+def test_paste_last_can_target_one_entry_by_id(
+ client: TestClient, _delivers: list[str]
+) -> None:
+ wanted = _add(text="the one I meant")
+ _add(text="a newer one")
+
+ body = client.post(
+ "/api/dictation/paste-last", json={"entry_id": wanted.id}
+ ).json()
+
+ assert body["entry_id"] == wanted.id
+ assert _delivers == ["the one I meant"]
+
+
+def test_paste_last_skips_discarded_entries(
+ client: TestClient, _delivers: list[str]
+) -> None:
+ """An entry the user hid is not the one they mean by "that again"."""
+ keep = _add(text="keep me")
+ hidden = _add(text="hidden")
+ _history().set_discarded(hidden.id, True)
+
+ body = client.post("/api/dictation/paste-last", json={}).json()
+
+ assert body["entry_id"] == keep.id
+
+
+def test_paste_last_409s_when_the_history_is_switched_off(app: FastAPI) -> None:
+ """Never keep a hidden copy to work around the user's privacy setting."""
+ app.state.config.dictation.history_enabled = False
+
+ resp = TestClient(app).post("/api/dictation/paste-last", json={})
+
+ assert resp.status_code == 409
+ assert "history" in resp.json()["detail"].lower()
+
+
+def test_paste_last_404s_when_there_is_nothing_saved(client: TestClient) -> None:
+ resp = client.post("/api/dictation/paste-last", json={})
+
+ assert resp.status_code == 404
+ assert resp.json()["detail"]
+
+
+def test_paste_last_404s_on_an_unknown_id(client: TestClient) -> None:
+ _add(text="something")
+
+ resp = client.post("/api/dictation/paste-last", json={"entry_id": "nope"})
+
+ assert resp.status_code == 404
+
+
+def test_paste_last_says_why_when_insertion_is_impossible(
+ client: TestClient, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Wayland / headless / an elevated window in front: a 200 with the
+ sentence, never a silent no-op and never a 500. The clipboard is not a
+ fallback here — a normal paste restores the previous content — so the text
+ also travels in the body for a CLI or SSH user."""
+ from jarvis.dictation import insert as insert_mod
+
+ _add(text="my words")
+ monkeypatch.setattr(
+ insert_mod,
+ "describe_target",
+ lambda: insert_mod.TargetReport(
+ can_insert=False,
+ reason="wayland",
+ detail="Wayland blocks one program from typing into another.",
+ ),
+ )
+ monkeypatch.setattr(
+ "jarvis.platform.clipboard.write_text", lambda text: True, raising=False
+ )
+ monkeypatch.setattr(
+ "jarvis.platform.clipboard.read_text", lambda: "", raising=False
+ )
+
+ body = client.post("/api/dictation/paste-last", json={}).json()
+
+ assert body["status"] == "clipboard_only"
+ assert "Wayland" in body["detail"]
+ assert body["text"] == "my words"
+
+
+def test_paste_last_needs_no_speech_pipeline(
+ client: TestClient, _delivers: list[str]
+) -> None:
+ """No microphone, no provider, no pipeline — it is a history read plus the
+ same delivery path a fresh dictation uses."""
+ _add(text="still works")
+
+ assert client.post("/api/dictation/paste-last", json={}).json()["ok"] is True
+
+
# ----------------------------------------------------------------------
# History
# ----------------------------------------------------------------------