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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(appshot): open the editor window at once — kept warm, no boot screen
rubenluetke10-beepa658d72da7b2
diff --git a/jarvis/appshot/editor_window.py b/jarvis/appshot/editor_window.pyindex 4e674b0337..15cf9a5416 100644--- a/jarvis/appshot/editor_window.py+++ b/jarvis/appshot/editor_window.py@@ -28,16 +28,34 @@ EDITOR_VIEW = "appshot-editor"_ID = re.compile(r"^[0-9a-f]{8,64}$")_opener: Callable[[str], dict[str, Any]] | None = None+_prewarm: Callable[[], dict[str, Any]] | None = None-def register_window_opener(opener: Callable[[str], dict[str, Any]] | None) -> None:+def register_window_opener(+ opener: Callable[[str], dict[str, Any]] | None,+ *,+ prewarm: Callable[[], dict[str, Any]] | None = None,+) -> None:"""Install (or, with ``None``, remove) the shell's window opener.``opener(query)`` must open or re-point the ``appshot-editor`` window and- may block — it is always called from a worker thread.+ may block — it is always called from a worker thread. ``prewarm()``+ creates that window hidden ahead of time, so opening it is instant."""- global _opener+ global _opener, _prewarm_opener = opener+ _prewarm = prewarm if opener is not None else None+++async def prewarm_editor_window() -> None:+ """Have the editor window loaded (hidden) before anyone clicks the card."""+ prewarm = _prewarm+ if prewarm is None:+ return+ try:+ await asyncio.to_thread(prewarm)+ except Exception: # noqa: BLE001 - opening on click still works, just slower+ log.debug("appshot: the editor window could not be prepared", exc_info=True)def can_open_window() -> bool:@@ -60,4 +78,10 @@ async def open_editor_window(shot_id: str) -> bool:return ok-__all__ = ["EDITOR_VIEW", "can_open_window", "open_editor_window", "register_window_opener"]+__all__ = [+ "EDITOR_VIEW",+ "can_open_window",+ "open_editor_window",+ "prewarm_editor_window",+ "register_window_opener",+]diff --git a/jarvis/appshot/effect.py b/jarvis/appshot/effect.pyindex f0191308d3..2f7106920d 100644--- a/jarvis/appshot/effect.py+++ b/jarvis/appshot/effect.py@@ -54,12 +54,19 @@ def on_shutter(target: Any, size: tuple[int, int], rgb: bytes, monitors: list[direturn# Before the capture's own border dismissal can quit the sidecar.controller.hold_for_snap()- task = asyncio.get_running_loop().create_task(+ loop = asyncio.get_running_loop()+ task = loop.create_task(_play(controller, tuple(target.bbox), size, rgb, monitors),name="appshot-effect",)_tasks.add(task)task.add_done_callback(_tasks.discard)+ # The card that follows opens the editor: have its window loaded by then.+ from jarvis.appshot.editor_window import prewarm_editor_window # noqa: PLC0415++ warm = loop.create_task(prewarm_editor_window(), name="appshot-editor-prewarm")+ _tasks.add(warm)+ warm.add_done_callback(_tasks.discard)async def _play(diff --git a/jarvis/ui/desktop_app.py b/jarvis/ui/desktop_app.pyindex bf5ae70df2..5f14ba3464 100644--- a/jarvis/ui/desktop_app.py+++ b/jarvis/ui/desktop_app.py@@ -2743,7 +2743,8 @@ class DesktopApp:from jarvis.appshot.editor_window import EDITOR_VIEW, register_window_openerregister_window_opener(- lambda query: self.open_detached_window(EDITOR_VIEW, query=query)+ lambda query: self.open_detached_window(EDITOR_VIEW, query=query),+ prewarm=self.prewarm_appshot_editor,)except Exception as exc: # noqa: BLE001 - the page editor stays the fallbackfrom loguru import logger as _alog@@ -5160,7 +5161,7 @@ class DesktopApp:return resolve_theme(self._configured_theme())- def open_detached_window(self, view: str) -> dict[str, Any]:+ def open_detached_window(self, view: str, query: str = "") -> dict[str, Any]:"""Open ``view`` in its own solo window — MUST run on a worker thread.pywebview materializes runtime windows only from a thread whose name is@@ -5172,11 +5173,26 @@ class DesktopApp:honest degrade on hosts whose webview backend cannot create runtimewindows."""- fallback = f"/?view={view}&solo=1"+ suffix = f"&{query}" if query else ""+ fallback = f"/?view={view}&solo=1{suffix}"if view not in DETACHABLE_VIEWS:return {"ok": False, "reason": "unknown_view"}existing = self._detached_windows.get(view)+ if existing is not None and view == "appshot-editor":+ # The editor window is kept warm and hidden between uses: point it+ # at the appshot in place and show it — no reload, no boot screen.+ return self._show_warm_editor(existing, query, fallback)if existing is not None:+ if query:+ # Same window, new content: navigate it rather than open a+ # second one (the title is the window's identity on Windows).+ try:+ existing.load_url(f"{self._url()}{fallback}")+ except Exception as exc: # noqa: BLE001+ from loguru import logger++ logger.opt(exception=exc).warning("Detached '{}' could not navigate", view)+ return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}_bring_window_to_front_by_title(self._detached_title(view))return {"ok": True, "already_open": True, "view": view}if self._window is None and not self._detached_windows:@@ -5220,6 +5236,73 @@ class DesktopApp:self._publish_detached_event_threadsafe(view, opened=True)return {"ok": True, "already_open": False, "view": view}+ def _show_warm_editor(self, window: Any, query: str, fallback: str) -> dict[str, Any]:+ """Show the kept-warm appshot editor on the appshot named in ``query``."""+ shot_id = query.partition("appshot=")[2].split("&", 1)[0]+ pointed = False+ if shot_id:+ try:+ pointed = bool(+ window.evaluate_js(+ "typeof window.__jarvisOpenAppshot === 'function'"+ f" && window.__jarvisOpenAppshot({json.dumps(shot_id)})"+ )+ )+ except Exception: # noqa: BLE001 - still loading: navigate instead+ pointed = False+ try:+ if shot_id and not pointed:+ # The page has not finished loading yet: load it on this shot.+ window.load_url(f"{self._url()}{fallback}")+ window.show()+ except Exception as exc: # noqa: BLE001+ from loguru import logger++ logger.opt(exception=exc).warning("The appshot editor window could not be shown")+ return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}+ _bring_window_to_front_by_title(self._detached_title("appshot-editor"))+ return {"ok": True, "already_open": True, "view": "appshot-editor"}++ def prewarm_appshot_editor(self) -> dict[str, Any]:+ """Create the appshot editor window hidden, so its first click is instant.++ Worker-thread only, like :meth:`open_detached_window`. Called when an+ appshot is taken: by the time its corner card is clicked, the editor+ page has loaded behind the scenes. A no-op when it already exists.+ """+ view = "appshot-editor"+ if view in self._detached_windows:+ return {"ok": True, "already_open": True}+ if self._window is None:+ return {"ok": False, "reason": "no_live_window"}+ try:+ import webview # noqa: PLC0415 — [desktop] extra, never module-level++ window = webview.create_window(+ self._detached_title(view),+ f"{self._url()}/?view={view}&solo=1",+ width=1100,+ height=750,+ min_size=(800, 520),+ resizable=True,+ frameless=True,+ easy_drag=False,+ confirm_close=False,+ hidden=True,+ background_color=self._window_background(),+ **TEXT_SELECTABLE,+ )+ except Exception as exc: # noqa: BLE001 - opening on click still works+ from loguru import logger++ logger.opt(exception=exc).debug("The appshot editor could not be prepared")+ return {"ok": False, "reason": f"{type(exc).__name__}: {exc}"}+ self._detached_windows[view] = window+ self._arm_window_frame(window)+ window.events.loaded += lambda w=window, v=view: self._inject_into_secondary(w, v)+ window.events.closed += lambda v=view: self._on_detached_closed(v)+ return {"ok": True, "already_open": False}+def close_detached_window(self, view: str) -> dict[str, Any]:"""Close the detached window for ``view`` — worker-thread only.@@ -5230,6 +5313,15 @@ class DesktopApp:window = self._detached_windows.get(view)if window is None:return {"ok": False, "reason": "not_detached"}+ if view == "appshot-editor":+ # Hidden, not destroyed: the next appshot opens it at once.+ try:+ window.hide()+ return {"ok": True, "view": view, "hidden": True}+ except Exception as exc: # noqa: BLE001 - a window that will not hide is closed+ from loguru import logger++ logger.opt(exception=exc).debug("Appshot editor window would not hide; closing it")try:window.destroy()except Exception as exc: # noqa: BLE001diff --git a/jarvis/ui/web/frontend/index.html b/jarvis/ui/web/frontend/index.htmlindex f29fa1dd60..319d2b8261 100644--- a/jarvis/ui/web/frontend/index.html+++ b/jarvis/ui/web/frontend/index.html@@ -45,6 +45,11 @@var root = document.documentElement;root.classList.toggle("dark", mode === "dark");root.style.colorScheme = mode;+ // The appshot editor window shows no boot splash: it is the editor or+ // nothing, never the app's start-up screen in front of a picture.+ if (new URLSearchParams(location.search).get("view") === "appshot-editor") {+ root.classList.add("jarvis-quiet-boot");+ }window.__JARVIS_BOOT_STARTED_AT = performance.now();})();</script>@@ -98,6 +103,7 @@--jbs-sub: #7a7a7a;}html, body { margin: 0; height: 100%; background: var(--jbs-bg); }+ .jarvis-quiet-boot #jarvis-boot-splash { display: none !important; }#jarvis-boot-splash {position: fixed; inset: 0; z-index: 2147483000;display: flex; flex-direction: column;diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.tsxindex e473c8967d..d23d1b8d15 100644--- a/jarvis/ui/web/frontend/src/components/AuthGate.tsx+++ b/jarvis/ui/web/frontend/src/components/AuthGate.tsx@@ -25,6 +25,8 @@ const SPLASH_EXIT_FALLBACK_MS = 1000;interface AuthGateProps {children: ReactNode;+ /** No boot splash while checking (the appshot editor window). */+ quiet?: boolean;}async function createSession(body: { control_key: string } | { session_token: string }) {@@ -57,7 +59,7 @@ function waitForInjectedToken(): Promise<string> {});}-export function AuthGate({ children }: AuthGateProps) {+export function AuthGate({ children, quiet = false }: AuthGateProps) {const t = useT();const started = useRef(false);// The HTML splash starts the reveal before React loads. Continue that same@@ -222,8 +224,10 @@ export function AuthGate({ children }: AuthGateProps) {// treats a bare splash in #root as "bundle still loading" and reloads it// after its grace period. A held cold boot can legitimately outlast that,// so the gate's splash must count as the app being up.+ // A quiet gate (the appshot editor window) shows nothing while it checks:+ // a start-up screen there would stand in front of the picture.const splashLayer =- splash === "gone" ? null : (+ quiet || splash === "gone" ? null : (<main id="jarvis-auth-splash"><BootSplashname={readCachedAssistantName("")}diff --git a/jarvis/ui/web/frontend/src/main.tsx b/jarvis/ui/web/frontend/src/main.tsxindex 648dfc8c9e..d80c35ca39 100644--- a/jarvis/ui/web/frontend/src/main.tsx+++ b/jarvis/ui/web/frontend/src/main.tsx@@ -146,7 +146,7 @@ function renderApp(): void {resetKey="root"onRecover={() => window.location.reload()}>- <AuthGate>+ <AuthGate quiet={isEditorWindow}>{isEditorWindow ? (<React.Suspense fallback={null}><AppshotEditorWindow />diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsxindex 202cac1b5d..e2149a1198 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useEventStore } from "@/store/events";@@ -111,6 +111,25 @@ describe("the appshot editor window", () => {vi.restoreAllMocks();});+ it("waits hidden without an appshot and opens one in place when pointed at it", async () => {+ window.history.replaceState(null, "", "/?view=appshot-editor&solo=1");+ const closeWindow = vi.fn(async () => undefined);+ render(<AppshotEditorWindow deps={{ returnCard: async () => undefined, closeWindow }} />);+ expect(screen.queryByTestId("appshot-editor")).toBeNull();++ await waitFor(() => expect(typeof window.__jarvisOpenAppshot).toBe("function"));+ expect(window.__jarvisOpenAppshot!("../../etc")).toBe(false);+ act(() => {+ expect(window.__jarvisOpenAppshot!("a1b2c3d4")).toBe(true);+ });+ await screen.findByTestId("appshot-editor-canvas");++ fireEvent.click(screen.getByTestId("appshot-editor-close"));+ await waitFor(() => expect(closeWindow).toHaveBeenCalledTimes(1));+ // Hidden again with nothing in it, ready for the next appshot.+ await waitFor(() => expect(screen.queryByTestId("appshot-editor")).toBeNull());+ });+it("still closes when the card cannot come back", async () => {const closeWindow = vi.fn(async () => undefined);render(<AppshotEditorWindow deps={{ returnCard: () => Promise.reject(new Error("no overlay")), closeWindow }} />);diff --git a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsxindex eefb84bc52..d142e52eca 100644--- a/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx+++ b/jarvis/ui/web/frontend/src/views/AppshotEditorWindow.tsx@@ -1,6 +1,7 @@-import { useCallback, useRef } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { ToastLayer } from "@/components/ToastLayer";+import { loadLocaleChunk } from "@/i18n";import { AppshotEditor, type EditorExit } from "@/views/AppshotEditor";/**@@ -12,7 +13,8 @@ import { AppshotEditor, type EditorExit } from "@/views/AppshotEditor";* (`POST /api/appshot/latest/card`), so it stays at hand — after Save or Done* it flies there from where the editor showed it, after Close it slides in —* and then the window closes itself through the shell- * (`POST /api/window/reattach`).+ * (`POST /api/window/reattach`), which only hides it: the window stays loaded+ * so the next click opens the editor at once.*/export const APPSHOT_EDITOR_VIEW = "appshot-editor";@@ -48,26 +50,57 @@ const browserDeps: EditorWindowDeps = {}),};+declare global {+ interface Window {+ /** The desktop shell points the warm (hidden) editor window at an appshot. */+ __jarvisOpenAppshot?: (id: string) => boolean;+ }+}+export function AppshotEditorWindow({ deps = browserDeps }: { deps?: EditorWindowDeps }) {- const appshotId = appshotIdFromUrl(window.location.search);+ // The window is kept warm and hidden between uses: it may start without an+ // appshot and be pointed at one later (window.__jarvisOpenAppshot), so the+ // editor opens at once instead of booting a fresh window each time.+ const [appshotId, setAppshotId] = useState(() => appshotIdFromUrl(window.location.search));+ const [session, setSession] = useState(0);const closing = useRef(false);+ useEffect(() => {+ // Waiting while hidden: have the editor's words ready before the click.+ void loadLocaleChunk("appshot_editor").catch(() => undefined);+ window.__jarvisOpenAppshot = (id: string) => {+ const valid = appshotIdFromUrl(`?appshot=${encodeURIComponent(id)}`);+ if (!valid) return false;+ closing.current = false;+ setAppshotId(valid);+ setSession((n) => n + 1);+ return true;+ };+ return () => {+ delete window.__jarvisOpenAppshot;+ };+ }, []);+const close = useCallback((exit?: EditorExit) => {if (closing.current) return;closing.current = true;// Back into the corner first: the window must not take the card's- // request down with it.+ // request down with it. Then forget the picture, so the hidden window+ // never flashes the previous appshot when it is shown again.void deps.returnCard(exit?.flyFrom).catch(() => undefined).finally(() => {+ setAppshotId("");void deps.closeWindow().catch(() => undefined);});}, [deps]);return (<div className="h-screen w-screen overflow-hidden bg-popover" data-testid="appshot-editor-window">- <AppshotEditor appshotId={appshotId || "missing"} onClose={close} variant="window" />+ {appshotId && (+ <AppshotEditor key={session} appshotId={appshotId} onClose={close} variant="window" />+ )}<ToastLayer /></div>);diff --git a/tests/unit/ui/test_appshot_editor_warm.py b/tests/unit/ui/test_appshot_editor_warm.pynew file mode 100644index 0000000000..a56c037dd2--- /dev/null+++ b/tests/unit/ui/test_appshot_editor_warm.py@@ -0,0 +1,133 @@+"""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 jarvis.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) -> None:+ self.page_ready = page_ready+ 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 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("jarvis.ui.desktop_app._bring_window_to_front_by_title", lambda _t: True)+ return app+++def test_prewarm_creates_the_editor_hidden_once(monkeypatch: pytest.MonkeyPatch) -> None:+ 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]["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 == [+ "js",+ "load http://127.0.0.1:47821/?view=appshot-editor&solo=1&appshot=a1b2c3d4",+ "show",+ ]+++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 jarvis.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"]