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): a start that cannot happen now says so, even under pythonw

Harald234b8379d6e4
diff --git a/jarvis/core/process_utils.py b/jarvis/core/process_utils.py
index 2568f75ad9..df6e9453dc 100644
--- a/jarvis/core/process_utils.py
+++ b/jarvis/core/process_utils.py
@@ -58,6 +58,9 @@ def ensure_standard_streams() -> None:
for name in ("stdout", "stderr"):
stream = getattr(sys, name, None)
if stream is None:
+ # Recorded in _NULL_STANDARD_STREAMS so callers can ask whether what
+ # they just printed actually reached a human — see
+ # ``standard_error_is_visible``.
replacement = open( # noqa: SIM115 - intentionally process-lifetime
os.devnull,
"w",
@@ -76,6 +79,24 @@ def ensure_standard_streams() -> None:
pass
+def standard_error_is_visible() -> bool:
+ """Can a human read what we write to ``sys.stderr``?
+
+ False in a windowed process — ``pythonw.exe``, a GUI PyInstaller build — where
+ ``ensure_standard_streams`` had to substitute the null device, so everything
+ printed there is discarded. Code that reports a fatal startup problem uses
+ this to decide whether stderr was enough or whether the message needs a
+ second, visible surface (a dialog). Getting that decision from the stream we
+ actually wrote to beats guessing from a console handle: a redirected build
+ log, a pipe and an IDE console are all legitimately readable, and none of
+ them own a console window.
+ """
+ stream = getattr(sys, "stderr", None)
+ if stream is None or getattr(stream, "closed", False):
+ return False
+ return not any(stream is null for null in _NULL_STANDARD_STREAMS)
+
+
if sys.platform == "win32":
NO_WINDOW_CREATIONFLAGS: int = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000)
else:
diff --git a/jarvis/ui/web/launcher.py b/jarvis/ui/web/launcher.py
index f4f50c372d..0c2862ec16 100644
--- a/jarvis/ui/web/launcher.py
+++ b/jarvis/ui/web/launcher.py
@@ -14,12 +14,14 @@ from __future__ import annotations
import argparse
import asyncio
+import contextlib
import os
import signal
import sys
import time
from jarvis.core.branding import CONFIG_FILE_NAME
+from jarvis.core.branding import PRODUCT_NAME as APP_DISPLAY_NAME
from jarvis.core.process_utils import ensure_standard_streams
from jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awareness
@@ -771,8 +773,82 @@ async def _run_headless(args) -> int:
return 0
+def _show_error_dialog(title: str, message: str) -> None:
+ """Last-resort visible surface: a native modal box. Windows-only, no-op else.
+
+ Separated from ``_report_startup_failure`` so tests can assert the decision
+ to show a box without a real one ever opening — an unattended dialog blocks
+ the process until someone clicks it, which in CI means a hung run.
+ """
+ if sys.platform != "win32":
+ return
+ with contextlib.suppress(Exception):
+ import ctypes
+
+ MB_ICONERROR = 0x10
+ ctypes.windll.user32.MessageBoxW(None, message, title, MB_ICONERROR)
+
+
+def _report_startup_failure(message: str) -> None:
+ """Put a desktop-start failure somewhere the user will actually see it.
+
+ A windowless interpreter is the whole problem here. ``pythonw`` — what the
+ Start-Menu shortcut and ``run.bat`` use, so no console flashes up — has no
+ standard streams, so the reason the app refused to start is written into the
+ null device ``ensure_standard_streams`` substituted. From the user's side
+ the app "just doesn't start any more": no window, no error, nothing to
+ search for. When stderr demonstrably went nowhere, say it in a dialog.
+
+ Whenever stderr IS readable — a terminal, a pipe, a redirected build log —
+ the print below is the whole job and a modal box would only be in the way.
+ The log line is written either way, so the reason survives for a support
+ question even if the box is clicked away.
+ """
+ print(message, file=sys.stderr, flush=True)
+ with contextlib.suppress(Exception):
+ from loguru import logger as _slog
+
+ _slog.error(message)
+ with contextlib.suppress(Exception):
+ from jarvis.core.process_utils import standard_error_is_visible
+
+ if not standard_error_is_visible():
+ _show_error_dialog(f"{APP_DISPLAY_NAME} could not start", message)
+
+
+def _missing_window_toolkit() -> str | None:
+ """Explain a missing pywebview, or ``None`` when the window can be built.
+
+ The base install ships without a window toolkit on purpose (it lives in the
+ ``[full]`` extra), and the shortcut can also end up aimed at a foreign
+ interpreter. Both end in the same ``ModuleNotFoundError`` deep inside the
+ boot — checked here so the user gets a sentence instead of a traceback, and
+ is told about the window-less mode that does work on their install.
+ """
+ import importlib.util
+
+ try:
+ if importlib.util.find_spec("webview") is not None:
+ return None
+ except (ImportError, ValueError): # broken/partial install
+ pass
+ return (
+ f"{APP_DISPLAY_NAME} cannot open its window: the pywebview package is "
+ f"missing from this Python install.\n\n"
+ f"Python: {sys.executable}\n\n"
+ f"Install the desktop extra:\n"
+ f" pip install 'personal-jarvis[full]'\n\n"
+ f"Or start it without a window:\n"
+ f" jarvis serve"
+ )
+
+
def _run_desktop(cfg, use_lock: bool) -> int:
- """Full desktop app with a pywebview window."""
+ """Full desktop app with a pywebview window.
+
+ ``main()`` has already established that pywebview is importable
+ (``_missing_window_toolkit``), so the window layer can be built here.
+ """
# AUMID must be set before pywebview creates the window (taskbar icon).
_ensure_windows_app_identity()
from jarvis.ui.desktop_app import (
@@ -1080,6 +1156,17 @@ def main(argv: list[str] | None = None) -> int:
_raw_argv = argv if argv is not None else sys.argv[1:]
args = _parse_args(_raw_argv)
+ # Refuse a window we cannot build, BEFORE paying for the boot. Everything
+ # below this line — config, control key, autostart, backend, voice — takes
+ # up to a minute and would all be thrown away at the pywebview import. Worse,
+ # under `pythonw` that import error has nowhere to print, so the app just
+ # never appears. Check the one import that decides it, and say so out loud.
+ if not args.headless:
+ _no_window = _missing_window_toolkit()
+ if _no_window is not None:
+ _report_startup_failure(_no_window)
+ return 4
+
# Drop administrator rights BEFORE booting, not after.
#
# An elevated window is unreachable for dictation apps, text expanders and
diff --git a/tests/unit/ui/test_launcher_visible_startup_failure.py b/tests/unit/ui/test_launcher_visible_startup_failure.py
new file mode 100644
index 0000000000..77dfe66103
--- /dev/null
+++ b/tests/unit/ui/test_launcher_visible_startup_failure.py
@@ -0,0 +1,188 @@
+"""A desktop start that cannot happen must SAY so — even under ``pythonw``.
+
+The Start-Menu shortcut and ``run.bat`` both launch ``pythonw``, whose standard
+streams point at nothing. So the ``ModuleNotFoundError: webview`` that ends the
+boot is written into the void: no window, no console, no error dialog. From the
+user's side the app "just doesn't start any more" — nothing to read, nothing to
+search for. These tests pin the two halves of the fix: the launcher refuses
+early and explains itself, and the explanation reaches a surface a user can see.
+"""
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from jarvis.ui.web import launcher
+
+
+class TestWindowToolkitProbe:
+ def test_none_when_pywebview_is_importable(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: object())
+ assert launcher._missing_window_toolkit() is None
+
+ def test_names_the_package_and_both_ways_out(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ msg = launcher._missing_window_toolkit()
+ assert msg is not None
+ assert "pywebview" in msg, "the user must learn WHAT is missing"
+ assert "personal-jarvis[full]" in msg, "…and how to install it"
+ assert "jarvis serve" in msg, "…and what already works without a window"
+ assert sys.executable in msg, (
+ "name the interpreter — the usual cause is a shortcut aimed at the "
+ "wrong Python, which is invisible without this line"
+ )
+
+ def test_broken_install_reads_as_missing(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ import importlib.util
+
+ def _raise(name: str) -> object:
+ raise ValueError("half-removed distribution")
+
+ monkeypatch.setattr(importlib.util, "find_spec", _raise)
+ assert launcher._missing_window_toolkit() is not None
+
+
+def dialogs(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str]]:
+ """Intercept the modal box.
+
+ Every test that can reach the dialog branch MUST use this. A real
+ ``MessageBoxW`` blocks the calling thread until a human clicks it, so an
+ unguarded test hangs the run — which is exactly what happened while writing
+ these tests.
+ """
+ seen: list[tuple[str, str]] = []
+ monkeypatch.setattr(
+ launcher, "_show_error_dialog", lambda title, msg: seen.append((title, msg))
+ )
+ return seen
+
+
+class TestFailureIsVisible:
+ def test_writes_to_stderr(
+ self, capsys: pytest.CaptureFixture[str], dialogs: list[tuple[str, str]]
+ ) -> None:
+ launcher._report_startup_failure("no window toolkit here")
+ assert "no window toolkit here" in capsys.readouterr().err
+
+ def test_no_dialog_while_stderr_is_readable(
+ self, monkeypatch: pytest.MonkeyPatch, dialogs: list[tuple[str, str]]
+ ) -> None:
+ """A terminal, a pipe or a build log already showed it — a box is noise."""
+ monkeypatch.setattr(
+ "jarvis.core.process_utils.standard_error_is_visible", lambda: True
+ )
+ launcher._report_startup_failure("readable stderr")
+ assert not dialogs
+
+ def test_dialog_when_stderr_went_nowhere(
+ self, monkeypatch: pytest.MonkeyPatch, dialogs: list[tuple[str, str]]
+ ) -> None:
+ """The pythonw case — the only surface left is a box."""
+ monkeypatch.setattr(
+ "jarvis.core.process_utils.standard_error_is_visible", lambda: False
+ )
+ launcher._report_startup_failure("pywebview is missing")
+ assert len(dialogs) == 1
+ title, body = dialogs[0]
+ assert "could not start" in title
+ assert "pywebview is missing" in body
+
+ def test_never_raises(
+ self, monkeypatch: pytest.MonkeyPatch, dialogs: list[tuple[str, str]]
+ ) -> None:
+ """Reporting a failed start must not itself blow up the process."""
+
+ def _explode(*a: object, **k: object) -> None:
+ raise RuntimeError("logging sink is gone")
+
+ monkeypatch.setattr("loguru.logger.error", _explode)
+ launcher._report_startup_failure("still has to survive this")
+
+ @pytest.mark.skipif(sys.platform == "win32", reason="tests the non-Windows no-op")
+ def test_dialog_is_a_noop_off_windows(self) -> None:
+ launcher._show_error_dialog("title", "body")
+
+
+class TestStandardErrorVisibility:
+ """The probe that decides whether a dialog is needed at all."""
+
+ def test_a_real_stream_counts_as_visible(self) -> None:
+ from jarvis.core.process_utils import standard_error_is_visible
+
+ assert standard_error_is_visible() is True
+
+ def test_the_substituted_null_device_does_not(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Reproduce the pythonw substitution and confirm it reads as invisible."""
+ import os
+
+ from jarvis.core import process_utils
+
+ null = open(os.devnull, "w", encoding="utf-8") # noqa: SIM115
+ try:
+ monkeypatch.setattr(process_utils.sys, "stderr", null)
+ monkeypatch.setattr(process_utils, "_NULL_STANDARD_STREAMS", [null])
+ assert process_utils.standard_error_is_visible() is False
+ finally:
+ null.close()
+
+ def test_missing_stream_does_not(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ from jarvis.core import process_utils
+
+ monkeypatch.setattr(process_utils.sys, "stderr", None)
+ assert process_utils.standard_error_is_visible() is False
+
+
+class TestLauncherRefusesEarly:
+ def test_headless_never_needs_a_window(self) -> None:
+ """`--headless` is the window-less path; the probe must not gate it.
+
+ This is the €5-VPS / Docker case from the open-source contract: no
+ pywebview anywhere, and the server still has to boot.
+ """
+ import inspect
+
+ src = inspect.getsource(launcher.main)
+ before_gate = src[: src.index("_missing_window_toolkit")]
+ assert "if not args.headless:" in before_gate.split("args = _parse_args")[-1], (
+ "the window-toolkit gate must sit behind `if not args.headless:` — "
+ "a headless host legitimately has no pywebview"
+ )
+
+ def test_gate_runs_before_the_expensive_boot(self) -> None:
+ """Fail in a second, not after a minute of discarded work."""
+ import inspect
+
+ src = inspect.getsource(launcher.main)
+ gate_at = src.index("_missing_window_toolkit")
+ for later in ("load_config()", "ensure_control_key", "_run_desktop("):
+ assert gate_at < src.index(later), (
+ f"the window check must run before {later}; otherwise the user "
+ "pays the full boot for an error that was knowable up front"
+ )
+
+ def test_refusal_reports_a_failing_exit_code(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ dialogs: list[tuple[str, str]],
+ ) -> None:
+ monkeypatch.setattr(
+ launcher, "_missing_window_toolkit", lambda: "pywebview is missing"
+ )
+ rc = launcher.main([])
+ assert rc == 4, "a start that never happened must not report success"
+ assert "pywebview is missing" in capsys.readouterr().err