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(launcher): stop calling a healthy window stuck when Windows refuses to raise it

rubenluetke10-beep36b13a4f48c2
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 33abc2dd63..1a8665d91d 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -599,11 +599,18 @@ def _pid_listening_on_port_netstat(port: int) -> int | None:
def _focus_response_means_window_raised(response: Any) -> bool:
- """True only when the running instance actually raised a window.
+ """True only when the running instance has a window on screen for the user.
HTTP 200 is not enough: a headless holder answers 200 with
``focused=False`` (and used to answer ``ok=True``), which made the
desktop launch exit as if it had brought a window forward.
+
+ A window that is shown but that Windows' foreground lock kept from being
+ activated still counts: the instance is healthy and its window is there.
+ Reading that refusal as "no window" asked the user to kill a working app
+ on almost every second launch (2026-10-06). Holders since then say
+ ``shown``; older ones only answered ``reason="foreground_lock"``, which
+ they sent after their GUI thread had already shown the window.
"""
if not (200 <= int(getattr(response, "status_code", 0)) < 300):
return False
@@ -613,6 +620,10 @@ def _focus_response_means_window_raised(response: Any) -> bool:
return True
if not isinstance(payload, dict):
return True
+ if payload.get("shown") is True:
+ return True
+ if payload.get("reason") == "foreground_lock":
+ return True
if "focused" in payload:
return bool(payload.get("focused"))
return bool(payload.get("ok", True))
@@ -693,6 +704,15 @@ def focus_existing_instance_robust() -> bool:
except Exception: # noqa: BLE001
httpx = None # type: ignore[assignment]
+ # The running instance is a background process to Windows: it may raise
+ # its own window only with the foreground right this launch got from the
+ # user's click. Hand it on before asking.
+ from loguru import logger
+
+ from jarvis.ui.foreground_grant import allow_foreground
+
+ allow_foreground(meta.get("pid") if isinstance(meta, dict) else None)
+
if httpx is not None:
for port in ports:
try:
@@ -704,6 +724,12 @@ def focus_existing_instance_robust() -> bool:
except Exception: # noqa: BLE001, S112
# This port is not the running instance; try the next candidate.
continue
+ logger.info(
+ "focus request to the running instance on port {}: HTTP {} {}",
+ port,
+ getattr(r, "status_code", "?"),
+ _focus_response_summary(r),
+ )
if _focus_response_means_window_raised(r):
_bring_window_to_front_by_title(WINDOW_TITLE)
return True
@@ -715,6 +741,18 @@ def focus_existing_instance_robust() -> bool:
return _bring_window_to_front_by_title(WINDOW_TITLE) or focused
+def _focus_response_summary(response: Any) -> str:
+ """The reply's ``focused``/``shown``/``reason`` fields, for the launch log."""
+ try:
+ payload = response.json()
+ except Exception: # noqa: BLE001 — a reply without JSON has nothing to show
+ return "(no JSON body)"
+ if not isinstance(payload, dict):
+ return "(no JSON object)"
+ keys = ("ok", "focused", "shown", "reason")
+ return " ".join(f"{k}={payload[k]}" for k in keys if k in payload) or "(empty)"
+
+
def _focus_response_reason(response: Any) -> str:
"""The ``reason`` a focus reply carries, or ``""`` when it has none."""
try:
@@ -1110,6 +1148,47 @@ def _bring_window_to_front_by_title(title: str) -> bool:
return False
+def _flash_taskbar_button(title: str) -> bool:
+ """Flash the taskbar button of the window titled ``title`` (Windows).
+
+ What Windows itself does when it refuses a background activation: the
+ button flashes until the user brings the window forward. Returns whether
+ a window was found to flash; other platforms have no such lock.
+ """
+ if sys.platform != "win32":
+ return False
+ try:
+ import ctypes
+ from ctypes import wintypes
+
+ class _FlashInfo(ctypes.Structure):
+ _fields_ = [
+ ("cbSize", wintypes.UINT),
+ ("hwnd", wintypes.HWND),
+ ("dwFlags", wintypes.DWORD),
+ ("uCount", wintypes.UINT),
+ ("dwTimeout", wintypes.DWORD),
+ ]
+
+ # Private WinDLL instance, same reason as _bring_window_to_front_by_title.
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+ user32.FindWindowW.restype = wintypes.HWND
+ user32.FlashWindowEx.argtypes = [ctypes.POINTER(_FlashInfo)]
+ user32.FlashWindowEx.restype = wintypes.BOOL
+ hwnd = user32.FindWindowW(None, title)
+ if not hwnd:
+ return False
+ flashw_tray, flashw_timernofg = 0x2, 0xC
+ info = _FlashInfo(ctypes.sizeof(_FlashInfo), hwnd, flashw_tray | flashw_timernofg, 0, 0)
+ user32.FlashWindowEx(ctypes.byref(info))
+ return True
+ except Exception as exc: # noqa: BLE001 - a hint for the user, never a failure
+ from loguru import logger
+
+ logger.debug("could not flash the taskbar button of {!r}: {}", title, exc)
+ return False
+
+
# ---------------------------------------------------------------------------
# Accidental-console suppression (Windows)
# ---------------------------------------------------------------------------
@@ -5221,7 +5300,14 @@ class DesktopApp:
self._restore_overlay_for_visible_window()
if focused:
return {"ok": True, "focused": True}
- return {"ok": False, "focused": False, "reason": "foreground_lock"}
+ # Windows refused the activation (the foreground lock), yet the window
+ # is on screen: a healthy instance, not a stuck one. Say so, and flash
+ # its taskbar button so the user finds it. A window that is still
+ # minimized or missing is not "shown".
+ shown = not window_needs_restore(WINDOW_TITLE)
+ if shown:
+ _flash_taskbar_button(WINDOW_TITLE)
+ return {"ok": shown, "focused": False, "shown": shown, "reason": "foreground_lock"}
# ---- Detached solo windows ----------------------------------------------
diff --git a/jarvis/ui/foreground_grant.py b/jarvis/ui/foreground_grant.py
new file mode 100644
index 0000000000..19406acbe3
--- /dev/null
+++ b/jarvis/ui/foreground_grant.py
@@ -0,0 +1,49 @@
+"""Pass the right to take the foreground on to another process (Windows).
+
+Windows lets a process activate a window only while it holds the foreground
+right. A launch the user just started from the Start menu, the taskbar or a
+desktop icon has it; the process it hands its boot to, and an instance that is
+already running in the background, do not. Without the right, the running
+instance's attempt to raise its own window is refused, and a second launch
+read that refusal as "no window" and offered to kill a healthy app
+(2026-10-06, twelve false "probably stuck" prompts in a day).
+
+``AllowSetForegroundWindow`` hands the right on for the next activation. It
+only works while the caller holds the right itself, so every hop of a launch
+passes it on as early as it can. Other platforms have no such lock: the call
+is a no-op there.
+"""
+
+from __future__ import annotations
+
+import sys
+
+from loguru import logger
+
+#: ``ASFW_ANY`` as an unsigned DWORD — any process may take the foreground next.
+_ASFW_ANY = 0xFFFFFFFF
+
+
+def allow_foreground(pid: int | None = None) -> bool:
+ """Let ``pid`` (or any process when ``None``) take the foreground next.
+
+ Returns whether Windows accepted the grant. ``False`` is normal when this
+ process holds no foreground right of its own; nothing else changes then.
+ """
+ if sys.platform != "win32":
+ return False
+ target = _ASFW_ANY
+ if pid is not None:
+ try:
+ target = int(pid)
+ except (TypeError, ValueError):
+ target = _ASFW_ANY
+ if target <= 0:
+ target = _ASFW_ANY
+ try:
+ import ctypes
+
+ return bool(ctypes.windll.user32.AllowSetForegroundWindow(ctypes.c_uint32(target).value))
+ except Exception as exc: # noqa: BLE001 - a nicety, never a reason to fail a launch
+ logger.debug("could not pass the foreground right on to {}: {}", pid, exc)
+ return False
diff --git a/jarvis/ui/icon_utils.py b/jarvis/ui/icon_utils.py
index 15e0bc380f..aac598defb 100644
--- a/jarvis/ui/icon_utils.py
+++ b/jarvis/ui/icon_utils.py
@@ -712,7 +712,7 @@ def maybe_reexec_through_branded_launcher(argv: list[str]) -> int | None:
# until stdio was given valid handles). The app logs to its own file sink.
detached = getattr(subprocess, "DETACHED_PROCESS", 0x00000008)
no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
- subprocess.Popen( # noqa: S603 — fixed argv, no shell, our own exe
+ child = subprocess.Popen( # noqa: S603 — fixed argv, no shell, our own exe
[str(branded), "-m", _LAUNCHER_MODULE, *argv],
env=env,
close_fds=True,
@@ -721,6 +721,12 @@ def maybe_reexec_through_branded_launcher(argv: list[str]) -> int | None:
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
+ # This process got the foreground right from the user's click; the
+ # child that does the real boot did not. Without it, the child cannot
+ # raise an instance that is already running (2026-10-06).
+ from jarvis.ui.foreground_grant import allow_foreground
+
+ allow_foreground(getattr(child, "pid", None))
logger.debug("Re-exec'd launcher through branded exe: {}", branded)
return 0
except Exception as exc: # noqa: BLE001
diff --git a/tests/unit/ui/test_desktop_show_window.py b/tests/unit/ui/test_desktop_show_window.py
index f98857dfbe..bc3f6afb86 100644
--- a/tests/unit/ui/test_desktop_show_window.py
+++ b/tests/unit/ui/test_desktop_show_window.py
@@ -226,6 +226,56 @@ def test_focus_window_now_leaves_a_quitting_window_alone() -> None:
assert window.calls == []
+def test_a_shown_window_windows_would_not_activate_is_reported_as_shown(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Live 2026-10-06: Windows' foreground lock refused the activation of a
+ healthy, visible window. The reply said only "not focused", and the second
+ launch offered to kill the app as "probably stuck". A window on screen is
+ reported as shown, and its taskbar button flashes."""
+ app = DesktopApp.__new__(DesktopApp)
+ window = _RecordingWindow()
+ app._window = window # noqa: SLF001
+ app._restore_overlay_for_visible_window = lambda: None # type: ignore[method-assign] # noqa: SLF001
+ flashed: list[str] = []
+ monkeypatch.setattr("jarvis.ui.desktop_app._bring_window_to_front_by_title", lambda _t: False)
+ monkeypatch.setattr("jarvis.ui.desktop_app.window_needs_restore", lambda _title: False)
+ monkeypatch.setattr("jarvis.ui.desktop_app.window_restores_maximized", lambda _title: False)
+ monkeypatch.setattr("jarvis.ui.desktop_app._flash_taskbar_button", flashed.append)
+
+ assert app._focus_window_now() == { # noqa: SLF001
+ "ok": True,
+ "focused": False,
+ "shown": True,
+ "reason": "foreground_lock",
+ }
+ assert flashed == [desktop_app_title()]
+
+
+def test_a_window_still_minimized_after_a_refused_activation_is_not_shown(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ app = DesktopApp.__new__(DesktopApp)
+ app._window = _RecordingWindow() # noqa: SLF001
+ app._restore_overlay_for_visible_window = lambda: None # type: ignore[method-assign] # noqa: SLF001
+ flashed: list[str] = []
+ monkeypatch.setattr("jarvis.ui.desktop_app._bring_window_to_front_by_title", lambda _t: False)
+ monkeypatch.setattr("jarvis.ui.desktop_app.window_needs_restore", lambda _title: True)
+ monkeypatch.setattr("jarvis.ui.desktop_app.window_restores_maximized", lambda _title: False)
+ monkeypatch.setattr("jarvis.ui.desktop_app._flash_taskbar_button", flashed.append)
+
+ reply = app._focus_window_now() # noqa: SLF001
+ assert reply["shown"] is False
+ assert reply["ok"] is False
+ assert flashed == []
+
+
+def desktop_app_title() -> str:
+ from jarvis.ui.desktop_app import WINDOW_TITLE
+
+ return WINDOW_TITLE
+
+
class _Reply:
def __init__(self, payload: dict) -> None:
self.status_code = 200
diff --git a/tests/unit/ui/test_focus_existing_instance.py b/tests/unit/ui/test_focus_existing_instance.py
index c15d9b8344..672c4b8d90 100644
--- a/tests/unit/ui/test_focus_existing_instance.py
+++ b/tests/unit/ui/test_focus_existing_instance.py
@@ -37,6 +37,60 @@ def test_focus_response_requires_a_raised_window():
assert not desktop_app._focus_response_means_window_raised(_Resp(status_code=403))
+def test_a_window_the_foreground_lock_kept_back_still_counts():
+ """Live 2026-10-06: a healthy instance answered "shown, but Windows would
+ not activate it", and the launch called it stuck and offered to kill it."""
+ from jarvis.ui import desktop_app
+
+ assert desktop_app._focus_response_means_window_raised(
+ _Resp(payload={"ok": True, "focused": False, "shown": True, "reason": "foreground_lock"})
+ )
+ # Holders from before the fix sent only the reason, after showing the window.
+ assert desktop_app._focus_response_means_window_raised(
+ _Resp(payload={"ok": False, "focused": False, "reason": "foreground_lock"})
+ )
+ assert not desktop_app._focus_response_means_window_raised(
+ _Resp(payload={"ok": False, "focused": False, "shown": False, "reason": "no_window"})
+ )
+
+
+def test_the_launch_hands_its_foreground_right_to_the_running_instance(monkeypatch):
+ from types import ModuleType
+
+ from jarvis.ui import desktop_app
+
+ order: list[str] = []
+ granted: list[object] = []
+
+ def _grant(pid=None):
+ order.append("grant")
+ granted.append(pid)
+ return True
+
+ def _post(url, headers=None, timeout=1.0): # noqa: ARG001
+ order.append("post")
+ return _Resp(payload={"ok": True, "focused": True})
+
+ monkeypatch.setattr("jarvis.ui.foreground_grant.allow_foreground", _grant)
+ monkeypatch.setattr(desktop_app, "_read_meta", lambda: {"pid": 4242, "port": 47821})
+ monkeypatch.setattr(desktop_app, "_focus_request_headers", lambda port: {})
+ monkeypatch.setattr(desktop_app, "_bring_window_to_front_by_title", lambda _t: True)
+ fake = ModuleType("httpx")
+ fake.post = _post # type: ignore[attr-defined]
+ monkeypatch.setitem(__import__("sys").modules, "httpx", fake)
+
+ assert desktop_app.focus_existing_instance_robust() is True
+ assert granted == [4242]
+ assert order[:2] == ["grant", "post"]
+
+
+def test_allow_foreground_is_a_quiet_no_op_off_windows(monkeypatch):
+ from jarvis.ui import foreground_grant
+
+ monkeypatch.setattr(foreground_grant.sys, "platform", "linux")
+ assert foreground_grant.allow_foreground(1234) is False
+
+
def test_focus_headers_send_the_control_key_when_one_exists(monkeypatch):
from jarvis.ui import desktop_app