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(desktop): reopening Jarvis right after closing it no longer stalls for minutes

rubenluetke10-beepa1fef169a9d7
diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.py
index 781a078c93..8448eeb594 100644
--- a/jarvis/ui/desktop_app.py
+++ b/jarvis/ui/desktop_app.py
@@ -614,10 +614,25 @@ def focus_existing_instance_robust() -> bool:
if _focus_response_means_window_raised(r):
_bring_window_to_front_by_title(WINDOW_TITLE)
return True
+ if _focus_response_reason(r) == "quitting":
+ # Its window is being torn down: raising it would only wait
+ # on a GUI thread that is busy destroying it.
+ return False
return _bring_window_to_front_by_title(WINDOW_TITLE) or focused
+def _focus_response_reason(response: Any) -> str:
+ """The ``reason`` a focus reply carries, or ``""`` when it has none."""
+ try:
+ payload = response.json()
+ except Exception: # noqa: BLE001 — a reply without JSON has no reason
+ return ""
+ if not isinstance(payload, dict):
+ return ""
+ return str(payload.get("reason") or "")
+
+
def _force_foreground_hwnd(hwnd: int, user32: Any, kernel32: Any) -> bool:
"""Raise one HWND through Windows' foreground-lock restriction.
@@ -671,6 +686,45 @@ def _force_foreground_hwnd(hwnd: int, user32: Any, kernel32: Any) -> bool:
user32.AttachThreadInput(current_thread, target_thread, False)
+#: How long a window may take to answer a no-op message before the focus path
+#: treats it as hung. Matches the threshold Windows itself uses for "Not
+#: responding", so a window that is merely busy for a moment is still raised.
+_WINDOW_ANSWER_TIMEOUT_MS = 5000
+
+
+def _window_answers(hwnd: int, user32: Any, *, timeout_ms: int = _WINDOW_ANSWER_TIMEOUT_MS) -> bool:
+ """True when the thread that owns ``hwnd`` services a message in time.
+
+ ``ShowWindow``, ``MoveWindow``, ``SetWindowPos`` and ``AttachThreadInput``
+ on another thread's window are synchronous: they wait, without a timeout,
+ until that thread pumps its queue. A window whose GUI thread is stuck — a
+ quit tearing WebView2 down on a machine that is paging — held a second
+ launch inside those calls for 92 s on 2026-09-30 while the user saw
+ nothing. ``SendMessageTimeoutW(WM_NULL)`` asks the same question with a
+ deadline, so a hung window costs seconds, not minutes.
+ """
+ from ctypes import byref, c_size_t
+
+ try:
+ if user32.IsHungAppWindow(hwnd):
+ return False
+ answer = c_size_t(0)
+ smto_abortifhung, smto_erroronexit, wm_null = 0x0002, 0x0020, 0x0000
+ return bool(
+ user32.SendMessageTimeoutW(
+ hwnd,
+ wm_null,
+ 0,
+ 0,
+ smto_abortifhung | smto_erroronexit,
+ int(timeout_ms),
+ byref(answer),
+ )
+ )
+ except Exception: # noqa: BLE001 — a probe that cannot run is no proof of a hang
+ return True
+
+
def _bring_window_to_front_by_title(title: str) -> bool:
"""Win32 fallback for hidden/minimized pywebview windows.
@@ -678,6 +732,9 @@ def _bring_window_to_front_by_title(title: str) -> bool:
when the window was previously hidden via a tray close — Edge/WebView2
keeps the HWND minimized. ``ShowWindow(SW_RESTORE) + SetForegroundWindow``
via the Win32 API path is the only reliable recovery.
+
+ A window that does not answer (:func:`_window_answers`) is reported as not
+ raised instead of touched: every call below would block on it.
"""
if sys.platform != "win32":
return False
@@ -691,6 +748,18 @@ def _bring_window_to_front_by_title(title: str) -> bool:
# calls, which rely on it staying argtypes-free.
user32 = ctypes.WinDLL("user32", use_last_error=True)
user32.FindWindowW.restype = wintypes.HWND
+ user32.IsHungAppWindow.argtypes = [wintypes.HWND]
+ user32.IsHungAppWindow.restype = wintypes.BOOL
+ user32.SendMessageTimeoutW.argtypes = [
+ wintypes.HWND,
+ wintypes.UINT,
+ wintypes.WPARAM,
+ wintypes.LPARAM,
+ wintypes.UINT,
+ wintypes.UINT,
+ ctypes.POINTER(ctypes.c_size_t),
+ ]
+ user32.SendMessageTimeoutW.restype = wintypes.LPARAM
user32.GetForegroundWindow.restype = wintypes.HWND
user32.GetWindowRect.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.RECT)]
user32.IsIconic.argtypes = [wintypes.HWND]
@@ -729,6 +798,14 @@ def _bring_window_to_front_by_title(title: str) -> bool:
hwnd = user32.FindWindowW(None, title)
if not hwnd:
return False
+ if not _window_answers(hwnd, user32):
+ from loguru import logger
+
+ logger.warning(
+ "Window {!r} is not responding — left alone instead of waiting on it.",
+ title,
+ )
+ return False
was_minimized = bool(user32.IsIconic(hwnd))
rect = wintypes.RECT()
user32.GetWindowRect(hwnd, ctypes.byref(rect))
@@ -4635,6 +4712,10 @@ class DesktopApp:
directly. Split out of the ``/api/window/focus`` route so tests can pin
the off-loop contract without a running server.
"""
+ if getattr(self, "_user_requested_quit", False) or getattr(self, "_shutdown_done", False):
+ # A second launch during a quit must not "raise" the window that is
+ # being destroyed and then exit as if it had succeeded (2026-09-30).
+ return {"ok": False, "focused": False, "reason": "quitting"}
if self._window is None:
if getattr(getattr(self, "_background", None), "keeper", None) is not None:
self._ensure_main_window()
@@ -5584,6 +5665,9 @@ class DesktopApp:
"runs in private mode and the interface forgets its wallpaper "
"and layout on every restart."
)
+ # Read by ``_begin_quit_from_close``: a force-exit backstop armed at the
+ # X only makes sense while a real window loop is tearing down.
+ self._webview_running = True
try:
webview.start(
func=self._inject_token,
@@ -5598,6 +5682,8 @@ class DesktopApp:
# Not swallowed: the exception is handed to the degrade path, which
# reports it and opens the UI in the default browser instead.
return self._degrade_to_browser_ui(exc)
+ finally:
+ self._webview_running = False
# webview.start returns once the window is destroyed. A real quit (the
# X, tray "Quit", or a restart) has set ``_user_requested_quit``; in that
# case tear every surface down AND guarantee the process dies, so nothing
@@ -5973,6 +6059,7 @@ class DesktopApp:
self._main_window_closing = True
if not self._detached_windows and not self._background_keeps_running():
self._user_requested_quit = True
+ self._begin_quit_from_close()
if getattr(getattr(self, "_background", None), "keeper", None) is not None:
# The closing event waits for us; native destruction must run
# after this callback releases the GUI thread.
@@ -5982,6 +6069,61 @@ class DesktopApp:
).start()
return True
+ #: Backstop for a quit that starts at the window's X. Longer than the 20 s
+ #: one ``run_window_only`` arms once ``webview.start()`` returns, because
+ #: this one also covers the window teardown in front of ``shutdown()``.
+ _CLOSE_QUIT_BACKSTOP_S = 45.0
+
+ def _begin_quit_from_close(self) -> None:
+ """Make a close-to-quit visible at once and bounded in time.
+
+ ``shutdown()`` runs only after pywebview has destroyed the window and
+ ``webview.start()`` has returned. On 2026-09-30 that teardown took about
+ 90 s on a machine that was paging: the window was gone, the Jarvis bar
+ stayed on screen and kept listening, and a new launch found an instance
+ that neither answered nor exited. The bar now leaves with the window,
+ and while a real window loop runs, the force-exit backstop starts
+ counting from the click instead of from the end of the teardown.
+ """
+ from loguru import logger
+
+ if getattr(self, "_quit_requested_at", None) is not None:
+ return
+ self._quit_requested_at = time.monotonic()
+ backstop = getattr(self, "_webview_running", False)
+ logger.info(
+ "Main window closed — quitting{}.",
+ f" (force-exit backstop in {self._CLOSE_QUIT_BACKSTOP_S:.0f} s)" if backstop else "",
+ )
+ if getattr(self, "_orb", None) is not None:
+ # Off the GUI thread: the closing callback holds it, and the
+ # window's destruction waits for this callback to return.
+ self._overlay_close_thread = threading.Thread(
+ target=self._stop_overlay, name="jarvis-overlay-close", daemon=True
+ )
+ self._overlay_close_thread.start()
+ if backstop:
+ self._arm_force_exit(after_s=self._CLOSE_QUIT_BACKSTOP_S)
+
+ def _stop_overlay(self) -> None:
+ """Take the on-screen bar or mascot down. Idempotent, never raises."""
+ orb = getattr(self, "_orb", None)
+ if orb is None:
+ return
+ try:
+ # Prefer stop() when the surface has it (jarvis bar: unsubscribes
+ # its level_tap sink + destroys the window). The mascot orb has no
+ # stop() → fall back to hide().
+ stop = getattr(orb, "stop", None)
+ if callable(stop):
+ stop()
+ else:
+ orb.hide()
+ except Exception: # noqa: BLE001, S110
+ # Teardown best-effort: the process is exiting and the OS
+ # reclaims the window regardless.
+ pass
+
def _suppress_overlay_for_hidden_window(self) -> None:
"""Take a NON-persistent overlay bar off the screen on minimise — but
NEVER touch a bar the user set to "show at all times".
@@ -6094,24 +6236,22 @@ class DesktopApp:
probe_client.close()
self._health_http = None
+ quit_requested_at = getattr(self, "_quit_requested_at", None)
+ if quit_requested_at is not None:
+ from loguru import logger as _logger
+
+ # The gap between the click and this line is the window teardown;
+ # it was invisible until 2026-09-30, when it took ~90 s.
+ _logger.info(
+ "Shutdown started {:.1f} s after the window was closed.",
+ time.monotonic() - quit_requested_at,
+ )
+
# Hide the orb overlay first — the event path (pipeline → supervisor
# → bus → OrbBridge) doesn't reliably reach the bridge anymore during a
# hard loop stop. A direct hide() guarantees the desktop icon
# top-right disappears before the process terminates.
- if self._orb is not None:
- try:
- # Prefer stop() when the surface has it (jarvis bar:
- # unsubscribes its level_tap sink + destroys the window). The
- # mascot orb has no stop() → fall back to hide().
- stop = getattr(self._orb, "stop", None)
- if callable(stop):
- stop()
- else:
- self._orb.hide()
- except Exception: # noqa: BLE001, S110
- # Teardown best-effort: the process is exiting and the OS
- # reclaims the window regardless.
- pass
+ self._stop_overlay()
# Restore other apps' audio (in case a session was muting music at quit).
ducker = getattr(self, "_ducker", None)
diff --git a/jarvis/ui/native_dialog.py b/jarvis/ui/native_dialog.py
index 1888d73caf..ad89e2c529 100644
--- a/jarvis/ui/native_dialog.py
+++ b/jarvis/ui/native_dialog.py
@@ -22,26 +22,86 @@ from __future__ import annotations
import contextlib
import os
import sys
+import threading
from collections.abc import Callable
-def _run_helper(cmd: list[str]) -> tuple[bool, int]:
- """Run a dialog helper; ``(ran, returncode)``. ``ran=False`` → not installed."""
+def _run_helper(
+ cmd: list[str], *, dismiss: threading.Event | None = None
+) -> tuple[bool, int]:
+ """Run a dialog helper; ``(ran, returncode)``. ``ran=False`` → not installed.
+
+ With ``dismiss``, setting that event closes the helper's dialog and the
+ call returns a non-zero code, which every caller reads as "no".
+ """
import subprocess
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
+ if dismiss is None:
+ try:
+ completed = subprocess.run( # noqa: S603 — fixed argv, no shell
+ cmd,
+ check=False,
+ encoding="utf-8",
+ errors="replace",
+ creationflags=NO_WINDOW_CREATIONFLAGS,
+ )
+ except (OSError, ValueError):
+ return False, -1
+ return True, int(getattr(completed, "returncode", 0) or 0)
try:
- completed = subprocess.run( # noqa: S603 — fixed argv, no shell
- cmd,
- check=False,
- encoding="utf-8",
- errors="replace",
- creationflags=NO_WINDOW_CREATIONFLAGS,
+ proc = subprocess.Popen( # noqa: S603 — fixed argv, no shell
+ cmd, creationflags=NO_WINDOW_CREATIONFLAGS
)
except (OSError, ValueError):
return False, -1
- return True, int(getattr(completed, "returncode", 0) or 0)
+ while proc.poll() is None:
+ if dismiss.wait(0.2):
+ proc.terminate()
+ try:
+ proc.wait(timeout=2.0)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ return True, -1
+ return True, int(proc.returncode or 0)
+
+
+def _dismiss_message_box_when_set(
+ thread_id: int, dismiss: threading.Event, done: threading.Event
+) -> None:
+ """Answer "No" on this thread's message box once ``dismiss`` is set.
+
+ ``MessageBoxW`` blocks the thread that shows it, so the close has to come
+ from outside: the box is a ``#32770`` dialog owned by that thread, and a
+ posted ``WM_COMMAND(IDNO)`` ends it exactly like the button would. The
+ post repeats until the box is gone, which also covers a dismissal that
+ arrives before the box has been created.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ # A private WinDLL instance: argtypes on the shared ctypes.windll.user32
+ # would leak into every other caller in the process.
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+ enum_proc = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
+ user32.EnumThreadWindows.argtypes = [wintypes.DWORD, enum_proc, wintypes.LPARAM]
+ user32.GetClassNameW.argtypes = [wintypes.HWND, wintypes.LPWSTR, ctypes.c_int]
+ user32.PostMessageW.argtypes = [wintypes.HWND, wintypes.UINT, wintypes.WPARAM, wintypes.LPARAM]
+ wm_command, idno = 0x0111, 7
+
+ def _answer_no(hwnd, _lparam):
+ name = ctypes.create_unicode_buffer(32)
+ user32.GetClassNameW(hwnd, name, 32)
+ if name.value == "#32770":
+ user32.PostMessageW(hwnd, wm_command, idno, 0)
+ return True
+
+ callback = enum_proc(_answer_no)
+ while not done.is_set():
+ if dismiss.wait(0.2):
+ user32.EnumThreadWindows(thread_id, callback, 0)
+ done.wait(0.2)
def _applescript_literal(text: str) -> str:
@@ -88,7 +148,8 @@ def ask_yes_no(
title: str,
message: str,
*,
- _run: Callable[[list[str]], tuple[bool, int]] = _run_helper,
+ dismiss: threading.Event | None = None,
+ _run: Callable[..., tuple[bool, int]] = _run_helper,
) -> bool:
"""Modal Yes/No question; ``True`` only on an explicit Yes.
@@ -96,20 +157,40 @@ def ask_yes_no(
error — is ``False``, so callers can only ever take the destructive branch
on a real click. ``_run`` is injectable for tests (the helper is otherwise
a real process that blocks on a real click).
+
+ ``dismiss`` lets the caller withdraw the question: once that event is set
+ the box closes and the answer is ``False``. The caller tells a withdrawal
+ from a "No" by looking at its own event.
"""
+ if dismiss is not None and dismiss.is_set():
+ return False
if sys.platform == "win32":
+ done = threading.Event()
try:
import ctypes
+ if dismiss is not None:
+ threading.Thread(
+ target=_dismiss_message_box_when_set,
+ args=(int(ctypes.windll.kernel32.GetCurrentThreadId()), dismiss, done),
+ name="jarvis-dialog-dismiss",
+ daemon=True,
+ ).start()
mb_yesno, mb_iconquestion, mb_defbutton2, idyes = 0x4, 0x20, 0x100, 6
result = ctypes.windll.user32.MessageBoxW(
None, message, title, mb_yesno | mb_iconquestion | mb_defbutton2
)
- return int(result) == idyes
+ return int(result) == idyes and not (dismiss is not None and dismiss.is_set())
except Exception: # noqa: BLE001 — no box → no consent
return False
+ finally:
+ done.set()
+
+ def _ask(cmd: list[str]) -> tuple[bool, int]:
+ return _run(cmd) if dismiss is None else _run(cmd, dismiss=dismiss)
+
if sys.platform == "darwin":
- ran, code = _run(
+ ran, code = _ask(
[
"osascript",
"-e",
@@ -131,7 +212,7 @@ def ask_yes_no(
["zenity", "--question", f"--title={title}", f"--text={message}", "--default-cancel"],
["kdialog", "--title", title, "--warningyesno", message],
):
- ran, code = _run(cmd)
+ ran, code = _ask(cmd)
if ran:
return code == 0 # both helpers exit 0 for Yes, 1 for No
return False
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index d33d01eb09..1c238e3ca1 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -19,6 +19,7 @@ import os
import re
import signal
import sys
+import threading
import time
from jarvis.core.branding import CONFIG_FILE_NAME
@@ -1135,6 +1136,45 @@ def _health_answers(port: int, *, timeout: float = 2.0) -> bool:
return response.status_code == 200
+def _holder_alive(pid: int) -> bool:
+ """False only when ``pid`` has certainly exited; an unknown answer is True.
+
+ Feeds the watcher that closes the "already running" question once the old
+ instance is gone, so a probe that cannot see the process must never claim
+ it left.
+ """
+ try:
+ import psutil
+ except Exception: # noqa: BLE001 — cannot tell → keep asking, never assume
+ return True
+ try:
+ return psutil.Process(int(pid)).status() != psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ return False
+ except Exception: # noqa: BLE001 — AccessDenied and friends: it exists
+ return True
+
+
+def _take_lock_after_holder_exit(recheck, sleep, *, attempts: int = 10, delay: float = 0.5):
+ """Take the lock a holder left behind by exiting; ``None`` when it stays held.
+
+ The lock can outlive the process by a moment (the OS releases the handle
+ and the port on its own schedule), so a few short retries separate that
+ from a genuinely taken lock.
+ """
+ for attempt in range(attempts):
+ handled, lock = recheck()
+ if handled:
+ return lock
+ if attempt < attempts - 1:
+ sleep(delay)
+ _report_startup_failure(
+ f"{APP_DISPLAY_NAME} closed, but its start lock is still held. "
+ "Start the app again in a few seconds."
+ )
+ return None
+
+
def _recover_from_already_running(
error: Exception,
*,
@@ -1149,6 +1189,8 @@ def _recover_from_already_running(
booting_grace: float = 20.0,
discover_pid=None,
health=None,
+ holder_alive=None,
+ watch_interval: float = 1.0,
):
"""The lock is held. Bring the holder forward — or, with consent, evict it.
@@ -1171,6 +1213,10 @@ def _recover_from_already_running(
A holder that is only a few seconds old and has no window yet (or has a
window that has not answered health yet) is not stuck — it is still
booting. Wait out the remaining boot grace before asking.
+
+ A holder that exits while the question is open — typically one that was
+ still quitting — closes the box by itself and this launch starts normally,
+ without a kill and without waiting for a click.
"""
from loguru import logger
@@ -1339,16 +1385,46 @@ def _recover_from_already_running(
"window that could be brought to the front. It is probably stuck.\n\n"
"Stop that process and start fresh?"
)
+ # The question can stay open for minutes. A holder that finishes quitting
+ # meanwhile needs no consent: close the box and start normally. On
+ # 2026-09-30 the box sat on screen for almost five minutes after the old
+ # instance had exited, and the app only started when the user clicked Yes.
+ alive = holder_alive or _holder_alive
+ holder_gone = threading.Event()
+ stop_watch = threading.Event()
+
+ def _watch_holder() -> None:
+ while not stop_watch.wait(watch_interval):
+ try:
+ still_there = bool(alive(pid))
+ except Exception: # noqa: BLE001 — a failed probe proves nothing
+ still_there = True
+ if not still_there:
+ holder_gone.set()
+ return
+
+ threading.Thread(
+ target=_watch_holder, name="jarvis-launcher-holder-watch", daemon=True
+ ).start()
consented = False
try:
consented = bool(
ask(
f"{APP_DISPLAY_NAME} is already running",
stuck_detail,
+ dismiss=holder_gone,
)
)
except Exception as exc: # noqa: BLE001
logger.warning("launcher: could not ask about the stuck instance: {}", exc)
+ finally:
+ stop_watch.set()
+ if holder_gone.is_set():
+ logger.info(
+ "launcher: holder pid={} exited while the question was open — starting normally",
+ pid,
+ )
+ return _take_lock_after_holder_exit(_recheck_lock, sleep)
logger.info(
"launcher: stuck holder pid={} — user {}",
pid,
diff --git a/tests/unit/ui/test_desktop_focus.py b/tests/unit/ui/test_desktop_focus.py
index 8a451e9af2..9a5ae0d28b 100644
--- a/tests/unit/ui/test_desktop_focus.py
+++ b/tests/unit/ui/test_desktop_focus.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from jarvis.ui.desktop_app import _force_foreground_hwnd
+from jarvis.ui.desktop_app import _force_foreground_hwnd, _window_answers
class _Kernel32:
@@ -50,6 +50,47 @@ class _User32:
return True
+class _ProbeUser32:
+ def __init__(self, *, hung: bool = False, answers: bool = True, raises: bool = False):
+ self.hung = hung
+ self.answers = answers
+ self.raises = raises
+ self.sent: list[tuple[int, int, int]] = []
+
+ def IsHungAppWindow(self, _hwnd: int) -> bool:
+ if self.raises:
+ raise OSError("probe unavailable")
+ return self.hung
+
+ def SendMessageTimeoutW(self, hwnd, msg, _wparam, _lparam, flags, timeout, _result) -> int:
+ self.sent.append((hwnd, msg, timeout))
+ return 1 if self.answers else 0
+
+
+def test_a_window_windows_reports_as_hung_gets_no_message() -> None:
+ user32 = _ProbeUser32(hung=True)
+
+ assert _window_answers(200, user32) is False
+ assert user32.sent == []
+
+
+def test_a_window_that_misses_the_deadline_is_not_touched() -> None:
+ """2026-09-30: a closing window held a second launch for 92 s inside the
+ synchronous ShowWindow calls. The probe has a deadline; those calls do not."""
+ user32 = _ProbeUser32(answers=False)
+
+ assert _window_answers(200, user32, timeout_ms=250) is False
+ assert user32.sent == [(200, 0, 250)]
+
+
+def test_a_responsive_window_is_raised_as_before() -> None:
+ assert _window_answers(200, _ProbeUser32()) is True
+
+
+def test_a_probe_that_cannot_run_does_not_claim_a_hang() -> None:
+ assert _window_answers(200, _ProbeUser32(raises=True)) is True
+
+
def test_foreground_lock_recovery_attaches_and_always_detaches() -> None:
user32 = _User32()
diff --git a/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py b/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py
index 4bbd6afbde..85748aa11a 100644
--- a/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py
+++ b/tests/unit/ui/test_desktop_minimize_to_tray_overlay.py
@@ -161,8 +161,10 @@ def test_window_closing_quits_and_does_not_minimise() -> None:
assert result is True # destroy allowed → full shutdown, not minimise
assert app._user_requested_quit is True
assert app._window.hidden is False # NOT hidden — the window is destroyed
- # The bar is torn down in shutdown(), never on the closing callback itself.
- assert bar.hidden is False
+ # The bar leaves with the window instead of waiting for shutdown(): on
+ # 2026-09-30 the teardown in between took ~90 s and the bar stayed up.
+ app._overlay_close_thread.join(timeout=5.0)
+ assert bar.hidden is True
def test_window_closing_quits_regardless_of_bar_persistence() -> None:
@@ -193,4 +195,33 @@ def test_window_closing_allows_genuine_quit() -> None:
assert result is True # allow the destroy → shutdown() handles teardown
assert app._window.hidden is False # not minimised
- assert bar.hidden is False # suppress NOT run on a real quit
+ assert bar._persistent is True # the minimise-suppress path did NOT run
+
+
+def test_close_to_quit_arms_the_backstop_only_under_a_real_window_loop() -> None:
+ """The force-exit timer counts from the click while webview.start() runs —
+ and never inside a test or a boot that has no window loop to tear down."""
+ armed: list[float] = []
+
+ for running in (False, True):
+ app = _app(persistent=True, orb=None, bridge=None)
+ app._window = FakeWindow()
+ app._user_requested_quit = False
+ app._webview_running = running
+ app._arm_force_exit = lambda *, after_s, _armed=armed: _armed.append(after_s)
+
+ app._on_window_closing()
+ app._on_window_closing() # a second closing event changes nothing
+
+ assert armed == [DesktopApp._CLOSE_QUIT_BACKSTOP_S]
+
+
+def test_shutdown_stops_an_overlay_the_close_already_stopped() -> None:
+ """Stopping twice is harmless: the close and shutdown() both call it."""
+ bar = FakeBar()
+ app = _app(persistent=True, orb=bar, bridge=None)
+
+ app._stop_overlay()
+ app._stop_overlay()
+
+ assert bar.hidden is True
diff --git a/tests/unit/ui/test_desktop_show_window.py b/tests/unit/ui/test_desktop_show_window.py
index 2ef16388f1..1964be4d01 100644
--- a/tests/unit/ui/test_desktop_show_window.py
+++ b/tests/unit/ui/test_desktop_show_window.py
@@ -136,3 +136,56 @@ def test_focus_window_now_without_window_reports_no_window() -> None:
app._window = None # noqa: SLF001
assert app._focus_window_now() == {"ok": False, "reason": "no_window"} # noqa: SLF001
+
+
+def test_focus_window_now_leaves_a_quitting_window_alone() -> None:
+ """A second launch during a quit must not raise the window being destroyed.
+
+ Live 2026-09-30: the focus reply said "raised", the launch exited as if it
+ had worked, and the user was left with no window at all.
+ """
+ app = DesktopApp.__new__(DesktopApp)
+ window = _RecordingWindow()
+ app._window = window # noqa: SLF001
+ app._user_requested_quit = True # noqa: SLF001
+
+ assert app._focus_window_now() == { # noqa: SLF001
+ "ok": False,
+ "focused": False,
+ "reason": "quitting",
+ }
+ assert window.calls == []
+
+
+class _Reply:
+ def __init__(self, payload: dict) -> None:
+ self.status_code = 200
+ self._payload = payload
+
+ def json(self) -> dict:
+ return self._payload
+
+
+def test_launcher_focus_does_not_fall_back_to_a_quitting_window(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A holder that reports "quitting" is not raised by title either."""
+ import sys
+ from types import ModuleType
+
+ from jarvis.ui import desktop_app
+
+ fake_httpx = ModuleType("httpx")
+ fake_httpx.post = lambda *_a, **_k: _Reply( # type: ignore[attr-defined]
+ {"ok": False, "focused": False, "reason": "quitting"}
+ )
+ monkeypatch.setitem(sys.modules, "httpx", fake_httpx)
+ monkeypatch.setattr(desktop_app, "_read_meta", lambda: {"port": 47821})
+ monkeypatch.setattr(desktop_app, "_focus_request_headers", lambda _port: {})
+ raised: list[str] = []
+ monkeypatch.setattr(
+ desktop_app, "_bring_window_to_front_by_title", lambda title: raised.append(title) or True
+ )
+
+ assert desktop_app.focus_existing_instance_robust() is False
+ assert raised == []
diff --git a/tests/unit/ui/test_launcher_boot_trace.py b/tests/unit/ui/test_launcher_boot_trace.py
index 37179e1f81..068f3fdd00 100644
--- a/tests/unit/ui/test_launcher_boot_trace.py
+++ b/tests/unit/ui/test_launcher_boot_trace.py
@@ -35,6 +35,15 @@ def test_early_log_path_honours_the_env_override(monkeypatch, tmp_path: Path):
assert desktop_log_path() == tmp_path / "jarvis_desktop.log"
+_REAL_HOLDER_ALIVE = launcher._holder_alive
+
+
[email protected](autouse=True)
+def _holder_stays_alive(monkeypatch):
+ """The recovery tests model a holder that lives; pid 4242 may not exist here."""
+ monkeypatch.setattr(launcher, "_holder_alive", lambda _pid: True)
+
+
class _Lock:
pass
@@ -56,7 +65,7 @@ class _Calls:
def read_meta(self):
return self.meta
- def ask(self, title, message):
+ def ask(self, title, message, dismiss=None):
self.asked.append((title, message))
return self.consent
@@ -435,6 +444,86 @@ def test_replacement_without_window_has_a_bounded_wait_and_is_not_killed(monkeyp
assert "stopped process" not in calls.reported[0]
+def test_a_holder_that_exits_during_the_question_closes_it_and_starts_normally():
+ """Live 2026-09-30: the question stayed up ~5 min after the old instance had
+ quit, and the app only started when the user clicked Yes. The box now
+ withdraws itself, and nothing is killed."""
+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=False)
+ exited = {"now": False}
+ withdrawn: list[bool] = []
+
+ def ask(title, message, dismiss=None):
+ calls.asked.append((title, message))
+ exited["now"] = True # the old instance finishes quitting meanwhile
+ withdrawn.append(dismiss.wait(5.0))
+ return False # a withdrawn box answers like "No"
+
+ def acquire():
+ calls.acquired += 1
+ if not exited["now"]:
+ raise SingleInstanceError("Jarvis is already running (pid=4242).")
+ return _Lock()
+
+ lock = launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=ask,
+ terminate=calls.terminate,
+ acquire=acquire,
+ process_age=lambda _pid: None,
+ discover_pid=_meta_pid,
+ holder_alive=lambda _pid: not exited["now"],
+ watch_interval=0.01,
+ )
+
+ assert isinstance(lock, _Lock)
+ assert withdrawn == [True]
+ assert len(calls.asked) == 1
+ assert calls.terminated == []
+
+
+def test_a_holder_that_exits_but_keeps_the_lock_is_reported(monkeypatch):
+ calls = _Calls(focused=False, meta={"pid": 4242}, consent=False)
+ monkeypatch.setattr(launcher, "_report_startup_failure", calls.reported.append)
+ slept: list[float] = []
+
+ def ask(title, message, dismiss=None):
+ dismiss.wait(5.0)
+ return False
+
+ assert (
+ launcher._recover_from_already_running(
+ RuntimeError("Jarvis is already running (pid=4242)."),
+ focus=calls.focus,
+ read_meta=calls.read_meta,
+ ask=ask,
+ terminate=calls.terminate,
+ acquire=calls.acquire, # stays held: nothing was terminated
+ process_age=lambda _pid: None,
+ discover_pid=_meta_pid,
+ sleep=slept.append,
+ holder_alive=lambda _pid: False,
+ watch_interval=0.01,
+ )
+ is None
+ )
+ assert calls.terminated == []
+ assert slept and all(delay == 0.5 for delay in slept)
+ assert "start lock is still held" in calls.reported[0]
+
+
+def test_holder_alive_is_false_only_for_a_process_that_is_gone():
+ import os
+ import subprocess
+ import sys
+
+ assert _REAL_HOLDER_ALIVE(os.getpid()) is True
+ child = subprocess.Popen([sys.executable, "-c", "pass"]) # noqa: S603 — our own interpreter
+ child.wait(timeout=30)
+ assert _REAL_HOLDER_ALIVE(child.pid) is False
+
+
def test_lock_io_failure_is_reported_without_terminating_holder(monkeypatch):
calls = _Calls(focused=False, meta={"pid": 4242}, consent=True)
monkeypatch.setattr(launcher, "_report_startup_failure", calls.reported.append)
diff --git a/tests/unit/ui/test_native_dialog_and_eviction.py b/tests/unit/ui/test_native_dialog_and_eviction.py
index 0dd85049e4..4bdd4b2ee9 100644
--- a/tests/unit/ui/test_native_dialog_and_eviction.py
+++ b/tests/unit/ui/test_native_dialog_and_eviction.py
@@ -65,6 +65,52 @@ def test_macos_yes_is_a_normal_osascript_return(monkeypatch):
assert native_dialog.ask_yes_no("t", "m", _run=lambda cmd: (True, 1)) is False
+def test_a_withdrawn_question_is_no_without_showing_anything(monkeypatch):
+ import threading
+
+ dismiss = threading.Event()
+ dismiss.set()
+
+ def _run(cmd, **kwargs):
+ raise AssertionError("a withdrawn question must not open a dialog")
+
+ assert native_dialog.ask_yes_no("t", "m", dismiss=dismiss, _run=_run) is False
+
+
[email protected](sys.platform == "win32", reason="Win32 branch opens a real box")
+def test_the_dismiss_event_reaches_the_helper(monkeypatch):
+ import threading
+
+ monkeypatch.setenv("DISPLAY", ":0")
+ monkeypatch.setattr(sys, "platform", "linux")
+ dismiss = threading.Event()
+ seen: list[object] = []
+
+ def _run(cmd, *, dismiss=None):
+ seen.append(dismiss)
+ return (True, -1) # the helper was closed from outside
+
+ assert native_dialog.ask_yes_no("t", "m", dismiss=dismiss, _run=_run) is False
+ assert seen == [dismiss]
+
+
+def test_a_dismissed_helper_process_is_closed_promptly():
+ """The real runner ends a helper that is still waiting for a click."""
+ import threading
+ import time
+
+ dismiss = threading.Event()
+ threading.Timer(0.3, dismiss.set).start()
+ started = time.monotonic()
+
+ ran, code = native_dialog._run_helper(
+ [sys.executable, "-c", "import time; time.sleep(60)"], dismiss=dismiss
+ )
+
+ assert ran is True
+ assert code != 0 # read as "no" by every caller
+ assert time.monotonic() - started < 10.0
+
def test_eviction_falls_back_to_the_process_tree_kill(monkeypatch):
"""psutil's kill did not take → the tree kill runs → liveness is re-checked."""
from jarvis.ui import desktop_app