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(linux): spec-escape XDG autostart entries and harden POSIX focus polling

rubenluetke10-beep896c6beace3c
diff --git a/jarvis/autostart/linux.py b/jarvis/autostart/linux.py
index a82812bf39..38b82a4b2b 100644
--- a/jarvis/autostart/linux.py
+++ b/jarvis/autostart/linux.py
@@ -8,6 +8,14 @@ brainstorming; a systemd ``--user`` boot-without-login unit is intentionally not
built here (see the design spec, Non-Goals).
Pure ``pathlib`` text I/O — fully CI-provable on any OS (write into a temp HOME).
+
+All ``.desktop`` text is encoded through :mod:`jarvis.core.desktop_entry` and
+read back through its group-aware parser, so writing and drift-checking can never
+disagree about escaping. That module's docstring explains why the format needs
+two nested escaping layers; the failure mode it prevents is specific to this file
+and invisible from both sides — the desktop discards a malformed entry without a
+word, and a writer comparing its own unescaped string still reports the dead
+entry as installed and current.
"""
from __future__ import annotations
@@ -25,11 +33,24 @@ from jarvis.core.branding import (
from jarvis.core.branding import (
LINUX_WM_CLASS as _WM_CLASS,
)
+from jarvis.core.desktop_entry import (
+ escape_value,
+ exec_value,
+ read_field,
+ reads_as_false,
+ reads_as_true,
+ unescape_value,
+)
from .protocol import AutostartStatus, LaunchSpec
log = logging.getLogger(__name__)
+# XDG basedir spec: a directory created for the user's config must not be
+# world-readable. The autostart entry itself carries no secrets, but the
+# directory is shared with everything else under $XDG_CONFIG_HOME.
+_XDG_DIR_MODE = 0o700
+
# The X11/Wayland window-class token the running window is pinned to (see
# ``jarvis.ui.icon_utils.pin_linux_wm_class``). ``StartupWMClass`` must match it
# for the desktop to map the running window to THIS .desktop entry — and thus
@@ -56,43 +77,79 @@ def _icon_value() -> str | None:
def _autostart_dir() -> Path:
- """``$XDG_CONFIG_HOME/autostart`` or the ``~/.config/autostart`` default."""
+ """``$XDG_CONFIG_HOME/autostart`` or the ``~/.config/autostart`` default.
+
+ A NON-ABSOLUTE ``XDG_CONFIG_HOME`` is ignored, as the XDG base-directory
+ spec requires ("if an implementation encounters a relative path in any of
+ these variables it should consider the path invalid and ignore it"). It is
+ not a theoretical case: a dotfile that exports the value in quotes
+ (``XDG_CONFIG_HOME="~/.config"``) leaves the tilde unexpanded, and the entry
+ then landed in a ``~/.config``-named folder under the process' working
+ directory — a path no desktop environment ever reads, so autostart was dead
+ while ``install()`` reported success.
+ """
xdg = os.environ.get("XDG_CONFIG_HOME", "").strip()
- base = Path(xdg) if xdg else Path.home() / ".config"
+ base: Path | None = None
+ if xdg:
+ candidate = Path(xdg)
+ if candidate.is_absolute():
+ base = candidate
+ else:
+ log.debug(
+ "Ignoring relative XDG_CONFIG_HOME=%r (XDG spec) — using ~/.config",
+ xdg,
+ )
+ if base is None:
+ base = Path.home() / ".config"
return base / "autostart"
def _exec_value(spec: LaunchSpec) -> str:
- """Canonical ``Exec=`` value. Double-quote the program if it has spaces
- (Desktop Entry spec quoting). Args are fixed and space-free."""
- program = f'"{spec.program}"' if " " in spec.program else spec.program
- return " ".join([program, *spec.args])
+ """Canonical, spec-escaped ``Exec=`` value.
+
+ Delegates to :mod:`jarvis.core.desktop_entry`, which implements both nested
+ escaping layers (argument quoting + ``%%`` field-code doubling + the
+ key-file string encoding). The previous "quote the program if it contains a
+ space" shortcut produced an entry the desktop silently discards for any
+ install path containing a ``%``, while ``status()`` kept reporting it as
+ installed and current because it compared the same unescaped string it had
+ written.
+ """
+ return exec_value(spec.program, spec.args)
def _render(spec: LaunchSpec) -> str:
icon = _icon_value()
- icon_line = f"Icon={icon}\n" if icon else ""
+ icon_line = f"Icon={escape_value(icon)}\n" if icon else ""
return (
"[Desktop Entry]\n"
"Type=Application\n"
- f"Name={_APP_NAME}\n"
+ f"Name={escape_value(_APP_NAME)}\n"
"Comment=Voice-driven meta-orchestrator (autostart)\n"
f"Exec={_exec_value(spec)}\n"
- f"Path={spec.working_dir}\n"
+ f"Path={escape_value(spec.working_dir)}\n"
"Terminal=false\n"
f"{icon_line}"
- f"StartupWMClass={_WM_CLASS}\n"
+ f"StartupWMClass={escape_value(_WM_CLASS)}\n"
"X-GNOME-Autostart-enabled=true\n"
"Hidden=false\n"
)
-def _read_field(text: str, key: str) -> str | None:
- prefix = key + "="
- for line in text.splitlines():
- if line.startswith(prefix):
- return line[len(prefix):].strip()
- return None
+def _disabled_by_desktop(text: str) -> bool:
+ """Has the desktop switched this autostart entry off behind our back?
+
+ Two independent off-switches exist and both leave the file in place:
+ ``Hidden=true`` is the spec's own "the user deleted this entry" marker, and
+ ``X-GNOME-Autostart-enabled=false`` is what GNOME's Startup Applications /
+ Tweaks writes. Ignoring them meant a switched-off entry reported
+ ``installed=True, matches_spec=True`` — the reconcile loop no-op'd, the
+ Settings toggle showed green, and Jarvis never started at login with nothing
+ anywhere saying why.
+ """
+ return reads_as_true(read_field(text, "Hidden")) or reads_as_false(
+ read_field(text, "X-GNOME-Autostart-enabled")
+ )
class LinuxAutostart:
@@ -101,6 +158,17 @@ class LinuxAutostart:
def __init__(self) -> None:
self._path = _autostart_dir() / _ENTRY_NAME
+ @property
+ def _tmp_path(self) -> Path:
+ """Staging path for the atomic write.
+
+ A sibling with a ``.tmp`` tail, so the desktop's autostart scan (which
+ only considers ``*.desktop``) never picks up a partial file. Derived by
+ name rather than ``with_suffix`` so an entry file name containing dots
+ cannot silently truncate it.
+ """
+ return self._path.with_name(self._path.name + ".tmp")
+
def status(self, spec: LaunchSpec) -> AutostartStatus:
if not self._path.exists():
return AutostartStatus(
@@ -121,41 +189,83 @@ class LinuxAutostart:
entry_path=str(self._path),
detail=f"Autostart entry present but unreadable: {exc}.",
)
- matches = (
- _read_field(text, "Exec") == _exec_value(spec)
- and _read_field(text, "Path") == spec.working_dir
+ # Exec is compared in its ENCODED form (both sides come from
+ # ``_exec_value``); Path is compared decoded, so an entry another tool
+ # re-encoded differently still recognises its own install.
+ points_here = (
+ read_field(text, "Exec") == _exec_value(spec)
+ and unescape_value(read_field(text, "Path") or "") == spec.working_dir
)
+ switched_off = _disabled_by_desktop(text)
+ matches = points_here and not switched_off
+ if matches:
+ detail = "Autostart enabled and current."
+ elif switched_off:
+ detail = (
+ "Autostart entry is present but switched off in the desktop's "
+ "startup-application settings (will be re-enabled)."
+ )
+ else:
+ detail = "Autostart entry points at a different install (will be refreshed)."
return AutostartStatus(
supported=True,
installed=True,
matches_spec=matches,
entry_path=str(self._path),
- detail=(
- "Autostart enabled and current."
- if matches
- else "Autostart entry points at a different install (will be refreshed)."
- ),
+ detail=detail,
)
def install( # noqa: ARG002 — per-user XDG .desktop never needs elevation
self, spec: LaunchSpec, *, interactive: bool = False
) -> AutostartStatus:
- self._path.parent.mkdir(parents=True, exist_ok=True)
+ self._path.parent.mkdir(parents=True, exist_ok=True, mode=_XDG_DIR_MODE)
# Atomic-ish: write tempfile then replace, so a crash never leaves a
# half-written .desktop the DE would choke on.
- tmp = self._path.with_suffix(".desktop.tmp")
- tmp.write_text(_render(spec), encoding="utf-8")
- tmp.replace(self._path)
+ tmp = self._tmp_path
+ try:
+ tmp.write_text(_render(spec), encoding="utf-8")
+ tmp.replace(self._path)
+ except BaseException:
+ # A half-written .desktop.tmp left in ~/.config/autostart is debris:
+ # the successful replace() consumes the temp file, so anything still
+ # there is from a failed write (a read-only home, a full disk).
+ # Mirrors the macOS LaunchAgent writer.
+ tmp.unlink(missing_ok=True)
+ raise
log.info("Linux autostart entry written: %s", self._path)
return self.status(spec)
def uninstall(self, *, interactive: bool = False) -> AutostartStatus: # noqa: ARG002
+ # Clean up debris from an earlier failed install() first — it is never
+ # load-bearing, and a failure to remove it must not mask the real result.
+ try:
+ self._tmp_path.unlink(missing_ok=True)
+ except OSError as exc:
+ log.debug("Could not remove %s: %s", self._tmp_path, exc)
+
+ error = ""
if self._path.exists():
try:
self._path.unlink()
log.info("Linux autostart entry removed: %s", self._path)
except OSError as exc:
log.warning("Could not remove %s: %s", self._path, exc)
+ error = str(exc)
+ if error:
+ # Reporting "Autostart disabled." while the .desktop survives was a
+ # lie: the desktop environment still launches Jarvis at the next
+ # login, and the Settings toggle showed off with nothing to explain
+ # the mismatch (AP-30). Same fix the macOS LaunchAgent already got.
+ return AutostartStatus(
+ supported=True,
+ installed=True,
+ matches_spec=False,
+ entry_path=str(self._path),
+ detail=(
+ f"The autostart entry 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/awareness/watchers/window.py b/jarvis/awareness/watchers/window.py
index 604aa3f92a..b4eeb45bbc 100644
--- a/jarvis/awareness/watchers/window.py
+++ b/jarvis/awareness/watchers/window.py
@@ -28,12 +28,14 @@ the Win32 drain loop uses, so both platforms publish identical
``FrameUpdated`` / ``AwarenessCaptureBlocked`` events. macOS always has a
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 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.
+``None`` without the optional Screen-Recording grant or without pyobjc).
+An empty probe only disables the fallback while NO probe has ever
+succeeded — that is a backend which cannot work here; afterwards it means
+"nothing is focused right now", which on X11 is an everyday state (see
+``_poll_loop``). A window that merely has no readable TITLE is a healthy
+probe too 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``
@@ -93,8 +95,62 @@ _PUMP_READY_TIMEOUT_S: float = 2.0 # start() wait-bis-Hook-gesetzt
# used there, so we poll at a modest cadence instead. 2 s balances staying
# off the voice hot path against noticing an app switch reasonably fast.
_POSIX_POLL_INTERVAL_S: float = 2.0
-_POSIX_POLL_MAX_FAILURES: int = 5 # consecutive empty probes before giving up
+_POSIX_POLL_MAX_FAILURES: int = 5 # empty probes BEFORE the first success
_POSIX_POLL_STOP_TIMEOUT_S: float = 1.5
+# Last-resort pid lookup for an X11 window (see ``_linux_window_pid``). Kept
+# generous on purpose: a slow answer is still a correct one, while a timeout
+# yields an empty process name, and the privacy rules that key on the process
+# (rather than the title) then have nothing to match against.
+_POSIX_PID_PROBE_TIMEOUT_S: float = 5.0
+
+
+def _linux_window_pid(window_id: int) -> int:
+ """Owning pid of an X11 window id via ``xdotool``, or ``0``. Never raises.
+
+ A LAST RESORT: ``window_state.foreground_window`` already reads the pid off
+ the very window it took the title from, so this only runs for a client that
+ advertises no ``_NET_WM_PID`` at all — which is also the property xdotool
+ reads, so the honest expectation is that it returns 0 as well. It stays as
+ the single documented seam for that lookup instead of being inlined, and it
+ no longer routes the routine "this window has no pid property" case through
+ a broad exception handler that logged it as a resolution failure with a
+ traceback, drowning the real ones.
+
+ Runs on a worker thread (called via ``asyncio.to_thread``), so it must be
+ bounded: every ``subprocess`` failure mode — a missing binary, a dead X
+ connection, a hung server — degrades to ``0``.
+ """
+ executable = shutil.which("xdotool")
+ if executable is None:
+ return 0
+ try:
+ proc = subprocess.run(
+ [executable, "getwindowpid", str(window_id)],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ timeout=_POSIX_PID_PROBE_TIMEOUT_S,
+ check=False,
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, subprocess.SubprocessError):
+ logger.debug(
+ "xdotool getwindowpid failed for window %s", window_id, exc_info=True,
+ )
+ return 0
+ if proc.returncode != 0:
+ logger.debug("xdotool reports no pid for X11 window %s", window_id)
+ return 0
+ raw = (proc.stdout or "").strip()
+ try:
+ pid = int(raw)
+ except ValueError:
+ logger.debug(
+ "xdotool returned a non-numeric pid %r for X11 window %s", raw, window_id,
+ )
+ return 0
+ return pid if pid > 0 else 0
class WindowFocusWatcher:
@@ -684,29 +740,54 @@ class WindowFocusWatcher:
async def _poll_loop(self) -> None:
"""Call ``_poll_once`` every ``_POSIX_POLL_INTERVAL_S`` until stopped.
- Stops itself after ``_POSIX_POLL_MAX_FAILURES`` consecutive probes
- that returned no usable window (missing pyobjc/xdotool, or a
- session that genuinely cannot be queried) instead of polling a
- dead backend forever. Waits on ``_poll_stop`` rather than a plain
- sleep so ``stop()`` wakes the loop immediately instead of waiting
- out the interval.
+ The failure counter is a STARTUP GATE, not a running health check: it
+ only disables the loop while no probe has EVER returned a usable window,
+ which is the signature of a backend that cannot work here (no pyobjc, no
+ xdotool, a ``DISPLAY`` pointing at an X server that is not actually
+ reachable). Once one window has been read, an empty probe is treated as a
+ healthy "nothing is focused right now" observation and the loop keeps
+ going.
+
+ That distinction is the whole point. ``xdotool getactivewindow`` exits
+ non-zero — and the probe therefore reports nothing — whenever no client
+ window holds the X11 input focus: the user is on the desktop or the
+ wallpaper, a window just closed, a lock/screensaver is up, or a
+ pointer-focus WM briefly parked focus on the root window. All of those
+ are ordinary, transient states. Counting them meant 10 s on the desktop
+ permanently killed focus tracking for the rest of the session and blamed
+ a missing xdotool in the log. This is the same conflation of "the backend
+ is broken" with "there is momentarily nothing to report" that
+ ``_poll_once`` already had to unlearn for title-less X11 windows.
+
+ Waits on ``_poll_stop`` rather than a plain sleep so ``stop()`` wakes the
+ loop immediately instead of waiting out the interval.
"""
consecutive_failures = 0
+ ever_succeeded = False
while not self._poll_stop.is_set():
try:
ok = await self._poll_once()
except asyncio.CancelledError:
break
+ except Exception: # noqa: BLE001
+ # Mirrors the Win32 drain loop: one bad iteration must not end
+ # focus tracking for the session. Without this the task died
+ # with an unretrieved exception and no log line at all — the
+ # feature was simply off, silently.
+ logger.debug("POSIX poll iteration failed", exc_info=True)
+ ok = False
if ok:
+ ever_succeeded = True
consecutive_failures = 0
- else:
+ elif not ever_succeeded:
consecutive_failures += 1
if consecutive_failures >= _POSIX_POLL_MAX_FAILURES:
logger.info(
- "window-focus polling produced no usable window info "
- "for %d consecutive attempts — stopping (missing "
- "pyobjc/xdotool, or the session cannot be probed)",
+ "window-focus polling never produced usable window info "
+ "(%d attempts) — stopping: no backend that can read the "
+ "foreground window here (missing pyobjc/xdotool, or the "
+ "advertised display cannot be queried)",
consecutive_failures,
)
return
@@ -760,8 +841,6 @@ class WindowFocusWatcher:
if not changed:
return True
- self._poll_last_handle = win.handle
- self._poll_last_title = win.title
try:
pid, process_name = await asyncio.to_thread(
self._resolve_posix_focus_meta, win,
@@ -775,6 +854,17 @@ class WindowFocusWatcher:
)
except Exception: # noqa: BLE001
logger.debug("POSIX frame emit failed", exc_info=True)
+ return True
+ # Commit the change-detection markers only AFTER the frame published.
+ # Claiming the window as "already reported" before the emit turned any
+ # transient failure in the tail (a raising privacy rule, a bus handler,
+ # a deep probe) into a permanent one: the next tick saw an unchanged
+ # focus and stayed quiet, so ``state.current_frame`` kept describing the
+ # PREVIOUS window until the user happened to switch again. Retrying one
+ # interval later costs nothing and is the same reasoning behind
+ # ``_reset_frame_state``.
+ self._poll_last_handle = win.handle
+ self._poll_last_title = win.title
return True
@staticmethod
@@ -799,45 +889,41 @@ class WindowFocusWatcher:
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.
+ the Screen-Recording nor the Accessibility grant); Linux:
+ :func:`_linux_window_pid` 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.
+
+ A non-positive result is normalised to ``0`` rather than passed on. A
+ negative pid would travel into ``FrameSnapshot.active_pid`` and every
+ consumer's ``pid > 0`` guard as a value that looks resolved but names no
+ process.
"""
pid = int(win.pid or 0)
if pid <= 0:
- try:
- plat = detect_platform()
- if plat == "darwin":
+ plat = detect_platform()
+ if plat == "darwin":
+ try:
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
+ except Exception: # noqa: BLE001 — no pyobjc / transient AppKit error
+ logger.debug("macOS frontmost pid lookup failed", exc_info=True)
+ pid = 0
+ elif plat == "linux" and win.handle:
+ pid = _linux_window_pid(int(win.handle))
+ if pid <= 0:
+ return 0, ""
process_name = ""
- if pid > 0:
- try:
- import psutil # noqa: PLC0415
+ try:
+ import psutil # noqa: PLC0415
- process_name = psutil.Process(pid).name()
- except Exception: # noqa: BLE001
- process_name = ""
+ process_name = psutil.Process(pid).name()
+ except Exception: # noqa: BLE001
+ process_name = ""
return pid, process_name
diff --git a/jarvis/core/desktop_entry.py b/jarvis/core/desktop_entry.py
new file mode 100644
index 0000000000..3884a04603
--- /dev/null
+++ b/jarvis/core/desktop_entry.py
@@ -0,0 +1,167 @@
+"""freedesktop Desktop Entry encoding — the ONE place `.desktop` text is built.
+
+Linux is the only consumer, but the module is pure stdlib and imports nothing
+from ``jarvis``, so it is CI-provable on any OS (the whole point of the
+"write into a temp HOME" test style used by the autostart port).
+
+Why this exists as a shared module: a ``.desktop`` file carries **two nested
+escaping layers**, and every hand-rolled writer in this code base only ever
+implemented a fragment of the outer one.
+
+ 1. *Key-file layer* (spec § "Value types"): the file is INI-shaped and the
+ reader decodes ``\\s`` ``\\n`` ``\\t`` ``\\r`` ``\\\\`` inside every value.
+ 2. *Exec layer* (spec § "Exec variables" + § "Quoting"): the ``Exec=`` value
+ is additionally parsed as an argument vector with double-quote quoting,
+ and a literal percent sign must be written ``%%`` because ``%`` starts a
+ field code.
+
+The layers compose, which is why the specification itself notes that a literal
+backslash inside a quoted argument needs **four** backslashes in the file: the
+Exec layer doubles it, then the key-file layer doubles that again. Getting this
+wrong fails silently on BOTH sides — the desktop environment discards an entry
+with an unknown field code without a word, and a writer that compares the same
+unescaped string it wrote still reports the dead entry as installed and current.
+
+Reading goes through :func:`read_field`, which is group-aware on purpose:
+``Exec=`` is a legal key in a ``[Desktop Action …]`` group too, so a naive
+line-prefix scan can answer a drift check with a completely different command
+once a desktop tool has rewritten the file.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Sequence
+
+# Characters that force an Exec argument to be quoted (spec § Quoting). Note
+# that ``%`` is deliberately absent: it needs doubling, not quoting.
+_EXEC_RESERVED: frozenset[str] = frozenset(" \t\n\r\"'\\><~|&;$*?#()`")
+
+# Characters that must additionally carry a backslash INSIDE a quoted argument.
+_EXEC_QUOTE_ESCAPED: frozenset[str] = frozenset('"`$\\')
+
+#: The group every launcher/autostart key we care about lives in.
+DESKTOP_ENTRY_GROUP = "Desktop Entry"
+
+
+def escape_value(value: str) -> str:
+ """Encode ``value`` for the key-file layer (spec § Value types).
+
+ Backslash first — the other replacements introduce backslashes that must
+ not be escaped a second time. A directory name containing a backslash is
+ perfectly legal on Linux, and unescaped it turns the rest of the value into
+ a bogus escape sequence.
+ """
+ out = value.replace("\\", "\\\\")
+ out = out.replace("\n", "\\n").replace("\r", "\\r").replace("\t", "\\t")
+ return out
+
+
+def unescape_value(value: str) -> str:
+ """Decode a key-file value written by :func:`escape_value`.
+
+ Used for drift detection: comparing the *decoded* on-disk value against the
+ plain string we intended keeps the comparison honest even for an entry a
+ desktop tool re-encoded differently than we would have. An undefined escape
+ sequence is passed through verbatim rather than dropped, so a foreign file
+ can never make the comparison silently succeed.
+ """
+ out: list[str] = []
+ index = 0
+ length = len(value)
+ simple = {"n": "\n", "r": "\r", "t": "\t", "s": " ", "\\": "\\"}
+ while index < length:
+ char = value[index]
+ if char != "\\" or index + 1 >= length:
+ out.append(char)
+ index += 1
+ continue
+ nxt = value[index + 1]
+ if nxt in simple:
+ out.append(simple[nxt])
+ index += 2
+ continue
+ out.append(char)
+ index += 1
+ return "".join(out)
+
+
+def exec_argument(value: str) -> str:
+ """Encode ONE ``Exec=`` argument through the Exec layer only.
+
+ Quoting is decided on the raw value, escaping is applied to the
+ percent-doubled one — a ``%`` never forces quotes, and the ``%%`` it becomes
+ must not pick up a backslash.
+ """
+ token = value.replace("%", "%%")
+ if any(char in _EXEC_RESERVED for char in value):
+ body = "".join(f"\\{char}" if char in _EXEC_QUOTE_ESCAPED else char for char in token)
+ return f'"{body}"'
+ return token
+
+
+def exec_value(program: str, args: Iterable[str] = ()) -> str:
+ """Render a complete, spec-correct ``Exec=`` value.
+
+ Both layers, in the order the reader unwinds them: Exec-quote each argument,
+ then key-file-escape the joined command line. An empty program is returned
+ as an empty string rather than a stray pair of quotes, so a caller with an
+ unresolved interpreter writes an obviously-broken entry instead of a
+ plausible-looking one.
+ """
+ if not program:
+ return ""
+ tokens: Sequence[str] = [exec_argument(program), *(exec_argument(a) for a in args)]
+ return escape_value(" ".join(tokens))
+
+
+def read_field(text: str, key: str, *, group: str = DESKTOP_ENTRY_GROUP) -> str | None:
+ """The raw (still key-file-escaped) value of ``key`` in ``group``, or ``None``.
+
+ Group-aware, comment-aware and tolerant of the spec-legal ``Key = value``
+ spacing. Locale-suffixed keys (``Name[de]``) do NOT match their base key.
+ A duplicated key resolves to the LAST occurrence, matching GLib's
+ ``GKeyFile`` — the reader every mainstream desktop actually uses.
+ """
+ target = f"[{group}]"
+ in_group = False
+ found: str | None = None
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ if line.startswith("[") and line.endswith("]"):
+ in_group = line == target
+ continue
+ if not in_group or "=" not in line:
+ continue
+ name, _, value = line.partition("=")
+ if name.strip() == key:
+ found = value.strip()
+ return found
+
+
+def reads_as_false(value: str | None) -> bool:
+ """Is ``value`` an explicit boolean ``false`` in a ``.desktop`` file?
+
+ ``None`` (key absent) is NOT false — the desktop-side "switched off"
+ markers (``Hidden``, ``X-GNOME-Autostart-enabled``) default to enabled when
+ missing, so only a written-out ``false`` may be read as a disabled entry.
+ """
+ return value is not None and value.strip().lower() == "false"
+
+
+def reads_as_true(value: str | None) -> bool:
+ """Is ``value`` an explicit boolean ``true`` in a ``.desktop`` file?"""
+ return value is not None and value.strip().lower() == "true"
+
+
+__all__ = [
+ "DESKTOP_ENTRY_GROUP",
+ "escape_value",
+ "exec_argument",
+ "exec_value",
+ "read_field",
+ "reads_as_false",
+ "reads_as_true",
+ "unescape_value",
+]
diff --git a/jarvis/ui/icon_utils.py b/jarvis/ui/icon_utils.py
index f2b49fc7a8..4fd6b73667 100644
--- a/jarvis/ui/icon_utils.py
+++ b/jarvis/ui/icon_utils.py
@@ -1104,21 +1104,28 @@ def ensure_linux_desktop_entry(applications_dir: Path | None = None) -> bool:
try:
from jarvis.assets import bundled_app_icon_png
from jarvis.core.config import PROJECT_ROOT
+ from jarvis.core.desktop_entry import escape_value, exec_value
png = bundled_app_icon_png()
- icon_line = f"Icon={png}\n" if png is not None and png.is_file() else ""
- program = sys.executable
- exec_value = f'"{program}"' if " " in program else program
+ icon_line = (
+ f"Icon={escape_value(str(png))}\n"
+ if png is not None and png.is_file()
+ else ""
+ )
+ # Both nested Desktop-Entry escaping layers, shared with the autostart
+ # writer: an install path containing a ``%`` is otherwise read as a field
+ # code and the desktop discards the whole entry — which takes the dock
+ # icon down with it, since StartupWMClass binding lives in THIS file.
content = (
"[Desktop Entry]\n"
"Type=Application\n"
- f"Name={APP_DISPLAY_NAME}\n"
+ f"Name={escape_value(APP_DISPLAY_NAME)}\n"
"Comment=Voice-driven meta-orchestrator\n"
- f"Exec={exec_value} -m {_LAUNCHER_MODULE}\n"
- f"Path={PROJECT_ROOT}\n"
+ f"Exec={exec_value(sys.executable, ('-m', _LAUNCHER_MODULE))}\n"
+ f"Path={escape_value(str(PROJECT_ROOT))}\n"
"Terminal=false\n"
f"{icon_line}"
- f"StartupWMClass={LINUX_WM_CLASS}\n"
+ f"StartupWMClass={escape_value(LINUX_WM_CLASS)}\n"
"Categories=Utility;\n"
)
entry = applications_dir / LINUX_DESKTOP_ENTRY_NAME
@@ -1130,7 +1137,7 @@ def ensure_linux_desktop_entry(applications_dir: Path | None = None) -> bool:
applications_dir.mkdir(parents=True, exist_ok=True)
# Atomic-ish (same idiom as the autostart entry): never leave a
# half-written .desktop the desktop environment would choke on.
- tmp = entry.with_suffix(".desktop.tmp")
+ tmp = entry.with_name(entry.name + ".tmp")
tmp.write_text(content, encoding="utf-8")
tmp.replace(entry)
logger.debug("Linux applications .desktop entry written: {}", entry)
diff --git a/tests/unit/autostart/test_linux.py b/tests/unit/autostart/test_linux.py
index 073f76684c..b60658fe5c 100644
--- a/tests/unit/autostart/test_linux.py
+++ b/tests/unit/autostart/test_linux.py
@@ -4,8 +4,11 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
from jarvis.autostart.linux import LinuxAutostart
from jarvis.autostart.protocol import LaunchSpec
+from jarvis.core.desktop_entry import escape_value
def _spec(
@@ -46,7 +49,10 @@ def test_install_brands_entry_with_icon_and_wmclass(monkeypatch, tmp_path: Path)
png = bundled_app_icon_png()
assert png is not None, "bundled jarvis.png must ship for the Linux Icon= key"
- assert f"Icon={png}" in text
+ # Every value goes through the key-file encoding. On a real Linux host that
+ # is the identity for an icon path; on a Windows dev/CI host the bundled
+ # path carries backslashes, and NOT escaping them would be the bug.
+ assert f"Icon={escape_value(str(png))}" in text
assert "StartupWMClass=personal-jarvis" in text
@@ -86,3 +92,223 @@ def test_status_supported_even_when_absent(monkeypatch, tmp_path: Path) -> None:
status = LinuxAutostart().status(_spec())
assert status.supported is True
assert status.installed is False
+
+
+# ---- Desktop Entry escaping (both nested layers) ----------------------------
+
+
+def _entry_text(tmp_path: Path) -> str:
+ return (tmp_path / "autostart" / "personal-jarvis.desktop").read_text(
+ encoding="utf-8"
+ )
+
+
+def test_percent_in_the_install_path_is_written_as_a_double_percent(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """A ``%`` starts a field code — unescaped it invalidates the whole entry.
+
+ The desktop then ignores the file without a word, and the old status check
+ still reported "enabled and current" because it compared the same unescaped
+ string it had just written: dead autostart, invisible from both sides.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec(program="/opt/100%pure/python3", working_dir="/srv/50%off")
+ status = mgr.install(spec)
+
+ assert "Exec=/opt/100%%pure/python3 -m jarvis.ui.web.launcher" in _entry_text(
+ tmp_path
+ )
+ assert status.matches_spec is True
+ assert mgr.status(spec).matches_spec is True
+
+
+def test_reserved_characters_are_quoted_and_backslash_escaped(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec(program="/opt/My $Apps/python3")
+ assert mgr.install(spec).matches_spec is True
+ # Two layers again: the Exec layer writes ``\$``, the key-file layer doubles
+ # its backslash — the reader unwinds both back to a literal ``$``.
+ assert 'Exec="/opt/My \\\\$Apps/python3" -m' in _entry_text(tmp_path)
+
+
+def test_a_backslash_in_the_working_dir_is_escaped_and_still_round_trips(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """A directory name may legally contain a backslash on Linux.
+
+ Written raw it turns the rest of ``Path=`` into a bogus escape sequence; the
+ drift check has to decode the value back to compare it honestly.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec(working_dir="/home/u/odd\\dir")
+ assert mgr.install(spec).matches_spec is True
+ assert "Path=/home/u/odd\\\\dir" in _entry_text(tmp_path)
+ assert mgr.status(spec).matches_spec is True
+
+
+# ---- Status honesty ---------------------------------------------------------
+
+
+def test_status_reports_drift_when_gnome_switched_the_entry_off(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """GNOME's Startup Applications writes ``X-GNOME-Autostart-enabled=false``.
+
+ The file stays in place, so ignoring the key reported installed + current
+ for an autostart that no longer runs — green toggle, no login start, no
+ diagnosis anywhere.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec()
+ mgr.install(spec)
+ entry = tmp_path / "autostart" / "personal-jarvis.desktop"
+ entry.write_text(
+ _entry_text(tmp_path).replace(
+ "X-GNOME-Autostart-enabled=true", "X-GNOME-Autostart-enabled=false"
+ ),
+ encoding="utf-8",
+ )
+
+ status = mgr.status(spec)
+ assert status.installed is True
+ assert status.matches_spec is False
+ assert "switched off" in status.detail
+
+
+def test_status_reports_drift_for_a_hidden_entry(monkeypatch, tmp_path: Path) -> None:
+ """``Hidden=true`` is the spec's own "the user deleted this entry" marker."""
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec()
+ mgr.install(spec)
+ entry = tmp_path / "autostart" / "personal-jarvis.desktop"
+ entry.write_text(
+ _entry_text(tmp_path).replace("Hidden=false", "Hidden=true"), encoding="utf-8"
+ )
+
+ assert mgr.status(spec).matches_spec is False
+
+
+def test_status_ignores_an_exec_from_another_group(monkeypatch, tmp_path: Path) -> None:
+ """A ``[Desktop Action …]`` group legally carries its own ``Exec=``.
+
+ A line-prefix scan can answer the drift check with that command and rewrite
+ a perfectly good entry on every boot.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec()
+ mgr.install(spec)
+ entry = tmp_path / "autostart" / "personal-jarvis.desktop"
+ entry.write_text(
+ _entry_text(tmp_path)
+ + "\n[Desktop Action new-window]\nExec=/somewhere/else --new\n",
+ encoding="utf-8",
+ )
+
+ assert mgr.status(spec).matches_spec is True
+
+
+def test_status_tolerates_spaces_around_the_equals_sign(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ spec = _spec()
+ mgr.install(spec)
+ entry = tmp_path / "autostart" / "personal-jarvis.desktop"
+ entry.write_text(
+ _entry_text(tmp_path).replace("Path=", "Path = "), encoding="utf-8"
+ )
+
+ assert mgr.status(spec).matches_spec is True
+
+
+# ---- XDG base-directory compliance ------------------------------------------
+
+
+def test_relative_xdg_config_home_is_ignored(monkeypatch, tmp_path: Path) -> None:
+ """The XDG spec says a relative value is invalid and must be ignored.
+
+ Honouring it wrote the entry under the process' working directory — a path
+ no desktop environment reads, so autostart was dead while install()
+ reported success.
+ """
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setenv("XDG_CONFIG_HOME", "~/.config")
+ monkeypatch.setattr(Path, "home", classmethod(lambda _cls: home))
+
+ status = LinuxAutostart().install(_spec())
+
+ assert (home / ".config" / "autostart" / "personal-jarvis.desktop").exists()
+ assert status.entry_path == str(
+ home / ".config" / "autostart" / "personal-jarvis.desktop"
+ )
+
+
+# ---- Write / remove failure honesty -----------------------------------------
+
+
+def test_failed_install_leaves_no_temp_file_behind(monkeypatch, tmp_path: Path) -> None:
+ """The successful replace() consumes the temp file — debris means a failure.
+
+ A stray ``personal-jarvis.desktop.tmp`` next to the real entry is confusing
+ at best; the macOS LaunchAgent writer already cleaned up after itself.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+
+ def _boom(self: Path, target: object) -> None:
+ raise OSError("simulated read-only home")
+
+ monkeypatch.setattr(Path, "replace", _boom)
+ with pytest.raises(OSError, match="simulated read-only home"):
+ mgr.install(_spec())
+
+ assert not (tmp_path / "autostart" / "personal-jarvis.desktop.tmp").exists()
+
+
+def test_uninstall_reports_honestly_when_the_entry_survives(
+ monkeypatch, tmp_path: Path
+) -> None:
+ """Claiming "Autostart disabled." while the .desktop is still there is a lie.
+
+ The desktop keeps launching Jarvis at the next login, and the Settings
+ toggle showed off with nothing to explain the mismatch (AP-30) — the same
+ fix the macOS LaunchAgent already got.
+ """
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ mgr.install(_spec())
+
+ def _boom(self: Path, *, missing_ok: bool = False) -> None:
+ raise OSError("permission denied")
+
+ monkeypatch.setattr(Path, "unlink", _boom)
+ status = mgr.uninstall()
+
+ assert status.installed is True
+ assert status.matches_spec is False
+ assert "could not be removed" in status.detail
+ assert (tmp_path / "autostart" / "personal-jarvis.desktop").exists()
+
+
+def test_uninstall_cleans_up_leftover_temp_debris(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))
+ mgr = LinuxAutostart()
+ mgr.install(_spec())
+ debris = tmp_path / "autostart" / "personal-jarvis.desktop.tmp"
+ debris.write_text("half written", encoding="utf-8")
+
+ status = mgr.uninstall()
+
+ assert not debris.exists()
+ assert status.installed is False
diff --git a/tests/unit/awareness/test_window_watcher.py b/tests/unit/awareness/test_window_watcher.py
index 8ff20efcc7..5e54e6e731 100644
--- a/tests/unit/awareness/test_window_watcher.py
+++ b/tests/unit/awareness/test_window_watcher.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import asyncio
import os
import time
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -389,6 +390,216 @@ async def test_posix_poll_loop_stops_after_max_consecutive_failures(monkeypatch)
await watcher.stop() # idempotent cleanup, no crash
+async def test_posix_poll_loop_keeps_going_after_a_success(monkeypatch) -> None:
+ """An empty probe after a working one is "nothing is focused", not a failure.
+
+ ``xdotool getactivewindow`` exits non-zero whenever no client window holds
+ the X11 input focus — the user is on the desktop, a window just closed, a
+ lock screen is up. Those are everyday states, and counting them meant 10 s
+ on the wallpaper permanently killed focus tracking for the whole session
+ while the log blamed a missing xdotool.
+ """
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(window_mod, "display_present", lambda: True)
+ monkeypatch.setattr(window_mod, "is_wayland", lambda: False)
+ monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)
+
+ # One usable window, then far more empty probes than the startup gate allows.
+ target = window_mod._POSIX_POLL_MAX_FAILURES * 3
+ reached = asyncio.Event()
+ loop = asyncio.get_running_loop()
+ state = {"calls": 0}
+
+ def _probe() -> WindowInfo | None:
+ # Runs on a worker thread (asyncio.to_thread) — signal back thread-safely.
+ state["calls"] += 1
+ if state["calls"] > target:
+ loop.call_soon_threadsafe(reached.set)
+ return WindowInfo(title="Terminal", handle=1, pid=5) if state["calls"] == 1 else None
+
+ bus, manager, privacy = _make_components()
+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
+ with patch.object(
+ WindowFocusWatcher, "_posix_foreground_window", staticmethod(_probe),
+ ):
+ await watcher.start()
+ task = watcher._poll_task
+ assert task is not None
+ await asyncio.wait_for(reached.wait(), timeout=5.0)
+ assert not task.done(), "the loop self-disabled on a healthy empty probe"
+ await watcher.stop()
+
+
+async def test_posix_poll_loop_survives_a_raising_iteration(monkeypatch) -> None:
+ """A single bad iteration must not end focus tracking silently.
+
+ Only ``CancelledError`` was caught, so anything else killed the task with an
+ unretrieved exception and no log line — the feature was simply off.
+ """
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "darwin")
+ monkeypatch.setattr(window_mod, "_POSIX_POLL_INTERVAL_S", 0.0)
+
+ real_poll_once = WindowFocusWatcher._poll_once
+ state = {"calls": 0}
+
+ async def _flaky_poll_once(self) -> bool:
+ state["calls"] += 1
+ if state["calls"] == 1:
+ raise RuntimeError("simulated iteration failure")
+ return await real_poll_once(self)
+
+ bus, manager, privacy = _make_components()
+ received: list[FrameUpdated] = []
+ published = asyncio.Event()
+
+ async def _collect(ev) -> None:
+ received.append(ev)
+ published.set()
+
+ bus.subscribe(FrameUpdated, _collect)
+ watcher = WindowFocusWatcher(manager=manager, privacy=privacy, bus=bus)
+ with patch.object(
+ WindowFocusWatcher, "_poll_once", _flaky_poll_once,
+ ), patch.object(
+ WindowFocusWatcher, "_posix_foreground_window",
+ staticmethod(lambda: WindowInfo(title="Terminal", handle=1, pid=5)),
+ ):
+ await watcher.start()
+ task = watcher._poll_task
+ assert task is not None
+ # The loop only reaches a publish if it survived the raising iteration.
+ await asyncio.wait_for(published.wait(), timeout=5.0)
+ assert not task.done()
+ await watcher.stop()
+
+ assert [ev.window_title for ev in received] == ["Terminal"]
+
+
+async def test_posix_poll_once_retries_a_window_whose_emit_failed() -> None:
+ """A failed publish must not mark the window as already reported.
+
+ Committing the change-detection markers before the emit turned a transient
+ tail failure into a permanent one: the next tick saw an unchanged focus and
+ stayed quiet, so ``state.current_frame`` kept describing the PREVIOUS window
+ until the user happened to switch again.
+ """
+ bus, manager, privacy = _make_components()
+ received: list[FrameUpdated] = []
+ bus.subscribe(FrameUpdated, _async_collect(received))
+
+ attempts = {"n": 0}
+
+ def _meta(win: WindowInfo) -> tuple[int, str]:
+ attempts["n"] += 1
+ if attempts["n"] == 1:
+ raise RuntimeError("transient psutil failure")
+ return 123, "gnome-terminal-server"
+
+ 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(_meta),
+ ):
+ assert await watcher._poll_once() is True # probe healthy, emit failed
+ assert received == []
+ assert await watcher._poll_once() is True # same window, retried
+
+ assert len(received) == 1
+ assert received[0].window_title == "Terminal"
+ assert manager.state.current_frame is not None
+ assert manager.state.current_frame.active_pid == 123
+
+
+# ---- Linux X11 pid resolution -----------------------------------------------
+
+
+def test_linux_window_pid_returns_zero_without_xdotool(monkeypatch) -> None:
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: None)
+ assert window_mod._linux_window_pid(7) == 0
+
+
+def test_linux_window_pid_reads_the_reported_pid(monkeypatch) -> None:
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
+ monkeypatch.setattr(
+ window_mod.subprocess, "run",
+ lambda *_a, **_kw: SimpleNamespace(returncode=0, stdout="4242\n", stderr=""),
+ )
+ assert window_mod._linux_window_pid(7) == 4242
+
+
+def test_linux_window_pid_uses_the_resolved_executable(monkeypatch) -> None:
+ """Spawn the binary ``which`` found, not a bare name re-resolved via PATH."""
+ seen: list[list[str]] = []
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/opt/bin/xdotool")
+
+ def _run(argv, **_kw):
+ seen.append(argv)
+ return SimpleNamespace(returncode=0, stdout="9\n", stderr="")
+
+ monkeypatch.setattr(window_mod.subprocess, "run", _run)
+ assert window_mod._linux_window_pid(7) == 9
+ assert seen == [["/opt/bin/xdotool", "getwindowpid", "7"]]
+
+
+def test_linux_window_pid_degrades_on_a_window_without_the_pid_property(
+ monkeypatch,
+) -> None:
+ """xdotool exits non-zero for a client that publishes no ``_NET_WM_PID``.
+
+ Routine, not an error — it must not surface as a resolution failure with a
+ traceback that buries the real ones.
+ """
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
+ monkeypatch.setattr(
+ window_mod.subprocess, "run",
+ lambda *_a, **_kw: SimpleNamespace(
+ returncode=1, stdout="", stderr="xdotool: window has no pid property",
+ ),
+ )
+ assert window_mod._linux_window_pid(7) == 0
+
+
+def test_linux_window_pid_degrades_on_unusable_output(monkeypatch) -> None:
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
+ for stdout in ("", "not-a-pid", "-3"):
+ monkeypatch.setattr(
+ window_mod.subprocess, "run",
+ lambda *_a, _out=stdout, **_kw: SimpleNamespace(
+ returncode=0, stdout=_out, stderr="",
+ ),
+ )
+ assert window_mod._linux_window_pid(7) == 0
+
+
+def test_linux_window_pid_degrades_when_the_probe_times_out(monkeypatch) -> None:
+ """A hung X connection must not propagate out of a poll-loop worker thread."""
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
+
+ def _timeout(*_a, **_kw):
+ raise window_mod.subprocess.TimeoutExpired(cmd="xdotool", timeout=5.0)
+
+ monkeypatch.setattr(window_mod.subprocess, "run", _timeout)
+ assert window_mod._linux_window_pid(7) == 0
+
+
+def test_posix_focus_meta_never_reports_a_negative_pid(monkeypatch) -> None:
+ """A negative pid looks resolved but names no process."""
+ monkeypatch.setattr(window_mod, "detect_platform", lambda: "linux")
+ monkeypatch.setattr(window_mod.shutil, "which", lambda _name: "/usr/bin/xdotool")
+ monkeypatch.setattr(
+ window_mod.subprocess, "run",
+ lambda *_a, **_kw: SimpleNamespace(returncode=0, stdout="-1", stderr=""),
+ )
+ assert WindowFocusWatcher._resolve_posix_focus_meta(
+ WindowInfo(title="x", handle=5),
+ ) == (0, "")
+
+
@pytest.mark.asyncio
async def test_posix_stop_without_start_is_noop() -> None:
"""stop() without a prior start() is a no-op on the POSIX path too."""
diff --git a/tests/unit/core/test_desktop_entry.py b/tests/unit/core/test_desktop_entry.py
new file mode 100644
index 0000000000..e0331c161f
--- /dev/null
+++ b/tests/unit/core/test_desktop_entry.py
@@ -0,0 +1,174 @@
+"""freedesktop Desktop Entry encoding — both nested escaping layers.
+
+Linux-only in effect, CI-provable everywhere: pure string transforms, no I/O.
+Each case pins a rule from the Desktop Entry Specification, because getting one
+wrong makes the desktop discard the entry silently while the writer still
+reports it as installed and current.
+"""
+
+from __future__ import annotations
+
+from jarvis.core.desktop_entry import (
+ escape_value,
+ exec_argument,
+ exec_value,
+ read_field,
+ reads_as_false,
+ reads_as_true,
+ unescape_value,
+)
+
+# ---- Key-file layer ---------------------------------------------------------
+
+
+def test_escape_value_encodes_backslash_and_whitespace() -> None:
+ assert escape_value(r"/home/u/back\slash") == r"/home/u/back\\slash"
+ assert escape_value("a\nb\tc\rd") == "a\\nb\\tc\\rd"
+
+
+def test_escape_value_escapes_the_backslash_first() -> None:
+ """Order matters: a naive newline-first pass would re-escape its own output."""
+ assert escape_value("\\n") == "\\\\n"
+ assert unescape_value(escape_value("\\n")) == "\\n"
+
+
+def test_escape_unescape_round_trips() -> None:
+ for raw in (
+ "/usr/bin/python3",
+ r"/opt/My Apps/back\slash/python3",
+ "tab\there",
+ "percent %f literal",
+ "",
+ ):
+ assert unescape_value(escape_value(raw)) == raw
+
+
+def test_unescape_decodes_the_space_escape_and_keeps_unknown_ones() -> None:
+ assert unescape_value(r"a\sb") == "a b"
+ # \" is not a defined key-file escape; passing it through verbatim keeps a
+ # foreign file from silently comparing equal to something we wrote.
+ assert unescape_value(r"a\"b") == r"a\"b"
+ assert unescape_value("trailing\\") == "trailing\\"
+
+
+# ---- Exec layer -------------------------------------------------------------
+
+
+def test_exec_argument_leaves_a_plain_token_alone() -> None:
+ assert exec_argument("/usr/bin/python3") == "/usr/bin/python3"
+ assert exec_argument("-m") == "-m"
+ assert exec_argument("jarvis.ui.web.launcher") == "jarvis.ui.web.launcher"
+
+
+def test_exec_argument_quotes_reserved_characters() -> None:
+ assert exec_argument("/opt/My Apps/python3") == '"/opt/My Apps/python3"'
+ for reserved in '"\'><~|&;$*?#()`':
+ assert exec_argument(f"a{reserved}b").startswith('"')
+
+
+def test_exec_argument_doubles_a_percent_without_quoting() -> None:
+ """``%`` starts a field code — a literal one must be written ``%%``.
+
+ It does not make the argument reserved, so no quotes are added: an unknown
+ field code invalidates the whole entry, which is exactly the silent-death
+ case this rule prevents.
+ """
+ assert exec_argument("/home/50%off/python3") == "/home/50%%off/python3"
+
+
+def test_exec_argument_backslash_escapes_inside_quotes() -> None:
+ assert exec_argument('say "hi"') == '"say \\"hi\\""'
+ assert exec_argument("cost $5") == '"cost \\$5"'
+ assert exec_argument("tick ` mark") == '"tick \\` mark"'
+
+
+def test_exec_value_needs_four_backslashes_for_a_literal_one() -> None:
+ """The spec's own worked example: the Exec layer doubles the backslash and
+ the key-file layer doubles that again."""
+ assert exec_value(r"/opt/a b/back\slash") == '"/opt/a b/back\\\\\\\\slash"'
+ assert exec_value(r"/opt/a b/back\slash").count("\\") == 4
+
+
+def test_exec_value_renders_program_plus_args() -> None:
+ assert exec_value("/usr/bin/python3", ("-m", "jarvis.ui.web.launcher")) == (
+ "/usr/bin/python3 -m jarvis.ui.web.launcher"
+ )
+
+
+def test_exec_value_of_an_empty_program_is_empty() -> None:
+ """Better an obviously-broken entry than a plausible pair of empty quotes."""
+ assert exec_value("", ("-m", "x")) == ""
+
+
+# ---- Reading ----------------------------------------------------------------
+
+_ENTRY = """\
+# a comment
+[Desktop Entry]
+Type=Application
+Name=Personal Jarvis
+Exec=/usr/bin/python3 -m jarvis.ui.web.launcher
+Path = /home/u/Personal Jarvis
+Name[de]=Persoenlicher Jarvis
+Hidden=false
+
+[Desktop Action new-window]
+Exec=/somewhere/else --new-window
+"""
+
+
+def test_read_field_reads_the_desktop_entry_group() -> None:
+ assert read_field(_ENTRY, "Type") == "Application"
+ assert read_field(_ENTRY, "Exec") == "/usr/bin/python3 -m jarvis.ui.web.launcher"
+
+
+def test_read_field_ignores_other_groups() -> None:
+ """A ``[Desktop Action …]`` group may legally carry its own ``Exec=``.
+
+ A line-prefix scan answers the drift check with that command instead, and
+ then rewrites a perfectly good entry on every single boot.
+ """
+ assert read_field(_ENTRY, "Exec") != "/somewhere/else --new-window"
+ assert read_field(_ENTRY, "Exec", group="Desktop Action new-window") == (
+ "/somewhere/else --new-window"
+ )
+
+
+def test_read_field_tolerates_spaces_around_the_equals_sign() -> None:
+ assert read_field(_ENTRY, "Path") == "/home/u/Personal Jarvis"
+
+
+def test_read_field_does_not_match_a_locale_suffixed_key() -> None:
+ assert read_field(_ENTRY, "Name") == "Personal Jarvis"
+
+
+def test_read_field_returns_none_for_a_missing_key() -> None:
+ assert read_field(_ENTRY, "StartupWMClass") is None
+ assert read_field("", "Exec") is None
+
+
+def test_read_field_takes_the_last_duplicate_like_gkeyfile() -> None:
+ text = "[Desktop Entry]\nHidden=false\nHidden=true\n"
+ assert read_field(text, "Hidden") == "true"
+
+
+def test_read_field_skips_comments() -> None:
+ text = "[Desktop Entry]\n#Exec=/commented/out\nExec=/real\n"
+ assert read_field(text, "Exec") == "/real"
+
+
+# ---- Booleans ---------------------------------------------------------------
+
+
+def test_boolean_readers_treat_a_missing_key_as_unset() -> None:
+ """Absent is NOT false: both desktop off-switches default to enabled."""
+ assert reads_as_false(None) is False
+ assert reads_as_true(None) is False
+
+
+def test_boolean_readers_are_case_and_space_tolerant() -> None:
+ assert reads_as_false("False") is True
+ assert reads_as_false(" false ") is True
+ assert reads_as_true("TRUE") is True
+ assert reads_as_false("true") is False
+ assert reads_as_true("0") is False