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.

13.4 KB
Raw Blame
"""Regression guard for the mascot-branded launcher exe (taskbar-icon fix).

The Windows taskbar button takes its icon from the executable that OWNS the
window — NOT the window/class icon, AUMID, Start-Menu shortcut, registry, or
icon cache (all verified to have no effect on the button). A bare
``pythonw.exe`` launch therefore shows the Python logo on the taskbar. The fix
re-execs the launcher through ``DodaiosApp.exe`` — a copy of the *base*
interpreter's ``pythonw`` (the real window-owner; a venv launcher only
redirects to it) carrying the mascot icon, with the venv re-attached via
``__PYVENV_LAUNCHER__``. These tests pin the contract without spawning a GUI.
"""
from __future__ import annotations

import inspect
import os
import sys
from pathlib import Path

import pytest

from dodaios.core.branding import WINDOWS_BRANDED_LAUNCHER_DIR_NAME
from dodaios.ui import icon_utils


def test_branded_launcher_api_is_importable() -> None:
    for name in (
        "ensure_branded_launcher_exe",
        "maybe_reexec_through_branded_launcher",
        "BRANDED_LAUNCHER_EXE_NAME",
    ):
        assert hasattr(icon_utils, name)
    assert icon_utils.BRANDED_LAUNCHER_EXE_NAME.lower().endswith(".exe")


def test_launcher_wires_the_reexec() -> None:
    """main() must call the re-exec chokepoint, or nothing brands the taskbar."""
    import dodaios.ui.web.launcher as launcher

    src = inspect.getsource(launcher)
    assert "maybe_reexec_through_branded_launcher" in src


