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(platform): repair macOS/Windows autostart, focus, input and ducking bugs

rubenluetke10-beep5a6a627b970e
diff --git a/jarvis/audio/ducking/factory.py b/jarvis/audio/ducking/factory.py
index 340ae54a7b..7591552bfc 100644
--- a/jarvis/audio/ducking/factory.py
+++ b/jarvis/audio/ducking/factory.py
@@ -28,7 +28,7 @@ def make_audio_ducker(cfg: Any | None = None) -> AudioDucker:
if sys.platform == "win32" and _pycaw_available():
from jarvis.audio.ducking.windows import WindowsPycawDucker
- return WindowsPycawDucker()
+ return WindowsPycawDucker.from_config(cfg)
if sys.platform == "darwin" and _osascript_available():
from jarvis.audio.ducking.macos import MacOSScriptDucker
diff --git a/jarvis/audio/ducking/macos.py b/jarvis/audio/ducking/macos.py
index 40adeed0b7..0ea2795a04 100644
--- a/jarvis/audio/ducking/macos.py
+++ b/jarvis/audio/ducking/macos.py
@@ -131,18 +131,42 @@ class MacOSScriptDucker:
del own_pid # per-app player volumes never touch our own process
skip = self._normalized_never(never)
ducked: list[int] = []
+ # "A known player is running" is NOT the same as "we ducked one": a
+ # player already sitting at (or below) the duck volume is running and
+ # handled, it simply needs no change. Falling back to the MASTER output
+ # in that case lowered Jarvis's own TTS — the exact side effect the
+ # opt-in fallback exists to keep rare — for no gain at all.
+ player_running = False
for token, (name, bundle_id) in _PLAYERS.items():
if name.lower() in skip:
continue
try:
proc = self._run(_duck_script(bundle_id, self._duck))
prev = self._parse_volume(proc, name)
- if prev is not None and prev > self._duck:
+ if prev is None:
+ continue # not running, or the script failed → not handled
+ player_running = True
+ if prev > self._duck:
self._saved[token] = prev
ducked.append(token)
+ elif token in self._saved:
+ # The player is still sitting at the duck volume AND we
+ # still hold the level it had before: a previous restore
+ # never landed (osascript timeout, an Automation prompt
+ # dismissed, Jarvis killed mid-session). Without this the
+ # token can never come back — the duck script reads the
+ # already-ducked volume, `prev > duck` stays false, so no
+ # session ever reports it again and the saved level is
+ # stranded in this dict while the user's music stays
+ # silent for good. Hand it to THIS session's restore.
+ log.info(
+ "ducking: re-adopting %s (still at the duck volume with "
+ "an unrestored level of %d)", name, self._saved[token],
+ )
+ ducked.append(token)
except Exception: # noqa: BLE001 — timeout/TCC denial: skip player
log.debug("ducking skip (%s)", name, exc_info=True)
- if not ducked and self._master_fallback:
+ if not ducked and not player_running and self._master_fallback:
try:
proc = self._run(_master_duck_script(self._duck))
prev = self._parse_volume(proc, "master")
diff --git a/jarvis/audio/ducking/windows.py b/jarvis/audio/ducking/windows.py
index 56318bc6af..b1979464b9 100644
--- a/jarvis/audio/ducking/windows.py
+++ b/jarvis/audio/ducking/windows.py
@@ -1,4 +1,14 @@
-"""Windows Core Audio per-app mute/restore via pycaw.
+"""Windows Core Audio per-app duck/restore via pycaw.
+
+Two modes, chosen by ``[ducking].duck_volume_percent``:
+
+* ``0`` (default) — hard-mute each other session and unmute it afterwards.
+* ``1..100`` — lower each other session's volume to that percentage and put
+ the previous level back afterwards, the same thing the macOS backend does
+ with the known players. The setting is a plain ``[ducking]`` field, not a
+ macOS-only one (``macos_master_fallback`` is the one that says so), yet
+ this backend used to ignore it entirely and always hard-mute: the number in
+ Settings did nothing on Windows and nothing said why (AP-31).
Must be called from a thread that has done ``CoInitialize()`` — the
``AudioDuckController`` runs these inside ``asyncio.to_thread`` with
@@ -9,37 +19,106 @@ to import on a host without it (the factory only constructs this class when
from __future__ import annotations
import logging
+from typing import Any
log = logging.getLogger("jarvis.audio.ducking")
+def _normalized_never(never: frozenset[str]) -> set[str]:
+ """Map never-mute entries to comparable app tokens.
+
+ ``[ducking].never_mute`` is documented as accepting either a Windows
+ process name ("Discord.exe") or a plain app name ("Spotify"), and the
+ macOS ducker already normalizes both. This one compared
+ ``proc.name()`` against the raw config strings, so it matched ONLY the
+ exact-case executable name: a user who wrote "Spotify" or "spotify.exe"
+ got their music muted anyway, silently, with the allowlist looking
+ correct in Settings. Case-fold and drop the ``.exe`` / ``.app`` suffix
+ so one entry means the same thing on both platforms.
+ """
+ out: set[str] = set()
+ for name in never:
+ token = name.strip().lower()
+ for suffix in (".exe", ".app"):
+ if token.endswith(suffix):
+ token = token[: -len(suffix)]
+ break
+ if token:
+ out.add(token)
+ return out
+
+
class WindowsPycawDucker:
+ def __init__(self, *, duck_volume_percent: int = 0) -> None:
+ self._duck = max(0, min(100, int(duck_volume_percent)))
+ #: pid -> master volume scalar before we lowered it. Only used in
+ #: volume mode; mute mode needs no state (unmute is unconditional).
+ self._saved: dict[int, float] = {}
+
+ @classmethod
+ def from_config(cls, cfg: Any | None) -> WindowsPycawDucker:
+ try:
+ ducking = getattr(cfg, "ducking", None)
+ return cls(
+ duck_volume_percent=int(
+ getattr(ducking, "duck_volume_percent", 0) or 0
+ ),
+ )
+ except Exception: # noqa: BLE001 — malformed config degrades to defaults
+ log.debug("ducking config read failed; using defaults", exc_info=True)
+ return cls()
+
def mute_others(self, *, own_pid: int, never: frozenset[str]) -> list[int]:
- """Mute every audio session except our own PID (protects Jarvis's TTS),
+ """Duck every audio session except our own PID (protects Jarvis's TTS),
the system-sounds session (PID 0 / no process), and the name allowlist.
- Returns the PIDs actually muted so restore() touches only those.
+ Returns the PIDs actually ducked so restore() touches only those.
+
+ Sessions the user already silenced are left alone in BOTH modes — we
+ only ever touch something currently audible, so restore can never turn
+ an app back on that the user had muted.
"""
from pycaw.pycaw import AudioUtilities
- muted: list[int] = []
+ skip = _normalized_never(never)
+ target = self._duck / 100.0
+ ducked: list[int] = []
for session in AudioUtilities.GetAllSessions():
try:
pid = session.ProcessId
if not pid or pid == own_pid: # 0 = system sounds; own = our TTS
continue
proc = session.Process
- if proc is not None and never and proc.name() in never:
- continue
+ if skip and proc is not None:
+ name = (proc.name() or "").strip().lower()
+ if name.endswith(".exe"):
+ name = name[: -len(".exe")]
+ if name in skip:
+ continue
vol = session.SimpleAudioVolume
- if not vol.GetMute(): # only mute ones currently audible
+ if vol.GetMute(): # already silent — nothing of ours to undo
+ continue
+ if self._duck <= 0:
vol.SetMute(1, None)
- muted.append(pid)
+ ducked.append(pid)
+ continue
+ prev = float(vol.GetMasterVolume())
+ if prev > target:
+ vol.SetMasterVolume(target, None)
+ self._saved[pid] = prev
+ ducked.append(pid)
except Exception: # noqa: BLE001 — COMError on protected sessions; skip
log.debug("ducking mute skip", exc_info=True)
- return muted
+ return ducked
def restore(self, pids: list[int]) -> None:
- """Unmute exactly the sessions whose PID we muted."""
+ """Undo exactly the sessions whose PID we ducked.
+
+ A pid with a saved volume gets that level back; anything else was
+ hard-muted, so it gets unmuted. Both are keyed off what we recorded at
+ duck time, never off the mode currently configured — turning the
+ duck-level knob mid-session must not strand an app at 10 % or leave a
+ muted one silent.
+ """
from pycaw.pycaw import AudioUtilities
want = set(pids)
@@ -47,7 +126,18 @@ class WindowsPycawDucker:
return
for session in AudioUtilities.GetAllSessions():
try:
- if session.ProcessId in want:
+ pid = session.ProcessId
+ if pid not in want:
+ continue
+ prev = self._saved.get(pid)
+ if prev is None:
session.SimpleAudioVolume.SetMute(0, None)
+ else:
+ session.SimpleAudioVolume.SetMasterVolume(prev, None)
except Exception: # noqa: BLE001
log.debug("ducking restore skip", exc_info=True)
+ # Drop the bookkeeping for every requested pid, including sessions that
+ # disappeared while ducked — otherwise a closed app's entry would sit
+ # here forever and a later pid reuse would restore a stranger's volume.
+ for pid in want:
+ self._saved.pop(pid, None)
diff --git a/jarvis/autostart/macos.py b/jarvis/autostart/macos.py
index 02d3938f33..e02486734d 100644
--- a/jarvis/autostart/macos.py
+++ b/jarvis/autostart/macos.py
@@ -39,12 +39,20 @@ def _program_arguments(spec: LaunchSpec) -> list[str]:
return [spec.program, *spec.args]
-def _launchctl(*argv: str) -> None:
- """Best-effort ``launchctl`` call — darwin-only, never raises."""
+def _launchctl(*argv: str) -> bool:
+ """Best-effort ``launchctl`` call — darwin-only, never raises.
+
+ Returns ``True`` when launchctl exited 0 (or when this is not darwin, where
+ the call is deliberately skipped). A non-zero exit used to be discarded
+ together with its stderr, so a failure like ``Load failed: 5: Input/output
+ error`` left NO trace at all while ``install`` still reported "Autostart
+ enabled and current" — the user saw a green toggle and no diagnosis for a
+ LaunchAgent that never armed in the running session (AP-30).
+ """
if sys.platform != "darwin":
- return
+ return True
try:
- subprocess.run(
+ proc = subprocess.run(
["launchctl", *argv],
capture_output=True,
text=True,
@@ -53,6 +61,16 @@ def _launchctl(*argv: str) -> None:
)
except Exception as exc: # noqa: BLE001 — live arming is a nicety, RunAtLoad covers next login
log.debug("launchctl %s failed (non-fatal): %s", " ".join(argv), exc)
+ return False
+ if proc.returncode != 0:
+ log.debug(
+ "launchctl %s exited %d: %s",
+ " ".join(argv),
+ proc.returncode,
+ (proc.stderr or proc.stdout or "").strip(),
+ )
+ return False
+ return True
class MacOSAutostart:
@@ -115,23 +133,56 @@ class MacOSAutostart:
"LimitLoadToSessionType": "Aqua",
}
tmp = self._path.with_suffix(".plist.tmp")
- with tmp.open("wb") as fh:
- plistlib.dump(plist, fh)
- tmp.replace(self._path)
+ try:
+ with tmp.open("wb") as fh:
+ plistlib.dump(plist, fh)
+ tmp.replace(self._path)
+ except BaseException:
+ # A half-written .plist.tmp left next to the real entry in
+ # ~/Library/LaunchAgents is confusing at best; the successful
+ # replace() consumes the temp file, so anything still there is
+ # debris from a failed write.
+ tmp.unlink(missing_ok=True)
+ raise
log.info("macOS LaunchAgent written: %s", self._path)
# Re-arm in the current session so it also works before the next login.
+ # unload WITHOUT -w (a plain refresh must not write Disabled=true into
+ # launchd's override database); load WITH -w to clear a Disabled flag a
+ # previous uninstall set.
_launchctl("unload", str(self._path))
- _launchctl("load", "-w", str(self._path))
+ if not _launchctl("load", "-w", str(self._path)):
+ log.info(
+ "macOS LaunchAgent written but launchctl could not arm it in this "
+ "session; RunAtLoad still starts Jarvis at the next login.",
+ )
return self.status(spec)
def uninstall(self, *, interactive: bool = False) -> AutostartStatus: # noqa: ARG002
_launchctl("unload", "-w", str(self._path))
+ removed = True
+ error = ""
if self._path.exists():
try:
self._path.unlink()
log.info("macOS LaunchAgent removed: %s", self._path)
except OSError as exc:
log.warning("Could not remove %s: %s", self._path, exc)
+ removed = False
+ error = str(exc)
+ if not removed:
+ # Reporting "Autostart disabled." while the plist survives was a
+ # lie: RunAtLoad still starts Jarvis at the next login, and the
+ # Settings toggle showed off with nothing to explain the mismatch.
+ return AutostartStatus(
+ supported=True,
+ installed=True,
+ matches_spec=False,
+ entry_path=str(self._path),
+ detail=(
+ f"The LaunchAgent could not be removed ({error}) — Jarvis may "
+ "still start at login; delete the file manually and retry."
+ ),
+ )
return AutostartStatus(
supported=True,
installed=False,
diff --git a/jarvis/autostart/windows.py b/jarvis/autostart/windows.py
index 52338e3f11..8174287f0d 100644
--- a/jarvis/autostart/windows.py
+++ b/jarvis/autostart/windows.py
@@ -106,6 +106,21 @@ def _current_user_id() -> str:
return getpass.getuser()
+def _ps_lit(value: object) -> str:
+ """Escape ``value`` for embedding in a SINGLE-quoted PowerShell literal.
+
+ A single-quoted PowerShell string takes everything literally except the
+ single quote itself, which is escaped by doubling it. Without this, one
+ apostrophe anywhere in the baked-in values ends the literal early and the
+ whole generated script fails to parse — so on a host whose login is
+ ``O'Brien`` (``C:\\Users\\O'Brien\\...``) or whose project folder is
+ ``Ruben's Jarvis``, task registration, task query and shortcut I/O all
+ fail and autostart silently never works. ``_run_powershell_elevated``
+ already escaped its own temp path this way; the script builders did not.
+ """
+ return str(value).replace("'", "''")
+
+
# --------------------------------------------------------------------------- #
# Pure PowerShell-script builders (CI-provable on any OS) #
# --------------------------------------------------------------------------- #
@@ -124,18 +139,18 @@ def build_register_task_script(
return (
"$ErrorActionPreference = 'Stop'\n"
"try {\n"
- f" $action = New-ScheduledTaskAction -Execute '{spec.program}' "
- f"-Argument '{args}' -WorkingDirectory '{spec.working_dir}'\n"
+ f" $action = New-ScheduledTaskAction -Execute '{_ps_lit(spec.program)}' "
+ f"-Argument '{_ps_lit(args)}' -WorkingDirectory '{_ps_lit(spec.working_dir)}'\n"
" $trigger = New-ScheduledTaskTrigger -AtLogOn\n"
f" $trigger.Delay = 'PT{int(delay_seconds)}S'\n"
- f" $principal = New-ScheduledTaskPrincipal -UserId '{user_id}' "
+ f" $principal = New-ScheduledTaskPrincipal -UserId '{_ps_lit(user_id)}' "
"-LogonType Interactive -RunLevel Limited\n"
" $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries "
"-DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) "
"-MultipleInstances IgnoreNew\n"
- f" Register-ScheduledTask -TaskName '{task_name}' -Action $action "
+ f" Register-ScheduledTask -TaskName '{_ps_lit(task_name)}' -Action $action "
"-Trigger $trigger -Principal $principal -Settings $settings "
- f"-Description '{WINDOWS_AUTOSTART_DESCRIPTION}' -Force | Out-Null\n"
+ f"-Description '{_ps_lit(WINDOWS_AUTOSTART_DESCRIPTION)}' -Force | Out-Null\n"
" exit 0\n"
"} catch { exit 1 }\n"
)
@@ -145,7 +160,7 @@ def build_query_task_script(task_name: str) -> str:
"""Pure: non-elevated PowerShell that prints the task action via sentinels."""
return (
"$ErrorActionPreference = 'SilentlyContinue'\n"
- f"$t = Get-ScheduledTask -TaskName '{task_name}'\n"
+ f"$t = Get-ScheduledTask -TaskName '{_ps_lit(task_name)}'\n"
"if ($t) {\n"
" $a = $t.Actions | Select-Object -First 1\n"
f" Write-Output ('{_QUERY_SENTINEL}' + $a.Execute)\n"
@@ -160,7 +175,7 @@ def build_unregister_task_script(task_name: str) -> str:
return (
"$ErrorActionPreference = 'Stop'\n"
"try {\n"
- f" Unregister-ScheduledTask -TaskName '{task_name}' -Confirm:$false "
+ f" Unregister-ScheduledTask -TaskName '{_ps_lit(task_name)}' -Confirm:$false "
"-ErrorAction SilentlyContinue\n"
" exit 0\n"
"} catch { exit 1 }\n"
@@ -194,15 +209,15 @@ def build_create_script(link: Path, spec: LaunchSpec, *, icon: str | None = None
"""
window_style = 7 if spec.minimized else 1
args = " ".join(spec.args)
- icon_line = f"$sc.IconLocation = '{icon},0'\n" if icon else ""
+ icon_line = f"$sc.IconLocation = '{_ps_lit(icon)},0'\n" if icon else ""
return (
"$ErrorActionPreference = 'Stop'\n"
"$ws = New-Object -ComObject WScript.Shell\n"
- f"$sc = $ws.CreateShortcut('{link}')\n"
- f"$sc.TargetPath = '{spec.program}'\n"
- f"$sc.Arguments = '{args}'\n"
- f"$sc.WorkingDirectory = '{spec.working_dir}'\n"
- f"$sc.Description = '{WINDOWS_AUTOSTART_DESCRIPTION}'\n"
+ f"$sc = $ws.CreateShortcut('{_ps_lit(link)}')\n"
+ f"$sc.TargetPath = '{_ps_lit(spec.program)}'\n"
+ f"$sc.Arguments = '{_ps_lit(args)}'\n"
+ f"$sc.WorkingDirectory = '{_ps_lit(spec.working_dir)}'\n"
+ f"$sc.Description = '{_ps_lit(WINDOWS_AUTOSTART_DESCRIPTION)}'\n"
f"{icon_line}"
f"$sc.WindowStyle = {window_style}\n"
"$sc.Save()\n"
@@ -214,7 +229,7 @@ def build_read_script(link: Path) -> str:
return (
"$ErrorActionPreference = 'Stop'\n"
"$ws = New-Object -ComObject WScript.Shell\n"
- f"$sc = $ws.CreateShortcut('{link}')\n"
+ f"$sc = $ws.CreateShortcut('{_ps_lit(link)}')\n"
f"Write-Output ('{_READBACK_SENTINEL}' + $sc.TargetPath)\n"
f"Write-Output ('{_READBACK_SENTINEL}' + $sc.Arguments)\n"
f"Write-Output ('{_READBACK_SENTINEL}' + $sc.WorkingDirectory)\n"
@@ -295,7 +310,14 @@ def _run_powershell_elevated(script: str) -> bool:
"""
fd, path = tempfile.mkstemp(suffix=".ps1")
try:
- with os.fdopen(fd, "w", encoding="utf-8") as fh:
+ # utf-8-SIG, not plain utf-8: Windows PowerShell 5.1 (the `powershell`
+ # this launches) decodes a BOM-less -File script with the system ANSI
+ # codepage. Without the BOM every non-ASCII character baked into the
+ # script — an accented or umlauted login name in the interpreter path,
+ # a project folder with one, the description — is mojibake'd, so the
+ # registered task points at a path that does not exist (AP-7's BOM
+ # class). Every non-English-speaking user has such a path.
+ with os.fdopen(fd, "w", encoding="utf-8-sig") as fh:
fh.write(script)
# Escape any single-quote in the temp path (e.g. a login like O'Brien →
# C:\Users\O'Brien\...\Temp) before baking it into the single-quoted PS arg.
@@ -414,6 +436,19 @@ class WindowsAutostart:
# Already correct → idempotent no-op (the common boot case once enabled).
info = self._task_probe()
if info is not None and self._task_matches(info, spec):
+ # ...except for a leftover fallback .lnk. A boot whose task probe
+ # transiently failed (PowerShell is slow under login load, and a
+ # failed query is treated as "no task") writes the shortcut, and
+ # nothing removed it once the task became visible again — so Jarvis
+ # launched TWICE at login, once via the task and once via the
+ # Explorer startup queue. The task is authoritative; drop the
+ # fallback whenever both exist.
+ if self._shortcut_present():
+ log.info(
+ "Autostart: removing the leftover startup shortcut — the "
+ "scheduled task already covers this install."
+ )
+ self._remove_shortcut()
return self.status(spec)
if interactive:
@@ -449,6 +484,28 @@ class WindowsAutostart:
info = self._task_probe()
if info is not None and interactive:
self._run_elevated(build_unregister_task_script(self._task_name))
+ info = self._task_probe() # did the elevated removal actually land?
+ if info is not None:
+ # Unregistering the task needs elevation: the silent boot reconcile
+ # must never prompt, and an interactive user can decline the UAC
+ # prompt. Reporting "disabled" in either case was a lie — the
+ # Settings toggle showed autostart off while the logon task kept
+ # starting Jarvis at every login, with nothing to explain why.
+ log.warning(
+ "Autostart: the logon scheduled task survives (removing it needs "
+ "a one-time admin confirmation) — reporting it as still installed."
+ )
+ return AutostartStatus(
+ supported=True,
+ installed=True,
+ matches_spec=False,
+ entry_path=self._task_entry_path(),
+ detail=(
+ "Startup shortcut removed, but the scheduled task still starts "
+ "Jarvis at login — turn instant start off in Settings and "
+ "confirm the admin prompt to remove it."
+ ),
+ )
return AutostartStatus(
supported=True,
installed=False,
@@ -480,7 +537,17 @@ class WindowsAutostart:
for line in result.stdout.splitlines()
if line.startswith(_READBACK_SENTINEL)
]
- target, args, workdir = (fields + ["", "", ""])[:3]
+ if len(fields) < 3:
+ # A truncated read-back is "unknown", not "matches". Padding the
+ # missing fields with "" made a half-failed COM read compare equal
+ # to any spec with no args — reporting a stale shortcut as current
+ # and suppressing the refresh that would have fixed it.
+ log.debug(
+ "shortcut read-back returned %d of 3 fields — treating as drift",
+ len(fields),
+ )
+ return False
+ target, args, workdir = fields[:3]
return (
_norm(target) == _norm(spec.program)
and args.strip() == " ".join(spec.args).strip()
diff --git a/jarvis/awareness/watchers/window.py b/jarvis/awareness/watchers/window.py
index 73f35e6fe6..6646a31a59 100644
--- a/jarvis/awareness/watchers/window.py
+++ b/jarvis/awareness/watchers/window.py
@@ -29,10 +29,11 @@ the Win32 drain loop uses, so both platforms publish identical
display (no TCC/Accessibility grant is needed just to read the frontmost
application — ``window_state.foreground_window()`` already degrades to
``None`` without the optional Screen-Recording grant or without pyobjc, and
-that "no usable window" case feeds the same consecutive-failure counter
-that disables the fallback rather than spinning forever). Headless Linux
-and Wayland sessions are gated up front (mirrors ``IdleDetector``): one
-honest log line, no polling task, no crash.
+that "no window at all" case feeds the consecutive-failure counter that
+disables the fallback rather than spinning forever; a window that merely
+has no readable TITLE is a healthy probe and never counts against it).
+Headless Linux and Wayland sessions are gated up front (mirrors
+``IdleDetector``): one honest log line, no polling task, no crash.
Lifecycle order in ``stop()`` (subagent Q4, 6 phases):
P1: cancel drain task (asyncio side first, so no ``bus.publish``
@@ -42,8 +43,12 @@ Lifecycle order in ``stop()`` (subagent Q4, 6 phases):
P4: defensive ``UnhookWinEvent`` in case the pump thread crashed; the
primary cleanup path is in the pump thread's finally block.
P5: ``CloseHandle(stop_event)``.
- P6: remaining queue items are GC'd (loss acceptable — Plan §5 does not
- require no-event-loss on shutdown).
+ P6: remaining queue items are DRAINED and the per-run change-detection
+ state is reset (loss acceptable — Plan §5 does not require
+ no-event-loss on shutdown — but carrying either into a later
+ ``start()`` is not: the queue and the "last seen window" markers live
+ on the instance, so a restart would replay pre-stop frames and then
+ swallow the first genuine one as "unchanged").
"""
from __future__ import annotations
@@ -194,6 +199,7 @@ class WindowFocusWatcher:
if detect_platform() != "win32":
try:
await self._stop_posix_polling()
+ self._reset_frame_state()
finally:
self._started = False
self._stopping = False
@@ -264,16 +270,41 @@ class WindowFocusWatcher:
pass
self._stop_event_handle = None
- # P6: leftover queue items get GC'd. Log the drops counter.
+ # P6: discard leftover queue items. They must NOT survive into a
+ # later start(): the queue lives on the instance, so a restart
+ # (awareness toggled off and on again) used to drain events
+ # captured before the stop and publish them as fresh frames with
+ # their old timestamps.
if self._drops > 0:
logger.info(
"WindowFocusWatcher: %d frames dropped (pump=%d, async=%d)",
self._drops, self._drops_pump, self._drops_async,
)
+ self._reset_frame_state()
finally:
self._started = False
self._stopping = False
+ def _reset_frame_state(self) -> None:
+ """Drop queued frames and per-run change-detection state.
+
+ Both survive on the instance across a stop/start cycle, and both are
+ wrong on the next run: the queued payloads describe windows from the
+ previous session, and the stale "last seen" markers make the FIRST
+ probe after a restart compare equal to what was focused before the
+ stop — so the POSIX poller emitted nothing at all until the user
+ happened to switch windows, leaving ``state.current_frame`` frozen.
+ """
+ while True:
+ try:
+ self._queue.get_nowait()
+ except asyncio.QueueEmpty:
+ break
+ self._last_hwnd = 0
+ self._last_emit_ns = 0
+ self._poll_last_handle = None
+ self._poll_last_title = ""
+
# ---- Win32-Pump-Thread --------------------------------------------------
@staticmethod
@@ -374,6 +405,7 @@ class WindowFocusWatcher:
# MsgWaitForMultipleObjects-Loop
QS_ALLINPUT = 0x04FF
WAIT_OBJECT_0 = 0x00000000
+ MSG_PENDING = WAIT_OBJECT_0 + 1
INFINITE = 0xFFFFFFFF
PM_REMOVE = 0x0001
@@ -383,9 +415,25 @@ class WindowFocusWatcher:
rc = win32event.MsgWaitForMultipleObjects(
[self._stop_event_handle], False, INFINITE, QS_ALLINPUT,
)
- if rc == WAIT_OBJECT_0:
- break # stop signalled
- # rc == WAIT_OBJECT_0 + 1 → messages are pending
+ # Only WAIT_OBJECT_0 + 1 means "messages are pending". Anything
+ # else is either the stop event (WAIT_OBJECT_0) or a wait that
+ # failed — WAIT_FAILED (0xFFFFFFFF) or WAIT_ABANDONED_0 on a
+ # closed/invalid stop handle. Falling through to PeekMessage on
+ # a failed wait spun this thread at 100 % CPU forever, because
+ # nothing in the loop can clear the failure and the wait returns
+ # immediately every time. Treat any non-message result as
+ # terminal and leave (same doctrine as AP-20 for socket loops):
+ # stop() still joins us, and the finally block unhooks.
+ if rc != MSG_PENDING:
+ if rc != WAIT_OBJECT_0:
+ logger.error(
+ "WindowFocusWatcher: MsgWaitForMultipleObjects "
+ "returned 0x%08X (last_error=%d) — pump stopped, "
+ "focus tracking is off until the next start()",
+ int(rc) & 0xFFFFFFFF,
+ ctypes.get_last_error(),
+ )
+ break
while user32.PeekMessageW(ctypes.byref(msg), 0, 0, 0, PM_REMOVE):
user32.TranslateMessage(ctypes.byref(msg))
user32.DispatchMessageW(ctypes.byref(msg))
@@ -541,14 +589,33 @@ class WindowFocusWatcher:
from ctypes import wintypes # noqa: PLC0415
try:
- user32 = ctypes.windll.user32
- length = user32.GetWindowTextLengthW(hwnd)
+ # Own WinDLL instance + explicit argtypes, exactly like the
+ # UnhookWinEvent call in stop(): with the shared ``ctypes.windll``
+ # and no signatures, the HWND is marshalled as a 32-bit c_int, so a
+ # handle above 0x7FFFFFFF raises ArgumentError (frame silently
+ # dropped) instead of resolving — and binding signatures on the
+ # PROCESS-WIDE windll would leak into vision/screenshot.py and
+ # window_state.py, which configure the same functions themselves.
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+ user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
+ user32.GetWindowTextLengthW.restype = ctypes.c_int
+ user32.GetWindowTextW.argtypes = [
+ wintypes.HWND, wintypes.LPWSTR, ctypes.c_int,
+ ]
+ user32.GetWindowTextW.restype = ctypes.c_int
+ user32.GetWindowThreadProcessId.argtypes = [
+ wintypes.HWND, ctypes.POINTER(wintypes.DWORD),
+ ]
+ user32.GetWindowThreadProcessId.restype = wintypes.DWORD
+
+ handle = wintypes.HWND(hwnd)
+ length = max(0, int(user32.GetWindowTextLengthW(handle)))
buf = ctypes.create_unicode_buffer(length + 1)
- user32.GetWindowTextW(hwnd, buf, length + 1)
+ user32.GetWindowTextW(handle, buf, length + 1)
title = buf.value or ""
pid = wintypes.DWORD()
- user32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
+ user32.GetWindowThreadProcessId(handle, ctypes.byref(pid))
pid_int = int(pid.value)
try:
@@ -655,10 +722,10 @@ class WindowFocusWatcher:
"""One polling iteration: probe the foreground window, emit a frame
via :meth:`_emit_frame` if focus actually changed.
- Returns ``True`` when the probe returned usable window info
- (whether or not focus changed — an unchanged focus is still a
- healthy probe), ``False`` when it returned nothing usable (feeds
- the consecutive-failure counter in :meth:`_poll_loop`).
+ Returns ``True`` when the probe itself worked (whether or not focus
+ changed — an unchanged focus is still a healthy probe), ``False``
+ only when the backend answered with nothing at all (feeds the
+ consecutive-failure counter in :meth:`_poll_loop`).
Independently testable — tests call this directly instead of
waiting out the real polling interval.
"""
@@ -668,9 +735,25 @@ class WindowFocusWatcher:
logger.debug("POSIX foreground-window probe failed", exc_info=True)
return False
- if win is None or not (win.title or "").strip():
+ if win is None:
return False
+ if not (win.title or "").strip():
+ # A window WITHOUT a readable title is not a broken backend — X11
+ # windows legitimately carry no name, and xdotool's getwindowname
+ # can fail for one window while getactivewindow keeps working.
+ # Counting it as a failure meant five such polls (10 s) permanently
+ # disabled focus tracking for the whole session, with no way back
+ # short of a restart. Report the probe as healthy, but publish
+ # nothing: a frame with no title is unidentifiable, and the privacy
+ # filter must never be handed an empty title to wave through.
+ logger.debug(
+ "POSIX foreground window has no readable title (handle=%s) — "
+ "probe healthy, frame not published",
+ win.handle,
+ )
+ return True
+
changed = (win.handle, win.title) != (self._poll_last_handle, self._poll_last_title)
if not changed:
return True
@@ -702,41 +785,50 @@ class WindowFocusWatcher:
def _resolve_posix_focus_meta(win: WindowInfo) -> tuple[int, str]:
"""Best-effort ``(pid, process_name)`` for a foreground ``WindowInfo``.
- macOS: the frontmost application via ``NSWorkspace`` — the same
- source ``window_state`` uses internally to resolve the foreground
- title, so pid and title stay consistent even without the
- Screen-Recording grant and without any Accessibility permission
- (NSWorkspace's frontmost-application query needs neither). Linux:
- ``xdotool`` resolves the owning pid from the X11 window id.
- ``psutil`` resolves the process name from the pid on both. Never
- raises — a missing pyobjc/xdotool or a transient lookup error
- degrades to ``(0, "")``; the frame still publishes and title-based
- privacy filtering still applies.
+ The pid the PROBE already resolved wins. ``window_state.foreground_window``
+ fills ``WindowInfo.pid`` on all three platforms from the very same
+ window it took the title from, so using it keeps title and process
+ identity from the same instant. Re-querying "who is frontmost NOW"
+ instead — as this did unconditionally — pairs app A's title with app
+ B's process whenever focus moves between the probe and this call
+ (a 2 s poll makes that window wide open), and the PrivacyFilter then
+ judges a title against the wrong process name in both directions:
+ a blocked app waved through, or an allowed one blocked.
+
+ Only when the probe carries no pid does this fall back to a live
+ query — macOS: ``NSWorkspace``'s frontmost application (needs neither
+ the Screen-Recording nor the Accessibility grant); Linux: ``xdotool``
+ resolves the owning pid from the X11 window id. ``psutil`` resolves
+ the process name from the pid on both. Never raises — a missing
+ pyobjc/xdotool or a transient lookup error degrades to ``(0, "")``;
+ the frame still publishes and title-based privacy filtering still
+ applies.
"""
- pid = 0
- try:
- plat = detect_platform()
- if plat == "darwin":
- from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415
-
- app = NSWorkspace.sharedWorkspace().frontmostApplication()
- if app is not None:
- pid = int(app.processIdentifier())
- elif plat == "linux" and win.handle and shutil.which("xdotool"):
- proc = subprocess.run(
- ["xdotool", "getwindowpid", str(int(win.handle))],
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=5,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if proc.returncode == 0:
- pid = int((proc.stdout or "").strip() or "0")
- except Exception: # noqa: BLE001
- logger.debug("POSIX focus pid resolution failed", exc_info=True)
- pid = 0
+ pid = int(win.pid or 0)
+ if pid <= 0:
+ try:
+ plat = detect_platform()
+ if plat == "darwin":
+ from AppKit import NSWorkspace # type: ignore[import-not-found] # noqa: PLC0415
+
+ app = NSWorkspace.sharedWorkspace().frontmostApplication()
+ if app is not None:
+ pid = int(app.processIdentifier())
+ elif plat == "linux" and win.handle and shutil.which("xdotool"):
+ proc = subprocess.run(
+ ["xdotool", "getwindowpid", str(int(win.handle))],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=5,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ if proc.returncode == 0:
+ pid = int((proc.stdout or "").strip() or "0")
+ except Exception: # noqa: BLE001
+ logger.debug("POSIX focus pid resolution failed", exc_info=True)
+ pid = 0
process_name = ""
if pid > 0:
diff --git a/jarvis/cu/actuate/windows.py b/jarvis/cu/actuate/windows.py
index f261657031..0191e4ba5c 100644
--- a/jarvis/cu/actuate/windows.py
+++ b/jarvis/cu/actuate/windows.py
@@ -78,6 +78,46 @@ _VK_TABLE: dict[str, int] = {
"decimal": 0x6E, "divide": 0x6F,
}
+# Control characters KEYEVENTF_UNICODE cannot deliver, mapped to the virtual
+# key that actually produces them. Windows edit controls act on the KEY, not on
+# a synthetic WM_CHAR: a U+000A sent as a unicode "scan code" types NOTHING, so
+# type_text("line1\nline2") landed as one run-on line and tabs vanished — while
+# the pynput backend on macOS/Linux pressed Enter/Tab for the same string. VK
+# 0x0D/0x09 are the main-block keys and deliberately NOT extended (E0 belongs to
+# numpad Enter).
+_TEXT_CONTROL_VKS: dict[str, int] = {"\n": 0x0D, "\r": 0x0D, "\t": 0x09}
+
+# Punctuation keys, by the character the UNSHIFTED key produces. The shared
+# Computer-Use vocabulary (``base.is_known_key_name``) accepts any single
+# printable character, and the pynput backend types it happily — but this
+# backend resolved only a-z and 0-9, so every punctuation shortcut raised
+# "Unknown key" and the action failed outright: Ctrl+- / Ctrl+= (zoom out/in,
+# the single most common CU shortcut after copy/paste), Ctrl+, (settings in
+# VS Code, Chrome, Slack), Ctrl+/ (comment/shortcut help), Ctrl+[ / Ctrl+]
+# (indent, browser back/forward).
+#
+# VK_OEM_PLUS/MINUS/COMMA/PERIOD are defined by Microsoft as the +, -, , and .
+# key "for any country/region", so those four are layout-independent. VK_OEM_1
+# and 3..7 are documented as US-layout positions and may sit under a different
+# character elsewhere — still strictly better than today's hard failure, and
+# applications bind zoom/comment shortcuts to these VKs by position anyway.
+# Shifted characters (+, _, {, ...) are deliberately absent: emitting the
+# unshifted key for them would send input the caller did not ask for, and a
+# loud "Unknown key" beats a wrong keystroke.
+_OEM_PUNCTUATION_VKS: dict[str, int] = {
+ ";": 0xBA, # VK_OEM_1 (US)
+ "=": 0xBB, # VK_OEM_PLUS (any layout)
+ ",": 0xBC, # VK_OEM_COMMA (any layout)
+ "-": 0xBD, # VK_OEM_MINUS (any layout)
+ ".": 0xBE, # VK_OEM_PERIOD (any layout)
+ "/": 0xBF, # VK_OEM_2 (US)
+ "`": 0xC0, # VK_OEM_3 (US)
+ "[": 0xDB, # VK_OEM_4 (US)
+ "\\": 0xDC, # VK_OEM_5 (US)
+ "]": 0xDD, # VK_OEM_6 (US)
+ "'": 0xDE, # VK_OEM_7 (US)
+}
+
# Extended keys (E0 prefix) — without KEYEVENTF_EXTENDEDKEY a standalone tap
# is rejected or misrouted.
_EXTENDED_VKS = frozenset({
@@ -98,6 +138,8 @@ def resolve_vk(key: str) -> int | None:
return ord(k.upper())
if "0" <= k <= "9":
return ord(k)
+ if k in _OEM_PUNCTUATION_VKS:
+ return _OEM_PUNCTUATION_VKS[k]
return None
@@ -374,20 +416,34 @@ class WindowsActuator(Actuator):
def type_text(self, text: str, *, delay_s: float = 0.02) -> None:
with input_space():
+ pending_cr = False
for char in text:
- # KEYEVENTF_UNICODE takes UTF-16 code UNITS; astral-plane
- # characters (emoji) need their surrogate pair sent as two
- # events each — a bare ord() overflows the WORD wScan field.
- units = char.encode("utf-16-le")
- events = []
- for i in range(0, len(units), 2):
- code = int.from_bytes(units[i:i + 2], "little")
- events.append(self._key_input(0, code, _KEYEVENTF_UNICODE))
- events.append(
- self._key_input(
- 0, code, _KEYEVENTF_UNICODE | _KEYEVENTF_KEYUP,
- ),
- )
+ # A CRLF pair is ONE line break, not two Enter presses.
+ if pending_cr and char == "\n":
+ pending_cr = False
+ continue
+ pending_cr = char == "\r"
+
+ vk = _TEXT_CONTROL_VKS.get(char)
+ if vk is not None:
+ events = [
+ self._key_input(vk, 0, 0),
+ self._key_input(vk, 0, _KEYEVENTF_KEYUP),
+ ]
+ else:
+ # KEYEVENTF_UNICODE takes UTF-16 code UNITS; astral-plane
+ # characters (emoji) need their surrogate pair sent as two
+ # events each — a bare ord() overflows the WORD wScan field.
+ units = char.encode("utf-16-le")
+ events = []
+ for i in range(0, len(units), 2):
+ code = int.from_bytes(units[i:i + 2], "little")
+ events.append(self._key_input(0, code, _KEYEVENTF_UNICODE))
+ events.append(
+ self._key_input(
+ 0, code, _KEYEVENTF_UNICODE | _KEYEVENTF_KEYUP,
+ ),
+ )
self._send(events)
if delay_s > 0:
time.sleep(delay_s)
diff --git a/jarvis/platform/window_state.py b/jarvis/platform/window_state.py
index c131e73ba3..c4cea72eec 100644
--- a/jarvis/platform/window_state.py
+++ b/jarvis/platform/window_state.py
@@ -263,9 +263,20 @@ def _force_foreground_windows(hwnd: int) -> bool:
get_thread.restype = wintypes.DWORD
get_thread.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
- # Restore if minimized, then try the cheap plain path first — it succeeds
- # whenever Jarvis launched the process and input is recent.
- user32.ShowWindow(hwnd, _SW_RESTORE)
+ # Restore ONLY if minimized, then try the cheap plain path first — it
+ # succeeds whenever Jarvis launched the process and input is recent.
+ #
+ # The IsIconic guard is load-bearing, not an optimization: SW_RESTORE
+ # means "restore to the size and position before minimize OR maximize",
+ # so calling it unconditionally UN-MAXIMIZED every already-maximized
+ # window this path touches. Every foreground site funnels through here —
+ # switch_window ("switch to Chrome"), the open_app already-running path,
+ # raise_after_launch, the CU settle fallback — so asking Jarvis to focus a
+ # maximized app shrank it back to its restored size as a side effect, and
+ # for Computer-Use it silently changed the very geometry the next
+ # screenshot is mapped against.
+ if user32.IsIconic(hwnd):
+ user32.ShowWindow(hwnd, _SW_RESTORE)
if user32.SetForegroundWindow(hwnd):
user32.SetActiveWindow(hwnd)
return True
@@ -285,7 +296,8 @@ def _force_foreground_windows(hwnd: int) -> bool:
user32.AttachThreadInput(cur_thread, target_thread, True)
)
user32.BringWindowToTop(hwnd)
- user32.ShowWindow(hwnd, _SW_RESTORE)
+ if user32.IsIconic(hwnd): # same rule as above: never un-maximize
+ user32.ShowWindow(hwnd, _SW_RESTORE)
ok = bool(user32.SetForegroundWindow(hwnd))
user32.SetActiveWindow(hwnd)
return ok
diff --git a/tests/unit/audio/test_ducking_macos.py b/tests/unit/audio/test_ducking_macos.py
index 0732acf595..65d872028b 100644
--- a/tests/unit/audio/test_ducking_macos.py
+++ b/tests/unit/audio/test_ducking_macos.py
@@ -147,3 +147,51 @@ def test_already_quiet_player_is_not_tokenized():
d = _ducker(run, duck_volume_percent=0)
assert d.mute_others(own_pid=1, never=frozenset()) == []
assert d._saved == {}
+
+
+def test_master_fallback_skipped_when_a_running_player_is_already_quiet():
+ """"Nothing was ducked" is not "no player is running".
+
+ Music running at volume 0 needs no duck, so the tier is already handled.
+ Falling through to the MASTER output there lowered Jarvis's own TTS — the
+ side effect the fallback is opt-in to avoid — and silenced the answer the
+ user was waiting for, for no gain.
+ """
+ run = FakeRunner({_MUSIC: "0", _SPOTIFY: "-", "master": "80"})
+ d = _ducker(run, master_fallback=True, duck_volume_percent=0)
+ assert d.mute_others(own_pid=1, never=frozenset()) == []
+ assert not any("output volume" in s for s in run.scripts)
+ assert d._saved == {}
+
+
+def test_unrestored_player_is_re_adopted_by_the_next_session():
+ """A duck whose restore never landed must not strand the user's volume.
+
+ The player then sits AT the duck volume with our saved level still in
+ ``_saved``: every later duck reads that already-ducked volume, so
+ ``prev > duck`` stays false and the token is never reported again — the
+ music stays silent for good. The next session has to re-adopt it.
+ """
+ run = FakeRunner({_MUSIC: "65", _SPOTIFY: "-"})
+ d = _ducker(run)
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]
+
+ # Session 1 ends, but the restore osascript times out -> saved level stays.
+ run._results[_MUSIC] = subprocess.TimeoutExpired(cmd="osascript", timeout=3.0)
+ d.restore([1])
+ assert d._saved == {1: 65}
+
+ # Session 2: Music still reads 0 (ducked). It must come back as a token.
+ run._results[_MUSIC] = "0"
+ assert d.mute_others(own_pid=1, never=frozenset()) == [1]
+ d.restore([1])
+ assert any("set sound volume to 65" in s for s in run.scripts)
+ assert d._saved == {}
+
+
+def test_re_adoption_needs_a_saved_level_not_just_a_quiet_player():
+ """A player the USER turned down must never be claimed as ours."""
+ run = FakeRunner({_MUSIC: "0", _SPOTIFY: "-"})
+ d = _ducker(run)
+ assert d.mute_others(own_pid=1, never=frozenset()) == []
+ assert d._saved == {}
diff --git a/tests/unit/audio/test_ducking_windows.py b/tests/unit/audio/test_ducking_windows.py
new file mode 100644
index 0000000000..6c99efc836
--- /dev/null
+++ b/tests/unit/audio/test_ducking_windows.py
@@ -0,0 +1,260 @@
+"""WindowsPycawDucker: mute mode, volume mode, allowlist and restore.
+
+pycaw is imported lazily inside the methods, so a fake ``pycaw.pycaw`` module
+covers the whole decision logic on any OS — no Core Audio, no Windows host.
+"""
+from __future__ import annotations
+
+import sys
+import types
+
+import pytest
+
+from jarvis.audio.ducking.windows import WindowsPycawDucker
+
+
+class _FakeVolume:
+ def __init__(self, master: float = 1.0, muted: bool = False) -> None:
+ self.master = float(master)
+ self.muted = bool(muted)
+
+ def GetMute(self) -> int: # noqa: N802 — mirrors the pycaw COM name
+ return int(self.muted)
+
+ def SetMute(self, value: int, _ctx: object) -> None: # noqa: N802
+ self.muted = bool(value)
+
+ def GetMasterVolume(self) -> float: # noqa: N802
+ return self.master
+
+ def SetMasterVolume(self, value: float, _ctx: object) -> None: # noqa: N802
+ self.master = float(value)
+
+
+class _FakeProcess:
+ def __init__(self, name: str) -> None:
+ self._name = name
+
+ def name(self) -> str:
+ return self._name
+
+
+class _FakeSession:
+ def __init__(
+ self,
+ pid: int,
+ process_name: str | None = None,
+ *,
+ master: float = 1.0,
+ muted: bool = False,
+ ) -> None:
+ self.ProcessId = pid
+ self.Process = _FakeProcess(process_name) if process_name else None
+ self.SimpleAudioVolume = _FakeVolume(master=master, muted=muted)
+
+
+def fake_pycaw(monkeypatch):
+ """Install a fake ``pycaw.pycaw`` whose session list the test controls."""
+ sessions: list[_FakeSession] = []
+ module = types.ModuleType("pycaw.pycaw")
+ module.AudioUtilities = types.SimpleNamespace(
+ GetAllSessions=lambda: list(sessions),
+ )
+ package = types.ModuleType("pycaw")
+ package.pycaw = module
+ monkeypatch.setitem(sys.modules, "pycaw", package)
+ monkeypatch.setitem(sys.modules, "pycaw.pycaw", module)
+ return sessions
+
+
+# --------------------------------------------------------------------------- #
+# Mute mode (duck_volume_percent = 0, the default) #
+# --------------------------------------------------------------------------- #
+
+
+def test_mutes_other_sessions_and_restores_them(fake_pycaw):
+ other = _FakeSession(4321, "spotify.exe")
+ fake_pycaw.extend([other])
+ ducker = WindowsPycawDucker()
+
+ assert ducker.mute_others(own_pid=111, never=frozenset()) == [4321]
+ assert other.SimpleAudioVolume.muted is True
+
+ ducker.restore([4321])
+ assert other.SimpleAudioVolume.muted is False
+
+
+def test_own_pid_and_system_session_are_never_touched(fake_pycaw):
+ system = _FakeSession(0)
+ own = _FakeSession(111, "pythonw.exe")
+ fake_pycaw.extend([system, own])
+
+ assert WindowsPycawDucker().mute_others(own_pid=111, never=frozenset()) == []
+ assert system.SimpleAudioVolume.muted is False
+ assert own.SimpleAudioVolume.muted is False
+
+
+def test_already_muted_session_is_left_alone_and_not_unmuted(fake_pycaw):
+ """A session the USER muted must never come back on through restore().
+
+ The guarantee is carried by the token list: an already-silent session is
+ not reported by ``mute_others``, so the controller — which only ever hands
+ back what it received — never asks restore() about it.
+ """
+ user_muted = _FakeSession(4321, "spotify.exe", muted=True)
+ audible = _FakeSession(4322, "chrome.exe")
+ fake_pycaw.extend([user_muted, audible])
+ ducker = WindowsPycawDucker()
+
+ ducked = ducker.mute_others(own_pid=1, never=frozenset())
+ assert ducked == [4322]
+
+ ducker.restore(ducked)
+ assert user_muted.SimpleAudioVolume.muted is True
+ assert audible.SimpleAudioVolume.muted is False
+
+
+ "entry", ["Discord.exe", "discord.exe", "Discord", "discord", "Discord.app"],
+)
+def test_never_list_matches_case_and_suffix_insensitively(fake_pycaw, entry):
+ """One allowlist entry means the same thing however the user wrote it."""
+ protected = _FakeSession(900, "Discord.exe")
+ other = _FakeSession(901, "chrome.exe")
+ fake_pycaw.extend([protected, other])
+
+ ducked = WindowsPycawDucker().mute_others(own_pid=1, never=frozenset({entry}))
+
+ assert ducked == [901]
+ assert protected.SimpleAudioVolume.muted is False
+
+
+def test_session_without_a_process_object_is_still_ducked(fake_pycaw):
+ """No Process handle (protected session) must not skip the duck entirely."""
+ headless = _FakeSession(700, None)
+ fake_pycaw.extend([headless])
+
+ ducked = WindowsPycawDucker().mute_others(own_pid=1, never=frozenset({"discord"}))
+
+ assert ducked == [700]
+
+
+def test_a_failing_session_does_not_abort_the_sweep(fake_pycaw):
+ class _Exploding(_FakeSession):
+ @property
+ def SimpleAudioVolume(self): # noqa: N802
+ raise OSError("COMError: session is protected")
+
+ @SimpleAudioVolume.setter
+ def SimpleAudioVolume(self, _value): # noqa: N802
+ pass
+
+ good = _FakeSession(802, "chrome.exe")
+ fake_pycaw.extend([_Exploding(801, "protected.exe"), good])
+
+ assert WindowsPycawDucker().mute_others(own_pid=1, never=frozenset()) == [802]
+ assert good.SimpleAudioVolume.muted is True
+
+
+# --------------------------------------------------------------------------- #
+# Volume mode (duck_volume_percent > 0) — the setting used to be ignored #
+# --------------------------------------------------------------------------- #
+
+
+def test_duck_volume_percent_lowers_instead_of_muting(fake_pycaw):
+ session = _FakeSession(4321, "spotify.exe", master=0.8)
+ fake_pycaw.extend([session])
+ ducker = WindowsPycawDucker(duck_volume_percent=20)
+
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == [4321]
+ assert session.SimpleAudioVolume.master == pytest.approx(0.2)
+ assert session.SimpleAudioVolume.muted is False # never hard-muted
+
+
+def test_duck_volume_percent_restores_the_previous_level(fake_pycaw):
+ session = _FakeSession(4321, "spotify.exe", master=0.8)
+ fake_pycaw.extend([session])
+ ducker = WindowsPycawDucker(duck_volume_percent=20)
+
+ ducker.restore(ducker.mute_others(own_pid=1, never=frozenset()))
+
+ assert session.SimpleAudioVolume.master == pytest.approx(0.8)
+ assert ducker._saved == {}
+
+
+def test_session_already_below_the_duck_level_is_not_touched(fake_pycaw):
+ quiet = _FakeSession(4321, "spotify.exe", master=0.1)
+ fake_pycaw.extend([quiet])
+
+ ducker = WindowsPycawDucker(duck_volume_percent=20)
+
+ assert ducker.mute_others(own_pid=1, never=frozenset()) == []
+ assert quiet.SimpleAudioVolume.master == pytest.approx(0.1)
+
+
+def test_restore_of_a_vanished_session_drops_its_saved_level(fake_pycaw):
+ """A ducked app that quits must not leave state a pid reuse could hit."""
+ session = _FakeSession(4321, "spotify.exe", master=0.8)
+ fake_pycaw.extend([session])
+ ducker = WindowsPycawDucker(duck_volume_percent=20)
+ ducked = ducker.mute_others(own_pid=1, never=frozenset())
+
+ fake_pycaw.clear() # the app exited while ducked
+ ducker.restore(ducked)
+
+ assert ducker._saved == {}
+
+
+def test_restore_uses_what_was_recorded_not_the_current_mode(fake_pycaw):
+ """Turning the duck-level knob mid-session must still undo cleanly."""
+ session = _FakeSession(4321, "spotify.exe", master=0.8)
+ fake_pycaw.extend([session])
+ ducker = WindowsPycawDucker() # mute mode
+ ducked = ducker.mute_others(own_pid=1, never=frozenset())
+
+ ducker._duck = 20 # user moves the slider before the session ends
+ ducker.restore(ducked)
+
+ assert session.SimpleAudioVolume.muted is False
+ assert session.SimpleAudioVolume.master == pytest.approx(0.8)
+
+
+# --------------------------------------------------------------------------- #
+# Config wiring #
+# --------------------------------------------------------------------------- #
+
+
+def test_from_config_reads_the_duck_level():
+ cfg = types.SimpleNamespace(
+ ducking=types.SimpleNamespace(duck_volume_percent=35),
+ )
+ assert WindowsPycawDucker.from_config(cfg)._duck == 35
+
+
+def test_from_config_without_config_defaults_to_mute_mode():
+ assert WindowsPycawDucker.from_config(None)._duck == 0
+
+
+def test_from_config_clamps_out_of_range_values():
+ cfg = types.SimpleNamespace(
+ ducking=types.SimpleNamespace(duck_volume_percent=500),
+ )
+ assert WindowsPycawDucker.from_config(cfg)._duck == 100
+
+
+def test_factory_threads_cfg_into_the_windows_backend(monkeypatch):
+ from jarvis.audio.ducking.factory import make_audio_ducker
+
+ monkeypatch.setattr("jarvis.audio.ducking.factory.sys.platform", "win32")
+ monkeypatch.setattr(
+ "jarvis.audio.ducking.factory._pycaw_available", lambda: True,
+ )
+ cfg = types.SimpleNamespace(
+ ducking=types.SimpleNamespace(duck_volume_percent=30),
+ )
+
+ ducker = make_audio_ducker(cfg)
+
+ assert isinstance(ducker, WindowsPycawDucker)
+ assert ducker._duck == 30
diff --git a/tests/unit/autostart/test_macos.py b/tests/unit/autostart/test_macos.py
index 2f8ba48e16..6f408ab8eb 100644
--- a/tests/unit/autostart/test_macos.py
+++ b/tests/unit/autostart/test_macos.py
@@ -9,6 +9,8 @@ from __future__ import annotations
import plistlib
from pathlib import Path
+import pytest
+
import jarvis.autostart.macos as macos
from jarvis.autostart.macos import MacOSAutostart
from jarvis.autostart.protocol import LaunchSpec
@@ -69,5 +71,43 @@ def test_uninstall_removes_plist(monkeypatch, tmp_path: Path) -> None:
monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)
mgr = MacOSAutostart()
mgr.install(_spec())
- mgr.uninstall()
+ status = mgr.uninstall()
assert not (tmp_path / "com.personal-jarvis.autostart.plist").exists()
+ assert status.installed is False
+
+
+def test_uninstall_reports_a_plist_it_could_not_remove(monkeypatch, tmp_path: Path) -> None:
+ """Reporting "Autostart disabled." while the LaunchAgent survives is a lie
+ — RunAtLoad still starts Jarvis at the next login, and the Settings toggle
+ showed off with nothing to explain the mismatch."""
+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)
+ mgr = MacOSAutostart()
+ mgr.install(_spec())
+
+ def _denied(self: Path, **_kwargs: object) -> None:
+ raise OSError("Operation not permitted")
+
+ monkeypatch.setattr(Path, "unlink", _denied)
+ status = mgr.uninstall()
+
+ assert status.installed is True
+ assert status.matches_spec is False
+ assert (tmp_path / "com.personal-jarvis.autostart.plist").exists()
+
+
+def test_install_leaves_no_temp_file_when_the_plist_write_fails(
+ monkeypatch, tmp_path: Path,
+) -> None:
+ """A half-written .plist.tmp next to the real entry is debris — the
+ successful replace() consumes the temp file, so anything left is a
+ failed write."""
+ monkeypatch.setattr(macos, "_agents_dir", lambda: tmp_path)
+
+ def _boom(*_args: object, **_kwargs: object) -> None:
+ raise OSError("disk full")
+
+ monkeypatch.setattr(macos.plistlib, "dump", _boom)
+ with pytest.raises(OSError, match="disk full"):
+ MacOSAutostart().install(_spec())
+
+ assert list(tmp_path.glob("*.tmp")) == []
diff --git a/tests/unit/autostart/test_windows_scripts.py b/tests/unit/autostart/test_windows_scripts.py
index 259ce62aae..535c274b67 100644
--- a/tests/unit/autostart/test_windows_scripts.py
+++ b/tests/unit/autostart/test_windows_scripts.py
@@ -57,3 +57,40 @@ def test_create_script_omits_icon_line_without_icon() -> None:
"""Back-compat: no icon given → no IconLocation line (never an empty ',0')."""
script = build_create_script(Path(r"C:\startup\Personal Jarvis.lnk"), _spec())
assert "IconLocation" not in script
+
+
+# --------------------------------------------------------------------------- #
+# Apostrophes in paths (a login like O'Brien, a folder like "Ruben's Jarvis") #
+# --------------------------------------------------------------------------- #
+
+_APOSTROPHE_SPEC = LaunchSpec(
+ program=r"C:\Users\O'Brien\.venv\Scripts\pythonw.exe",
+ args=("-m", "jarvis.ui.web.launcher"),
+ working_dir=r"C:\Users\O'Brien\Ruben's Jarvis",
+)
+
+
+def _quotes_balanced(script: str) -> bool:
+ """Every line closes each single-quoted literal it opens."""
+ return all(line.count("'") % 2 == 0 for line in script.splitlines())
+
+
+def test_create_script_escapes_apostrophes_in_paths() -> None:
+ # An unescaped apostrophe terminates the single-quoted PowerShell literal
+ # early, so the whole script fails to parse and autostart silently never
+ # installs for that user.
+ script = build_create_script(
+ Path(r"C:\Users\O'Brien\Startup\Personal Jarvis.lnk"),
+ _APOSTROPHE_SPEC,
+ icon=r"C:\Users\O'Brien\jarvis.ico",
+ )
+ assert r"$sc.TargetPath = 'C:\Users\O''Brien\.venv\Scripts\pythonw.exe'" in script
+ assert r"Ruben''s Jarvis" in script
+ assert r"$sc.IconLocation = 'C:\Users\O''Brien\jarvis.ico,0'" in script
+ assert _quotes_balanced(script)
+
+
+def test_read_script_escapes_apostrophes_in_the_link_path() -> None:
+ script = build_read_script(Path(r"C:\Users\O'Brien\Startup\Personal Jarvis.lnk"))
+ assert r"O''Brien" in script
+ assert _quotes_balanced(script)
diff --git a/tests/unit/autostart/test_windows_task.py b/tests/unit/autostart/test_windows_task.py
index eb388ee55f..f55f5175d4 100644
--- a/tests/unit/autostart/test_windows_task.py
+++ b/tests/unit/autostart/test_windows_task.py
@@ -85,6 +85,34 @@ def test_query_script_emits_sentinel_lines() -> None:
assert script.count("Write-Output") >= 3
+def test_register_script_escapes_apostrophes_in_paths() -> None:
+ # An unescaped apostrophe closes the single-quoted PowerShell literal early,
+ # so the whole script fails to parse. For a login like O'Brien — or a folder
+ # named "Ruben's Jarvis" — task registration, task query and shortcut I/O
+ # then all fail and autostart silently never works on that machine.
+ spec = LaunchSpec(
+ program=r"C:\Users\O'Brien\.venv\Scripts\pythonw.exe",
+ args=("-m", "jarvis.ui.web.launcher"),
+ working_dir=r"C:\Users\O'Brien\Ruben's Jarvis",
+ )
+ script = build_register_task_script(TASK_NAME, spec, user_id=r"DOM\O'Brien")
+ assert r"-Execute 'C:\Users\O''Brien\.venv\Scripts\pythonw.exe'" in script
+ assert r"Ruben''s Jarvis" in script
+ assert r"-UserId 'DOM\O''Brien'" in script
+ # Every line closes each literal it opens.
+ assert all(line.count("'") % 2 == 0 for line in script.splitlines())
+
+
+def test_query_and_unregister_scripts_escape_apostrophes() -> None:
+ weird = "Personal Jarvis' Autostart"
+ for script in (
+ build_query_task_script(weird),
+ build_unregister_task_script(weird),
+ ):
+ assert "Personal Jarvis'' Autostart" in script
+ assert all(line.count("'") % 2 == 0 for line in script.splitlines())
+
+
def test_parse_task_query_roundtrips_register_fields() -> None:
out = parse_task_query(build_fake_query_output())
assert out is not None
@@ -258,3 +286,64 @@ def test_uninstall_noninteractive_never_elevates() -> None:
mgr.uninstall(interactive=False)
assert "remove_shortcut" in calls
assert "elevate_unregister" not in calls
+
+
+def test_uninstall_reports_the_task_that_survived_the_silent_path() -> None:
+ # Removing the task needs elevation, which the boot reconcile must not
+ # prompt for. Reporting "Autostart disabled." anyway was a lie: the logon
+ # task kept starting Jarvis every login while Settings showed the toggle
+ # off, with nothing to explain the mismatch.
+ mgr, _ = _mk(task_info=_MATCHING_INFO, shortcut_present=True)
+ st = mgr.uninstall(interactive=False)
+ assert st.installed is True
+ assert "scheduled task" in st.detail.lower()
+
+
+def test_uninstall_reports_the_task_that_survived_a_declined_uac() -> None:
+ mgr, calls = _mk(
+ task_info=_MATCHING_INFO, shortcut_present=True, elevate_ok=False,
+ )
+ st = mgr.uninstall(interactive=True)
+ assert "elevate_unregister" in calls
+ assert st.installed is True
+
+
+def test_uninstall_reports_disabled_once_the_task_is_really_gone() -> None:
+ mgr, _ = _mk(task_info=_MATCHING_INFO, shortcut_present=True)
+ st = mgr.uninstall(interactive=True)
+ assert st.installed is False
+ assert st.detail == "Autostart disabled."
+
+
+def test_install_drops_a_leftover_shortcut_when_the_task_already_matches() -> None:
+ # A boot whose task query transiently failed (a failed query reads as "no
+ # task") writes the .lnk fallback; nothing removed it once the task became
+ # visible again, so Jarvis started TWICE at login — via the task and via
+ # the Explorer startup queue.
+ mgr, calls = _mk(task_info=_MATCHING_INFO, shortcut_present=True)
+ mgr.install(_SPEC, interactive=False)
+ assert calls == ["remove_shortcut"]
+
+
+def test_truncated_shortcut_readback_is_drift_not_a_match(monkeypatch) -> None:
+ # Padding the missing fields with "" made a half-failed COM read compare
+ # equal to a spec with no args/working dir — reporting a stale shortcut as
+ # current and suppressing the refresh that would have fixed it.
+ import subprocess
+ from pathlib import Path
+
+ from jarvis.autostart import windows as win_mod
+
+ bare = LaunchSpec(program=r"C:\Python\pythonw.exe", args=(), working_dir="")
+ monkeypatch.setattr(Path, "exists", lambda self: True)
+ monkeypatch.setattr(
+ win_mod,
+ "_run_powershell",
+ lambda script: subprocess.CompletedProcess(
+ ["powershell"],
+ 0,
+ stdout=win_mod._READBACK_SENTINEL + bare.program + "\n",
+ stderr="",
+ ),
+ )
+ assert WindowsAutostart()._default_shortcut_matches(bare) is False
diff --git a/tests/unit/awareness/test_window_watcher.py b/tests/unit/awareness/test_window_watcher.py
index a12d3f63d7..8ff20efcc7 100644
--- a/tests/unit/awareness/test_window_watcher.py
+++ b/tests/unit/awareness/test_window_watcher.py
@@ -396,3 +396,131 @@ async def test_posix_stop_without_start_is_noop() -> None:
watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
await watcher.stop()
await watcher.stop()
+
+
+async def test_posix_poll_once_treats_a_titleless_window_as_a_healthy_probe() -> None:
+ """A window with no readable title is not a dead backend.
+
+ X11 windows legitimately carry no name, and xdotool's getwindowname can
+ fail for one window while getactivewindow keeps working. Counting that as
+ a failure meant five such polls (10 s) permanently disabled focus tracking
+ for the rest of the session. Nothing is published either — an empty title
+ is unidentifiable and must never be handed to the privacy filter.
+ """
+ bus, manager, privacy = _make_components()
+ updated: list[FrameUpdated] = []
+ blocked: list[AwarenessCaptureBlocked] = []
+ bus.subscribe(FrameUpdated, _async_collect(updated))
+ bus.subscribe(AwarenessCaptureBlocked, _async_collect(blocked))
+
+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
+ with patch.object(
+ WindowFocusWatcher, "_posix_foreground_window",
+ staticmethod(lambda: WindowInfo(title=" ", handle=7)),
+ ):
+ assert await watcher._poll_once() is True
+ assert await watcher._poll_once() is True
+
+ assert updated == []
+ assert blocked == []
+
+
+async def test_stop_discards_queued_frames_and_stale_focus_state(monkeypatch) -> None:
+ """A restart must not replay pre-stop frames, and must not swallow the
+ first genuine frame after it as "unchanged".
+
+ Queue and change-detection markers live on the instance, so both used to
+ survive a stop/start cycle (awareness toggled off and on in Settings):
+ stale payloads were published as fresh frames, and the poller then saw the
+ unchanged foreground window as "already reported" and emitted nothing —
+ leaving ``state.current_frame`` frozen until the user switched windows.
+ """
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
+ bus, manager, privacy = _make_components()
+ received: list[FrameUpdated] = []
+ bus.subscribe(FrameUpdated, _async_collect(received))
+
+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
+ with patch.object(
+ WindowFocusWatcher, "_posix_foreground_window",
+ staticmethod(lambda: WindowInfo(title="Terminal", handle=42)),
+ ), patch.object(
+ WindowFocusWatcher, "_resolve_posix_focus_meta",
+ staticmethod(lambda win: (123, "Terminal.app")),
+ ):
+ watcher._started = True
+ await watcher._poll_once()
+ watcher._safe_enqueue((time.time_ns(), 4242)) # frame captured pre-stop
+
+ await watcher.stop()
+ assert watcher._queue.empty()
+ assert watcher._poll_last_handle is None
+ assert watcher._poll_last_title == ""
+ assert watcher._last_hwnd == 0
+
+ watcher._started = True
+ await watcher._poll_once() # same window, fresh run → must re-emit
+
+ assert len(received) == 2
+
+
+async def test_posix_focus_meta_uses_the_pid_the_probe_already_resolved(
+ monkeypatch,
+) -> None:
+ """Title and process identity must come from the SAME instant.
+
+ ``window_state.foreground_window`` fills ``WindowInfo.pid`` from the very
+ window it read the title off. Asking "who is frontmost NOW" a second time
+ instead paired app A's title with app B's process whenever focus moved in
+ between — a 2 s poll leaves that gap wide open — and the PrivacyFilter then
+ judged a title against the wrong process name in both directions.
+ """
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
+
+ def _must_not_run():
+ raise AssertionError("re-queried the frontmost app instead of using win.pid")
+
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: _must_not_run())
+
+ pid, _name = WindowFocusWatcher._resolve_posix_focus_meta(
+ WindowInfo(title="Notes", handle=7, pid=4242),
+ )
+
+ assert pid == 4242
+
+
+async def test_posix_focus_meta_degrades_to_zero_without_a_probe_pid(
+ monkeypatch,
+) -> None:
+ """No pid from the probe and no usable backend → (0, ""), never a raise."""
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
+
+ assert WindowFocusWatcher._resolve_posix_focus_meta(
+ WindowInfo(title="untitled", handle=9),
+ ) == (0, "")
+
+
+async def test_posix_poll_emits_the_probe_pid_end_to_end(monkeypatch) -> None:
+ """The published frame carries the probe's own pid, not a re-query."""
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
+
+ bus, manager, privacy = _make_components()
+ received: list[FrameUpdated] = []
+ bus.subscribe(FrameUpdated, _async_collect(received))
+
+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
+ with patch.object(
+ WindowFocusWatcher, "_posix_foreground_window",
+ staticmethod(lambda: WindowInfo(title="Terminal", handle=3, pid=777)),
+ ):
+ assert await watcher._poll_once() is True
+
+ assert len(received) == 1
+ assert received[0].pid == 777
diff --git a/tests/unit/cu/test_actuate.py b/tests/unit/cu/test_actuate.py
index c19c90630b..26d6fd0bed 100644
--- a/tests/unit/cu/test_actuate.py
+++ b/tests/unit/cu/test_actuate.py
@@ -292,6 +292,56 @@ def test_normalize_virtualdesk_folds_negative_origin():
assert 0 < nx < 65535 and 0 < ny < 65535
+def _recording_windows_actuator():
+ """A WindowsActuator that records key events instead of calling SendInput.
+
+ Built via ``__new__`` so no ctypes/Win32 struct setup runs — the mapping
+ under test is pure, and this keeps the test host-agnostic.
+ """
+ from jarvis.cu.actuate.windows import WindowsActuator
+
+ actuator = WindowsActuator.__new__(WindowsActuator)
+ sent: list[list[tuple[int, int, int]]] = []
+ actuator._t = None
+ actuator._key_input = lambda vk, scan, flags: (vk, scan, flags)
+ actuator._send = lambda events: sent.append(list(events))
+ return actuator, sent
+
+
+def test_type_text_presses_enter_for_a_newline():
+ """KEYEVENTF_UNICODE cannot deliver U+000A: Windows edit controls act on
+ the KEY, so a unicode LF typed NOTHING and every multi-line type_text
+ landed as one run-on line — while pynput on macOS/Linux pressed Enter."""
+ from jarvis.cu.actuate.windows import _KEYEVENTF_KEYUP
+
+ actuator, sent = _recording_windows_actuator()
+ actuator.type_text("a\nb", delay_s=0)
+
+ assert len(sent) == 3
+ assert sent[1] == [(0x0D, 0, 0), (0x0D, 0, _KEYEVENTF_KEYUP)]
+ # The surrounding characters still go out as unicode code units.
+ assert sent[0][0][0] == 0 and sent[0][0][1] == ord("a")
+ assert sent[2][0][1] == ord("b")
+
+
+def test_type_text_maps_tab_and_collapses_crlf_to_one_enter():
+ actuator, sent = _recording_windows_actuator()
+ actuator.type_text("\t\r\n", delay_s=0)
+
+ assert [batch[0][0] for batch in sent] == [0x09, 0x0D]
+
+
+def test_type_text_still_sends_astral_characters_as_surrogate_pairs():
+ from jarvis.cu.actuate.windows import _KEYEVENTF_UNICODE
+
+ actuator, sent = _recording_windows_actuator()
+ actuator.type_text("\U0001F600", delay_s=0) # emoji → two UTF-16 units
+
+ assert len(sent) == 1
+ assert len(sent[0]) == 4 # down+up per surrogate half
+ assert all(vk == 0 and flags & _KEYEVENTF_UNICODE for vk, _scan, flags in sent[0])
+
+
def test_normalize_virtualdesk_clamps_outside_points():
assert normalize_virtualdesk(-9999, -9999, 0, 0, 1920, 1080) == (0, 0)
assert normalize_virtualdesk(99999, 99999, 0, 0, 1920, 1080) == (65535, 65535)
@@ -310,6 +360,34 @@ def test_resolve_vk_letters_digits_and_names():
assert resolve_vk("") is None
+def test_resolve_vk_maps_punctuation_shortcut_keys():
+ """The shared vocabulary accepts any single printable character and the
+ pynput backend types it — this backend resolved only a-z/0-9, so every
+ punctuation shortcut (Ctrl+- / Ctrl+= zoom, Ctrl+, settings, Ctrl+/
+ comment) raised "Unknown key" and the whole action failed."""
+ assert resolve_vk("-") == 0xBD # VK_OEM_MINUS — any layout
+ assert resolve_vk("=") == 0xBB # VK_OEM_PLUS — any layout
+ assert resolve_vk(",") == 0xBC # VK_OEM_COMMA — any layout
+ assert resolve_vk(".") == 0xBE # VK_OEM_PERIOD — any layout
+ assert resolve_vk("/") == 0xBF
+ assert resolve_vk("[") == 0xDB
+ assert resolve_vk("]") == 0xDD
+
+
+def test_resolve_vk_refuses_shifted_characters():
+ """Emitting the unshifted key for '+' would send input nobody asked for —
+ a loud "Unknown key" beats a wrong keystroke."""
+ for shifted in ("+", "_", "{", "}", ":", "?", "~"):
+ assert resolve_vk(shifted) is None, shifted
+
+
+def test_punctuation_shortcut_survives_the_whole_combo_path():
+ """expand_combo_keys already split "ctrl+-"; resolve_vk then rejected it."""
+ expanded = expand_combo_keys(["ctrl+-"])
+ assert expanded == ["ctrl", "-"]
+ assert [resolve_vk(k) for k in expanded] == [0x11, 0xBD]
+
+
def test_expand_combo_keys_splits_known_combos_only():
assert expand_combo_keys(["ctrl+v"]) == ["ctrl", "v"]
assert expand_combo_keys(["ctrl+shift+t"]) == ["ctrl", "shift", "t"]