Agent Zero AI framework
Persist Agent Zero Desktop lifecycle
Alessandro9390e42bcc57
diff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.pyindex 2d8ffbdda..2ec186b9c 100644--- a/plugins/_office/api/office_session.py+++ b/plugins/_office/api/office_session.py@@ -63,6 +63,8 @@ class OfficeSession(ApiHandler):return self._desktop_sync(input)if action == "desktop_state":return self._desktop_state(input)+ if action == "desktop_shutdown":+ return self._desktop_shutdown(input)return {"ok": False, "error": f"Unsupported office session action: {action}"}async def _open_document(self, doc: dict, input: dict, request: Request) -> dict:@@ -196,6 +198,13 @@ class OfficeSession(ApiHandler):include_screenshot = bool(input.get("include_screenshot") is True)return libreoffice_desktop.get_manager().state(include_screenshot=include_screenshot)+ def _desktop_shutdown(self, input: dict) -> dict:+ save_first = input.get("save_first") is not False+ return libreoffice_desktop.get_manager().shutdown_system_desktop(+ save_first=save_first,+ source=str(input.get("source") or "api"),+ )+def _origin(self, request: Request) -> str:origin = request.headers.get("Origin") or request.host_url.rstrip("/")return origin.rstrip("/")diff --git a/plugins/_office/extensions/webui/right-canvas-panels/office-panel.html b/plugins/_office/extensions/webui/right-canvas-panels/office-panel.htmlindex 694aed418..75dfb6b21 100644--- a/plugins/_office/extensions/webui/right-canvas-panels/office-panel.html+++ b/plugins/_office/extensions/webui/right-canvas-panels/office-panel.html@@ -2,7 +2,7 @@class="right-canvas-surface-panel office-canvas-surface"data-surface-id="office"x-show="$store.rightCanvas && $store.rightCanvas.isOpen && $store.rightCanvas.activeSurfaceId === 'office'"- x-effect="$store.office?.setDesktopHostVisible?.($store.rightCanvas && $store.rightCanvas.isOpen && $store.rightCanvas.activeSurfaceId === 'office')"+ x-effect="(() => { const visible = Boolean($store.rightCanvas && $store.rightCanvas.isOpen && $store.rightCanvas.activeSurfaceId === 'office'); (globalThis.queueMicrotask || ((callback) => globalThis.setTimeout(callback, 0)))(() => $store.office?.setDesktopHostVisible?.(visible)); })()"style="display: none;"><x-component path="/plugins/_office/webui/office-panel.html"></x-component>diff --git a/plugins/_office/helpers/libreoffice_desktop.py b/plugins/_office/helpers/libreoffice_desktop.pyindex 7e8cf7eff..1b5e1e0ab 100644--- a/plugins/_office/helpers/libreoffice_desktop.py+++ b/plugins/_office/helpers/libreoffice_desktop.py@@ -50,6 +50,10 @@ HIDDEN_XFCE_MENU_ENTRIES = (("exo-web-browser.desktop", "Web Browser"),("xfce4-mail-reader.desktop", "Mail Reader"),("xfce4-web-browser.desktop", "Web Browser"),+ ("xfce4-session-logout.desktop", "Log Out"),+ ("xfce4-lock-screen.desktop", "Lock Screen"),+ ("xflock4.desktop", "Lock Screen"),+ ("xfce4-switch-user.desktop", "Switch User"),)DESKTOP_README_SOURCE = Path(__file__).resolve().parents[1] / "assets" / "desktop" / "README.md"DESKTOP_FOLDER_LINKS = (@@ -61,6 +65,9 @@ DESKTOP_FOLDER_LINKS = (URL_INTENT_MAX_ITEMS = 50URL_INTENT_MAX_LENGTH = 8192URL_HANDLER_DESKTOP_ID = "agent-zero-browser.desktop"+SHUTDOWN_HANDLER_DESKTOP_ID = "agent-zero-shutdown.desktop"+SHUTDOWN_PANEL_LAUNCHER_ID = SHUTDOWN_HANDLER_DESKTOP_ID+SHUTDOWN_CONFIRM_SECONDS = 8OOR_NS = "http://openoffice.org/2001/registry"XS_NS = "http://www.w3.org/2001/XMLSchema"XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"@@ -197,6 +204,12 @@ class LibreOfficeDesktopManager:except Exception:passurl_intents = self.claim_url_intents(session.session_id)+ shutdown_request = self.claim_shutdown_request(session.session_id)+ if shutdown_request:+ return self.shutdown_system_desktop(+ save_first=True,+ source=str(shutdown_request.get("source") or "tray"),+ )doc = self._document_for_save(session, file_id)if not doc:return {@@ -224,6 +237,50 @@ class LibreOfficeDesktopManager:return []return _claim_url_intents(session)+ def claim_shutdown_request(self, session_id: str = SYSTEM_SESSION_ID) -> dict[str, Any] | None:+ session = self.get(session_id) or self.get(SYSTEM_SESSION_ID)+ if not session:+ return None+ return _claim_shutdown_request(session)++ def shutdown_system_desktop(self, *, save_first: bool = True, source: str = "api") -> dict[str, Any]:+ with self._lock:+ session = self._sessions.get(SYSTEM_SESSION_ID)+ if not session:+ _remove_system_manifest()+ return {+ "ok": True,+ "closed": 0,+ "session_id": SYSTEM_SESSION_ID,+ "shutdown": True,+ "intentional_shutdown": True,+ "source": source,+ }++ save_result = None+ if save_first:+ try:+ save_result = self.save(session.session_id)+ except Exception as exc:+ save_result = {"ok": False, "error": str(exc)}++ with self._lock:+ if self._sessions.get(SYSTEM_SESSION_ID) is session:+ self._sessions.pop(SYSTEM_SESSION_ID, None)+ virtual_desktop.unregister_session(session.token)+ self._terminate_session(session)+ self._remove_manifest(session.session_id)+ _clear_shutdown_request(session)+ return {+ "ok": True,+ "closed": 1,+ "session_id": session.session_id,+ "shutdown": True,+ "intentional_shutdown": True,+ "source": source,+ "save": save_result,+ }+def retarget_document(self, file_id: str, doc: dict[str, Any]) -> dict[str, Any]:session = self._find_by_file_id(file_id)if not session:@@ -643,6 +700,7 @@ class LibreOfficeDesktopManager:applications_dir.mkdir(parents=True, exist_ok=True)browser_bridge = _write_url_bridge_script(session)+ shutdown_bridge = _write_shutdown_bridge_script(session)helpers_rc = config_dir / "xfce4" / "helpers.rc"helpers_rc.parent.mkdir(parents=True, exist_ok=True)helpers_rc.write_text(@@ -672,6 +730,23 @@ class LibreOfficeDesktopManager:mime_types=_url_handler_mime_types(),no_display=True,)+ _write_desktop_launcher(+ applications_dir / SHUTDOWN_HANDLER_DESKTOP_ID,+ name="Shutdown Desktop",+ exec_line=_desktop_exec(shutdown_bridge),+ icon="system-shutdown",+ categories="System;",+ try_exec=str(shutdown_bridge),+ no_display=True,+ )+ _write_desktop_launcher(+ config_dir / "xfce4" / "panel" / "launcher-9" / SHUTDOWN_HANDLER_DESKTOP_ID,+ name="Shutdown Desktop",+ exec_line=_desktop_exec(shutdown_bridge),+ icon="system-shutdown",+ categories="System;",+ try_exec=str(shutdown_bridge),+ )_write_desktop_launcher(desktop_dir / "Browser.desktop",name="Browser",@@ -737,7 +812,9 @@ class LibreOfficeDesktopManager:ET.SubElement(plugins, "property", {"name": "plugin-6", "type": "string", "value": "separator"})ET.SubElement(plugins, "property", {"name": "plugin-7", "type": "string", "value": "clock"})ET.SubElement(plugins, "property", {"name": "plugin-8", "type": "string", "value": "separator"})- ET.SubElement(plugins, "property", {"name": "plugin-9", "type": "string", "value": "actions"})+ shutdown = ET.SubElement(plugins, "property", {"name": "plugin-9", "type": "string", "value": "launcher"})+ shutdown_items = ET.SubElement(shutdown, "property", {"name": "items", "type": "array"})+ ET.SubElement(shutdown_items, "value", {"type": "string", "value": SHUTDOWN_PANEL_LAUNCHER_ID})tree = ET.ElementTree(root)try:@@ -764,15 +841,7 @@ if command -v xfconf-query >/dev/null 2>&1; thenxfconf-query -c xfce4-desktop -p /desktop-icons/file-icons/show-filesystem -n -t bool -s false >/dev/null 2>&1 || truexfconf-query -c xfce4-desktop -p /desktop-icons/file-icons/show-removable -n -t bool -s false >/dev/null 2>&1 || truexfconf-query -c xfce4-desktop -p /desktop-icons/file-icons/show-trash -n -t bool -s false >/dev/null 2>&1 || true- xfconf-query -c xfce4-panel -p /panels -n -a -t int -s 1 >/dev/null 2>&1 || true- xfconf-query -c xfce4-panel -p /panels/panel-2 -r -R >/dev/null 2>&1 || true- xfconf-query -c xfce4-panel -p /panels/panel-1/plugin-ids -r -R >/dev/null 2>&1 || true- xfconf-query -c xfce4-panel -p /panels/panel-1/plugin-ids -n -a -t int -s 1 -t int -s 2 -t int -s 3 -t int -s 4 -t int -s 5 -t int -s 6 -t int -s 7 -t int -s 8 -t int -s 9 >/dev/null 2>&1 || true- for plugin_id in $(seq 10 30); do- xfconf-query -c xfce4-panel -p "/plugins/plugin-${plugin_id}" -r -R >/dev/null 2>&1 || true- donefi-rm -rf "$XDG_CONFIG_HOME"/xfce4/panel/launcher-* 2>/dev/null || truefor launcher in "$HOME"/Desktop/*.desktop; do[ -f "$launcher" ] || continuechmod +x "$launcher" 2>/dev/null || true@@ -1281,6 +1350,18 @@ def _url_bridge_lock_path(session: DesktopSession) -> Path:return _url_bridge_dir(session) / "browser-url-intents.lock"+def _shutdown_request_path(session: DesktopSession) -> Path:+ return _url_bridge_dir(session) / "shutdown-request.json"+++def _shutdown_arm_path(session: DesktopSession) -> Path:+ return _url_bridge_dir(session) / "shutdown-request.arm.json"+++def _shutdown_lock_path(session: DesktopSession) -> Path:+ return _url_bridge_dir(session) / "shutdown-request.lock"++def _write_url_bridge_script(session: DesktopSession) -> Path:bridge_dir = _url_bridge_dir(session)bridge_dir.mkdir(parents=True, exist_ok=True)@@ -1331,6 +1412,117 @@ if __name__ == "__main__":return script+def _write_shutdown_bridge_script(session: DesktopSession) -> Path:+ bridge_dir = _url_bridge_dir(session)+ bridge_dir.mkdir(parents=True, exist_ok=True)+ script = bridge_dir / "shutdown-desktop"+ request = _shutdown_request_path(session)+ arm = _shutdown_arm_path(session)+ lock = _shutdown_lock_path(session)+ script.write_text(+ f"""#!/usr/bin/env python3+import fcntl+import json+import os+import shutil+import subprocess+import time++REQUEST_PATH = {str(request)!r}+ARM_PATH = {str(arm)!r}+LOCK_PATH = {str(lock)!r}+CONFIRM_SECONDS = {SHUTDOWN_CONFIRM_SECONDS}+++def notify(message, timeout=None):+ if not os.environ.get("DISPLAY"):+ return+ xmessage = shutil.which("xmessage")+ if not xmessage:+ return+ try:+ subprocess.Popen(+ [+ xmessage,+ "-buttons",+ "",+ "-timeout",+ str(timeout or CONFIRM_SECONDS),+ "-center",+ message,+ ],+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ except OSError:+ pass+++def read_arm(now):+ try:+ with open(ARM_PATH, "r", encoding="utf-8") as handle:+ payload = json.load(handle)+ except (OSError, json.JSONDecodeError):+ return None+ try:+ created_at = float(payload.get("created_at"))+ except (TypeError, ValueError):+ return None+ if now - created_at > CONFIRM_SECONDS:+ return None+ return created_at+++def write_json_atomic(path, payload):+ tmp_path = path + ".tmp"+ with open(tmp_path, "w", encoding="utf-8") as handle:+ json.dump(payload, handle, ensure_ascii=True)+ handle.write("\\n")+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(tmp_path, path)+++def main():+ os.makedirs(os.path.dirname(REQUEST_PATH), exist_ok=True)+ now = time.time()+ with open(LOCK_PATH, "a+", encoding="utf-8") as lock_file:+ fcntl.flock(lock_file, fcntl.LOCK_EX)+ armed_at = read_arm(now)+ if armed_at is None:+ write_json_atomic(ARM_PATH, {{"created_at": now, "source": "tray"}})+ notify(+ f"Shutdown Desktop armed. Click Shutdown Desktop again within {{CONFIRM_SECONDS}} seconds to close it.",+ CONFIRM_SECONDS,+ )+ return+ try:+ os.unlink(ARM_PATH)+ except OSError:+ pass+ payload = {{+ "created_at": now,+ "armed_at": armed_at,+ "source": "tray",+ }}+ write_json_atomic(REQUEST_PATH, payload)+ notify("Shutting down Agent Zero Desktop.", 2)+++if __name__ == "__main__":+ main()+""",+ encoding="utf-8",+ )+ try:+ script.chmod(0o755)+ except OSError:+ pass+ return script++def _claim_url_intents(session: DesktopSession) -> list[dict[str, Any]]:queue = _url_bridge_queue_path(session)lock = _url_bridge_lock_path(session)@@ -1374,6 +1566,45 @@ def _claim_url_intents(session: DesktopSession) -> list[dict[str, Any]]:return intents+def _claim_shutdown_request(session: DesktopSession) -> dict[str, Any] | None:+ request = _shutdown_request_path(session)+ if not request.exists():+ return None+ try:+ raw = request.read_text(encoding="utf-8")+ request.unlink(missing_ok=True)+ except OSError:+ return None+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError:+ payload = {}+ created_at = payload.get("created_at")+ try:+ created_at = float(created_at)+ except (TypeError, ValueError):+ created_at = time.time()+ return {+ "created_at": created_at,+ "source": str(payload.get("source") or "tray"),+ }+++def _clear_shutdown_request(session: DesktopSession) -> None:+ request = _shutdown_request_path(session)+ arm = _shutdown_arm_path(session)+ lock = _shutdown_lock_path(session)+ request.unlink(missing_ok=True)+ request.with_suffix(request.suffix + ".tmp").unlink(missing_ok=True)+ arm.unlink(missing_ok=True)+ arm.with_suffix(arm.suffix + ".tmp").unlink(missing_ok=True)+ lock.unlink(missing_ok=True)+++def _remove_system_manifest() -> None:+ (SESSION_DIR / f"{SYSTEM_SESSION_ID}.json").unlink(missing_ok=True)++def _url_handler_mime_types() -> tuple[str, ...]:return ("x-scheme-handler/http",diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.htmlindex 4e364fc68..4dccc8e40 100644--- a/plugins/_office/webui/office-panel.html+++ b/plugins/_office/webui/office-panel.html@@ -103,16 +103,11 @@<div class="office-editor-wrap" x-show="$store.office.session" style="display: none;"><div class="office-editor-scroll" :class="{ 'is-desktop': $store.office.hasOfficialOffice(), 'is-source': $store.office.isMarkdown() }" @click.self="$store.office.focusEditor()"><template x-if="$store.office.hasOfficialOffice()">- <div class="office-desktop-wrap">- <iframe- class="office-desktop-frame"- data-office-desktop-frame- tabindex="0"- :src="$store.office.officialOfficeUrl()"- aria-label="Desktop"- allow="clipboard-read; clipboard-write; autoplay"- @load="$store.office.onDesktopFrameLoaded($event)"- ></iframe>+ <div+ class="office-desktop-wrap"+ data-office-desktop-host+ x-init="$nextTick(() => $store.office.mountDesktopFrameHost($el))"+ ></div></template>@@ -130,6 +125,15 @@</div></div>++ <div class="office-desktop-empty" x-show="$store.office.shouldShowDesktopEmptyState()" style="display: none;">+ <span class="material-symbols-outlined" aria-hidden="true">power_settings_new</span>+ <span class="office-desktop-empty-title">Desktop is shut down</span>+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.restartDesktopSession()">+ <span class="material-symbols-outlined" aria-hidden="true">restart_alt</span>+ <span class="office-button-label">Restart Desktop</span>+ </button>+ </div></div></div></template>@@ -460,10 +464,7 @@flex: 1 1 auto;min-height: 0;overflow: hidden;- background:- linear-gradient(90deg, rgba(44, 123, 229, 0.05), transparent 38%),- linear-gradient(180deg, rgba(44, 165, 141, 0.04), transparent 46%),- #eef2f7;+ background: var(--color-background);}.office-body.is-source {@@ -510,6 +511,29 @@background: #1f2329;}+ .office-desktop-empty {+ display: grid;+ flex: 1 1 auto;+ place-items: center;+ align-content: center;+ gap: 12px;+ min-width: 0;+ min-height: 0;+ padding: 24px;+ color: var(--color-text-secondary);+ text-align: center;+ }++ .office-desktop-empty > .material-symbols-outlined {+ font-size: 32px;+ color: color-mix(in srgb, var(--color-text) 68%, transparent);+ }++ .office-desktop-empty-title {+ font-size: 13px;+ font-weight: 700;+ }+.office-desktop-frame {flex: 1 1 auto;width: 100%;diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.jsindex d2b198767..f2e1cec71 100644--- a/plugins/_office/webui/office-store.js+++ b/plugins/_office/webui/office-store.js@@ -19,6 +19,7 @@ const SYSTEM_DESKTOP_FILE_ID = "system-desktop";const BROWSER_MODAL_PATH = "/plugins/_browser/webui/main.html";const OFFICE_MODAL_PATH = "/plugins/_office/webui/main.html";const URL_INTENT_PANEL_TIMEOUT_MS = 5000;+const DESKTOP_SHUTDOWN_STORAGE_KEY = "a0.office.desktopShutdown";const MAX_HISTORY = 80;function currentContextId() {@@ -236,8 +237,14 @@ const model = {_desktopStarting: null,_desktopUrlIntentBusy: false,_desktopUrlIntentQueue: [],+ _desktopFrame: null,+ _desktopFrameHost: null,+ _desktopFrameLoadHandler: null,+ _desktopKeepaliveHost: null,+ _desktopIntentionalShutdown: false,async init(element = null) {+ this.restoreDesktopShutdownState();return await this.onMount(element, { mode: "canvas" });},@@ -254,12 +261,18 @@ const model = {},async onOpen(payload = {}) {+ this.restoreDesktopShutdownState();await this.refresh();if (payload?.path || payload?.file_id) {await this.openSession({path: payload.path || "",file_id: payload.file_id || "",});+ } else if (this._desktopIntentionalShutdown) {+ this.session = null;+ this.activeTabId = "";+ this.editorText = "";+ this.dirty = false;} else {await this.ensureDesktopSession({ select: !this.session });}@@ -271,6 +284,9 @@ const model = {this._desktopHostVisible = false;this.flushInput();this.clearDesktopViewportSyncTimers();+ this.stopDesktopMonitor();+ this.stopDesktopKeyboardBridge();+ this.stopDesktopClipboardBridge();this.unloadDesktopFrames();},@@ -282,6 +298,7 @@ const model = {this.stopXpraDesktopPrime();this.stopDesktopKeyboardBridge();this.stopDesktopClipboardBridge();+ if (!this._desktopIntentionalShutdown) this.moveDesktopFrameToKeepalive();this._floatingCleanup?.();this._floatingCleanup = null;if (this._mode === "modal") this._root = null;@@ -297,7 +314,110 @@ const model = {}},+ restoreDesktopShutdownState() {+ try {+ this._desktopIntentionalShutdown = localStorage.getItem(DESKTOP_SHUTDOWN_STORAGE_KEY) === "1";+ } catch {+ this._desktopIntentionalShutdown = Boolean(this._desktopIntentionalShutdown);+ }+ },++ persistDesktopShutdownState() {+ try {+ if (this._desktopIntentionalShutdown) {+ localStorage.setItem(DESKTOP_SHUTDOWN_STORAGE_KEY, "1");+ } else {+ localStorage.removeItem(DESKTOP_SHUTDOWN_STORAGE_KEY);+ }+ } catch {+ // Shutdown state is still correct for this page even without storage.+ }+ },++ setDesktopIntentionalShutdown(value) {+ this._desktopIntentionalShutdown = Boolean(value);+ this.persistDesktopShutdownState();+ },++ isDesktopShutdown() {+ return Boolean(this._desktopIntentionalShutdown);+ },++ shouldShowDesktopEmptyState() {+ return Boolean(this._desktopIntentionalShutdown && !this.session);+ },++ async restartDesktopSession() {+ this.error = "";+ const session = await this.ensureDesktopSession({+ force: true,+ restart: true,+ select: true,+ message: "Restarting Agent Zero Desktop environment",+ });+ if (!session) {+ this.setDesktopIntentionalShutdown(true);+ return null;+ }+ this.restoreDesktopFrames();+ this.requestDesktopViewportSync({ force: true });+ return session;+ },++ async shutdownDesktop(options = {}) {+ this.loading = options.progress !== false;+ this.message = this.loading ? "Shutting down Desktop" : this.message;+ this.error = "";+ try {+ const response = await callOffice("desktop_shutdown", {+ save_first: options.saveFirst !== false,+ source: options.source || "ui",+ });+ await this.handleIntentionalDesktopShutdown(response);+ return response;+ } catch (error) {+ this.error = error instanceof Error ? error.message : String(error);+ return null;+ } finally {+ if (options.progress !== false) {+ this.loading = false;+ if (this.message === "Shutting down Desktop") this.message = "";+ }+ }+ },++ async handleIntentionalDesktopShutdown(response = {}) {+ this.setDesktopIntentionalShutdown(true);+ this.stopDesktopMonitor();+ this.stopDesktopResizeObserver();+ this.clearDesktopViewportSyncTimers();+ this.stopXpraDesktopPrime();+ this.stopDesktopKeyboardBridge();+ this.stopDesktopClipboardBridge();+ this.destroyDesktopFrame();+ const activeTabId = this.activeTabId;+ this.tabs = this.tabs.filter((tab) => !this.isDesktopSession(tab) && !this.hasOfficialOffice(tab));+ if (!this.tabs.some((tab) => tab.tab_id === activeTabId)) {+ this.session = null;+ this.activeTabId = "";+ this.editorText = "";+ this.dirty = false;+ this.resetHistory("");+ }+ this._desktopStarting = null;+ this._desktopHeartbeatMisses = 0;+ this.message = response?.source === "tray" ? "Desktop shut down from system tray" : "Desktop is shut down";+ await this.refresh();+ },+async ensureDesktopSession(options = {}) {+ if (this._desktopIntentionalShutdown && options.restart !== true) {+ return null;+ }+ if (options.restart === true) {+ this.setDesktopIntentionalShutdown(false);+ this.destroyDesktopFrame();+ }const existing = this.tabs.find((tab) => this.isDesktopSession(tab));if (existing && !options.force) {if (options.select) this.selectTab(existing.tab_id, { focus: false });@@ -323,6 +443,7 @@ const model = {}const response = await callOffice("desktop");if (response?.ok === false) throw new Error(response.error || "Desktop session could not be opened.");+ this.setDesktopIntentionalShutdown(false);const session = normalizeSession(response);const existingIndex = this.tabs.findIndex((tab) => this.isDesktopSession(tab));let desktopTabId = session.tab_id;@@ -347,6 +468,7 @@ const model = {} else {this.updateDesktopMonitor();}+ this.restoreDesktopFrames();return { ...session, tab_id: desktopTabId };} catch (error) {this.error = error instanceof Error ? error.message : String(error);@@ -434,6 +556,7 @@ const model = {},installDesktopDocumentSession(session) {+ this.setDesktopIntentionalShutdown(false);this.tabs = this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));let desktopTab = this.tabs.find((tab) => this.isDesktopSession(tab));if (!desktopTab) {@@ -468,12 +591,19 @@ const model = {selectTab(tabId, options = {}) {const tab = this.tabs.find((item) => item.tab_id === tabId) || this.tabs[0] || null;+ if (this.hasOfficialOffice(this.session) && !this.hasOfficialOffice(tab)) {+ this.moveDesktopFrameToKeepalive();+ }this.session = tab;this.activeTabId = tab?.tab_id || "";this.editorText = String(tab?.text || "");this.dirty = Boolean(tab?.dirty);this.resetHistory(this.editorText);this.queueRender({ focus: Boolean(tab) && options.focus !== false });+ if (this.hasOfficialOffice(tab)) {+ this.restoreDesktopFrames();+ this.requestDesktopViewportSync({ force: true });+ }this.updateDesktopMonitor();},@@ -898,9 +1028,11 @@ const model = {},desktopFrames() {- const frames = Array.from(document.querySelectorAll("[data-office-desktop-frame]"));- const rootFrame = this._root?.querySelector?.("[data-office-desktop-frame]");- if (rootFrame && !frames.includes(rootFrame)) frames.push(rootFrame);+ const frames = [];+ if (this._desktopFrame) frames.push(this._desktopFrame);+ for (const frame of Array.from(document.querySelectorAll("[data-office-desktop-frame]"))) {+ if (!frames.includes(frame)) frames.push(frame);+ }return frames;},@@ -924,29 +1056,149 @@ const model = {})[0] || null;},+ isUsableDesktopHost(host) {+ if (!host?.appendChild) return false;+ const rect = host.getBoundingClientRect?.();+ return Boolean(rect && rect.width >= 120 && rect.height >= 80);+ },++ desktopHost(preferred = null) {+ if (preferred?.matches?.("[data-office-desktop-host]")) return preferred;+ const rootHost = this._root?.querySelector?.("[data-office-desktop-host]");+ if (this.isUsableDesktopHost(rootHost)) return rootHost;+ const hosts = Array.from(document.querySelectorAll("[data-office-desktop-host]"));+ return hosts+ .filter((host) => this.isUsableDesktopHost(host))+ .sort((left, right) => {+ const leftRect = left.getBoundingClientRect();+ const rightRect = right.getBoundingClientRect();+ return (rightRect.width * rightRect.height) - (leftRect.width * leftRect.height);+ })[0] || rootHost || hosts[0] || null;+ },++ ensureDesktopKeepaliveHost() {+ if (this._desktopKeepaliveHost?.isConnected) return this._desktopKeepaliveHost;+ const host = document.createElement("div");+ host.className = "office-desktop-keepalive";+ host.dataset.officeDesktopKeepalive = "true";+ Object.assign(host.style, {+ position: "fixed",+ left: "-10000px",+ top: "-10000px",+ width: "720px",+ height: "480px",+ overflow: "hidden",+ pointerEvents: "none",+ visibility: "hidden",+ });+ document.body?.appendChild(host);+ this._desktopKeepaliveHost = host;+ return host;+ },++ rememberDesktopFrameSize() {+ const frame = this._desktopFrame;+ const rect = frame?.getBoundingClientRect?.();+ const hostRect = this._desktopFrameHost?.getBoundingClientRect?.();+ const width = Math.round(rect?.width || hostRect?.width || 720);+ const height = Math.round(rect?.height || hostRect?.height || 480);+ const keepalive = this.ensureDesktopKeepaliveHost();+ keepalive.style.width = `${Math.max(320, width)}px`;+ keepalive.style.height = `${Math.max(220, height)}px`;+ return keepalive;+ },++ ensureDesktopFrame() {+ if (this._desktopFrame) return this._desktopFrame;+ const frame = document.createElement("iframe");+ frame.className = "office-desktop-frame";+ frame.dataset.officeDesktopFrame = "true";+ frame.dataset.officePersistentDesktopFrame = "true";+ frame.setAttribute("tabindex", "0");+ frame.setAttribute("aria-label", "Desktop");+ frame.setAttribute("allow", "clipboard-read; clipboard-write; autoplay");+ this._desktopFrameLoadHandler = (event) => this.onDesktopFrameLoaded(event);+ frame.addEventListener("load", this._desktopFrameLoadHandler);+ this._desktopFrame = frame;+ return frame;+ },++ desktopFrameSrcMatches(frame, url) {+ const current = frame?.getAttribute?.("src") || frame?.src || "";+ if (!current && !url) return true;+ try {+ return new URL(current, window.location.href).href === new URL(url, window.location.href).href;+ } catch {+ return current === url;+ }+ },++ attachDesktopFrame(host = null) {+ if (!this.hasOfficialOffice()) return false;+ const target = this.desktopHost(host);+ if (!target) return false;+ const frame = this.ensureDesktopFrame();+ if (frame.parentElement !== target) {+ frame.parentElement?.removeAttribute?.("data-office-desktop-attached");+ target.appendChild(frame);+ }+ target.dataset.officeDesktopAttached = "true";+ if (this._desktopFrameHost !== target) this._desktopFrameHost = target;+ const url = this.officialOfficeUrl();+ if (url && !this.desktopFrameSrcMatches(frame, url)) {+ frame.setAttribute("src", url);+ }+ return true;+ },++ mountDesktopFrameHost(host = null) {+ const attached = this.attachDesktopFrame(host);+ if (attached && this.isDesktopHostVisible()) {+ this.requestDesktopViewportSync({ force: true, frame: this._desktopFrame, followup: true });+ }+ return attached;+ },++ moveDesktopFrameToKeepalive() {+ const frame = this._desktopFrame;+ if (!frame) return false;+ const keepalive = this.rememberDesktopFrameSize();+ if (frame.parentElement !== keepalive) {+ frame.parentElement?.removeAttribute?.("data-office-desktop-attached");+ keepalive.appendChild(frame);+ }+ this._desktopFrameHost = keepalive;+ this._desktopKeyboardActive = false;+ this.updateDesktopKeyboardCaptureState(frame);+ return true;+ },++ destroyDesktopFrame() {+ const frame = this._desktopFrame;+ if (!frame) return;+ if (this._desktopFrameLoadHandler) {+ frame.removeEventListener("load", this._desktopFrameLoadHandler);+ }+ frame.setAttribute("src", "about:blank");+ frame.remove();+ this._desktopFrame = null;+ this._desktopFrameHost = null;+ this._desktopFrameLoadHandler = null;+ this._desktopBridgeReady = false;+ this.updateDesktopKeyboardCaptureState();+ this._desktopKeepaliveHost?.remove?.();+ this._desktopKeepaliveHost = null;+ },+unloadDesktopFrames() {this.stopDesktopResizeObserver();this.stopXpraDesktopPrime();- for (const frame of this.desktopFrames()) {- if (!frame?.getAttribute) continue;- const current = frame.getAttribute("src") || "";- if (!current || current === "about:blank") continue;- frame.dataset.officeDesktopUnloaded = "true";- frame.setAttribute("src", "about:blank");- }+ this.moveDesktopFrameToKeepalive();},restoreDesktopFrames() {if (!this.isDesktopHostVisible()) return;- const url = this.officialOfficeUrl();- if (!url) return;- for (const frame of this.desktopFrames()) {- if (!frame?.getAttribute) continue;- const current = frame.getAttribute("src") || "";- if (current && current !== "about:blank" && frame.dataset.officeDesktopUnloaded !== "true") continue;- delete frame.dataset.officeDesktopUnloaded;- frame.setAttribute("src", url);- }+ this.attachDesktopFrame();},afterDesktopHostShown() {@@ -1908,6 +2160,10 @@ const model = {desktop_session_id: sessionId,file_id: this.session.file_id || "",});+ if (response?.intentional_shutdown || response?.shutdown) {+ await this.handleIntentionalDesktopShutdown(response);+ return;+ }if (response?.ok === false) throw new Error(response.error || "Desktop session closed.");this._desktopHeartbeatMisses = 0;await this.handleDesktopUrlIntents(response?.url_intents);@@ -1945,6 +2201,7 @@ const model = {},async handleOfficialOfficeClosed(tabId) {+ if (this._desktopIntentionalShutdown) return;const tab = this.tabs.find((item) => item.tab_id === tabId);const hiddenDesktopDocument = !tab && this.session?.tab_id === tabId && this.isDesktopOfficeDocument(this.session)? this.sessiondiff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.pyindex c13e974a2..7cb34def0 100644--- a/tests/test_office_canvas_setup.py+++ b/tests/test_office_canvas_setup.py@@ -22,9 +22,12 @@ def test_document_canvas_uses_markdown_editor_and_official_libreoffice_desktop_fassert "office-rich-editor" not in panelassert "office-docx-pages" not in panelassert "office-desktop-frame" in panel- assert "data-office-desktop-frame" in panel+ assert "data-office-desktop-host" in panel+ assert 'x-init="$nextTick(() => $store.office.mountDesktopFrameHost($el))"' in panel+ assert 'x-effect="$store.office.attachDesktopFrame($el)"' not in panel+ assert "data-office-desktop-frame" in storeassert 'title="LibreOffice desktop"' not in panel- assert 'aria-label="Desktop"' in panel+ assert 'frame.setAttribute("aria-label", "Desktop")' in storeassert "office-command-button" in panelassert "office-button-label" in panelassert "grid-template-columns: minmax(0, 1fr) auto auto auto" in panel@@ -32,7 +35,7 @@ def test_document_canvas_uses_markdown_editor_and_official_libreoffice_desktop_fassert ".modal-inner.office-modal .modal-scroll" in panelassert "office-modal-resizer" in panelassert "resize: both" not in panel- assert 'tabindex="0"' in panel+ assert 'frame.setAttribute("tabindex", "0")' in storeassert "format_underlined" not in panelassert "format_align_center" not in panelassert "is-native-tile" not in panel@@ -55,6 +58,7 @@ def test_document_canvas_uses_markdown_editor_and_official_libreoffice_desktop_fassert "isDesktopHostVisible" in storeassert "clearDesktopViewportSyncTimers" in storeassert "setDesktopHostVisible" in canvas_panel+ assert "queueMicrotask" in canvas_panelassert "Starting Agent Zero Desktop environment" in storeassert "handleOfficialOfficeClosed" in storeassert "ResizeObserver" in store@@ -67,8 +71,22 @@ def test_document_canvas_uses_markdown_editor_and_official_libreoffice_desktop_fassert "right-canvas-resize-end" in storeassert "isDesktopSession" in storeassert "desktopFrame" in store+ assert "attachDesktopFrame" in store+ assert "mountDesktopFrameHost" in store+ assert "desktopFrameSrcMatches" in store+ assert "moveDesktopFrameToKeepalive" in store+ assert "destroyDesktopFrame" in store+ assert "office-desktop-keepalive" in store+ assert "DESKTOP_SHUTDOWN_STORAGE_KEY" in store+ assert 'callOffice("desktop_shutdown"' in store+ assert "intentional_shutdown" in store+ assert "restartDesktopSession" in store+ assert "shouldShowDesktopEmptyState" in store+ assert "Restart Desktop" in panel+ assert "office-desktop-empty" in panelassert "unloadDesktopFrames" in storeassert "restoreDesktopFrames" in store+ assert "officeDesktopUnloaded" not in storeassert "primeXpraDesktopFrame" in storeassert "normalizeXpraDesktopWindow" in storeassert "installXpraDesktopWheelBridge" in store@@ -306,11 +324,21 @@ def test_official_libreoffice_desktop_route_and_packages_are_declared():assert "DESKTOP_FOLDER_LINKS" in desktopassert "HIDDEN_XPRA_DESKTOP_ENTRIES" in desktopassert "HIDDEN_XFCE_MENU_ENTRIES" in desktop+ assert "SHUTDOWN_HANDLER_DESKTOP_ID" in desktop+ assert "SHUTDOWN_PANEL_LAUNCHER_ID" in desktop+ assert "SHUTDOWN_CONFIRM_SECONDS" in desktop+ assert "Shutdown Desktop" in desktop+ assert "shutdown-request.json" in desktop+ assert "shutdown-request.arm.json" in desktop+ assert "shutdown_system_desktop" in desktop+ assert "claim_shutdown_request" in desktopassert "last-show-hidden" in desktopassert "exo-mail-reader.desktop" in desktopassert "exo-web-browser.desktop" in desktopassert "xfce4-mail-reader.desktop" in desktopassert "xfce4-web-browser.desktop" in desktop+ assert "xfce4-session-logout.desktop" in desktop+ assert "agent-zero-shutdown.desktop" in desktopassert "libreoffice-gtk3" in installassert "libreofficekit" not in installassert "gir1.2-lokdocview" not in installdiff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex 6f6bca34e..b21ff9a8d 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -4,6 +4,7 @@ import asyncioimport importlib.utilimport jsonimport os+import subprocessimport sysimport typesimport zipfile@@ -554,6 +555,51 @@ def test_office_session_desktop_state_action_defaults_without_screenshot(monkeypmonkeypatch.delattr(api_package, "office_session", raising=False)+def test_office_session_desktop_shutdown_action_calls_manager(monkeypatch):+ api_module = types.ModuleType("helpers.api")++ class ApiHandler:+ def __init__(self, app=None, thread_lock=None):+ self.app = app+ self.thread_lock = thread_lock++ api_module.ApiHandler = ApiHandler+ api_module.Request = object+ monkeypatch.setitem(sys.modules, "helpers.api", api_module)+ monkeypatch.delitem(sys.modules, "plugins._office.api.office_session", raising=False)++ from plugins._office.api import office_session++ calls = []++ class FakeManager:+ def shutdown_system_desktop(self, *, save_first=True, source="api"):+ calls.append({"save_first": save_first, "source": source})+ return {+ "ok": True,+ "closed": 1,+ "shutdown": True,+ "intentional_shutdown": True,+ "source": source,+ }++ monkeypatch.setattr(office_session.libreoffice_desktop, "get_manager", lambda: FakeManager())+ handler = office_session.OfficeSession(app=None, thread_lock=None)+ request = types.SimpleNamespace(headers={}, host_url="http://localhost:32080")++ result = asyncio.run(+ handler.process({"action": "desktop_shutdown", "save_first": False, "source": "ui"}, request),+ )++ assert result["ok"] is True+ assert result["intentional_shutdown"] is True+ assert calls == [{"save_first": False, "source": "ui"}]+ monkeypatch.delitem(sys.modules, "plugins._office.api.office_session", raising=False)+ api_package = sys.modules.get("plugins._office.api")+ if api_package is not None:+ monkeypatch.delattr(api_package, "office_session", raising=False)++def test_official_libreoffice_desktop_manager_opens_binary_session(office_state, tmp_path, monkeypatch):class FakeProcess:pid = 4242@@ -704,7 +750,47 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,).read_text(encoding="utf-8")assert "panel-1" in panel_profileassert "panel-2" not in panel_profile- assert "launcher" not in panel_profile+ assert 'value="actions"' not in panel_profile+ assert 'value="launcher"' in panel_profile+ assert "agent-zero-shutdown.desktop" in panel_profile+ shutdown_app = (+ tmp_path+ / "desktop"+ / "profiles"+ / payload["session_id"]+ / ".local"+ / "share"+ / "applications"+ / "agent-zero-shutdown.desktop"+ ).read_text(encoding="utf-8")+ assert "Shutdown Desktop" in shutdown_app+ assert "shutdown-desktop" in shutdown_app+ shutdown_panel_launcher = (+ tmp_path+ / "desktop"+ / "profiles"+ / payload["session_id"]+ / ".config"+ / "xfce4"+ / "panel"+ / "launcher-9"+ / "agent-zero-shutdown.desktop"+ ).read_text(encoding="utf-8")+ assert "Shutdown Desktop" in shutdown_panel_launcher+ assert "shutdown-desktop" in shutdown_panel_launcher+ shutdown_script = (+ tmp_path+ / "desktop"+ / "profiles"+ / payload["session_id"]+ / ".agent-zero"+ / "shutdown-desktop"+ ).read_text(encoding="utf-8")+ assert "CONFIRM_SECONDS" in shutdown_script+ assert "ARM_PATH" in shutdown_script+ assert "Click Shutdown Desktop again" in shutdown_script+ assert "xmessage" in shutdown_script+ assert '"-buttons",' in shutdown_scriptdesktop_helper = (PROJECT_ROOT / "plugins" / "_office" / "helpers" / "libreoffice_desktop.py").read_text(encoding="utf-8")@@ -731,11 +817,17 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,assert "agent-zero-settings.desktop" not in profile_scriptassert "metadata::xfce-exe-checksum" in profile_scriptassert "xfconf-query -c thunar -p /last-show-hidden" in profile_script+ assert "xfconf-query -c xfce4-panel" not in profile_script+ assert "launcher-*" not in profile_scriptfor filename in ("exo-mail-reader.desktop","exo-web-browser.desktop","xfce4-mail-reader.desktop","xfce4-web-browser.desktop",+ "xfce4-session-logout.desktop",+ "xfce4-lock-screen.desktop",+ "xflock4.desktop",+ "xfce4-switch-user.desktop",):entry = (tmp_path@@ -754,6 +846,106 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,assert manager.close(payload["session_id"], save_first=False)["persistent"] is True+def test_shutdown_panel_launcher_requires_second_click(tmp_path):+ profile_dir = tmp_path / "desktop" / "profiles" / libreoffice_desktop.SYSTEM_SESSION_ID+ profile_dir.mkdir(parents=True)+ desktop_path = tmp_path / "workdir"+ desktop_path.mkdir()+ session = libreoffice_desktop.DesktopSession(+ session_id=libreoffice_desktop.SYSTEM_SESSION_ID,+ file_id=libreoffice_desktop.SYSTEM_FILE_ID,+ extension="desktop",+ path=str(desktop_path),+ title=libreoffice_desktop.SYSTEM_TITLE,+ display=libreoffice_desktop.DISPLAY_BASE,+ xpra_port=libreoffice_desktop.XPRA_PORT_BASE,+ token=libreoffice_desktop.SYSTEM_SESSION_ID,+ url="/desktop/session/agent-zero-desktop/index.html",+ profile_dir=profile_dir,+ )+ script = libreoffice_desktop._write_shutdown_bridge_script(session)+ request = libreoffice_desktop._shutdown_request_path(session)+ arm = libreoffice_desktop._shutdown_arm_path(session)+ env = dict(os.environ)+ env.pop("DISPLAY", None)++ subprocess.run([sys.executable, str(script)], check=True, env=env)++ assert arm.exists()+ assert not request.exists()++ subprocess.run([sys.executable, str(script)], check=True, env=env)++ payload = json.loads(request.read_text(encoding="utf-8"))+ assert payload["source"] == "tray"+ assert payload["armed_at"] <= payload["created_at"]+ assert not arm.exists()+++def test_libreoffice_desktop_sync_consumes_shutdown_marker(tmp_path, monkeypatch):+ class FakeProcess:+ pid = 5252+ terminated = False++ def poll(self):+ return None if not self.terminated else 0++ def terminate(self):+ self.terminated = True++ def wait(self, timeout=None):+ self.terminated = True+ return 0++ def kill(self):+ self.terminated = True++ monkeypatch.setattr(libreoffice_desktop, "STATE_DIR", tmp_path / "desktop")+ monkeypatch.setattr(libreoffice_desktop, "SESSION_DIR", tmp_path / "desktop" / "sessions")+ monkeypatch.setattr(libreoffice_desktop, "PROFILE_DIR", tmp_path / "desktop" / "profiles")++ profile_dir = tmp_path / "desktop" / "profiles" / libreoffice_desktop.SYSTEM_SESSION_ID+ profile_dir.mkdir(parents=True)+ desktop_path = tmp_path / "workdir"+ desktop_path.mkdir()+ session = libreoffice_desktop.DesktopSession(+ session_id=libreoffice_desktop.SYSTEM_SESSION_ID,+ file_id=libreoffice_desktop.SYSTEM_FILE_ID,+ extension="desktop",+ path=str(desktop_path),+ title=libreoffice_desktop.SYSTEM_TITLE,+ display=libreoffice_desktop.DISPLAY_BASE,+ xpra_port=libreoffice_desktop.XPRA_PORT_BASE,+ token=libreoffice_desktop.SYSTEM_SESSION_ID,+ url="/desktop/session/agent-zero-desktop/index.html",+ profile_dir=profile_dir,+ processes={"xpra": FakeProcess()},+ )+ manager = libreoffice_desktop.LibreOfficeDesktopManager()+ manager._sessions[session.session_id] = session+ manager._write_manifest(session)+ libreoffice_desktop._write_url_bridge_script(session)+ shutdown_request = libreoffice_desktop._shutdown_request_path(session)+ shutdown_request.write_text('{"source": "tray", "created_at": 123.0}\n', encoding="utf-8")+ save_calls = []+ monkeypatch.setattr(+ manager,+ "save",+ lambda session_id, file_id="": save_calls.append((session_id, file_id)) or {"ok": True},+ )++ result = manager.sync(session_id=session.session_id)++ assert result["ok"] is True+ assert result["intentional_shutdown"] is True+ assert result["source"] == "tray"+ assert result["closed"] == 1+ assert save_calls == [(libreoffice_desktop.SYSTEM_SESSION_ID, "")]+ assert not shutdown_request.exists()+ assert not (libreoffice_desktop.SESSION_DIR / f"{session.session_id}.json").exists()+ assert manager.get(session.session_id) is None++def test_libreoffice_desktop_cleanup_preserves_live_owner_manifest(tmp_path, monkeypatch):session_dir = tmp_path / "sessions"session_dir.mkdir()