def test_non_windows_never_brands() -> None:
    """Everything is a no-op off Windows (Linux/macOS brand via .desktop/iconphoto)."""
    if sys.platform == "win32":
        pytest.skip("Windows path covered elsewhere")
    assert icon_utils.ensure_branded_launcher_exe() is None
    assert icon_utils.maybe_reexec_through_branded_launcher([]) is None


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_reexec_is_guarded_against_relaunch_loops(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """The env marker set on the child must short-circuit a second re-exec."""
    monkeypatch.setenv(icon_utils._BRANDED_LAUNCH_ENV, "1")
    assert icon_utils.maybe_reexec_through_branded_launcher(["--x"]) is None


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_reexec_skips_a_debug_console_run(monkeypatch: pytest.MonkeyPatch) -> None:
    """A visible-console/debug run must not be swallowed by a windowless re-exec."""
    monkeypatch.delenv(icon_utils._BRANDED_LAUNCH_ENV, raising=False)
    monkeypatch.setenv("JARVIS_DEBUG", "1")
    assert icon_utils.maybe_reexec_through_branded_launcher([]) is None


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_branded_candidates_prefer_the_venv_then_base_then_user_dir(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """Candidate 1 sits INSIDE the venv, copied from the venv's own launcher —
    self-contained (finds its environment from pyvenv.cfg), so it is the only
    one usable as a Start-Menu shortcut target, and the only one that survives a
    Microsoft Store Python. Candidate 2 sits beside the BASE pythonw (zero-copy
    DLL adjacency); candidate 3 is the always-writable per-user dir — the fix
    for machines where the base dir is read-only (Program Files installs)."""
    monkeypatch.setenv("LOCALAPPDATA", str(tmp_path))
    candidates = icon_utils._branded_launcher_candidates()
    if not candidates:
        pytest.skip("no interpreter resolvable in this environment")
    venv = icon_utils._venv_pythonw_executable()
    targets = [t for _src, t in candidates]
    if venv is not None:
        assert candidates[0] == (venv, venv.with_name(icon_utils.BRANDED_LAUNCHER_EXE_NAME))
        targets = targets[1:]
    if icon_utils._base_pythonw_executable() is not None:
        assert targets[0].parent == Path(sys.base_prefix)
        assert targets[1] == tmp_path / WINDOWS_BRANDED_LAUNCHER_DIR_NAME / "bin" / (
            icon_utils.BRANDED_LAUNCHER_EXE_NAME
        )
    assert all(t.name == icon_utils.BRANDED_LAUNCHER_EXE_NAME for _s, t in candidates)


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_no_localappdata_drops_only_the_per_user_home(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.delenv("LOCALAPPDATA", raising=False)
    candidates = icon_utils._branded_launcher_candidates()
    if not candidates:
        pytest.skip("no interpreter resolvable in this environment")
    targets = [t for _s, t in candidates]
    # Nothing may point into the (now unknown) per-user dir.
    assert all(f"{WINDOWS_BRANDED_LAUNCHER_DIR_NAME}\\bin" not in str(t) for t in targets)
    if icon_utils._base_pythonw_executable() is not None:
        assert any(t.parent == Path(sys.base_prefix) for t in targets)


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_venv_copy_is_recognised_as_self_contained() -> None:
    """Only a copy inside the venv resolves its environment by location, which
    is what lets a shortcut (which carries no environment) launch it."""
    venv = icon_utils._venv_pythonw_executable()
    if venv is None:
        pytest.skip("not running inside a venv")
    branded = venv.with_name(icon_utils.BRANDED_LAUNCHER_EXE_NAME)
    assert icon_utils._is_self_contained_branded_exe(branded) is True
    # A per-user home has no pyvenv.cfg above it, so it is NOT self-contained.
    user_dir = icon_utils._user_launcher_dir()
    if user_dir is not None:
        assert (
            icon_utils._is_self_contained_branded_exe(
                user_dir / icon_utils.BRANDED_LAUNCHER_EXE_NAME
            )
            is False
        )


def _fake_interpreter_dir(tmp_path: Path) -> Path:
    """A fake base-interpreter dir: pythonw stub + the runtime DLL set."""
    src_dir = tmp_path / "base"
    src_dir.mkdir()
    (src_dir / "pythonw.exe").write_bytes(b"MZ fake interpreter")
    (src_dir / "python311.dll").write_bytes(b"dll")
    (src_dir / "python3.dll").write_bytes(b"dll")
    (src_dir / "vcruntime140.dll").write_bytes(b"dll")
    return src_dir


def _brandable(monkeypatch: pytest.MonkeyPatch, *, boots: bool = True) -> None:
    """Stub the two Win32-only steps so copy/DLL logic is testable anywhere."""
    monkeypatch.setattr(icon_utils, "_replace_exe_icon", lambda *_a: True)
    monkeypatch.setattr(icon_utils, "_branded_copy_boots", lambda *_a: boots)


def test_relocated_copy_carries_the_runtime_dlls(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """A copy OUTSIDE the base dir must bring python3*/vcruntime140* along —
    without them the relocated exe dies before any window exists."""
    _brandable(monkeypatch)
    src_dir = _fake_interpreter_dir(tmp_path)
    ico = tmp_path / "dodaios.ico"
    ico.write_bytes(b"ico")
    target = tmp_path / "user" / "bin" / icon_utils.BRANDED_LAUNCHER_EXE_NAME

    built = icon_utils._ensure_branded_copy_at(src_dir / "pythonw.exe", target, ico)

    assert built == target
    assert target.is_file()
    for dll in ("python311.dll", "python3.dll", "vcruntime140.dll"):
        assert (target.parent / dll).is_file(), dll


def test_relocated_copy_that_fails_the_smoke_start_is_discarded(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """A relocated copy that cannot boot would strand the user with NO app
    (the re-exec parent already exited) — it must be deleted, not returned."""
    _brandable(monkeypatch, boots=False)
    src_dir = _fake_interpreter_dir(tmp_path)
    ico = tmp_path / "dodaios.ico"
    ico.write_bytes(b"ico")
    target = tmp_path / "user" / "bin" / icon_utils.BRANDED_LAUNCHER_EXE_NAME

    assert icon_utils._ensure_branded_copy_at(src_dir / "pythonw.exe", target, ico) is None
    assert not target.exists()


def test_relocated_copy_missing_a_dll_is_rebuilt(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """Freshness must include the DLL set: an exe-only leftover (older partial
    build) cannot start and would otherwise be trusted forever."""
    _brandable(monkeypatch)
    src_dir = _fake_interpreter_dir(tmp_path)
    ico = tmp_path / "dodaios.ico"
    ico.write_bytes(b"ico")
    target = tmp_path / "user" / "bin" / icon_utils.BRANDED_LAUNCHER_EXE_NAME
    target.parent.mkdir(parents=True)
    target.write_bytes(b"stale exe, no dlls")
    import os as _os
    import time as _time

    future = _time.time() + 3600  # newer than every input → "fresh" by mtime alone
    _os.utime(target, (future, future))

    built = icon_utils._ensure_branded_copy_at(src_dir / "pythonw.exe", target, ico)

    assert built == target
    assert (target.parent / "python311.dll").is_file()


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_unwritable_first_home_falls_through_to_the_user_dir(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
    """THE fresh-machine fix: base dir not writable (Program Files / non-admin)
    must not end branding — the per-user candidate takes over."""
    _brandable(monkeypatch)
    src_dir = _fake_interpreter_dir(tmp_path)
    src = src_dir / "pythonw.exe"
    ico = tmp_path / "dodaios.ico"
    ico.write_bytes(b"ico")
    # Candidate 1's parent is a FILE → every write attempt there fails, like a
    # read-only Program Files dir. Candidate 2 is a writable user dir.
    blocker = tmp_path / "readonly"
    blocker.write_bytes(b"not a directory")
    bad = blocker / icon_utils.BRANDED_LAUNCHER_EXE_NAME
    good = tmp_path / "user" / "bin" / icon_utils.BRANDED_LAUNCHER_EXE_NAME
    monkeypatch.setattr(icon_utils, "_base_pythonw_executable", lambda: src)
    monkeypatch.setattr(
        icon_utils, "_branded_launcher_candidates", lambda: [(src, bad), (src, good)]
    )
    monkeypatch.setattr(icon_utils, "project_icon_path", lambda: ico)

    assert icon_utils.ensure_branded_launcher_exe() == good
    assert good.is_file()
    assert (good.parent / "python311.dll").is_file()


@pytest.mark.skipif(sys.platform != "win32", reason="Windows-only branding")
def test_ms_store_alias_base_is_skipped_not_copied(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """A 0-byte base exe (the MS Store app-execution alias) copies to an empty
    husk, so that source must be skipped rather than branded.

    Not the same as "no branding at all" any more: on a Store install the venv's
    own launcher is a real binary and takes over (see the venv candidate). This
    pins the SOURCE rule — never copy an alias — while leaving that fallback
    free to succeed, which is what put the app back in Windows Search.
    """
    fake_base = icon_utils._base_pythonw_executable()
    if fake_base is None:
        pytest.skip("no base pythonw resolvable")
    # Isolate the base-source rule: drop the venv candidate for this test.
    monkeypatch.setattr(icon_utils, "_venv_pythonw_executable", lambda: None)

    real_stat = os.stat

    class _ZeroStat:
        def __init__(self, st):
            self._st = st

        def __getattr__(self, k):
            if k == "st_size":
                return 0
            return getattr(self._st, k)

    def _fake_stat(path, *a, **k):
        st = real_stat(path, *a, **k)
        if Path(path) == fake_base:
            return _ZeroStat(st)
        return st

    monkeypatch.setattr(icon_utils.os, "stat", _fake_stat, raising=False)
    # Path.stat() is used in the code; patch that too.
    orig_path_stat = Path.stat

    def _fake_path_stat(self, *a, **k):
        st = orig_path_stat(self, *a, **k)
        if self == fake_base:
            return _ZeroStat(st)
        return st

    monkeypatch.setattr(Path, "stat", _fake_path_stat, raising=False)
    assert icon_utils.ensure_branded_launcher_exe() is None



@pytest.mark.parametrize("which", ["current", "earlier"])
def test_reexec_never_rebrands_a_process_that_is_the_branded_exe(
    monkeypatch: pytest.MonkeyPatch, tmp_path: Path, which: str
) -> None:
    """A copy under the earlier name (a pinned button of an earlier release
    starts it) is the branded app already: re-exec'ing it into the current
    name would cost a second process and a boot delay on every launch."""
    name = (
        icon_utils.BRANDED_LAUNCHER_EXE_NAME
        if which == "current"
        else icon_utils.LEGACY_BRANDED_LAUNCHER_EXE_NAMES[0]
    )
    monkeypatch.setattr(icon_utils.sys, "platform", "win32")
    monkeypatch.delenv(icon_utils._BRANDED_LAUNCH_ENV, raising=False)
    monkeypatch.delenv("JARVIS_DEBUG", raising=False)
    monkeypatch.setattr(icon_utils.sys, "_base_executable", str(tmp_path / name), raising=False)

    def must_not_build() -> Path:  # pragma: no cover - must never run
        raise AssertionError("a branded process must not build another branded copy")

    monkeypatch.setattr(icon_utils, "ensure_branded_launcher_exe", must_not_build)
    assert icon_utils.maybe_reexec_through_branded_launcher([]) is None


def test_the_branded_exe_and_its_home_carry_the_current_names() -> None:
    from dodaios.core.branding import (
        LEGACY_WINDOWS_BRANDED_LAUNCHER_FILE_NAMES,
        WINDOWS_BRANDED_LAUNCHER_DIR_NAME,
        WINDOWS_BRANDED_LAUNCHER_FILE_NAME,
        WINDOWS_USER_DATA_DIR_NAME,
    )

    assert icon_utils.BRANDED_LAUNCHER_EXE_NAME == WINDOWS_BRANDED_LAUNCHER_FILE_NAME
    legacy = icon_utils.LEGACY_BRANDED_LAUNCHER_EXE_NAMES
    assert legacy == LEGACY_WINDOWS_BRANDED_LAUNCHER_FILE_NAMES
    # The per-user home is not the data directory beside it.
    assert WINDOWS_BRANDED_LAUNCHER_DIR_NAME.casefold() != WINDOWS_USER_DATA_DIR_NAME.casefold()