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
"""Regression tests for the F1+F2 (hangup) / F3+F4 (call) global hotkeys.
These lock the lifecycle of ``dodaios.trigger.hotkey.HotkeyTrigger`` against the
bug that silently bricked the shortcuts after an in-process pipeline restart:
* ``__aexit__`` handed ``global_hotkeys.remove_hotkeys`` the full
``[combo, on_press, on_release]`` rows instead of plain combo **strings**,
so removal raised ``AttributeError`` (swallowed) and the module-level
singleton kept the stale registration.
* The next ``__aenter__`` then hit "The hotkey [...] is already registered."
inside the *un-wrapped* ``register_hotkeys`` call, which aborted the whole
registration — so **every** hotkey (call AND hangup) went dead.
The tests run against ``FakeGlobalHotkeys`` (no Windows hooks, no OS thread),
which faithfully reproduces the real module's contract — duplicate-combo
rejection and the string-only ``remove_hotkeys`` signature included.
"""
from __future__ import annotations
import asyncio
import sys
import pytest
from tests.fakes.fake_global_hotkeys import FakeGlobalHotkeys
# Exactly the bindings the live SpeechPipeline wires (pipeline.py defaults).
CALL_COMBOS = ["ctrl+right_alt+j", "f3+f4"]
HANGUP_COMBOS = ["f1+f2"]
LIVE_BINDINGS = {"call": CALL_COMBOS, "hangup": HANGUP_COMBOS}
@pytest.fixture()
def fake_gh(monkeypatch):
"""Install a fresh FakeGlobalHotkeys into ``sys.modules`` for the test.
Also resets the module-level checker refcount so the single-checker
invariant is asserted from a clean slate regardless of test ordering.
"""
import dodaios.trigger.hotkey as hk
fake = FakeGlobalHotkeys()
saved = sys.modules.get("global_hotkeys")
sys.modules["global_hotkeys"] = fake
hk._reset_checker_state_for_tests()
# This module verifies the Windows global-hotkeys contract. Pin the
# backend explicitly so the same tests remain valid on the macOS and Linux
# CI legs instead of silently selecting Quartz/pynput from the host OS.
from dodaios.trigger.backends.global_hotkeys import GlobalHotkeysBackend
monkeypatch.setattr(hk, "make_hotkey_backend", GlobalHotkeysBackend)
try:
yield fake
finally:
hk._reset_checker_state_for_tests()
if saved is not None:
sys.modules["global_hotkeys"] = saved
else:
sys.modules.pop("global_hotkeys", None)
async def _next_event(trig, timeout_s: float = 1.0) -> str:
return await asyncio.wait_for(trig.events().__anext__(), timeout_s)
# ----------------------------------------------------------------------
# Normalization
# ----------------------------------------------------------------------
def test_normalize_combo_maps_modifiers_and_keeps_fkeys():
from dodaios.trigger.hotkey import _normalize_combo
assert _normalize_combo("ctrl+right_alt+j") == "control + alt + j"
assert _normalize_combo("f1+f2") == "f1 + f2"
assert _normalize_combo("f3+f4") == "f3 + f4"
# ----------------------------------------------------------------------
# Hotkey validation (editable PTT hotkey)
# ----------------------------------------------------------------------
import pytest as _pytest # noqa: E402
@_pytest.mark.parametrize(
"combo",
[
"ctrl+right_alt+j", # the default
"ctrl+right_alt+k",
"ctrl+shift+space",
"f3+f4", # two-key chord, no modifier — still safe
"ctrl+alt+m",
# Solo function keys: never hit while typing, the natural PTT keys
# (Discord-style). The old blanket "single key" rejection blocked these.
"f5",
"f13",
# Solo navigation-cluster keys: allowed deliberately (user choice) —
# they only fire during text navigation, not while typing characters.
"up",
"home",
"page_up",
"delete",
# Modifier + nav key still fine.
"ctrl+up",
],
)
def test_validate_hotkey_accepts_safe_combos(combo):
from dodaios.trigger.hotkey import validate_hotkey
ok, reason = validate_hotkey(combo)
assert ok, f"{combo!r} should be valid, got: {reason}"
@_pytest.mark.parametrize("combo", ["", " ", "+", " + "])
def test_validate_hotkey_rejects_only_the_meaningless(combo):
"""The ONLY hard refusal left (maintainer directive 2026-07-28): a combo
with no keys in it. Everything else the user asks for, the user gets."""
from dodaios.trigger.hotkey import validate_hotkey
ok, reason = validate_hotkey(combo)
assert not ok, f"{combo!r} should be rejected"
assert reason, "a rejection must carry a user-facing reason"
@_pytest.mark.parametrize(
("combo", "caution_marker"),
[
# Was: "a combo of only Ctrl/Alt/Shift cannot be a trigger."
("ctrl+alt+shift", "modifier keys only"),
("ctrl+win", "modifier keys only"),
# Was: "This key fires while typing normal text."
("j", "while you type"),
("5", "while you type"),
("space", "while you type"),
("enter", "while you type"),
("tab", "while you type"),
("backspace", "while you type"),
("numpad_5", "while you type"),
# Was: OS-critical refusals.
("alt+f4", "Alt+F4"),
("ctrl+c", "Ctrl+C"),
("f12", "debugger"),
],
)
def test_formerly_refused_combos_are_accepted_with_a_caution(combo, caution_marker):
"""The refusals became a NON-BLOCKING warning channel: the combo saves, and
the UI can tell the user what it will cost them. A caution that is empty is
the real regression here — that would be silent acceptance."""
from dodaios.trigger.hotkey import validate_hotkey
verdict = validate_hotkey(combo, platform="win32")
assert verdict.ok is True, f"{combo!r} must be selectable now"
assert caution_marker in verdict.caution, verdict.caution
def test_the_verdict_still_unpacks_as_the_historical_pair():
"""Every existing caller does ``ok, reason = validate_hotkey(...)``. A third
tuple element would have turned all of them into a ValueError."""
from dodaios.trigger.hotkey import validate_hotkey
ok, reason = validate_hotkey("ctrl+win", platform="win32")
assert ok is True
assert reason == ""
ok, reason = validate_hotkey("")
assert ok is False
assert reason
def test_a_clean_combo_carries_no_caution():
"""Cautions must stay rare, or the UI trains the user to ignore them."""
from dodaios.trigger.hotkey import validate_hotkey
verdict = validate_hotkey("ctrl+right_alt+j", platform="win32")
assert verdict.ok is True
assert verdict.cautions == ()
assert verdict.caution == ""
def test_validate_hotkey_allows_ctrl_c_when_part_of_larger_combo():
"""Ctrl+C alone is the interrupt; Ctrl+Shift+C is a different, safe combo."""
from dodaios.trigger.hotkey import validate_hotkey
verdict = validate_hotkey("ctrl+shift+c")
assert verdict.ok
assert verdict.cautions == ()
@_pytest.mark.parametrize(
("combo", "registers_as"),
[
("super+d", {"window", "d"}),
("meta+d", {"window", "d"}),
("ctrl+super+space", {"control", "window", "space"}),
("ctrl+meta+j", {"control", "window", "j"}),
("shift+super+k", {"shift", "window", "k"}),
],
)
@_pytest.mark.parametrize("platform", ["win32", "darwin", "linux"])
def test_the_super_and_meta_aliases_normalize_to_a_key_that_fires(
combo, registers_as, platform
):
"""INVERTED from ``..._rejects_the_super_and_meta_aliases``.
The bug that test recorded was real and must stay closed: ``super``/``meta``
are the SAME physical key as ``win``, and a combo using them was once armed
against a token no backend knew — armed, and permanently dead. Refusing them
was the wrong cure (the maintainer wants Ctrl+Win), so the guarantee moves
from "rejected" to "accepted AND actually reaches the key every backend
watches": the alias folds onto ``window``, which the Windows poller reads as
VK_LWIN/VK_RWIN, the Quartz tap decodes from the Command flag, and pynput
matches through its ``cmd`` aliases. Accepting them WITHOUT this assertion
would re-open the original bug."""
from dodaios.trigger.backends.pynput import _GENERIC_MODIFIER_ALIASES, _parse_combo_tokens
from dodaios.trigger.hotkey import normalized_combo_tokens, validate_hotkey
verdict = validate_hotkey(combo, platform=platform)
assert verdict.ok is True, f"{combo!r} must be selectable on {platform}"
# It normalizes onto the one token the backends share...
assert normalized_combo_tokens(combo) == registers_as
# ...and that token resolves to a real physical key in the pynput matcher
# rather than a literal string nothing can ever match.
tokens = _parse_combo_tokens(_normalize_for_test(combo))
assert "cmd" in tokens
assert _GENERIC_MODIFIER_ALIASES["cmd"] == frozenset({"cmd", "cmd_l", "cmd_r"})
def _normalize_for_test(combo: str) -> str:
from dodaios.trigger.hotkey import _normalize_combo
return _normalize_combo(combo)
def test_legacy_super_combos_still_normalize_to_a_real_key():
"""A jarvis.toml written before the rule above must not arm a token no
backend understands: super/meta fold to the same key ``win`` does."""
from dodaios.trigger.hotkey import _normalize_combo
assert _normalize_combo("ctrl+super+space") == "control + window + space"
assert _normalize_combo("ctrl+meta+space") == "control + window + space"
assert _normalize_combo("ctrl+win+space") == "control + window + space"
def test_command_chords_stay_valid_on_macos():
"""Closing the Super hole must not take macOS Command with it."""
from dodaios.trigger.hotkey import validate_hotkey
ok, reason = validate_hotkey("cmd+d", platform="darwin")
assert ok, reason
# ----------------------------------------------------------------------
# Registration
# ----------------------------------------------------------------------
async def test_enter_registers_all_call_and_hangup_combos(fake_gh):
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS):
assert "control+alt+j" in fake_gh.registered
assert "f3+f4" in fake_gh.registered
assert "f1+f2" in fake_gh.registered
assert fake_gh.checker_running
async def test_hangup_combo_press_yields_hangup_event(fake_gh):
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS) as trig:
fake_gh.fire("f1+f2")
assert await _next_event(trig) == "hangup"
async def test_both_call_combos_yield_call_event(fake_gh):
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS) as trig:
fake_gh.fire("f3+f4")
assert await _next_event(trig) == "call"
# Fire the *normalized* combo — that is the key the trigger registers
# ("ctrl+right_alt+j" -> "control + alt + j"); the real package fires on
# virtual-key codes, the fake matches on the registered string.
fake_gh.fire("control + alt + j")
assert await _next_event(trig) == "call"
# ----------------------------------------------------------------------
# Lifecycle — the actual bug
# ----------------------------------------------------------------------
async def test_exit_removes_hotkeys_with_string_format(fake_gh):
"""REGRESSION: __aexit__ must pass combo STRINGS to remove_hotkeys.
The historical bug passed ``[combo, None, handler]`` rows, which the real
``remove_hotkeys`` rejects with AttributeError (the fake reproduces this).
A clean exit must leave the singleton registry empty so the next run can
re-register.
"""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS):
pass
# No AttributeError was swallowed, and everything was unregistered.
assert fake_gh.registered == {}
# Every payload handed to remove_hotkeys was a list of plain strings.
for call in fake_gh.remove_calls:
for item in call:
assert isinstance(item, str), f"remove_hotkeys got non-string: {item!r}"
async def test_reentry_after_exit_does_not_raise_already_registered(fake_gh):
"""The proven in-process-restart scenario: enter -> exit -> enter again.
Before the fix the second enter raised "already registered" and killed
every hotkey. After the fix it re-registers cleanly.
"""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS):
pass
# Second lifecycle in the SAME process / SAME singleton must succeed.
async with HotkeyTrigger(LIVE_BINDINGS) as trig2:
assert "f1+f2" in fake_gh.registered
fake_gh.fire("f1+f2")
assert await _next_event(trig2) == "hangup"
async def test_exit_leaves_no_live_checker(fake_gh):
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS):
assert fake_gh.checker_running
assert not fake_gh.checker_running
async def test_missing_global_hotkeys_degrades_gracefully():
"""Cloud-first VPS path: when the optional ``global_hotkeys`` package is
not installed, entering the trigger must NOT crash the voice pipeline —
it degrades to "no hotkeys" and voice still works via wake word.
"""
from dodaios.trigger.hotkey import HotkeyTrigger
saved = sys.modules.get("global_hotkeys")
sys.modules["global_hotkeys"] = None # forces ImportError on `import`
try:
async with HotkeyTrigger(LIVE_BINDINGS) as trig:
assert trig is not None # entered cleanly, no exception
assert trig._gh is None # degraded — no module handle
# __aexit__ is also clean (no AttributeError on a None module).
finally:
if saved is not None:
sys.modules["global_hotkeys"] = saved
else:
sys.modules.pop("global_hotkeys", None)
async def test_register_failure_degrades_without_crashing_the_pipeline(fake_gh):
"""If global_hotkeys.register_hotkeys raises (e.g. an invalid combo), the
trigger must NOT propagate — that would crash the whole voice pipeline at
`async with HotkeyTrigger(...)`. It degrades to "no hotkeys" (AD-OE6), and
the shared checker refcount stays balanced so the next trigger is healthy.
"""
import dodaios.trigger.hotkey as hk
from dodaios.trigger.hotkey import HotkeyTrigger
fake_gh.register_error = Exception("simulated register failure")
async with HotkeyTrigger(LIVE_BINDINGS) as trig:
assert trig._gh is None # degraded, no crash
assert hk._CHECKER_REFCOUNT == 0 # never incremented on failure
assert fake_gh.start_calls == 0 # checker never started
assert not fake_gh.checker_running
async def test_concurrent_instances_share_a_single_checker(fake_gh):
"""Two HotkeyTrigger instances alive at once (e.g. pipeline + kill-switch)
must not spawn two checker loops — a duplicate loop double-fires every
press. Peak live checkers stays at 1.
"""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger({"call": ["f3+f4"]}):
async with HotkeyTrigger({"kill": ["ctrl+alt+shift+k"]}):
assert fake_gh.checker_running
assert fake_gh.peak_live == 1
assert not fake_gh.checker_running
# ----------------------------------------------------------------------
# Live re-arm — a keybind change applies without an app restart
# ----------------------------------------------------------------------
async def test_rearm_swaps_bindings_live_without_reentry(fake_gh):
"""``rearm`` re-registers in place: the OLD combo stops firing, the NEW one
starts — the fix for "I set a key but nothing happens until I restart". The
single shared checker is preserved (no leaked second loop)."""
import dodaios.trigger.hotkey as hk
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger({"call": ["f3+f4"]}) as trig:
fake_gh.fire("f3+f4")
assert await _next_event(trig) == "call"
await trig.rearm({"call": ["f7+f8"]})
assert "f3+f4" not in fake_gh.registered # old binding gone
assert "f7+f8" in fake_gh.registered # new binding live
assert fake_gh.checker_running
assert hk._CHECKER_REFCOUNT == 1 # refcount balanced
assert fake_gh.peak_live == 1 # never spawned a 2nd checker
# The old combo is dead; the new one yields the call event.
fake_gh.fire("f3+f4")
fake_gh.fire("f7+f8")
assert await _next_event(trig) == "call"
async def test_rearm_switches_a_toggle_into_push_to_talk(fake_gh):
"""Re-arming can also flip an action into push-to-talk (both edges)."""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger({"call": ["f3+f4"]}) as trig:
await trig.rearm({"ptt": ["ctrl+right_alt+j"]}, push_to_talk={"ptt"})
on_press, on_release = fake_gh.registered["control+alt+j"]
assert on_press is not None # PTT needs the down edge
fake_gh.fire_press("control + alt + j")
assert await _next_event(trig) == "ptt_press"
async def test_rearm_when_degraded_is_a_safe_noop():
"""Re-arming a trigger that entered degraded (no package) never raises."""
from dodaios.trigger.hotkey import HotkeyTrigger
saved = sys.modules.get("global_hotkeys")
sys.modules["global_hotkeys"] = None
try:
async with HotkeyTrigger(LIVE_BINDINGS) as trig:
assert trig._gh is None
await trig.rearm({"call": ["f7+f8"]}) # must not raise
finally:
if saved is not None:
sys.modules["global_hotkeys"] = saved
else:
sys.modules.pop("global_hotkeys", None)
# ----------------------------------------------------------------------
# Push-to-talk — both key edges (press starts recording, release submits)
# ----------------------------------------------------------------------
PTT_BINDINGS = {"ptt": ["ctrl+right_alt+j"], "hangup": HANGUP_COMBOS}
async def test_ptt_press_and_release_yield_distinct_edge_events(fake_gh):
"""A push-to-talk binding fires ``<name>_press`` on the down edge and
``<name>_release`` on the up edge — the two events the pipeline needs to
start the recording on press and submit it on release."""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(PTT_BINDINGS, push_to_talk={"ptt"}) as trig:
fake_gh.fire_press("control + alt + j")
assert await _next_event(trig) == "ptt_press"
fake_gh.fire_release("control + alt + j")
assert await _next_event(trig) == "ptt_release"
async def test_ptt_binding_registers_an_on_press_handler(fake_gh):
"""Unlike a normal toggle binding (on_release only), a push-to-talk combo
must register a live on_press handler so the down edge is observable."""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(PTT_BINDINGS, push_to_talk={"ptt"}):
on_press, on_release = fake_gh.registered["control+alt+j"]
assert on_press is not None, "push-to-talk needs the down edge"
assert on_release is not None, "push-to-talk needs the up edge"
async def test_non_ptt_binding_stays_release_only(fake_gh):
"""A binding NOT marked push-to-talk keeps the legacy contract: only the
on_release edge fires, so a held key triggers exactly once (not per
key-repeat poll). The press edge must be ``None``."""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(PTT_BINDINGS, push_to_talk={"ptt"}) as trig:
on_press, on_release = fake_gh.registered["f1+f2"]
assert on_press is None, "toggle binding must not fire on the down edge"
assert on_release is not None
# And firing the press edge yields nothing — only release does.
fake_gh.fire_release("f1+f2")
assert await _next_event(trig) == "hangup"
async def test_default_has_no_push_to_talk_bindings(fake_gh):
"""Without the push_to_talk argument every binding is a release-only
toggle — the pre-PTT behaviour is preserved by default."""
from dodaios.trigger.hotkey import HotkeyTrigger
async with HotkeyTrigger(LIVE_BINDINGS):
for combo in ("control+alt+j", "f3+f4", "f1+f2"):
on_press, on_release = fake_gh.registered[combo]
assert on_press is None
assert on_release is not None