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): open the area picker the instant the shortcut is pressed (#1107)

Ruben Lütke6542348bc291
diff --git a/dodaios/appshot/hotkey.py b/dodaios/appshot/hotkey.py
index c025c069a9..1f4693e53e 100644
--- a/dodaios/appshot/hotkey.py
+++ b/dodaios/appshot/hotkey.py
@@ -23,6 +23,8 @@ from dataclasses import dataclass
from typing import Any
log = logging.getLogger(__name__)
+#: Pickers of replaced presses still being closed.
+_DISCARDS: set[asyncio.Task] = set()
BOTH_ALT = "alt+alt"
BOTH_SHIFT = "shift+shift"
@@ -249,6 +251,13 @@ class AppshotShortcut:
self._run_combos(combos), name="appshot-hotkey"
)
if owns and bool(getattr(getattr(config, "screen_context", None), "enabled", False)):
+ from dodaios.appshot.picker_host import get_picker_host # noqa: PLC0415
+
+ language = str(getattr(getattr(config, "ui", None), "language", "") or "en")
+ get_picker_host().configure(
+ language.lower()[:2],
+ bool(getattr(config.appshot, "region_keep_area", False)),
+ )
self._warm_task = asyncio.create_task(
self._warm_surfaces(bool(getattr(config.appshot, "effect", True))),
name="appshot-surfaces-warm",
@@ -338,7 +347,7 @@ class AppshotShortcut:
if probe is None:
return ShortcutStatus(hotkey=hotkey, armed=False, detail=reason)
watcher = BothKeysWatcher(
- lambda: self._fire_threadsafe(scope),
+ lambda: self._press(scope),
probe=probe,
together_s=together_window(family),
)
@@ -406,7 +415,7 @@ class AppshotShortcut:
listener = AppshotKeyEvents()
rows = [
- [_normalize_combo(combo), None, lambda scope=scope: self._fire_threadsafe(scope)]
+ [_normalize_combo(combo), None, lambda scope=scope: self._press(scope)]
for scope, combo in combos.items()
]
try:
@@ -445,6 +454,23 @@ class AppshotShortcut:
combo, False, "The keyboard event listener stopped."
)
+ def _press(self, scope: str) -> None:
+ """A shortcut went down (listener thread): open the area picker now.
+
+ The event loop may be busy for a while (a full RAM, a long turn); the
+ picker is already warm in its own process, so the overlay must not
+ wait for the loop, the config or the screen freeze. The take that
+ follows picks up this open picker instead of starting another.
+ """
+ if scope == "region":
+ host = getattr(sys.modules.get("dodaios.appshot.picker_host"), "_host", None)
+ if host is not None:
+ try:
+ host.open_now()
+ except Exception: # noqa: BLE001 - the take still opens it the usual way
+ log.debug("appshot: opening the picker on the press failed", exc_info=True)
+ self._fire_threadsafe(scope)
+
def _fire_threadsafe(self, scope: str) -> None:
loop = self._loop
if loop is None or loop.is_closed():
@@ -455,7 +481,13 @@ class AppshotShortcut:
def _fire(self, scope: str = "window") -> None:
busy_field = "_recording_busy" if scope == "recording" else "_busy"
if getattr(self, busy_field):
+ replaced = self._pending.get(busy_field)
self._pending[busy_field] = scope
+ if replaced == "region" and scope != "region":
+ # The replaced press may have opened the picker already.
+ task = asyncio.get_running_loop().create_task(self._discard_opened())
+ _DISCARDS.add(task)
+ task.add_done_callback(_DISCARDS.discard)
return
self._begin_take(scope, busy_field)
@@ -482,17 +514,33 @@ class AppshotShortcut:
return
from dodaios.appshot.service import take_appshot # noqa: PLC0415
- result = await take_appshot(
- trigger="hotkey",
- bus=self._bus,
- scope="region" if scope == "region" else "window",
- )
+ try:
+ result = await take_appshot(
+ trigger="hotkey",
+ bus=self._bus,
+ scope="region" if scope == "region" else "window",
+ )
+ finally:
+ if scope == "region":
+ # A refusal before the picker (switched off, say) leaves the
+ # picker this press opened on the glass.
+ await self._discard_opened()
if result.ok:
return
log.info("appshot: shortcut press refused — %s", result.message)
if result.reason_code != "cancelled": # Esc on the picker needs no toast
await self._publish_refusal(result.message)
+ @staticmethod
+ async def _discard_opened() -> None:
+ host = getattr(sys.modules.get("dodaios.appshot.picker_host"), "_host", None)
+ if host is None:
+ return
+ try:
+ await host.discard_opened()
+ except Exception: # noqa: BLE001 - the next press re-warms it
+ log.debug("appshot: could not close the picker the press opened", exc_info=True)
+
async def _publish_refusal(self, message: str) -> None:
try:
from dodaios.core.events import AppshotTaken # noqa: PLC0415
diff --git a/dodaios/appshot/picker/__init__.py b/dodaios/appshot/picker/__init__.py
index 4d2b50e74e..8667f003af 100644
--- a/dodaios/appshot/picker/__init__.py
+++ b/dodaios/appshot/picker/__init__.py
@@ -33,7 +33,10 @@ stdin::
{"cmd": "start", "language": "en", "monitors": [], # resident: fresh capture
"windows": [], "handles": [], # (handles: hwnds beside the
- "keep_area": false} # window rects; keep the area)
+ "keep_area": false, "shield": false} # window rects; keep the area;
+ # shield: hidden from screen
+ # captures until "unshield")
+ {"cmd": "unshield"} # the parent froze the screens
{"cmd": "quit"} # release the runtime
{"cmd": "layout", "monitors": [...], # mss monitors and the
"windows": [[l, t, w, h], ...], "handles": [...]} # snap targets, top first
@@ -65,6 +68,7 @@ CMD_CANCEL = "cancel"
CMD_LAYOUT = "layout"
CMD_START = "start"
CMD_QUIT = "quit"
+CMD_UNSHIELD = "unshield"
def encode(payload: dict[str, Any]) -> str:
@@ -90,6 +94,7 @@ __all__ = [
"CMD_LAYOUT",
"CMD_START",
"CMD_QUIT",
+ "CMD_UNSHIELD",
"EVENT_MARKING",
"EVENT_OPTION",
"EVENT_READY",
diff --git a/dodaios/appshot/picker/renderer.py b/dodaios/appshot/picker/renderer.py
index 43c4b17917..ad700281b2 100644
--- a/dodaios/appshot/picker/renderer.py
+++ b/dodaios/appshot/picker/renderer.py
@@ -34,6 +34,7 @@ from __future__ import annotations
import sys
import threading
+import time
from contextlib import suppress
from typing import TYPE_CHECKING
@@ -58,6 +59,7 @@ if TYPE_CHECKING:
from dodaios.appshot.region import (
grab_preview,
match_monitor,
+ preview_capture_allowed,
selection_fractions,
snap_targets_on_screen,
)
@@ -129,6 +131,27 @@ def _claim_keyboard(window: QWidget) -> None:
sys.stderr.write(f"appshot-picker: could not take the keyboard ({exc!r}).\n")
+def _shield(window: QWidget, hidden: bool) -> None:
+ """Windows: keep ``window`` out of screen captures, or let them see it again.
+
+ A shortcut press opens the picker at once, while the main process is
+ still freezing the screens for the appshot itself: until that frame is
+ taken, the overlay must not be in it.
+ """
+ if sys.platform != "win32":
+ return
+ try:
+ from dodaios.platform import capture_exclusion # noqa: PLC0415
+
+ hwnd = int(window.winId())
+ if hidden:
+ capture_exclusion.exclude_hwnd_from_capture(hwnd)
+ else:
+ capture_exclusion.include_hwnd_in_capture(hwnd)
+ except Exception as exc: # noqa: BLE001 - only a screen recorder notices
+ sys.stderr.write(f"appshot-picker: capture shield failed ({exc!r}).\n")
+
+
def number_font() -> QFont:
font = QFont()
font.setPointSizeF(_NUMBER_PT)
@@ -487,8 +510,10 @@ class Picker(QObject):
#: the first pick, then kept warm with the rest of the runtime.
self._parts: ElementScanner | None = None
self._parts_asked: set[int] = set()
+ #: The overlay is hidden from screen captures until ``unshield``.
+ self._shielded = False
- def start(self) -> None:
+ def start(self, *, shield: bool = False) -> None:
if self._started:
return
self._started = True
@@ -501,6 +526,10 @@ class Picker(QObject):
# Freeze every screen BEFORE any overlay window exists.
frozen = {id(s): self._grab(s) for s in screens}
self._windows = [self.make_window(s, frozen[id(s)]) for s in screens]
+ self._shielded = shield
+ if shield:
+ for win in self._windows:
+ _shield(win, True) # before show: not one frame may reach a capture
cursor_screen = QGuiApplication.screenAt(QCursor.pos()) or QGuiApplication.primaryScreen()
self._focused = next(
(w for w in self._windows if w.screen_ref is cursor_screen),
@@ -515,7 +544,43 @@ class Picker(QObject):
self._focused.setFocus()
_claim_keyboard(self._focused)
self._app.processEvents()
- _emit({"event": wire.EVENT_READY})
+ # ``at`` (wall clock) lets the parent log press-to-visible across processes.
+ _emit({"event": wire.EVENT_READY, "at": time.time()})
+
+ def unshield(self) -> None:
+ if not self._shielded:
+ return
+ self._shielded = False
+ for win in self._windows:
+ _shield(win, False)
+
+ def warm_up(self) -> None:
+ """Build and paint one overlay off the glass, without any pixels.
+
+ Qt's first window, toolbar icons, fonts and paint path cost several
+ hundred milliseconds once; paid here in standby, the first shortcut
+ press opens as fast as every later one.
+ """
+ screen = QGuiApplication.primaryScreen()
+ if screen is None:
+ return
+ with suppress(Exception):
+ # Reads the grant only (its first import is ~200 ms); takes no pixels.
+ preview_capture_allowed()
+ try:
+ win = self.make_window(screen, None)
+ win.setAttribute(Qt.WidgetAttribute.WA_DontShowOnScreen)
+ win.arm()
+ win.show()
+ self._app.processEvents()
+ win.repaint()
+ win.hide()
+ win.release_capture()
+ win.close()
+ win.deleteLater()
+ self._app.processEvents()
+ except Exception as exc: # noqa: BLE001 - the first press only pays the cost
+ sys.stderr.write(f"appshot-picker: warm-up failed ({exc!r}).\n")
def make_window(self, screen, frozen: QPixmap | None) -> _SelectWindow:
"""The appshot's window; capture modes provide their own."""
@@ -651,10 +716,12 @@ class Picker(QObject):
if cmd == wire.CMD_START and self._resident and not self._started:
self.language = str(payload.get("language") or "en")
self.keep_area = payload.get("keep_area") is True
- self.start()
+ self.start(shield=payload.get("shield") is True)
self.set_layout(
payload.get("monitors", []), payload.get("windows", []), payload.get("handles")
)
+ elif cmd == wire.CMD_UNSHIELD:
+ self.unshield()
elif cmd == wire.CMD_QUIT:
self.on_eof()
elif cmd == wire.CMD_CANCEL and self._started:
@@ -716,6 +783,7 @@ def run(language: str = "en", *, resident: bool = False) -> int:
if resident:
# Import/initialize Qt without taking pixels, creating windows or
# stealing focus. The next start command samples the current desktop.
+ picker.warm_up()
_emit({"event": wire.EVENT_STANDBY})
else:
picker.start()
diff --git a/dodaios/appshot/picker_host.py b/dodaios/appshot/picker_host.py
index 5cc8bb43f6..fca6aaa6a5 100644
--- a/dodaios/appshot/picker_host.py
+++ b/dodaios/appshot/picker_host.py
@@ -4,14 +4,23 @@ Qt lives in a child process. Only an explicit pick command takes a fresh
desktop image; standby imports the GUI without opening a window. Readers are
joined before reuse and a cancelled or timed-out request discards its process,
so a late result can never complete the next request.
+
+A shortcut press opens the warm picker straight from the listener's thread
+(:meth:`PickerHost.open_now`), before the event loop, the config and the
+screen freeze have had their turn: the overlay is up in a frame, like a
+native screenshot tool. Until the parent has frozen the screens, the overlay
+is hidden from screen captures, so the appshot never contains it.
"""
from __future__ import annotations
import asyncio
import contextlib
+import functools
import logging
import subprocess
+import sys
+import threading
import time
from typing import Any
@@ -20,6 +29,8 @@ from dodaios.appshot import region
log = logging.getLogger(__name__)
_START_TIMEOUT_S = 5.0
+#: Opening on the press needs the overlay hidden from captures meanwhile.
+FAST_OPEN = sys.platform == "win32"
class PickerHost:
@@ -27,6 +38,68 @@ class PickerHost:
self._lock = asyncio.Lock()
self._proc: subprocess.Popen[str] | None = None
self._active: asyncio.Task | None = None
+ #: Guards the picker's stdin and the fast-open state across threads.
+ self._io = threading.RLock()
+ self._picking = False
+ #: Wall clock of a press that already opened the picker, not yet picked.
+ self._opened_at: float | None = None
+ self._shielded = False
+ self._language = "en"
+ self._keep_area = False
+
+ def configure(self, language: str, keep_area: bool) -> None:
+ """What the next press opens with, before the config is read again."""
+ with self._io:
+ self._language = language or "en"
+ self._keep_area = bool(keep_area)
+
+ def open_now(self) -> bool:
+ """Show the warm picker at once. Safe from any thread; never blocks.
+
+ ``False`` when it cannot (no warm picker, one already open, not
+ Windows): the normal path then opens it as before.
+ """
+ if not FAST_OPEN:
+ return False
+ with self._io:
+ proc = self._proc
+ if self._picking or self._opened_at is not None:
+ return False
+ if proc is None or proc.poll() is not None:
+ return False
+ try:
+ self._send(
+ proc,
+ {
+ "cmd": wire.CMD_START,
+ "language": self._language,
+ "keep_area": self._keep_area,
+ "shield": True,
+ },
+ )
+ except (OSError, ValueError, region.RegionUnavailable):
+ log.debug("appshot: fast open skipped; the take opens the picker", exc_info=True)
+ return False
+ self._opened_at = time.time()
+ self._shielded = True
+ return True
+
+ async def discard_opened(self) -> None:
+ """Close a picker a press opened when no selection followed (a refusal)."""
+ with self._io:
+ if self._opened_at is None or self._picking:
+ return
+ self._opened_at = None
+ self._shielded = False
+ log.info("appshot: closing the picker the press opened; nothing was selected")
+ async with self._lock:
+ # Its "ready" and the cancel's answer are still in the pipe: a fresh
+ # process is the only way the next pick cannot read them.
+ await self._dispose()
+ try:
+ await self._ensure()
+ except Exception: # noqa: BLE001 - the next press retries
+ log.debug("appshot: picker re-warm failed", exc_info=True)
async def prewarm(self) -> None:
if not region.picker_capability()[0]:
@@ -50,12 +123,16 @@ class PickerHost:
proc.stdin.write(wire.encode(payload))
proc.stdin.flush()
+ def _write(self, proc: subprocess.Popen[str], payload: dict) -> None:
+ with self._io:
+ self._send(proc, payload)
+
async def _dispose(self) -> None:
proc, self._proc = self._proc, None
if proc is None:
return
try:
- await asyncio.to_thread(self._send, proc, {"cmd": wire.CMD_QUIT})
+ await asyncio.to_thread(self._write, proc, {"cmd": wire.CMD_QUIT})
except (OSError, ValueError, region.RegionUnavailable):
log.debug("appshot: picker pipe already closed during shutdown")
await asyncio.to_thread(region._reap, proc)
@@ -90,18 +167,40 @@ class PickerHost:
) -> tuple[Any, int | None, bool]:
async with self._lock:
self._active = asyncio.current_task()
+ self.configure(language, keep_area)
+ with self._io:
+ self._picking = True
+ opened_at, self._opened_at = self._opened_at, None
+ opened_proc = self._proc if opened_at is not None else None
try:
- return await self._pick(timeout_s, language, keep_area)
+ return await self._pick(timeout_s, language, keep_area, opened_at, opened_proc)
finally:
+ with self._io:
+ self._picking = False
+ self._shielded = False
self._active = None
async def _pick(
- self, timeout_s: float, language: str, keep_area: bool
+ self,
+ timeout_s: float,
+ language: str,
+ keep_area: bool,
+ opened_at: float | None = None,
+ opened_proc: subprocess.Popen[str] | None = None,
) -> tuple[Any, int | None, bool]:
- started = time.perf_counter()
+ started = time.time()
proc = await self._ensure()
+ # The press opened this very process; a replaced one never saw it.
+ preopened = opened_at is not None and opened_proc is proc
+ if preopened and self._shielded:
+ # The caller froze the screens before picking: captures may see it.
+ with self._io:
+ self._shielded = False
+ await asyncio.to_thread(self._write, proc, {"cmd": wire.CMD_UNSHIELD})
try:
- layout = await asyncio.to_thread(region.snap_layout)
+ # Up already, the overlay must not become a snap target itself.
+ read = functools.partial(region.snap_layout, skip_pid=proc.pid)
+ layout = await asyncio.to_thread(read if preopened else region.snap_layout)
except Exception:
log.debug("appshot: snap layout unavailable", exc_info=True)
layout = {}
@@ -110,24 +209,30 @@ class PickerHost:
payload = None
timed_out = False
try:
- await asyncio.to_thread(
- self._send,
- proc,
- {"cmd": wire.CMD_START, "language": language, "keep_area": keep_area, **layout},
- )
+ if preopened:
+ await asyncio.to_thread(self._write, proc, {"cmd": wire.CMD_LAYOUT, **layout})
+ else:
+ start = {"cmd": wire.CMD_START, "language": language, "keep_area": keep_area}
+ await asyncio.to_thread(self._write, proc, {**start, **layout})
loop = asyncio.get_running_loop()
escape = loop.create_task(region._escape_cancels(proc), name="appshot-region-esc")
def marking() -> None:
loop.call_soon_threadsafe(escape.cancel)
- def ready() -> None:
+ def ready(event: dict[str, Any]) -> None:
+ at = event.get("at")
+ shown = float(at) if isinstance(at, (int, float)) else time.time()
+ since = opened_at if preopened and opened_at is not None else started
log.info(
- "appshot: picker visible in %.1f ms", (time.perf_counter() - started) * 1000
+ "appshot: picker visible %.1f ms after the %s",
+ (shown - since) * 1000,
+ "press" if preopened else "request",
)
def option(payload: dict[str, Any]) -> None:
if isinstance(payload.get("keep_area"), bool):
+ self.configure(language, payload["keep_area"])
loop.call_soon_threadsafe(_remember_keep_area, payload["keep_area"])
reader = asyncio.create_task(
diff --git a/dodaios/appshot/recording_worker.py b/dodaios/appshot/recording_worker.py
index 3cae2d86d4..aef8f2d5e8 100644
--- a/dodaios/appshot/recording_worker.py
+++ b/dodaios/appshot/recording_worker.py
@@ -158,8 +158,8 @@ def run(
def make_window(self, screen, frozen):
return RecordingSelectWindow(screen, frozen, self)
- def start(self) -> None:
- super().start()
+ def start(self, *, shield: bool = False) -> None:
+ super().start(shield=shield)
for window in self._windows:
screen = window.screen_ref
dpr = screen.devicePixelRatio()
diff --git a/dodaios/appshot/region.py b/dodaios/appshot/region.py
index 0744c686c1..74c19e4ca3 100644
--- a/dodaios/appshot/region.py
+++ b/dodaios/appshot/region.py
@@ -295,10 +295,11 @@ def _is_cloaked(handle: int | None) -> bool:
return False
-def snap_layout() -> dict[str, Any]:
+def snap_layout(*, skip_pid: int | None = None) -> dict[str, Any]:
"""Monitors and window rectangles for the picker's window snapping.
- Read BEFORE the picker exists, so its own overlay never becomes a target.
+ Read BEFORE the picker exists, so its own overlay never becomes a target,
+ or with ``skip_pid`` (the picker's process) once it is already up.
Rects are in capture coordinates, top-most window first; an empty window
list (Wayland, an unreadable desktop) only switches snapping off.
``handles`` runs alongside ``windows`` (``0`` = unknown): the picker reads
@@ -318,6 +319,8 @@ def snap_layout() -> dict[str, Any]:
for win in ws.list_windows():
if getattr(win, "minimized", False) or _is_cloaked(getattr(win, "handle", None)):
continue
+ if skip_pid and getattr(win, "pid", None) == skip_pid:
+ continue
rect = ws.window_frame_rect(win) or ws.window_rect(win)
if rect and rect[2] > 0 and rect[3] > 0:
handle = getattr(win, "handle", None)
@@ -347,7 +350,7 @@ def _spawn(language: str = "en", *, resident: bool = False) -> subprocess.Popen[
def _read_result(
proc: subprocess.Popen[str], on_marking: Callable[[], None] | None = None,
- on_ready: Callable[[], None] | None = None,
+ on_ready: Callable[[dict[str, Any]], None] | None = None,
on_option: Callable[[dict[str, Any]], None] | None = None,
) -> dict[str, Any] | None:
"""Block until the picker reports its selection; ``None`` on EOF.
@@ -367,7 +370,7 @@ def _read_result(
if event == wire.EVENT_SELECTION:
return payload
if event == wire.EVENT_READY and on_ready is not None:
- on_ready()
+ on_ready(payload)
if event == wire.EVENT_MARKING and on_marking is not None:
with contextlib.suppress(Exception): # a lost hint only keeps the global Esc
on_marking()
diff --git a/dodaios/platform/capture_exclusion.py b/dodaios/platform/capture_exclusion.py
index 8c3fe5dc42..4aa96a90ea 100644
--- a/dodaios/platform/capture_exclusion.py
+++ b/dodaios/platform/capture_exclusion.py
@@ -20,6 +20,7 @@ from typing import Any
log = logging.getLogger(__name__)
+_WDA_NONE = 0x00000000
_WDA_EXCLUDEFROMCAPTURE = 0x00000011
# AppKit.NSWindowSharingNone — keep the numeric literal so a host without
# pyobjc still documents the contract.
@@ -50,15 +51,24 @@ def _user32() -> Any:
def exclude_hwnd_from_capture(hwnd: int) -> bool:
"""Hide one native window from screen capture. No-op off Windows."""
+ return _set_affinity(hwnd, _WDA_EXCLUDEFROMCAPTURE)
+
+
+def include_hwnd_in_capture(hwnd: int) -> bool:
+ """Undo :func:`exclude_hwnd_from_capture`: captures see the window again."""
+ return _set_affinity(hwnd, _WDA_NONE)
+
+
+def _set_affinity(hwnd: int, affinity: int) -> bool:
if sys.platform != "win32" or not hwnd:
return False
user32 = _user32()
if user32 is None:
return False
try:
- return bool(user32.SetWindowDisplayAffinity(int(hwnd), _WDA_EXCLUDEFROMCAPTURE))
+ return bool(user32.SetWindowDisplayAffinity(int(hwnd), affinity))
except Exception: # noqa: BLE001 — overlay must degrade, never crash
- log.debug("exclude_hwnd_from_capture failed for hwnd=%s", hwnd, exc_info=True)
+ log.debug("SetWindowDisplayAffinity(%s) failed for hwnd=%s", affinity, hwnd, exc_info=True)
return False
@@ -161,4 +171,5 @@ __all__ = [
"exclude_hwnd_from_capture",
"exclude_macos_app_windows",
"exclude_tk_window_from_capture",
+ "include_hwnd_in_capture",
]
diff --git a/tests/unit/appshot/test_picker_host.py b/tests/unit/appshot/test_picker_host.py
index cb0e0b19aa..755abe8760 100644
--- a/tests/unit/appshot/test_picker_host.py
+++ b/tests/unit/appshot/test_picker_host.py
@@ -34,6 +34,7 @@ class Process:
self.stdout = Output()
self.stdin = self
self.returncode = None
+ self.pid = 1
self.commands: list[dict] = []
self.finish = finish
self.closed = False
@@ -90,7 +91,7 @@ def host(monkeypatch):
monkeypatch.setattr(region, "_spawn", spawn)
monkeypatch.setattr(region, "_escape_cancels", escape)
monkeypatch.setattr(region, "picker_capability", lambda: (True, ""))
- monkeypatch.setattr(region, "snap_layout", lambda: {"monitors": [], "windows": []})
+ monkeypatch.setattr(region, "snap_layout", lambda **_kw: {"monitors": [], "windows": []})
return picker_host.PickerHost(), children
@@ -218,3 +219,93 @@ async def test_no_display_never_spawns(host, monkeypatch):
monkeypatch.setattr(region, "picker_capability", lambda: (False, "no display"))
await owner.prewarm()
assert children == []
+
+
+# -- a shortcut press opens the warm picker before the take reaches it --------
+
+
+def fast(monkeypatch):
+ monkeypatch.setattr(picker_host, "FAST_OPEN", True)
+
+
+async def test_press_opens_shielded_and_the_take_adopts_it(host, monkeypatch, fast):
+ owner, children = host
+ seen: list[object] = []
+
+ def layout(**kwargs):
+ seen.append(kwargs.get("skip_pid"))
+ return {"windows": [[0, 0, 5, 5]]}
+
+ monkeypatch.setattr(region, "snap_layout", layout)
+ try:
+ await owner.prewarm()
+ owner.configure("de", True)
+ proc = children[0]
+ proc.pid = 4242
+ assert owner.open_now() is True
+ assert owner.open_now() is False # one open picker at a time
+ assert proc.commands == [
+ {"cmd": wire.CMD_START, "language": "de", "keep_area": True, "shield": True}
+ ]
+ payload, _code, _timed_out = await owner.pick(1, "de", keep_area=True)
+ assert payload["cancelled"]
+ # No second start: the shield lifts, then the snap targets follow,
+ # read without the picker's own windows.
+ assert [c["cmd"] for c in proc.commands] == [
+ wire.CMD_START,
+ wire.CMD_UNSHIELD,
+ wire.CMD_LAYOUT,
+ ]
+ assert proc.commands[-1]["windows"] == [[0, 0, 5, 5]]
+ assert seen == [4242]
+ # The next pick without a press opens the usual way.
+ await owner.pick(1, "de")
+ assert proc.commands[-1]["cmd"] == wire.CMD_START
+ assert "shield" not in proc.commands[-1]
+ assert len(children) == 1
+ finally:
+ await owner.close()
+
+
+async def test_press_without_warm_picker_or_during_a_pick_does_nothing(host, fast):
+ owner, children = host
+ assert owner.open_now() is False # nothing warm yet
+ try:
+ await owner.prewarm()
+ children[0].finish = False
+ task = asyncio.create_task(owner.pick(30, "en"))
+ assert await asyncio.to_thread(children[0].started.wait, 1)
+ assert owner.open_now() is False
+ assert [c["cmd"] for c in children[0].commands] == [wire.CMD_START]
+ children[0].stdout.emit({"event": wire.EVENT_SELECTION, "cancelled": True})
+ await task
+ finally:
+ await owner.close()
+
+
+async def test_refused_take_closes_the_opened_picker_and_rewarms(host, fast):
+ owner, children = host
+ try:
+ await owner.prewarm()
+ assert owner.open_now() is True
+ await owner.discard_opened()
+ # Its ready and cancel answers die with it; a fresh one stands by.
+ assert children[0].returncode == 0 and children[0].stdout.closed
+ assert len(children) == 2 and children[1].commands == []
+ await owner.discard_opened() # nothing open: no-op
+ assert len(children) == 2
+ assert owner.open_now() is True
+ finally:
+ await owner.close()
+
+
+async def test_no_fast_open_off_windows(host, monkeypatch):
+ owner, children = host
+ monkeypatch.setattr(picker_host, "FAST_OPEN", False)
+ try:
+ await owner.prewarm()
+ assert owner.open_now() is False
+ assert children[0].commands == []
+ finally:
+ await owner.close()
diff --git a/tests/unit/appshot/test_shortcut_prewarm.py b/tests/unit/appshot/test_shortcut_prewarm.py
index b590282e2d..e8a7eda080 100644
--- a/tests/unit/appshot/test_shortcut_prewarm.py
+++ b/tests/unit/appshot/test_shortcut_prewarm.py
@@ -41,3 +41,35 @@ async def test_prewarm_is_deferred_and_scoped_to_enabled_primary_instance(
assert not entered.is_set() and owner._warm_task is None
await owner.stop()
assert stopped.is_set() == (enabled and owns)
+
+
+async def test_area_press_opens_the_warm_picker_before_the_loop_runs(monkeypatch):
+ from dodaios.appshot import picker_host
+
+ opened: list[str] = []
+ discarded: list[bool] = []
+
+ class Host:
+ def open_now(self):
+ opened.append("open")
+ return True
+
+ async def discard_opened(self):
+ discarded.append(True)
+
+ monkeypatch.setattr(picker_host, "_host", Host())
+ owner = AppshotShortcut(object())
+ fired: list[str] = []
+ monkeypatch.setattr(owner, "_fire_threadsafe", fired.append)
+ owner._press("window")
+ assert opened == [] and fired == ["window"]
+ owner._press("region") # straight from the listener thread
+ assert opened == ["open"] and fired == ["window", "region"]
+
+ async def refused(**_kwargs):
+ return SimpleNamespace(ok=False, reason_code="disabled", message="off")
+
+ monkeypatch.setattr("dodaios.appshot.service.take_appshot", refused)
+ monkeypatch.setattr(owner, "_publish_refusal", lambda _message: asyncio.sleep(0))
+ await owner._take("region")
+ assert discarded == [True] # the refusal closes the picker the press opened