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(appshot): report a crashed area picker and serialize shortcut reloads

rubenluetke10-beep0ba6f9c19adc
diff --git a/jarvis/appshot/hotkey.py b/jarvis/appshot/hotkey.py
index 895894c287..30717f07c3 100644
--- a/jarvis/appshot/hotkey.py
+++ b/jarvis/appshot/hotkey.py
@@ -68,6 +68,9 @@ class AppshotShortcut:
not_started = ShortcutStatus(hotkey="", armed=False, detail="Not started yet.")
self._statuses: dict[str, ShortcutStatus] = dict.fromkeys(SCOPE_KEYS, not_started)
self._subscribed = False
+ # The settings route and the ConfigReloaded subscriber can both reload
+ # for one write; unserialized, the loser's listener would be orphaned.
+ self._reload_lock = asyncio.Lock()
@property
def status(self) -> ShortcutStatus:
@@ -84,6 +87,10 @@ class AppshotShortcut:
async def reload(self) -> ShortcutStatus:
"""Re-read both shortcuts and re-arm. Never raises."""
+ async with self._reload_lock:
+ return await self._reload()
+
+ async def _reload(self) -> ShortcutStatus:
await self.stop()
try:
from jarvis.core.config import load_config # noqa: PLC0415
@@ -118,6 +125,7 @@ class AppshotShortcut:
)
except Exception as exc: # noqa: BLE001 - a bad shortcut must not break boot
log.warning("appshot: shortcut could not be armed", exc_info=True)
+ await self.stop() # never leave half of a failed arming running
failed = ShortcutStatus(
hotkey="",
armed=False,
diff --git a/jarvis/appshot/region.py b/jarvis/appshot/region.py
index 52921f34db..a87239916a 100644
--- a/jarvis/appshot/region.py
+++ b/jarvis/appshot/region.py
@@ -71,6 +71,11 @@ class RegionUnavailable(RuntimeError):
"""No area can be selected on this host; the message says why."""
+#: One picker at a time: a second shortcut press, the page button and the
+#: voice tool must not stack overlays (one Esc would cancel all of them).
+_picking = False
+
+
# --------------------------------------------------------------------------
# Pure geometry
# --------------------------------------------------------------------------
@@ -287,14 +292,48 @@ async def pick_region(*, timeout_s: float = PICK_TIMEOUT_S) -> Selection | None:
Raises :class:`RegionUnavailable` when no picker can run on this host.
"""
- from jarvis.appshot.picker import EXIT_NO_GUI # noqa: PLC0415
-
+ global _picking
ok, reason = picker_capability()
if not ok:
raise RegionUnavailable(f"An area cannot be selected here: {reason}.")
+ if _picking:
+ raise RegionUnavailable("An area is already being selected. Finish or press Esc first.")
+ _picking = True
+ try:
+ payload, code, timed_out = await _run_picker(timeout_s)
+ finally:
+ _picking = False
+ if payload is None and not timed_out and code not in (0, None):
+ log.warning("appshot: area picker exited with code %s and no selection", code)
+ raise RegionUnavailable(_exit_message(code))
+ selection = parse_selection(payload) if payload is not None else None
+ if selection is not None:
+ await asyncio.sleep(_SETTLE_S)
+ return selection
+
+
+def _exit_message(code: int) -> str:
+ from jarvis.appshot.picker import EXIT_NO_GUI # noqa: PLC0415
+
+ if code == EXIT_NO_GUI:
+ return "An area cannot be selected here: the selection overlay found no usable screen."
+ return f"The selection overlay stopped unexpectedly (exit code {code}). Nothing was captured."
+
+
+async def _run_picker(timeout_s: float) -> tuple[dict[str, Any] | None, int | None, bool]:
+ """Spawn, wait for one selection, always reap. ``(payload, exit code, timed out)``."""
hint = await asyncio.to_thread(_hint)
+ # Shielded: a caller cancelled mid-spawn must still get the process reaped,
+ # or its overlay would cover the screens until the stdin timeout.
+ spawn = asyncio.ensure_future(asyncio.to_thread(_spawn, hint))
try:
- proc = await asyncio.to_thread(_spawn, hint)
+ proc = await asyncio.shield(spawn)
+ except asyncio.CancelledError:
+ with contextlib.suppress(Exception): # a failed spawn leaves nothing to reap
+ late = await spawn
+ await asyncio.to_thread(_cancel, late)
+ await asyncio.to_thread(_reap, late)
+ raise
except Exception as exc: # noqa: BLE001 - surfaced to the user as unavailable
log.warning("appshot: area picker could not be started", exc_info=True)
raise RegionUnavailable("The selection overlay could not be started.") from exc
@@ -302,27 +341,24 @@ async def pick_region(*, timeout_s: float = PICK_TIMEOUT_S) -> Selection | None:
_escape_cancels(proc), name="appshot-region-esc"
)
reader = asyncio.ensure_future(asyncio.to_thread(_read_result, proc))
+ timed_out = False
+ payload: dict[str, Any] | None = None
try:
try:
payload = await asyncio.wait_for(asyncio.shield(reader), timeout=timeout_s)
except TimeoutError:
+ timed_out = True
await asyncio.to_thread(_cancel, proc)
- payload = None
finally:
escape.cancel()
with contextlib.suppress(asyncio.CancelledError):
await escape
+ if payload is None and not timed_out:
+ await asyncio.to_thread(_cancel, proc) # a cancelled caller closes the overlay
code = await asyncio.to_thread(_reap, proc)
with contextlib.suppress(Exception): # EOF after the reap ends the reader
await reader
- if payload is None and code == EXIT_NO_GUI:
- raise RegionUnavailable(
- "An area cannot be selected here: the selection overlay found no usable screen."
- )
- selection = parse_selection(payload) if payload is not None else None
- if selection is not None:
- await asyncio.sleep(_SETTLE_S)
- return selection
+ return payload, code, timed_out
__all__ = [
diff --git a/tests/unit/appshot/test_appshot_region.py b/tests/unit/appshot/test_appshot_region.py
index be38d088d6..fec5271a40 100644
--- a/tests/unit/appshot/test_appshot_region.py
+++ b/tests/unit/appshot/test_appshot_region.py
@@ -387,3 +387,96 @@ def test_one_key_for_both_shortcuts_is_refused_before_writing(client, monkeypatc
assert response.status_code == 400
assert "two different shortcuts" in response.json()["detail"]
assert writes == []
+
+
+# ----------------------------------------------------------- picker outcomes
+
+
+def picker_host(monkeypatch):
+ monkeypatch.setattr(region, "picker_capability", lambda: (True, ""))
+ monkeypatch.setattr(region, "_SETTLE_S", 0.0)
+ region._picking = False
+ yield monkeypatch
+ region._picking = False
+
+
+def _runs(monkeypatch, outcome) -> None:
+ async def run_picker(_timeout_s):
+ return outcome
+
+ monkeypatch.setattr(region, "_run_picker", run_picker)
+
+
+async def test_a_crashed_picker_is_reported_not_taken_for_a_cancel(picker_host) -> None:
+ _runs(picker_host, (None, 1, False))
+ with pytest.raises(region.RegionUnavailable, match="stopped unexpectedly"):
+ await region.pick_region()
+
+
+async def test_a_picker_without_a_screen_says_so(picker_host) -> None:
+ from jarvis.appshot.picker import EXIT_NO_GUI
+
+ _runs(picker_host, (None, EXIT_NO_GUI, False))
+ with pytest.raises(region.RegionUnavailable, match="no usable screen"):
+ await region.pick_region()
+
+
[email protected]("outcome", [(None, 0, False), (None, 1, True)])
+async def test_a_clean_exit_or_a_timeout_is_a_quiet_cancel(picker_host, outcome) -> None:
+ _runs(picker_host, outcome)
+ assert await region.pick_region() is None
+
+
+async def test_a_second_picker_is_refused_while_one_is_open(picker_host) -> None:
+ import asyncio
+
+ release = asyncio.Event()
+
+ async def run_picker(_timeout_s):
+ await release.wait()
+ return (None, 0, False)
+
+ picker_host.setattr(region, "_run_picker", run_picker)
+ first = asyncio.create_task(region.pick_region())
+ await asyncio.sleep(0)
+ with pytest.raises(region.RegionUnavailable, match="already being selected"):
+ await region.pick_region()
+ release.set()
+ assert await first is None
+ assert region._picking is False, "the gate opens again after the first pick"
+
+
+async def test_overlapping_reloads_leave_exactly_one_listener(monkeypatch) -> None:
+ import asyncio
+
+ import jarvis.appshot.hotkey as hotkey_module
+ import jarvis.core.config as config_module
+ import jarvis.core.instance as instance_module
+ import jarvis.platform.probes as probes
+
+ class Cfg:
+ class appshot: # noqa: N801
+ hotkey = "ctrl+alt+a"
+ region_hotkey = "alt+win+a"
+
+ monkeypatch.setattr(config_module, "load_config", lambda: Cfg)
+ monkeypatch.setattr(instance_module, "current_instance", lambda: _Instance())
+ monkeypatch.setattr(probes, "has_hotkey", lambda: True)
+ running: list[int] = []
+
+ async def run_combos(self, combos):
+ running.append(1)
+ try:
+ await asyncio.Event().wait()
+ finally:
+ running.pop()
+
+ monkeypatch.setattr(hotkey_module.AppshotShortcut, "_run_combos", run_combos)
+ shortcut = AppshotShortcut(bus=object())
+ await asyncio.gather(shortcut.reload(), shortcut.reload(), shortcut.reload())
+ await asyncio.sleep(0)
+ assert len(running) == 1
+ await shortcut.stop()
+ await asyncio.sleep(0)
+ assert running == []