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.

7.4 KB
Raw Blame
"""The appshot editor window is kept warm: prepared hidden, shown in place, hidden on close."""

from __future__ import annotations

import sys
from types import ModuleType

import pytest

from dodaios.ui.desktop_app import DesktopApp


class _Events:
    def __init__(self) -> None:
        self.loaded = _Hook()
        self.closed = _Hook()


class _Hook:
    def __init__(self) -> None:
        self.handlers: list = []

    def __iadd__(self, handler):
        self.handlers.append(handler)
        return self


class _Window:
    def __init__(self, *, page_ready: bool = True, width: int = 900, height: int = 600) -> None:
        self.page_ready = page_ready
        self.width = width
        self.height = height
        self.events = _Events()
        self.calls: list[str] = []

    def evaluate_js(self, js: str):
        self.calls.append("js")
        return self.page_ready

    def load_url(self, url: str) -> None:
        self.calls.append(f"load {url}")

    def show(self) -> None:
        self.calls.append("show")

    def restore(self) -> None:
        self.calls.append("restore")

    def resize(self, width: int, height: int) -> None:
        self.calls.append(f"resize {width}x{height}")
        self.width = width
        self.height = height

    def hide(self) -> None:
        self.calls.append("hide")

    def destroy(self) -> None:
        self.calls.append("destroy")


def _app(monkeypatch: pytest.MonkeyPatch) -> DesktopApp:
    app = DesktopApp.__new__(DesktopApp)
    app._detached_windows = {}  # noqa: SLF001
    app._window = object()  # noqa: SLF001 - a live main window
    app._url = lambda: "http://127.0.0.1:47821"  # type: ignore[method-assign]  # noqa: SLF001
    app._window_background = lambda: "#000000"  # type: ignore[method-assign]  # noqa: SLF001
    app._arm_window_frame = lambda _w: None  # type: ignore[method-assign]  # noqa: SLF001
    monkeypatch.setattr("dodaios.ui.desktop_app._bring_window_to_front_by_title", lambda _t: True)
    return app


@pytest.mark.parametrize("platform", ["darwin", "win32", "linux"])
def test_prewarm_creates_the_editor_hidden_once(
    monkeypatch: pytest.MonkeyPatch, platform: str,
) -> None:
    monkeypatch.setattr(sys, "platform", platform)
    created: list[dict] = []

    def create_window(title, url, **kwargs):
        created.append({"title": title, "url": url, **kwargs})
        return _Window()

    monkeypatch.setitem(sys.modules, "webview", ModuleType("webview"))
    sys.modules["webview"].create_window = create_window  # type: ignore[attr-defined]
    app = _app(monkeypatch)

    first = app.prewarm_appshot_editor()
    second = app.prewarm_appshot_editor()

    assert first == {"ok": True, "already_open": False}
    assert second == {"ok": True, "already_open": True}
    assert len(created) == 1
    assert created[0]["hidden"] is True
    assert created[0]["frameless"] is (platform != "darwin")
    assert created[0]["resizable"] is True
    assert created[0]["url"].endswith("/?view=appshot-editor&solo=1")


def test_a_page_still_loading_is_navigated_then_shown(monkeypatch: pytest.MonkeyPatch) -> None:
    app = _app(monkeypatch)
    window = _Window(page_ready=False)
    app._detached_windows["appshot-editor"] = window  # noqa: SLF001

    result = app.open_detached_window("appshot-editor", query="appshot=a1b2c3d4")

    assert result["ok"] is True
    assert window.calls[:3] == [
        "js",
        "load http://127.0.0.1:47821/?view=appshot-editor&solo=1&appshot=a1b2c3d4",
        "show",
    ]
    # Windows paints a WebView that was created hidden only after a size change.
    if sys.platform == "win32":
        assert window.calls[3:] == ["resize 900x601", "resize 900x600"]
    elif sys.platform == "darwin":
        assert window.calls[3:] == ["restore"]
    else:
        assert window.calls[3:] == []


def test_reopening_the_editor_on_macos_restores_it_from_the_dock(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr(sys, "platform", "darwin")
    app = _app(monkeypatch)
    window = _Window()
    app._detached_windows["appshot-editor"] = window

    result = app.open_detached_window("appshot-editor", query="appshot=a1b2c3d4")

    assert result["ok"] is True
    assert window.calls == ["js", "show", "restore"]
    assert app._detached_windows["appshot-editor"] is window


def test_macos_editor_restore_failure_is_reported(monkeypatch: pytest.MonkeyPatch) -> None:
    monkeypatch.setattr(sys, "platform", "darwin")
    app = _app(monkeypatch)
    window = _Window()

    def failed_restore() -> None:
        raise RuntimeError("window unavailable")

    window.restore = failed_restore
    app._detached_windows["appshot-editor"] = window

    result = app.open_detached_window("appshot-editor", query="appshot=a1b2c3d4")

    assert result["ok"] is False
    assert app._detached_windows["appshot-editor"] is window


def test_a_script_result_that_is_not_true_still_loads_the_shot(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    """A truthy non-boolean (an error object, a leftover string) is not success.

    Treating it as success skipped navigation and showed the empty gray shell.
    """
    app = _app(monkeypatch)
    window = _Window()
    window.evaluate_js = lambda _js: window.calls.append("js") or {"pywebview": "still booting"}  # type: ignore[method-assign]
    app._detached_windows["appshot-editor"] = window  # noqa: SLF001

    result = app.open_detached_window("appshot-editor", query="appshot=a1b2c3d4")

    assert result["ok"] is True
    assert any(call.startswith("load ") and "appshot=a1b2c3d4" in call for call in window.calls)
    assert "show" in window.calls


def test_showing_the_warm_editor_on_windows_nudges_its_size(
    monkeypatch: pytest.MonkeyPatch,
) -> None:
    monkeypatch.setattr("dodaios.ui.desktop_app.sys.platform", "win32")
    app = _app(monkeypatch)
    window = _Window(width=1024, height=662)
    app._detached_windows["appshot-editor"] = window  # noqa: SLF001

    result = app.open_detached_window("appshot-editor", query="appshot=a1b2c3d4")

    assert result["ok"] is True
    assert window.calls[-2:] == ["resize 1024x663", "resize 1024x662"]
    assert window.width == 1024
    assert window.height == 662


def test_closing_the_editor_hides_it_and_keeps_it(monkeypatch: pytest.MonkeyPatch) -> None:
    app = _app(monkeypatch)
    window = _Window()
    app._detached_windows["appshot-editor"] = window  # noqa: SLF001

    assert app.close_detached_window("appshot-editor") == {
        "ok": True,
        "view": "appshot-editor",
        "hidden": True,
    }
    assert window.calls == ["hide"]
    assert app._detached_windows["appshot-editor"] is window  # noqa: SLF001


def test_other_detached_views_still_close_for_real(monkeypatch: pytest.MonkeyPatch) -> None:
    app = _app(monkeypatch)
    window = _Window()
    app._detached_windows["visualization"] = window  # noqa: SLF001

    assert app.close_detached_window("visualization")["ok"] is True
    assert window.calls == ["destroy"]


async def test_the_editor_window_is_prepared_through_the_registered_prewarmer() -> None:
    from dodaios.appshot import editor_window

    calls: list[str] = []
    editor_window.register_window_opener(
        lambda _q: {"ok": True}, prewarm=lambda: calls.append("warm") or {"ok": True}
    )
    try:
        await editor_window.prewarm_editor_window()
    finally:
        editor_window.register_window_opener(None)
    await editor_window.prewarm_editor_window()  # no shell: a quiet no-op
    assert calls == ["warm"]