Skip to content

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

fix(dictation): stop Jarvis' own paste chord from firing its own shortcuts

Personal Jarvis Maintainer7fc6e792327e
diff --git a/jarvis/cu/actuate/posix.py b/jarvis/cu/actuate/posix.py
index 86846f4dba..c570ff59ed 100644
--- a/jarvis/cu/actuate/posix.py
+++ b/jarvis/cu/actuate/posix.py
@@ -325,14 +325,20 @@ class PosixActuator(Actuator):
self._pyautogui.scroll(dy)
def key_combo(self, keys: list[str]) -> None:
- # Accept "ctrl+t" combined tokens like the Windows backend. The
- # self_input stamp keeps a Jarvis-typed Esc from tripping the
- # Escape-to-cancel listener (jarvis.cu.indicator).
+ # Accept "ctrl+t" combined tokens like the Windows backend. Two
+ # different self-input stamps, answering two different questions:
+ # ``stamp_if_escape`` keeps a Jarvis-typed Esc from tripping the
+ # Escape-to-cancel listener (jarvis.cu.indicator), and
+ # ``synthetic_input`` keeps this keystroke from firing Jarvis's OWN
+ # global shortcuts (jarvis.platform.self_input) — on macOS the paste
+ # chord ``cmd+v`` literally spells the default dictation hotkey.
from jarvis.cu.actuate.windows import expand_combo_keys # noqa: PLC0415
from jarvis.cu.indicator.self_input import stamp_if_escape # noqa: PLC0415
+ from jarvis.platform.self_input import synthetic_input # noqa: PLC0415
expanded = expand_combo_keys([str(k) for k in keys])
stamp_if_escape(expanded)
+ resolved: list[Any] = []
if self._keyboard is None:
aliases = {"cmd", "command", "meta", "super", "win", "windows", "lwin"}
mapped: list[str] = []
@@ -349,9 +355,11 @@ class PosixActuator(Actuator):
mapped.append("num" + normalized[6:])
else:
mapped.append(normalized)
- self._pyautogui.hotkey(*mapped)
+ with synthetic_input():
+ self._pyautogui.hotkey(*mapped)
return
- resolved: list[Any] = []
+ # Resolution stays OUTSIDE the window: an unknown key raises, and a
+ # raise that never posted a keystroke has nothing to attribute.
for k in expanded:
kl = k.strip().lower()
if kl in self._keys:
@@ -360,10 +368,11 @@ class PosixActuator(Actuator):
resolved.append(kl)
else:
raise ValueError(f"Unknown key: {k!r}")
- for r in resolved:
- self._keyboard.press(r)
- for r in reversed(resolved):
- self._keyboard.release(r)
+ with synthetic_input():
+ for r in resolved:
+ self._keyboard.press(r)
+ for r in reversed(resolved):
+ self._keyboard.release(r)
@staticmethod
def _quartz_button_spec(quartz: Any, button: str) -> tuple[Any, Any, Any, Any]:
@@ -454,6 +463,11 @@ class PosixActuator(Actuator):
can stay honest about a partial/failed type instead of claiming a full
success (the base contract widens ``None`` -> dropped-count).
"""
+ # Typing is synthetic input too, and it runs for seconds — the window
+ # is held open for the whole burst rather than stamped per character
+ # (jarvis.platform.self_input).
+ from jarvis.platform.self_input import synthetic_input # noqa: PLC0415
+
if self._keyboard is None:
# pyautogui.typewrite silently DROPS every non-ASCII character
# (umlauts, eszett, accents, CJK), and Linux always runs on this fallback (the
@@ -461,27 +475,30 @@ class PosixActuator(Actuator):
# kernel headers). Route non-ASCII through `xdotool type`, which
# synthesizes arbitrary Unicode on X11 and is provisioned by the
# installer since deep-dive 2026-07-15 H-01.
- if not text.isascii() and self._xdotool_type(text, delay_s=delay_s):
+ with synthetic_input():
+ if not text.isascii() and self._xdotool_type(text, delay_s=delay_s):
+ return 0
+ dropped = 0
+ if not text.isascii():
+ # Only non-ASCII codepoints are lost; pyautogui still types
+ # the ASCII portion of a mixed string, so count exactly the
+ # losses.
+ dropped = sum(1 for char in text if not char.isascii())
+ logger.warning(
+ "[cu] typing non-ASCII text via pyautogui — %d character(s) "
+ "outside ASCII will be dropped (install xdotool or pynput "
+ "for Unicode input).",
+ dropped,
+ )
+ self._pyautogui.typewrite(text, interval=delay_s)
+ return dropped
+ with synthetic_input():
+ if delay_s <= 0:
+ self._keyboard.type(text)
return 0
- dropped = 0
- if not text.isascii():
- # Only non-ASCII codepoints are lost; pyautogui still types the
- # ASCII portion of a mixed string, so count exactly the losses.
- dropped = sum(1 for char in text if not char.isascii())
- logger.warning(
- "[cu] typing non-ASCII text via pyautogui — %d character(s) "
- "outside ASCII will be dropped (install xdotool or pynput "
- "for Unicode input).",
- dropped,
- )
- self._pyautogui.typewrite(text, interval=delay_s)
- return dropped
- if delay_s <= 0:
- self._keyboard.type(text)
- return 0
- for char in text:
- self._keyboard.type(char)
- time.sleep(delay_s)
+ for char in text:
+ self._keyboard.type(char)
+ time.sleep(delay_s)
return 0
@staticmethod
diff --git a/jarvis/cu/actuate/windows.py b/jarvis/cu/actuate/windows.py
index e28c2890af..90ed43cef8 100644
--- a/jarvis/cu/actuate/windows.py
+++ b/jarvis/cu/actuate/windows.py
@@ -509,9 +509,14 @@ class WindowsActuator(Actuator):
def key_combo(self, keys: list[str]) -> None:
expanded = expand_combo_keys([str(k) for k in keys])
- # A Jarvis-typed Esc must not trip the Escape-to-cancel listener
- # (jarvis.cu.indicator) — stamp BEFORE the OS sees the keystroke.
+ # Two self-input stamps, two questions. A Jarvis-typed Esc must not
+ # trip the Escape-to-cancel listener (jarvis.cu.indicator), and a
+ # Jarvis-typed chord must not fire Jarvis's OWN global shortcuts
+ # (jarvis.platform.self_input) — ``ctrl`` as the dictation key sits
+ # right next to the ``ctrl+v`` paste. Both stamp BEFORE the OS sees the
+ # keystroke.
from jarvis.cu.indicator.self_input import stamp_if_escape # noqa: PLC0415
+ from jarvis.platform.self_input import synthetic_input # noqa: PLC0415
stamp_if_escape(expanded)
vk_codes: list[int] = []
@@ -532,11 +537,13 @@ class WindowsActuator(Actuator):
# emitted order is unchanged: modifiers first, released last.
downs = [self._key_input(vk, 0, flags(vk, keyup=False)) for vk in vk_codes]
ups = [self._key_input(vk, 0, flags(vk, keyup=True)) for vk in vk_codes]
- with input_space():
+ with input_space(), synthetic_input():
self._send_press_release(downs, ups)
def type_text(self, text: str, *, delay_s: float = 0.02) -> None:
- with input_space():
+ from jarvis.platform.self_input import synthetic_input # noqa: PLC0415
+
+ with input_space(), synthetic_input():
pending_cr = False
for char in text:
# A CRLF pair is ONE line break, not two Enter presses.
diff --git a/jarvis/platform/self_input.py b/jarvis/platform/self_input.py
new file mode 100644
index 0000000000..037d6002e2
--- /dev/null
+++ b/jarvis/platform/self_input.py
@@ -0,0 +1,101 @@
+"""Was Jarvis itself just typed? — so its own keystrokes cannot trigger it.
+
+An OS-level hotkey listener cannot tell synthetic input from human input: a
+session event tap (macOS), a polling matcher (Windows) and an X11 listener all
+see the keystroke this very process just posted. So every global shortcut is
+also armed against Jarvis's own actuation — and the collision is not exotic,
+it is the DEFAULT on macOS:
+
+ ``[hotkeys].dictate = "cmd"`` (a hold-to-dictate key) + the platform paste
+ chord ``cmd+v``
+
+Every dictation ended by pasting its own transcript, the tap saw the Cmd flag
+rise, and the bare-Cmd dictation shortcut fired a fresh press — into a lane
+that was still finishing, which refused it as ``already_running`` and painted
+the Jarvis Bar's failure mark over a dictation that had just pasted perfectly
+(live log, 2026-08-09 22:05:57). The same shape is one config away on Windows
+(``ctrl`` as the dictation key next to ``ctrl+v``), and it is strictly worse
+during a Computer-Use mission: there no dictation is running, so the phantom
+press does not refuse — it STARTS a recording and takes the microphone.
+
+The fix is a stamp, not a guess: the actuation layer marks the window in which
+this process is synthesizing input, and the hotkey trigger drops the shortcut
+edges that would START something inside it. It is deliberately time-boxed and
+fail-open — a stamp that somehow never cleared must degrade to "hotkeys work",
+never to a keyboard that has gone quietly dead.
+
+Related but NOT the same: :mod:`jarvis.cu.indicator.self_input` answers "did
+Jarvis type the ESCAPE that just arrived" for the mission-cancel listener, and
+must stay that narrow — a user's own Esc has to cancel a mission even while
+Jarvis is typing.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+#: How long after the last synthesized keystroke an arriving shortcut edge is
+#: still attributed to us. It only has to cover the delivery lag between
+#: ``CGEventPost`` (or ``SendInput``) and the listener that observes it — a few
+#: milliseconds in practice. 250 ms is generous by two orders of magnitude and
+#: still far below the reaction time of someone reaching for a shortcut after
+#: watching Jarvis type.
+SUPPRESS_WINDOW_MS = 250
+
+_lock = threading.Lock()
+#: Nesting depth: > 0 while a synthesis call is actually in flight, which is
+#: what covers a ``type_text`` that runs for seconds. The timestamp alone could
+#: not — it would expire in the middle of a long typing burst.
+_depth = 0
+_last_release_ns = 0
+
+
+@contextmanager
+def synthetic_input() -> Iterator[None]:
+ """Mark the block that synthesizes keystrokes as ours.
+
+ Re-entrant and thread-safe (actuation runs off the event loop, listeners
+ run on their own threads). The window stays open for
+ :data:`SUPPRESS_WINDOW_MS` after the block exits, because the listener sees
+ the event slightly later than the call that posted it returns.
+ """
+ global _depth, _last_release_ns
+ with _lock:
+ _depth += 1
+ try:
+ yield
+ finally:
+ with _lock:
+ _depth = max(0, _depth - 1)
+ _last_release_ns = time.monotonic_ns()
+
+
+def synthetic_input_recent(window_ms: int = SUPPRESS_WINDOW_MS) -> bool:
+ """True while a keystroke arriving now is most likely one we just sent."""
+ with _lock:
+ depth = _depth
+ stamp = _last_release_ns
+ if depth > 0:
+ return True
+ if stamp == 0:
+ return False
+ return (time.monotonic_ns() - stamp) < window_ms * 1_000_000
+
+
+def reset() -> None:
+ """Test hook: forget the window and any leaked depth."""
+ global _depth, _last_release_ns
+ with _lock:
+ _depth = 0
+ _last_release_ns = 0
+
+
+__all__ = [
+ "SUPPRESS_WINDOW_MS",
+ "reset",
+ "synthetic_input",
+ "synthetic_input_recent",
+]
diff --git a/jarvis/trigger/hotkey.py b/jarvis/trigger/hotkey.py
index 3ab94e4516..4264bc2854 100644
--- a/jarvis/trigger/hotkey.py
+++ b/jarvis/trigger/hotkey.py
@@ -56,6 +56,7 @@ from typing import Any
# the test-isolation hooks remain reachable at this module path. None of these
# import ``global_hotkeys`` at module scope — that import is lazy inside the
# backend's ``register`` (HN-7).
+from jarvis.platform.self_input import synthetic_input_recent
from jarvis.trigger.backends import HotkeyBackend, make_hotkey_backend
from jarvis.trigger.backends import global_hotkeys as _gh_backend
from jarvis.trigger.backends.global_hotkeys import (
@@ -82,6 +83,34 @@ def __getattr__(name: str):
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+# Shortcut events that Jarvis's OWN synthetic keystrokes must not fire.
+#
+# A listener cannot tell a posted keystroke from a pressed one, so every combo
+# is armed against our own actuation. On macOS that is not a corner case: the
+# platform paste chord is ``cmd+v`` and the offered hold-to-dictate key is a
+# bare ``cmd``, so every dictation ended by pasting its own transcript and
+# tripping its own shortcut (live log 2026-08-09; the lane was still finishing,
+# refused the phantom press as ``already_running``, and the Jarvis Bar wore the
+# failure mark over a dictation that had pasted perfectly). During a
+# Computer-Use mission the same press is worse than cosmetic: nothing is
+# running to refuse it, so it STARTS a recording and takes the microphone.
+#
+# A DENY list, deliberately, not an allow list: everything unnamed keeps
+# firing. These are exactly the edges that START something and cost nothing to
+# miss for a quarter second. Every STOP gesture — ``kill`` (the kill switch),
+# ``cu_cancel``, ``hangup`` — and every ``*_release`` edge is absent on
+# purpose, because a suppressed release strands the latch it was meant to
+# clear, and a suppressed kill switch is indefensible at any window length.
+SELF_INPUT_SUPPRESSED_EVENTS: frozenset[str] = frozenset(
+ {
+ "ptt_press",
+ "dictate_press",
+ "dictate", # legacy [dictation].mode = "toggle"
+ "dictate_toggle",
+ "paste_last",
+ }
+)
+
# Tokens that are modifiers, not "real" keys. A hotkey made of ONLY modifiers
# is not a usable trigger; a usable combo needs at least one real key.
_MODIFIER_TOKENS = frozenset(
@@ -488,6 +517,12 @@ class HotkeyTrigger:
def _make_handler(self, event_name: str):
def _on_press() -> None:
+ if event_name in SELF_INPUT_SUPPRESSED_EVENTS and synthetic_input_recent():
+ log.debug(
+ "Hotkey %r ignored: Jarvis is synthesizing input right now.",
+ event_name,
+ )
+ return
if self._loop and not self._loop.is_closed():
self._loop.call_soon_threadsafe(self._push_nowait, event_name)
return _on_press
@@ -658,6 +693,7 @@ class HotkeyTrigger:
__all__ = [
"MOUSE_BUTTON_TOKENS",
+ "SELF_INPUT_SUPPRESSED_EVENTS",
"HotkeyTrigger",
"HotkeyVerdict",
"combos_collide",
diff --git a/tests/unit/trigger/test_hotkey_self_input.py b/tests/unit/trigger/test_hotkey_self_input.py
new file mode 100644
index 0000000000..ebb3e6b806
--- /dev/null
+++ b/tests/unit/trigger/test_hotkey_self_input.py
@@ -0,0 +1,217 @@
+"""Jarvis's own keystrokes must not fire Jarvis's own shortcuts.
+
+A listener sees synthetic input exactly like human input, and on macOS the
+collision is the DEFAULT configuration rather than a corner case: the platform
+paste chord is ``cmd+v`` and the offered hold-to-dictate key is a bare ``cmd``.
+So every dictation ended by pasting its own transcript, the session event tap
+saw the Cmd flag rise, and the dictation shortcut fired a fresh press into a
+lane that was still finishing — refused as ``already_running``, which put the
+Jarvis Bar's failure mark on a dictation that had just pasted perfectly (live
+log, 2026-08-09 22:05:57).
+
+These tests pin the two halves of the repair that can regress independently:
+the actuation layer marking its own synthesis, and the trigger dropping only
+the edges it is allowed to drop.
+"""
+
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jarvis.platform import self_input
+from jarvis.trigger.hotkey import SELF_INPUT_SUPPRESSED_EVENTS, HotkeyTrigger
+
+
[email protected](autouse=True)
+def _clean_window():
+ self_input.reset()
+ yield
+ self_input.reset()
+
+
+async def _armed_trigger() -> HotkeyTrigger:
+ """A trigger whose handlers are the real ones, bound to this test's loop.
+
+ No backend and no OS registration: the handlers ``_build_bindings`` hands a
+ backend are ordinary callables, so a test can invoke exactly what a real
+ key edge would.
+ """
+ trig = HotkeyTrigger(
+ {"dictate": ["cmd"], "hangup": ["f1+f2"]},
+ push_to_talk=frozenset({"dictate"}),
+ )
+ trig._loop = asyncio.get_running_loop()
+ return trig
+
+
+async def _pushed(trigger: HotkeyTrigger) -> list[str]:
+ """Drain what the trigger queued, after the loop hop has run."""
+ await asyncio.sleep(0)
+ out: list[str] = []
+ while not trigger._queue.empty():
+ out.append(trigger._queue.get_nowait())
+ return out
+
+
+# --------------------------------------------------------------------------
+# The stamp
+# --------------------------------------------------------------------------
+def test_the_window_is_open_inside_the_block_and_shuts_after_it() -> None:
+ assert self_input.synthetic_input_recent() is False
+ with self_input.synthetic_input():
+ assert self_input.synthetic_input_recent() is True
+ # Still ours for the delivery lag ...
+ assert self_input.synthetic_input_recent() is True
+ # ... and not a millisecond of it is claimed retroactively.
+ assert self_input.synthetic_input_recent(window_ms=0) is False
+
+
+def test_a_long_typing_burst_never_expires_mid_way() -> None:
+ """A ``type_text`` runs for seconds. A timestamp taken once at the start
+ would go stale inside it, which is why the depth counter exists."""
+ with self_input.synthetic_input():
+ assert self_input.synthetic_input_recent(window_ms=0) is True
+
+
+def test_nesting_holds_the_window_until_the_outermost_block_ends() -> None:
+ with self_input.synthetic_input():
+ with self_input.synthetic_input():
+ pass
+ assert self_input.synthetic_input_recent(window_ms=0) is True
+ assert self_input.synthetic_input_recent(window_ms=0) is False
+
+
+def test_the_window_closes_even_when_the_synthesis_raises() -> None:
+ with pytest.raises(ValueError):
+ with self_input.synthetic_input():
+ raise ValueError("unknown key")
+ assert self_input.synthetic_input_recent(window_ms=0) is False
+
+
+# --------------------------------------------------------------------------
+# The filter
+# --------------------------------------------------------------------------
+async def test_a_self_typed_paste_does_not_start_a_dictation() -> None:
+ """The reported bug, at the trigger's own seam."""
+ trig = await _armed_trigger()
+ press = trig._make_handler("dictate_press")
+
+ with self_input.synthetic_input():
+ press() # the Cmd of our own cmd+v
+
+ assert await _pushed(trig) == []
+
+
+async def test_a_real_press_after_the_window_still_starts_a_dictation() -> None:
+ trig = await _armed_trigger()
+ press = trig._make_handler("dictate_press")
+
+ with self_input.synthetic_input():
+ pass
+ self_input.reset() # the window has closed
+ press()
+
+ assert await _pushed(trig) == ["dictate_press"]
+
+
+async def test_a_release_edge_is_never_suppressed() -> None:
+ """A swallowed release strands the latch it was meant to clear — the mic
+ stays open with no key held. Worse than any phantom press."""
+ trig = await _armed_trigger()
+ release = trig._make_handler("dictate_release")
+
+ with self_input.synthetic_input():
+ release()
+
+ assert await _pushed(trig) == ["dictate_release"]
+
+
+async def test_no_stop_gesture_can_be_suppressed() -> None:
+ """The kill switch, the mission cancel and the hangup key must fire while
+ Jarvis is typing — that is exactly when a user reaches for them."""
+ for event in ("kill", "cu_cancel", "hangup"):
+ assert event not in SELF_INPUT_SUPPRESSED_EVENTS
+
+ trig = await _armed_trigger()
+ hangup = trig._make_handler("hangup")
+ with self_input.synthetic_input():
+ hangup()
+
+ assert await _pushed(trig) == ["hangup"]
+
+
+def test_the_deny_list_only_names_events_that_start_something() -> None:
+ """Fail-open by construction: an unnamed (future) event keeps firing."""
+ assert SELF_INPUT_SUPPRESSED_EVENTS == {
+ "ptt_press",
+ "dictate_press",
+ "dictate",
+ "dictate_toggle",
+ "paste_last",
+ }
+ assert not any(name.endswith("_release") for name in SELF_INPUT_SUPPRESSED_EVENTS)
+
+
+# --------------------------------------------------------------------------
+# The seam: actuation has to OPEN the window, or the filter above guards
+# nothing. Both backends, because the collision exists on both (cmd+v next to
+# a bare-cmd dictation key on macOS; ctrl+v next to a ctrl one on Windows).
+# --------------------------------------------------------------------------
+def test_the_posix_actuator_marks_its_own_chord() -> None:
+ import types
+
+ from jarvis.cu.actuate.posix import PosixActuator
+
+ seen: list[bool] = []
+
+ class _Keyboard:
+ def press(self, _key) -> None:
+ seen.append(self_input.synthetic_input_recent(window_ms=0))
+
+ def release(self, _key) -> None:
+ pass
+
+ actuator = object.__new__(PosixActuator)
+ actuator._keyboard = _Keyboard()
+ actuator._keys = types.MappingProxyType({"cmd": "cmd"})
+
+ actuator.key_combo(["cmd", "v"])
+
+ assert seen == [True, True], "the paste chord was posted outside the window"
+ assert self_input.synthetic_input_recent(window_ms=0) is False
+
+
+def test_the_posix_actuator_marks_its_own_typing() -> None:
+ from jarvis.cu.actuate.posix import PosixActuator
+
+ seen: list[bool] = []
+
+ class _Keyboard:
+ def type(self, _text) -> None:
+ seen.append(self_input.synthetic_input_recent(window_ms=0))
+
+ actuator = object.__new__(PosixActuator)
+ actuator._keyboard = _Keyboard()
+
+ actuator.type_text("hello", delay_s=0)
+
+ assert seen == [True]
+
+
+def test_an_unknown_key_never_leaves_the_window_open() -> None:
+ """The resolution raise happens before anything is posted; a window that
+ outlived it would deafen the shortcuts for no keystroke at all."""
+ import types
+
+ from jarvis.cu.actuate.posix import PosixActuator
+
+ actuator = object.__new__(PosixActuator)
+ actuator._keyboard = object()
+ actuator._keys = types.MappingProxyType({})
+
+ with pytest.raises(ValueError):
+ actuator.key_combo(["nonexistent_key"])
+
+ assert self_input.synthetic_input_recent(window_ms=0) is False