Agent Zero AI framework
Show Desktop install progress during runtime prep
Alessandro28a0b35ad455
diff --git a/plugins/_desktop/api/desktop_session.py b/plugins/_desktop/api/desktop_session.pyindex 4455f9ece..33dd6b6b0 100644--- a/plugins/_desktop/api/desktop_session.py+++ b/plugins/_desktop/api/desktop_session.py@@ -32,6 +32,7 @@ class DesktopSession(ApiHandler):return {"ok": False,"error": desktop.get("error") or "Desktop session is unavailable.",+ "status": desktop.get("status") or {},"desktop": desktop,"libreoffice": libreoffice.collect_status(),}diff --git a/plugins/_desktop/helpers/desktop_session.py b/plugins/_desktop/helpers/desktop_session.pyindex 6cd3ff540..1acc974cf 100644--- a/plugins/_desktop/helpers/desktop_session.py+++ b/plugins/_desktop/helpers/desktop_session.py@@ -43,6 +43,10 @@ BLOCKING_DIALOG_TITLES = ("Remote Files", "File Services")DISPLAY_START_TIMEOUT_SECONDS = 30.0PORT_START_TIMEOUT_SECONDS = 30.0STARTUP_GRACE_SECONDS = 45+RUNTIME_INSTALL_MESSAGE = (+ "Installing Agent Zero Desktop runtime dependencies. "+ "This can take a few minutes after an update."+)HIDDEN_XPRA_DESKTOP_ENTRIES = ("xpra.desktop","xpra-gui.desktop",@@ -1585,20 +1589,36 @@ def collect_desktop_status() -> dict[str, Any]:if desktop.get("binaries", {}).get("xpra") and desktop.get("packages", {}).get("xpra-x11") is False:missing.append("xpra-x11")healthy = not missing+ preparation = _runtime_preparation_status()+ installing = bool(preparation.get("preparing")) and not healthyreturn {"ok": True,"healthy": healthy,- "state": "healthy" if healthy else "missing",+ "state": "healthy" if healthy else "installing" if installing else "missing",+ "installing": installing,+ "missing": missing,+ "preparation": preparation,"binaries": binaries,"xpra_html_root": str(desktop.get("xpra_html_root") or ""),"message": ("Agent Zero Desktop sessions are available."if healthy+ else RUNTIME_INSTALL_MESSAGE+ if installingelse f"Agent Zero Desktop sessions need: {', '.join(missing)}."),}+def _runtime_preparation_status() -> dict[str, Any]:+ try:+ from plugins._desktop import hooks++ return hooks.runtime_preparation_status()+ except Exception:+ return {"preparing": False, "active_count": 0, "started_at": 0.0, "completed_at": 0.0}++def cleanup_stale_runtime_state() -> dict[str, Any]:killed: list[int] = []errors: list[str] = []diff --git a/plugins/_desktop/hooks.py b/plugins/_desktop/hooks.pyindex 2b369ef9c..a220bd587 100644--- a/plugins/_desktop/hooks.py+++ b/plugins/_desktop/hooks.py@@ -3,6 +3,8 @@ from __future__ import annotationsimport osimport shutilimport subprocess+import threading+import timeimport urllib.requestfrom pathlib import Pathfrom typing import Any@@ -59,29 +61,89 @@ OPTIONAL_RUNTIME_PACKAGES = (RETIRED_RUNTIME_PACKAGES = ("firefox-esr",)+_preparation_lock = threading.RLock()+_preparation_state: dict[str, Any] = {+ "preparing": False,+ "active_count": 0,+ "started_at": 0.0,+ "completed_at": 0.0,+ "result": None,+ "error": "",+}def cleanup_stale_runtime_state(force: bool = False) -> dict[str, Any]:"""Prepare the Linux Desktop runtime and reap stale Desktop sessions."""- installed: list[str] = []- removed: list[str] = []- errors: list[str] = []-- retired_packages = _installed_packages(RETIRED_RUNTIME_PACKAGES)- if retired_packages:- _purge_packages(removed, errors, installed_packages=retired_packages)-- _ensure_runtime_dependencies(installed, errors)- _cleanup_desktop_sessions(errors)-- return {- "ok": not errors,- "skipped": False,- "removed": removed,- "installed": installed,- "errors": errors,- }+ _begin_runtime_preparation()+ result: dict[str, Any] | None = None+ error = ""+ try:+ installed: list[str] = []+ removed: list[str] = []+ errors: list[str] = []++ retired_packages = _installed_packages(RETIRED_RUNTIME_PACKAGES)+ if retired_packages:+ _purge_packages(removed, errors, installed_packages=retired_packages)++ _ensure_runtime_dependencies(installed, errors)+ _cleanup_desktop_sessions(errors)++ result = {+ "ok": not errors,+ "skipped": False,+ "removed": removed,+ "installed": installed,+ "errors": errors,+ }+ return result+ except Exception as exc:+ error = str(exc)+ raise+ finally:+ _finish_runtime_preparation(result=result, error=error)+++def runtime_preparation_status() -> dict[str, Any]:+ with _preparation_lock:+ return {+ "preparing": bool(_preparation_state["preparing"]),+ "active_count": int(_preparation_state["active_count"]),+ "started_at": float(_preparation_state["started_at"]),+ "completed_at": float(_preparation_state["completed_at"]),+ "result": _preparation_state["result"],+ "error": str(_preparation_state["error"]),+ }+++def _begin_runtime_preparation() -> None:+ with _preparation_lock:+ if not _preparation_state["active_count"]:+ _preparation_state["preparing"] = True+ _preparation_state["started_at"] = time.time()+ _preparation_state["completed_at"] = 0.0+ _preparation_state["result"] = None+ _preparation_state["error"] = ""+ _preparation_state["active_count"] = int(_preparation_state["active_count"]) + 1+++def _finish_runtime_preparation(+ *,+ result: dict[str, Any] | None = None,+ error: str = "",+) -> None:+ with _preparation_lock:+ active_count = max(0, int(_preparation_state["active_count"]) - 1)+ _preparation_state["active_count"] = active_count+ if result is not None:+ _preparation_state["result"] = result+ if error:+ _preparation_state["error"] = error+ if active_count:+ return+ _preparation_state["preparing"] = False+ _preparation_state["completed_at"] = time.time()def _installed_packages(packages: tuple[str, ...]) -> list[str]:diff --git a/plugins/_desktop/webui/desktop-store.js b/plugins/_desktop/webui/desktop-store.jsindex b42bdbf1b..7342aa539 100644--- a/plugins/_desktop/webui/desktop-store.js+++ b/plugins/_desktop/webui/desktop-store.js@@ -12,6 +12,9 @@ const INPUT_PUSH_DELAY_MS = 650;const DESKTOP_HEARTBEAT_MS = 3500;const DESKTOP_RESIZE_DELAY_MS = 80;const DESKTOP_START_MESSAGE = "Starting Agent Zero Desktop environment";+const DESKTOP_RUNTIME_INSTALL_MESSAGE = "Installing Agent Zero Desktop runtime dependencies. This can take a few minutes after an update.";+const DESKTOP_RUNTIME_INSTALL_POLL_MS = 4000;+const DESKTOP_RUNTIME_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;const XPRA_DESKTOP_PRIME_INTERVAL_MS = 220;const XPRA_DESKTOP_PRIME_ATTEMPTS = 120;const SYSTEM_DESKTOP_FILE_ID = "system-desktop";@@ -124,6 +127,10 @@ function placeCaretAtEnd(element) {selection.addRange(range);}+function sleep(ms) {+ return new Promise((resolve) => globalThis.setTimeout(resolve, ms));+}+function normalizeDocument(doc = {}) {const path = doc.path || "";const extension = String(doc.extension || extensionOf(path)).toLowerCase();@@ -453,7 +460,7 @@ const model = {this.message = progressMessage;this.error = "";}- const response = await callDesktop("desktop");+ const response = await this.openDesktopWhenRuntimeReady(showProgress);if (response?.ok === false) throw new Error(response.error || "Desktop session could not be opened.");this.setDesktopIntentionalShutdown(false);const session = normalizeSession(response);@@ -488,7 +495,7 @@ const model = {} finally {if (showProgress) {this.loading = false;- if (this.message === progressMessage) this.message = "";+ if (this.message === progressMessage || this.message === DESKTOP_RUNTIME_INSTALL_MESSAGE) this.message = "";}this._desktopStarting = null;}@@ -496,6 +503,37 @@ const model = {return await this._desktopStarting;},+ async openDesktopWhenRuntimeReady(showProgress = true) {+ const startedAt = Date.now();+ let response = await callDesktop("desktop");+ while (response?.ok === false && this.isDesktopRuntimeInstalling(response)) {+ if (showProgress) {+ this.loading = true;+ this.error = "";+ this.message = this.desktopRuntimeInstallMessage(response);+ }+ if (Date.now() - startedAt > DESKTOP_RUNTIME_INSTALL_TIMEOUT_MS) {+ return {+ ...response,+ error: "Agent Zero Desktop runtime installation is still running. Please try again in a moment.",+ };+ }+ await sleep(DESKTOP_RUNTIME_INSTALL_POLL_MS);+ response = await callDesktop("desktop");+ }+ return response;+ },++ isDesktopRuntimeInstalling(response = {}) {+ const status = response?.status || response?.desktop?.status || response?.libreoffice?.desktop || {};+ return Boolean(status.installing || status.state === "installing" || status.preparation?.preparing);+ },++ desktopRuntimeInstallMessage(response = {}) {+ const status = response?.status || response?.desktop?.status || response?.libreoffice?.desktop || {};+ return String(status.message || DESKTOP_RUNTIME_INSTALL_MESSAGE);+ },+async create(kind = "document", format = "") {const fmt = String(format || (kind === "spreadsheet" ? "ods" : kind === "presentation" ? "odp" : "md")).toLowerCase();const title = this.defaultTitle(kind, fmt);diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.pyindex c531d49fc..984262c3c 100644--- a/tests/test_office_canvas_setup.py+++ b/tests/test_office_canvas_setup.py@@ -166,10 +166,15 @@ def test_desktop_plugin_owns_routes_runtime_surface_and_state_paths():assert "virtual_desktop_routes.install_route_hooks()" in desktop_startupassert 'action in {"open_document", "document"}' in desktop_api+ assert '"status": desktop.get("status") or {}' in desktop_apiassert 'callJsonApi("/plugins/_desktop/desktop_session"' in desktop_storeassert 'callDesktop("open_document"' in desktop_storeassert 'callOffice("create"' in desktop_storeassert "open_in_desktop: isOfficialExtension(fmt)" in desktop_store+ assert "DESKTOP_RUNTIME_INSTALL_MESSAGE" in desktop_store+ assert "openDesktopWhenRuntimeReady" in desktop_store+ assert "isDesktopRuntimeInstalling" in desktop_store+ assert "Installing Agent Zero Desktop runtime dependencies" in desktop_sessionassert "__a0XpraOffsetWarnPatched" in desktop_storeassert "window does not fit in canvas, offsets" in desktop_storeassert "decode error packet" in desktop_storediff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex a6a662233..b96af6b7c 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -505,6 +505,33 @@ def test_official_desktop_session_status_and_url_contract(tmp_path, monkeypatch)assert "printing=true" in url+def test_desktop_status_reports_installing_during_runtime_preparation(monkeypatch):+ monkeypatch.setattr(+ desktop_session.virtual_desktop,+ "collect_status",+ lambda: {+ "binaries": {},+ "packages": {},+ "xpra_html_root": "",+ },+ )+ monkeypatch.setattr(desktop_session.libreoffice, "find_soffice", lambda: "")+ monkeypatch.setattr(desktop_session.shutil, "which", lambda _name: "")+ monkeypatch.setattr(+ desktop_session,+ "_runtime_preparation_status",+ lambda: {"preparing": True, "active_count": 1, "started_at": 123.0},+ )++ status = desktop_session.collect_desktop_status()++ assert status["healthy"] is False+ assert status["installing"] is True+ assert status["state"] == "installing"+ assert status["message"].startswith("Installing Agent Zero Desktop runtime dependencies")+ assert "soffice" in status["missing"]++def test_desktop_gateway_patches_xpra_menu_script():source = (PROJECT_ROOT / "helpers" / "virtual_desktop_routes.py").read_text(encoding="utf-8")