Skip to content

Agent Zero AI framework

Reduce Office to document ownership

Alessandro0c08fa65f31c
diff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.py
index 69691c24d..b78a799d7 100644
--- a/plugins/_office/api/office_session.py
+++ b/plugins/_office/api/office_session.py
@@ -1,7 +1,8 @@
from __future__ import annotations
from helpers.api import ApiHandler, Request
-from plugins._office.helpers import document_store, libreoffice, libreoffice_desktop, markdown_sessions
+from plugins._desktop.helpers import desktop_session
+from plugins._office.helpers import document_store, libreoffice, markdown_sessions
class OfficeSession(ApiHandler):
@@ -14,6 +15,7 @@ class OfficeSession(ApiHandler):
if action == "home":
return {"ok": True, "path": document_store.default_open_path(context_id)}
if action == "desktop":
+ # Compatibility only. New Desktop callers use /plugins/_desktop/desktop_session.
return self._desktop()
if action == "close":
closed = document_store.close_session(
@@ -58,30 +60,47 @@ class OfficeSession(ApiHandler):
if action == "renamed":
return self._renamed(input, context_id)
if action == "desktop_save":
+ # Compatibility only. New Desktop callers use /plugins/_desktop/desktop_session.
return self._desktop_save(input)
if action == "desktop_sync":
+ # Compatibility only. New Desktop callers use /plugins/_desktop/desktop_session.
return self._desktop_sync(input)
if action == "desktop_state":
+ # Compatibility only. New Desktop callers use /plugins/_desktop/desktop_session.
return self._desktop_state(input)
if action == "desktop_shutdown":
+ # Compatibility only. New Desktop callers use /plugins/_desktop/desktop_session.
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:
mode = "edit" if str(input.get("mode") or "edit").lower() == "edit" else "view"
- store_session = document_store.create_session(
- doc["file_id"],
- user_id=str(input.get("user_id") or "agent-zero-user"),
- permission="write" if mode == "edit" else "read",
- origin=self._origin(request),
- )
- if str(doc.get("extension") or "").lower() in libreoffice_desktop.OFFICIAL_EXTENSIONS:
- desktop = libreoffice_desktop.get_manager().open(doc, refresh=input.get("refresh") is True)
+ if str(doc.get("extension") or "").lower() in desktop_session.OFFICIAL_EXTENSIONS:
+ if input.get("open_in_desktop") is not True:
+ return {
+ "ok": True,
+ "requires_desktop": True,
+ "file_id": doc["file_id"],
+ "title": doc["basename"],
+ "extension": doc["extension"],
+ "path": doc["path"],
+ "text": "",
+ "document": _public_doc(doc),
+ "version": document_store.item_version(doc),
+ "mode": mode,
+ }
+ store_session = document_store.create_session(
+ doc["file_id"],
+ user_id=str(input.get("user_id") or "agent-zero-user"),
+ permission="write" if mode == "edit" else "read",
+ origin=self._origin(request),
+ )
+ desktop = desktop_session.get_manager().open(doc, refresh=input.get("refresh") is True)
if not desktop.get("available"):
document_store.close_session(session_id=store_session["session_id"])
return {
"ok": False,
- "error": desktop.get("error") or desktop.get("reason") or "Official LibreOffice desktop session is unavailable.",
+ "error": desktop.get("error") or desktop.get("reason") or "Desktop session is unavailable.",
"desktop": desktop,
"libreoffice": libreoffice.collect_status(),
}
@@ -100,6 +119,12 @@ class OfficeSession(ApiHandler):
"store_session_id": store_session["session_id"],
"mode": mode,
}
+ store_session = document_store.create_session(
+ doc["file_id"],
+ user_id=str(input.get("user_id") or "agent-zero-user"),
+ permission="write" if mode == "edit" else "read",
+ origin=self._origin(request),
+ )
try:
editor = markdown_sessions.get_manager().open(doc, sid="")
except ValueError as exc:
@@ -135,8 +160,8 @@ class OfficeSession(ApiHandler):
except Exception as exc:
return {"ok": False, "error": str(exc)}
desktop = None
- if str(updated.get("extension") or "").lower() in libreoffice_desktop.OFFICIAL_EXTENSIONS:
- desktop = libreoffice_desktop.get_manager().retarget_document(file_id, updated)
+ if str(updated.get("extension") or "").lower() in desktop_session.OFFICIAL_EXTENSIONS:
+ desktop = desktop_session.get_manager().retarget_document(file_id, updated)
return {
"ok": True,
"document": _public_doc(updated),
@@ -146,7 +171,7 @@ class OfficeSession(ApiHandler):
}
def _desktop(self) -> dict:
- desktop = libreoffice_desktop.get_manager().ensure_system_desktop()
+ desktop = desktop_session.get_manager().ensure_system_desktop()
if not desktop.get("available"):
return {
"ok": False,
@@ -155,7 +180,7 @@ class OfficeSession(ApiHandler):
"libreoffice": libreoffice.collect_status(),
}
document = {
- "file_id": libreoffice_desktop.SYSTEM_FILE_ID,
+ "file_id": desktop_session.SYSTEM_FILE_ID,
"path": desktop["path"],
"basename": desktop["title"],
"title": desktop["title"],
@@ -167,7 +192,7 @@ class OfficeSession(ApiHandler):
"ok": True,
"session_id": desktop["session_id"],
"desktop_session_id": desktop["session_id"],
- "file_id": libreoffice_desktop.SYSTEM_FILE_ID,
+ "file_id": desktop_session.SYSTEM_FILE_ID,
"title": desktop["title"],
"extension": "desktop",
"path": desktop["path"],
@@ -183,24 +208,24 @@ class OfficeSession(ApiHandler):
session_id = str(input.get("desktop_session_id") or input.get("session_id") or "").strip()
if not session_id:
return {"ok": False, "error": "desktop_session_id is required."}
- return libreoffice_desktop.get_manager().save(
+ return desktop_session.get_manager().save(
session_id,
file_id=str(input.get("file_id") or ""),
)
def _desktop_sync(self, input: dict) -> dict:
- return libreoffice_desktop.get_manager().sync(
+ return desktop_session.get_manager().sync(
session_id=str(input.get("desktop_session_id") or input.get("session_id") or ""),
file_id=str(input.get("file_id") or ""),
)
def _desktop_state(self, input: dict) -> dict:
include_screenshot = bool(input.get("include_screenshot") is True)
- return libreoffice_desktop.get_manager().state(include_screenshot=include_screenshot)
+ return desktop_session.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(
+ return desktop_session.get_manager().shutdown_system_desktop(
save_first=save_first,
source=str(input.get("source") or "api"),
)
diff --git a/plugins/_office/extensions/webui/lib/document-actions.js b/plugins/_office/extensions/webui/lib/document-actions.js
index 2b26c9f95..f9abba1ba 100644
--- a/plugins/_office/extensions/webui/lib/document-actions.js
+++ b/plugins/_office/extensions/webui/lib/document-actions.js
@@ -2,6 +2,9 @@ import {
createActionButton,
copyToClipboard,
} from "/components/messages/action-buttons/simple-action-buttons.js";
+import { ensureModalOpen } from "/js/modals.js";
+import { open as openSurface } from "/js/surfaces.js";
+import { store as officeStore } from "/plugins/_office/webui/office-store.js";
function basename(path = "") {
const value = String(path || "").split("?")[0].split("#")[0];
@@ -33,10 +36,8 @@ export function documentFromLog(args = {}, result = {}) {
};
}
-export async function openOfficeCanvas(kvps = {}) {
- const canvas = globalThis.Alpine?.store?.("rightCanvas")
- || (await import("/components/canvas/right-canvas-store.js")).store;
- await canvas?.open?.("office", {
+export async function openDocumentInDesktop(kvps = {}) {
+ await openSurface("desktop", {
path: kvps.path || "",
file_id: kvps.file_id || "",
refresh: true,
@@ -44,6 +45,33 @@ export async function openOfficeCanvas(kvps = {}) {
});
}
+export async function openDocumentArtifact(kvps = {}) {
+ if (usesDesktop(kvps)) {
+ await openDocumentInDesktop(kvps);
+ return;
+ }
+ await ensureModalOpen("/plugins/_office/webui/main.html");
+ await officeStore.openSession?.({
+ path: kvps.path || "",
+ file_id: kvps.file_id || "",
+ refresh: true,
+ source: "message-action",
+ });
+}
+
+function usesDesktop(doc = {}) {
+ const format = String(doc.format || doc.extension || "").toLowerCase();
+ return ["odt", "ods", "odp", "docx", "xlsx", "pptx"].includes(format);
+}
+
+function desktopActionLabel(doc = {}) {
+ const format = String(doc.format || doc.extension || "").toLowerCase();
+ if (["odt", "docx"].includes(format)) return "Edit in Writer";
+ if (["ods", "xlsx"].includes(format)) return "Edit in Calc";
+ if (["odp", "pptx"].includes(format)) return "Edit in Impress";
+ return "Open Document";
+}
+
export function downloadDocument(doc = {}) {
const path = String(doc.path || "");
if (!path) return;
@@ -59,7 +87,8 @@ export function buildDocumentFileActionButtons(document = {}) {
const hasTarget = Boolean(document?.path || document?.file_id);
const buttons = [];
if (hasTarget) {
- buttons.push(createActionButton("dock_to_right", "Open in canvas", () => openOfficeCanvas(document)));
+ const icon = usesDesktop(document) ? "desktop_windows" : "article";
+ buttons.push(createActionButton(icon, desktopActionLabel(document), () => openDocumentArtifact(document)));
}
if (document?.path) {
buttons.push(
diff --git a/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js b/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js
index 755073992..360233cda 100644
--- a/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js
+++ b/plugins/_office/extensions/webui/set_messages_after_loop/auto-open-document-results.js
@@ -1,14 +1,18 @@
+import { store as officeStore } from "/plugins/_office/webui/office-store.js";
+import { ensureModalOpen } from "/js/modals.js";
+import { open as openSurface } from "/js/surfaces.js";
+
const SYNC_WINDOW_MS = 10 * 60 * 1000;
-const DESKTOP_OFFICE_FORMATS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);
+const DESKTOP_DOCUMENT_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);
const syncedDocumentResults = new Set();
-export default async function syncDocumentResultsIntoOpenCanvas(context) {
+export default async function syncDocumentResultsIntoOpenOfficeModal(context) {
if (!context?.results?.length || context.historyEmpty) return;
for (const { args } of context.results) {
const payload = getDocumentPayload(args);
if (getToolName(payload) !== "document_artifact") continue;
- if (!shouldSyncOpenOfficeCanvas(args, payload)) continue;
+ if (!shouldSyncOpenOfficeModal(args, payload)) continue;
const document = payload.document && typeof payload.document === "object" ? payload.document : {};
const path = payload.path || document.path || "";
@@ -25,14 +29,16 @@ export default async function syncDocumentResultsIntoOpenCanvas(context) {
if (syncedDocumentResults.has(key)) continue;
syncedDocumentResults.add(key);
- if (!isOfficeCanvasOrModalOpen() && shouldColdOpenOfficeCanvas(payload, document)) {
- await openOfficeCanvasFromResult({ path, file_id: fileId });
+ if (shouldOpenDocumentUiFromResult(payload, document)) {
+ globalThis.setTimeout(() => {
+ void openDocumentUiFromResult({ path, file_id: fileId }, payload, document);
+ }, 0);
continue;
}
globalThis.setTimeout(async () => {
- if (!isOfficeCanvasOrModalOpen()) return;
- const office = globalThis.Alpine?.store?.("office");
+ if (!isOfficeModalOpen()) return;
+ const office = officeStore;
if (!office || isDirtySameDocument(office, { path, file_id: fileId })) return;
await office.openSession?.({
path,
@@ -63,8 +69,14 @@ function pickPayloadFields(args = {}) {
"tool_name",
"action",
"canvas_surface",
+ "extension",
"file_id",
"format",
+ "open_canvas",
+ "open_document",
+ "open_desktop",
+ "open_in_canvas",
+ "open_in_desktop",
"path",
"version",
"last_modified",
@@ -78,54 +90,62 @@ function getToolName(payload = {}) {
return String(payload._tool_name || payload.tool_name || "").trim();
}
-function shouldSyncOpenOfficeCanvas(args = {}, payload = {}) {
+function shouldSyncOpenOfficeModal(args = {}, payload = {}) {
if (!isFresh(args.timestamp, payload.last_modified || payload.document?.last_modified)) return false;
const action = String(payload.action || "").trim().toLowerCase().replace("-", "_");
return ["create", "open", "edit", "restore_version"].includes(action);
}
-function shouldColdOpenOfficeCanvas(payload = {}, document = {}) {
- const action = String(payload.action || "").trim().toLowerCase().replace("-", "_");
- if (!["create", "open"].includes(action)) return false;
- return DESKTOP_OFFICE_FORMATS.has(documentFormat(payload, document));
+function shouldOpenDocumentUiFromResult(payload = {}, document = {}) {
+ if (!isExplicitDocumentUiRequest(payload)) return false;
+ return Boolean(documentExtension(payload, document));
}
-async function openOfficeCanvasFromResult(document = {}) {
- const canvas = globalThis.Alpine?.store?.("rightCanvas")
- || (await import("/components/canvas/right-canvas-store.js")).store;
- await canvas?.open?.("office", {
- path: document.path || "",
- file_id: document.file_id || "",
+function isExplicitDocumentUiRequest(payload = {}) {
+ const action = String(payload.action || "").trim().toLowerCase().replace("-", "_");
+ return action === "open"
+ || truthy(payload.open_in_canvas)
+ || truthy(payload.open_canvas)
+ || truthy(payload.open_document)
+ || truthy(payload.open_in_desktop)
+ || truthy(payload.open_desktop);
+}
+
+async function openDocumentUiFromResult(target = {}, payload = {}, document = {}) {
+ if (isDesktopDocument(payload, document)) {
+ await openSurface("desktop", {
+ path: target.path || "",
+ file_id: target.file_id || "",
+ refresh: true,
+ source: "tool-result-open",
+ });
+ return;
+ }
+
+ await ensureModalOpen("/plugins/_office/webui/main.html");
+ await officeStore.openSession?.({
+ path: target.path || "",
+ file_id: target.file_id || "",
refresh: true,
- source: "tool-result-sync",
+ source: "tool-result-open",
});
}
-function documentFormat(payload = {}, document = {}) {
+function isDesktopDocument(payload = {}, document = {}) {
+ return DESKTOP_DOCUMENT_EXTENSIONS.has(documentExtension(payload, document));
+}
+
+function documentExtension(payload = {}, document = {}) {
return String(
payload.format
|| payload.extension
|| document.extension
- || extensionOf(payload.path || document.path || ""),
- ).trim().toLowerCase().replace(/^\./, "");
+ || document.format
+ || "",
+ ).toLowerCase();
}
-function extensionOf(path = "") {
- const name = String(path || "").split("?")[0].split("#")[0].split("/").filter(Boolean).pop() || "";
- const index = name.lastIndexOf(".");
- return index >= 0 ? name.slice(index + 1) : "";
-}
-
-function isOfficeCanvasAlreadyOpen() {
- const canvas = globalThis.Alpine?.store?.("rightCanvas");
- return Boolean(canvas?.isOpen && canvas?.activeSurfaceId === "office");
-}
-
-function isOfficeCanvasOrModalOpen() {
- return Boolean(isOfficeCanvasAlreadyOpen() || isOfficeModalAlreadyOpen());
-}
-
-function isOfficeModalAlreadyOpen() {
+function isOfficeModalOpen() {
return Boolean(
globalThis.isModalOpen?.("/plugins/_office/webui/main.html")
|| globalThis.isModalOpen?.("plugins/_office/webui/main.html")
@@ -143,6 +163,13 @@ function isDirtySameDocument(office, document = {}) {
);
}
+function truthy(value) {
+ if (value === true) return true;
+ if (value === false || value == null) return false;
+ if (typeof value === "number") return value !== 0;
+ return ["1", "true", "yes", "y", "on"].includes(String(value).trim().toLowerCase());
+}
+
function isFresh(...timestamps) {
const now = Date.now();
for (const value of timestamps) {
diff --git a/plugins/_office/helpers/artifact_editor.py b/plugins/_office/helpers/artifact_editor.py
index bbec68e1e..78d6b66ea 100644
--- a/plugins/_office/helpers/artifact_editor.py
+++ b/plugins/_office/helpers/artifact_editor.py
@@ -141,9 +141,9 @@ def _refresh_open_editor_sessions(file_id: str) -> None:
# Direct artifact edits should never fail just because no canvas is open.
pass
try:
- from plugins._office.helpers import libreoffice_desktop
+ from plugins._desktop.helpers import desktop_session
- libreoffice_desktop.get_manager().refresh_document(file_id)
+ desktop_session.get_manager().refresh_document(file_id)
except Exception:
pass
diff --git a/plugins/_office/helpers/canvas_context.py b/plugins/_office/helpers/canvas_context.py
index cd4f0b604..395194269 100644
--- a/plugins/_office/helpers/canvas_context.py
+++ b/plugins/_office/helpers/canvas_context.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from typing import Any
-from plugins._office.helpers import desktop_state
+from plugins._desktop.helpers import desktop_state
from plugins._office.helpers import document_store
@@ -13,7 +13,7 @@ def build_context(max_items: int = 6) -> str:
return desktop_context
lines = [
- "These document artifacts have active canvas sessions. Content is omitted; load skill `office-artifacts` for edit workflow, then use document_artifact:read before content-sensitive edits.",
+ "These document artifacts have active document sessions. Content is omitted; load skill `document-artifacts` for edit workflow, then use document_artifact:read before content-sensitive edits.",
]
for doc in documents:
lines.append(format_document_line(doc))
@@ -46,5 +46,5 @@ def build_desktop_context() -> str:
return (
"[DESKTOP STATE]\n"
f"- unavailable={exc}\n"
- "- next=Open the Desktop canvas manually, then run plugins/_office/skills/linux-desktop/scripts/desktopctl.sh observe --json."
+ "- next=Open the Desktop surface manually, then run plugins/_desktop/skills/linux-desktop/scripts/desktopctl.sh observe --json."
)
diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.py
index f357bb7e0..dbdb8843b 100644
--- a/plugins/_office/helpers/document_store.py
+++ b/plugins/_office/helpers/document_store.py
@@ -40,7 +40,7 @@ ODF_MIMETYPES = {
"odp": "application/vnd.oasis.opendocument.presentation",
}
-STATE_DIR = Path(files.get_abs_path("usr", "plugins", PLUGIN_NAME, "documents"))
+STATE_DIR = Path(files.get_abs_path("usr", PLUGIN_NAME, "documents"))
DB_PATH = STATE_DIR / "documents.sqlite3"
BACKUP_DIR = STATE_DIR / "backups"
WORKDIR = Path(files.get_abs_path("usr", "workdir"))
diff --git a/plugins/_office/helpers/libreoffice.py b/plugins/_office/helpers/libreoffice.py
index 92e29fd25..d5d4862cf 100644
--- a/plugins/_office/helpers/libreoffice.py
+++ b/plugins/_office/helpers/libreoffice.py
@@ -36,9 +36,9 @@ def collect_status() -> dict[str, Any]:
"message": "LibreOffice is available." if soffice else "LibreOffice is not installed in this runtime.",
}
try:
- from plugins._office.helpers import libreoffice_desktop
+ from plugins._desktop.helpers import desktop_session
- status["desktop"] = libreoffice_desktop.collect_desktop_status()
+ status["desktop"] = desktop_session.collect_desktop_status()
except Exception as exc:
status["desktop"] = {"ok": False, "healthy": False, "error": str(exc)}
return status
diff --git a/plugins/_office/plugin.yaml b/plugins/_office/plugin.yaml
index b1397b6aa..965925a8e 100644
--- a/plugins/_office/plugin.yaml
+++ b/plugins/_office/plugin.yaml
@@ -1,6 +1,6 @@
name: _office
title: LibreOffice
-description: Markdown writing and ODF-first LibreOffice document artifacts in the right canvas.
+description: Markdown writing and ODF-first LibreOffice document artifacts.
version: "0.1"
settings_sections:
- developer
diff --git a/plugins/_office/prompts/agent.system.tool.document_artifact.md b/plugins/_office/prompts/agent.system.tool.document_artifact.md
index baa29d947..3c51ab3e0 100644
--- a/plugins/_office/prompts/agent.system.tool.document_artifact.md
+++ b/plugins/_office/prompts/agent.system.tool.document_artifact.md
@@ -1,15 +1,17 @@
### document_artifact
-create/open/read/edit reusable document artifacts in the Agent Zero canvas
+create/open/read/edit reusable document artifacts in Agent Zero
formats: md odt ods odp docx xlsx pptx
default format: md
methods: create open read edit inspect export version_history restore_version status
common args: method action kind title format content path file_id
+optional UI intent args: open_in_canvas open_in_desktop
`method` is accepted as an alias for action when the tool_name has no suffix
-tool results save or update artifacts only; they do not open the canvas automatically
-created/updated artifacts are shown with explicit Download and Open in canvas message actions
-ODF is first-class for LibreOffice: use ODT for Writer, ODS for Spreadsheet/Calc, and ODP for Presentation/Impress unless the user explicitly requests Microsoft compatibility
+create/read/edit results save or update artifacts only; they do not open a surface automatically unless the user explicitly asks to open the document UI
+use action `open`, `open_in_canvas: true`, or `open_in_desktop: true` only when the user explicitly asks to open the document/editor/Desktop
+created/updated artifacts are shown with explicit Download, Open Document, or Desktop edit message actions
+ODF is first-class for LibreOffice: use ODT for Writer, ODS for Spreadsheet/Calc, and ODP for Presentation/Impress unless the user explicitly requests OOXML compatibility
DOCX/XLSX/PPTX are compatibility formats, not defaults
XLSX charts: use edit operation `create_chart` with `chart` object instead of code execution for embedded spreadsheet charts when an embedded chart is required
chart types: line bar column pie area scatter stock ohlc candlestick
ODS/XLSX create/edit tabular content: CSV, TSV, Markdown tables, or rows arrays become real spreadsheet cells
-for nontrivial document artifact work, load skill `office-artifacts` or the specific Markdown/Writer/Calc/Impress skill first
+for nontrivial document artifact work, load skill `document-artifacts` or the specific Markdown/Writer/Calc/Impress skill first
diff --git a/plugins/_office/tools/document_artifact.py b/plugins/_office/tools/document_artifact.py
index e2b9de21a..c0f5d2006 100644
--- a/plugins/_office/tools/document_artifact.py
+++ b/plugins/_office/tools/document_artifact.py
@@ -28,10 +28,22 @@ class DocumentArtifact(Tool):
chart: Any = None,
slides: Any = None,
max_chars: int | str = 12000,
+ open_in_canvas: bool = False,
+ open_in_desktop: bool = False,
method: str = "",
**kwargs: Any,
) -> Response:
action = str(action or method or self.method or "status").strip().lower().replace("-", "_")
+ open_in_canvas = _truthy(
+ open_in_canvas
+ or kwargs.get("open_canvas")
+ or kwargs.get("open_document")
+ )
+ open_in_desktop = _truthy(
+ open_in_desktop
+ or kwargs.get("open_desktop")
+ or kwargs.get("desktop")
+ )
try:
if action == "create":
doc = document_store.create_document(
@@ -56,10 +68,22 @@ class DocumentArtifact(Tool):
message=f"document_artifact create failed: {validation.get('error')}",
break_loop=False,
)
- return self._document_response("Created document artifact.", doc, action=action)
+ return self._document_response(
+ "Created document artifact.",
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "open":
doc = self._document_from_input(file_id=file_id, path=path)
- return self._document_response("Opened document artifact.", doc, action=action)
+ return self._document_response(
+ "Opened document artifact.",
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action in {"read", "extract"}:
doc = self._document_from_input(file_id=file_id, path=path)
payload = {
@@ -68,7 +92,13 @@ class DocumentArtifact(Tool):
"document": self._public_doc(doc),
"content": artifact_editor.read_artifact(doc, max_chars=int(max_chars or 12000)),
}
- return self._json_response(payload, doc=doc, action="read")
+ return self._json_response(
+ payload,
+ doc=doc,
+ action="read",
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action in {"edit", "update", "patch"}:
doc = self._document_from_input(file_id=file_id, path=path)
updated_doc, payload = artifact_editor.edit_artifact(
@@ -85,20 +115,44 @@ class DocumentArtifact(Tool):
**kwargs,
)
payload["document"] = self._public_doc(updated_doc)
- return self._json_response(payload, doc=updated_doc, action="edit")
+ return self._json_response(
+ payload,
+ doc=updated_doc,
+ action="edit",
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "inspect":
doc = self._document_from_input(file_id=file_id, path=path)
- return self._json_response({"ok": True, "action": action, "document": self._public_doc(doc)}, doc=doc, action=action)
+ return self._json_response(
+ {"ok": True, "action": action, "document": self._public_doc(doc)},
+ doc=doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "version_history":
doc = self._document_from_input(file_id=file_id, path=path)
versions = document_store.version_history(doc["file_id"])
- return self._json_response({"ok": True, "action": action, "versions": versions}, doc=doc, action=action)
+ return self._json_response(
+ {"ok": True, "action": action, "versions": versions},
+ doc=doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "restore_version":
if version_id is None or str(version_id).strip() == "":
return Response(message="version_id is required for restore_version.", break_loop=False)
doc = self._document_from_input(file_id=file_id, path=path)
restored = document_store.restore_version(doc["file_id"], int(version_id))
- return self._document_response("Restored document artifact version.", restored, action=action)
+ return self._document_response(
+ "Restored document artifact version.",
+ restored,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "export":
doc = self._document_from_input(file_id=file_id, path=path)
target_format = str(kwargs.get("target_format") or kwargs.get("export_format") or "").lower().lstrip(".")
@@ -111,13 +165,30 @@ class DocumentArtifact(Tool):
"path": document_store.display_path(result["path"]),
"document": self._public_doc(doc),
}
- return self._json_response(payload, doc=doc, action=action)
+ return self._json_response(
+ payload,
+ doc=doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
return Response(
message=f"document_artifact export failed: {result.get('error')}",
break_loop=False,
- additional=self._additional(doc, action=action),
+ additional=self._additional(
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ ),
)
- return self._document_response("Document artifact export path is ready.", doc, action=action)
+ return self._document_response(
+ "Document artifact export path is ready.",
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ )
if action == "status":
return self._json_response({"ok": True, "action": action, "status": libreoffice.collect_status()}, action=action)
return Response(message=f"Unknown document_artifact action: {action}", break_loop=False)
@@ -143,28 +214,75 @@ class DocumentArtifact(Tool):
def _context_id(self) -> str:
return self.agent.context.id if self.agent and self.agent.context else ""
- def _document_response(self, message: str, doc: dict[str, Any], action: str = "") -> Response:
+ def _document_response(
+ self,
+ message: str,
+ doc: dict[str, Any],
+ action: str = "",
+ *,
+ open_in_canvas: bool = False,
+ open_in_desktop: bool = False,
+ ) -> Response:
payload = {"ok": True, "action": action, "message": message, "document": self._public_doc(doc)}
return Response(
message=json.dumps(payload, indent=2, ensure_ascii=False),
break_loop=False,
- additional=self._additional(doc, action=action),
+ additional=self._additional(
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ ),
)
- def _json_response(self, payload: dict[str, Any], doc: dict[str, Any] | None = None, action: str = "") -> Response:
+ def _json_response(
+ self,
+ payload: dict[str, Any],
+ doc: dict[str, Any] | None = None,
+ action: str = "",
+ *,
+ open_in_canvas: bool = False,
+ open_in_desktop: bool = False,
+ ) -> Response:
return Response(
message=json.dumps(payload, indent=2, ensure_ascii=False, default=str),
break_loop=False,
- additional=self._additional(doc, action=action) if doc else {"_tool_name": self.name, "canvas_surface": "office", "action": action},
+ additional=self._additional(
+ doc,
+ action=action,
+ open_in_canvas=open_in_canvas,
+ open_in_desktop=open_in_desktop,
+ ) if doc else {
+ "_tool_name": self.name,
+ "canvas_surface": "office",
+ "action": action,
+ "open_in_canvas": bool(open_in_canvas),
+ "open_in_desktop": bool(open_in_desktop),
+ },
)
- def _additional(self, doc: dict[str, Any] | None, action: str = "") -> dict[str, Any]:
+ def _additional(
+ self,
+ doc: dict[str, Any] | None,
+ action: str = "",
+ *,
+ open_in_canvas: bool = False,
+ open_in_desktop: bool = False,
+ ) -> dict[str, Any]:
if not doc:
- return {"_tool_name": self.name, "canvas_surface": "office", "action": action}
+ return {
+ "_tool_name": self.name,
+ "canvas_surface": "office",
+ "action": action,
+ "open_in_canvas": bool(open_in_canvas),
+ "open_in_desktop": bool(open_in_desktop),
+ }
return {
"_tool_name": self.name,
"canvas_surface": "office",
"action": action,
+ "open_in_canvas": bool(open_in_canvas),
+ "open_in_desktop": bool(open_in_desktop),
"file_id": doc["file_id"],
"title": doc["basename"],
"format": doc["extension"],
@@ -183,3 +301,13 @@ class DocumentArtifact(Tool):
"last_modified": doc["last_modified"],
"exists": Path(doc["path"]).exists(),
}
+
+
+def _truthy(value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ if value is None:
+ return False
+ if isinstance(value, (int, float)):
+ return value != 0
+ return str(value).strip().lower() in {"1", "true", "yes", "y", "on"}
diff --git a/plugins/_office/webui/main.html b/plugins/_office/webui/main.html
index 8248c6d03..dcf7d21c0 100644
--- a/plugins/_office/webui/main.html
+++ b/plugins/_office/webui/main.html
@@ -1,12 +1,6 @@
-<html
- class="office-modal modal-no-backdrop"
- data-canvas-surface="office"
- data-canvas-modal-path="/plugins/_office/webui/main.html"
- data-canvas-dock-title="Open Desktop in canvas"
- data-canvas-dock-icon="dock_to_right"
->
+<html class="office-modal">
<head>
- <title>Desktop</title>
+ <title>Documents</title>
<script type="module">
import { store } from "/plugins/_office/webui/office-store.js";
</script>
diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.html
index 095d17ad5..ac46cec7d 100644
--- a/plugins/_office/webui/office-panel.html
+++ b/plugins/_office/webui/office-panel.html
@@ -5,123 +5,130 @@
</script>
</head>
<body>
- <div class="office-panel" x-data x-create="$store.office.onMount($el, xAttrs($el) || {})" x-destroy="$store.office.cleanup()">
+ <div x-data>
<template x-if="$store.office">
- <div class="office-shell">
- <div class="office-document-header" x-show="$store.office.hasActiveFile()" style="display: none;">
- <div class="office-document-title" :title="$store.office.tabLabel($store.office.session)">
- <span class="material-symbols-outlined office-document-icon" aria-hidden="true" x-text="$store.office.tabIcon($store.office.session)"></span>
- <span class="office-document-name" x-text="$store.office.tabTitle($store.office.session)"></span>
- <span class="office-document-dirty" x-show="$store.office.dirty" aria-hidden="true">*</span>
- </div>
+ <div class="office-panel" x-create="$store.office.onMount($el, xAttrs($el) || {})" x-destroy="$store.office.cleanup()">
+ <div class="office-shell">
+ <div class="office-document-header" x-show="$store.office.hasActiveFile()" style="display: none;">
+ <div class="office-document-title" :title="$store.office.tabLabel($store.office.session)">
+ <span class="material-symbols-outlined office-document-icon" aria-hidden="true" x-text="$store.office.tabIcon($store.office.session)"></span>
+ <span class="office-document-name" x-text="$store.office.tabTitle($store.office.session)"></span>
+ <span class="office-document-dirty" x-show="$store.office.dirty" aria-hidden="true">*</span>
+ </div>
- <button
- type="button"
- class="office-icon-button office-document-save-button"
- title="Save"
- aria-label="Save"
- :class="{ 'is-primary': $store.office.dirty }"
- :disabled="$store.office.saving"
- @click="$store.office.save()"
- >
- <span class="material-symbols-outlined" :class="{ spinning: $store.office.saving }" x-text="$store.office.saving ? 'progress_activity' : 'save'"></span>
- </button>
-
- <div class="office-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false">
<button
type="button"
- class="office-icon-button office-file-menu-button"
- title="File actions"
- aria-label="File actions"
- aria-haspopup="menu"
- :aria-expanded="open.toString()"
+ class="office-icon-button office-document-save-button"
+ title="Save"
+ aria-label="Save"
+ :class="{ 'is-primary': $store.office.dirty }"
:disabled="$store.office.saving"
- @click.stop="open = !open"
+ @click="$store.office.save()"
>
- <span class="material-symbols-outlined">more_vert</span>
+ <span class="material-symbols-outlined" :class="{ spinning: $store.office.saving }" x-text="$store.office.saving ? 'progress_activity' : 'save'"></span>
</button>
- <div class="office-new-menu office-file-menu" role="menu" x-show="open" @click.stop>
- <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.saving" @click="open = false; $store.office.renameActiveFile()">
- <span class="material-symbols-outlined" aria-hidden="true">edit</span>
- <span>Rename</span>
- </button>
- <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.loading" @click="open = false; $store.office.closeActiveFile()">
- <span class="material-symbols-outlined" aria-hidden="true">close</span>
- <span>Close File</span>
+
+ <div class="office-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false">
+ <button
+ type="button"
+ class="office-icon-button office-file-menu-button"
+ title="File actions"
+ aria-label="File actions"
+ aria-haspopup="menu"
+ :aria-expanded="open.toString()"
+ :disabled="$store.office.saving"
+ @click.stop="open = !open"
+ >
+ <span class="material-symbols-outlined">more_vert</span>
</button>
+ <div class="office-new-menu office-file-menu" role="menu" x-show="open" @click.stop>
+ <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.saving" @click="open = false; $store.office.renameActiveFile()">
+ <span class="material-symbols-outlined" aria-hidden="true">edit</span>
+ <span>Rename</span>
+ </button>
+ <button type="button" class="office-new-menu-item" role="menuitem" :disabled="$store.office.loading" @click="open = false; $store.office.closeActiveFile()">
+ <span class="material-symbols-outlined" aria-hidden="true">close</span>
+ <span>Close File</span>
+ </button>
+ </div>
</div>
</div>
- </div>
- <div class="office-toolbar" x-show="$store.office.session && $store.office.isMarkdown()" style="display: none;">
- <div class="office-toolbar-row">
- <div class="office-tool-group office-editor-tools" x-show="$store.office.session && $store.office.isMarkdown()" style="display: none;">
- <button type="button" class="office-icon-button" title="Undo" aria-label="Undo" :disabled="!$store.office.canUndo()" @click="$store.office.undo()">
- <span class="material-symbols-outlined">undo</span>
- </button>
- <button type="button" class="office-icon-button" title="Redo" aria-label="Redo" :disabled="!$store.office.canRedo()" @click="$store.office.redo()">
- <span class="material-symbols-outlined">redo</span>
- </button>
- <button type="button" class="office-icon-button" title="Bold" aria-label="Bold" @click="$store.office.format('bold')">
- <span class="material-symbols-outlined">format_bold</span>
- </button>
- <button type="button" class="office-icon-button" title="Italic" aria-label="Italic" @click="$store.office.format('italic')">
- <span class="material-symbols-outlined">format_italic</span>
- </button>
- <button type="button" class="office-icon-button" title="List" aria-label="List" @click="$store.office.format('list')">
- <span class="material-symbols-outlined">format_list_bulleted</span>
- </button>
- <button type="button" class="office-icon-button" title="Numbered list" aria-label="Numbered list" @click="$store.office.format('numbered')">
- <span class="material-symbols-outlined">format_list_numbered</span>
- </button>
- <button type="button" class="office-icon-button" title="Table" aria-label="Table" @click="$store.office.format('table')">
- <span class="material-symbols-outlined">table</span>
- </button>
+ <div class="office-toolbar" x-show="$store.office.session && $store.office.isMarkdown()" style="display: none;">
+ <div class="office-toolbar-row">
+ <div class="office-tool-group office-editor-tools">
+ <button type="button" class="office-icon-button" title="Undo" aria-label="Undo" :disabled="!$store.office.canUndo()" @click="$store.office.undo()">
+ <span class="material-symbols-outlined">undo</span>
+ </button>
+ <button type="button" class="office-icon-button" title="Redo" aria-label="Redo" :disabled="!$store.office.canRedo()" @click="$store.office.redo()">
+ <span class="material-symbols-outlined">redo</span>
+ </button>
+ <button type="button" class="office-icon-button" title="Bold" aria-label="Bold" @click="$store.office.format('bold')">
+ <span class="material-symbols-outlined">format_bold</span>
+ </button>
+ <button type="button" class="office-icon-button" title="Italic" aria-label="Italic" @click="$store.office.format('italic')">
+ <span class="material-symbols-outlined">format_italic</span>
+ </button>
+ <button type="button" class="office-icon-button" title="List" aria-label="List" @click="$store.office.format('list')">
+ <span class="material-symbols-outlined">format_list_bulleted</span>
+ </button>
+ <button type="button" class="office-icon-button" title="Numbered list" aria-label="Numbered list" @click="$store.office.format('numbered')">
+ <span class="material-symbols-outlined">format_list_numbered</span>
+ </button>
+ <button type="button" class="office-icon-button" title="Table" aria-label="Table" @click="$store.office.format('table')">
+ <span class="material-symbols-outlined">table</span>
+ </button>
+ </div>
+ <span class="office-toolbar-spacer"></span>
</div>
-
- <span class="office-toolbar-spacer"></span>
</div>
- </div>
- <div class="office-state-line" x-show="$store.office.message || $store.office.error || $store.office.loading" style="display: none;">
- <span class="material-symbols-outlined" :class="{ spinning: $store.office.loading }" x-text="$store.office.loading ? 'progress_activity' : ($store.office.error ? 'error' : 'check_circle')"></span>
- <span x-text="$store.office.error || $store.office.message || 'Working'"></span>
- </div>
-
- <div class="office-body" :class="{ 'is-source': $store.office.isMarkdown() }">
- <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"
- data-office-desktop-host
- x-init="$nextTick(() => $store.office.mountDesktopFrameHost($el))"
- >
- </div>
- </template>
-
- <textarea
- class="office-source-editor"
- data-office-source
- aria-label="Markdown source"
- x-show="$store.office.isMarkdown()"
- x-model="$store.office.editorText"
- @input="$store.office.onSourceInput()"
- @blur="$store.office.flushInput()"
- spellcheck="true"
- style="display: none;"
- ></textarea>
+ <div class="office-state-line" x-show="$store.office.message || $store.office.error || $store.office.loading" style="display: none;">
+ <span class="material-symbols-outlined" :class="{ spinning: $store.office.loading }" x-text="$store.office.loading ? 'progress_activity' : ($store.office.error ? 'error' : 'check_circle')"></span>
+ <span x-text="$store.office.error || $store.office.message || 'Working'"></span>
+ </div>
+ <div class="office-body" :class="{ 'is-source': $store.office.isMarkdown() }">
+ <div class="office-editor-wrap" x-show="$store.office.session" style="display: none;">
+ <div class="office-editor-scroll is-source" @click.self="$store.office.focusEditor()">
+ <textarea
+ class="office-source-editor"
+ data-office-source
+ aria-label="Markdown source"
+ x-show="$store.office.isMarkdown()"
+ x-model="$store.office.editorText"
+ @input="$store.office.onSourceInput()"
+ @blur="$store.office.flushInput()"
+ spellcheck="true"
+ style="display: none;"
+ ></textarea>
+ </div>
</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 class="office-empty" x-show="!$store.office.session && !$store.office.loading" style="display: none;">
+ <div class="office-empty-actions">
+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('open')">
+ <span class="material-symbols-outlined" aria-hidden="true">folder_open</span>
+ <span class="office-button-label">Open</span>
+ </button>
+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('markdown')">
+ <span class="material-symbols-outlined" aria-hidden="true">article</span>
+ <span class="office-button-label">Markdown</span>
+ </button>
+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('writer')">
+ <span class="material-symbols-outlined" aria-hidden="true">description</span>
+ <span class="office-button-label">Writer</span>
+ </button>
+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('spreadsheet')">
+ <span class="material-symbols-outlined" aria-hidden="true">table_chart</span>
+ <span class="office-button-label">Calc</span>
+ </button>
+ <button type="button" class="office-icon-button office-command-button" @click="$store.office.runNewMenuAction('presentation')">
+ <span class="material-symbols-outlined" aria-hidden="true">co_present</span>
+ <span class="office-button-label">Impress</span>
+ </button>
+ </div>
+ </div>
</div>
</div>
</div>
@@ -148,24 +155,13 @@
.modal-inner.office-modal {
box-sizing: border-box;
- width: min(1120px, calc(100vw - 32px));
- height: min(820px, calc(100vh - 32px));
- min-width: min(720px, calc(100vw - 16px));
- min-height: min(520px, calc(100vh - 16px));
+ width: min(1040px, calc(100vw - 32px));
+ height: min(760px, calc(100vh - 32px));
+ min-width: min(640px, calc(100vw - 16px));
+ min-height: min(460px, calc(100vh - 16px));
max-width: none;
max-height: none;
- resize: none;
overflow: hidden;
- will-change: width, height, left, top;
- }
-
- .modal-inner.office-modal.is-resizing,
- .modal-inner.office-modal.is-dragging {
- user-select: none;
- }
-
- .modal-inner.office-modal.is-focus-mode {
- border-radius: 6px;
}
.modal-inner.office-modal .modal-scroll {
@@ -178,592 +174,211 @@
}
.modal-inner.office-modal .modal-header {
- grid-template-columns: minmax(0, 1fr) repeat(5, auto);
- }
-
- .office-modal-input-shield {
- position: absolute;
- inset: 42px 0 0 0;
- z-index: 4;
- display: none;
- background: transparent;
- }
-
- .office-modal-resizer {
- position: absolute;
- z-index: 5;
- display: block;
- touch-action: none;
- }
-
- .office-modal-resizer.is-right {
- top: 42px;
- right: -4px;
- bottom: 12px;
- width: 10px;
- cursor: ew-resize;
- }
-
- .office-modal-resizer.is-bottom {
- right: 12px;
- bottom: -4px;
- left: 0;
- height: 10px;
- cursor: ns-resize;
- }
-
- .office-modal-resizer.is-corner {
- right: 0;
- bottom: 0;
- width: 22px;
- height: 22px;
- cursor: nwse-resize;
- }
-
- .office-modal-resizer.is-corner::after {
- content: "";
- position: absolute;
- right: 6px;
- bottom: 6px;
- width: 9px;
- height: 9px;
- border-right: 2px solid color-mix(in srgb, var(--color-text) 42%, transparent);
- border-bottom: 2px solid color-mix(in srgb, var(--color-text) 42%, transparent);
- border-radius: 1px;
- }
-
- .modal-inner.office-modal.is-focus-mode .office-modal-resizer {
- display: none;
- }
-
- .modal-inner.office-modal .modal-bd.office-modal-body,
- .modal-inner.office-modal .modal-bd.office-modal-body > x-component,
- .modal-inner.office-modal .modal-bd.office-modal-body > x-component > .office-panel {
- display: flex;
- flex: 1 1 auto;
- min-height: 0;
- height: 100%;
- padding: 0;
- }
-
- .office-toolbar {
- display: flex;
- flex-direction: row;
- align-items: stretch;
- flex-wrap: nowrap;
- min-height: 0;
- padding: 6px 10px;
- overflow: hidden;
- border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 20%);
- background: color-mix(in srgb, var(--color-background), var(--color-panel) 48%);
- }
-
- .office-toolbar-row {
- display: flex;
- align-items: center;
- flex: 0 0 auto;
- flex-wrap: nowrap;
- gap: 6px;
- width: 100%;
- min-width: 0;
- min-height: 32px;
- overflow-x: auto;
- overflow-y: hidden;
- scrollbar-width: thin;
+ grid-template-columns: minmax(0, 1fr) auto auto;
}
- .office-tool-group {
+ .office-document-header,
+ .office-toolbar,
+ .office-state-line {
display: flex;
align-items: center;
- flex-wrap: nowrap;
- flex: 0 0 auto;
- gap: 4px;
+ gap: 8px;
+ border-bottom: 1px solid var(--color-border);
+ padding: 8px 10px;
min-width: 0;
}
- .office-editor-tools {
- gap: 3px;
- }
-
- .office-tool-actions {
- justify-content: flex-end;
- }
-
- .office-toolbar-spacer {
- flex: 1 1 16px;
- min-width: 8px;
- }
-
- .office-toolbar-divider {
- flex: 0 0 auto;
- width: 1px;
- height: 22px;
- margin-inline: 2px;
- background: color-mix(in srgb, var(--color-border), transparent 18%);
- }
-
- .office-document-header {
- display: flex;
- align-items: center;
- gap: 10px;
- min-height: 38px;
- padding: 5px 10px 5px 12px;
- border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);
- background: color-mix(in srgb, var(--color-panel), var(--color-background) 30%);
- }
-
.office-document-title {
display: flex;
align-items: center;
- gap: 7px;
+ gap: 8px;
min-width: 0;
flex: 1 1 auto;
- color: var(--color-text);
- }
-
- .office-document-icon {
- flex: 0 0 auto;
- font-size: 19px;
- line-height: 1;
+ font-size: 14px;
+ font-weight: 600;
}
.office-document-name {
- min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
- font-size: 13px;
- font-weight: 750;
- letter-spacing: 0;
- line-height: 1.2;
}
.office-document-dirty {
- flex: 0 0 auto;
- color: #2ca58d;
- font-size: 14px;
- font-weight: 800;
- line-height: 1;
- }
-
- .office-file-actions {
- position: relative;
- display: inline-flex;
- align-items: center;
- flex: 0 0 auto;
- }
-
- .office-document-save-button,
- .office-file-menu-button {
- width: 30px;
- height: 30px;
- min-width: 30px;
- }
-
- .office-header-actions {
- position: relative;
- display: inline-flex;
- align-items: center;
- flex: 0 0 auto;
+ color: var(--color-accent);
}
- .office-header-new-button {
- appearance: none;
+ .office-icon-button {
display: inline-flex;
align-items: center;
justify-content: center;
- gap: 4px;
- height: 34px;
- min-height: 34px;
- padding: 0 9px 0 8px;
- border: 1px solid transparent;
- border-radius: 7px;
- background: transparent;
+ gap: 6px;
+ height: 32px;
+ min-width: 32px;
+ border: 1px solid var(--color-border);
+ border-radius: 6px;
+ background: var(--color-background);
color: var(--color-text);
cursor: pointer;
- font: inherit;
- font-size: 12px;
- font-weight: 750;
- letter-spacing: 0;
- line-height: 1;
- opacity: 0.82;
- white-space: nowrap;
- transition: background-color 0.16s ease, border-color 0.16s ease, opacity 0.16s ease;
}
- .office-header-new-button:hover,
- .office-header-actions.is-open .office-header-new-button {
- opacity: 1;
- border-color: color-mix(in srgb, var(--color-primary) 28%, var(--color-border));
- background: color-mix(in srgb, var(--color-background-hover) 72%, transparent);
+ .office-icon-button:hover:not(:disabled) {
+ background: var(--color-surface);
+ }
+
+ .office-icon-button:disabled {
+ cursor: default;
+ opacity: 0.55;
}
- .office-header-new-button .material-symbols-outlined {
- font-size: 18px;
- line-height: 1;
+ .office-document-save-button.is-primary {
+ border-color: var(--color-accent);
+ color: var(--color-accent);
}
- .office-header-new-button .office-new-chevron {
- margin-left: -2px;
- font-size: 16px;
- opacity: 0.8;
+ .office-file-actions {
+ position: relative;
}
.office-new-menu {
position: absolute;
top: calc(100% + 6px);
right: 0;
- z-index: 100;
- min-width: 184px;
- padding: 5px;
- border: 1px solid color-mix(in srgb, var(--color-border), transparent 10%);
- border-radius: 8px;
- background: color-mix(in srgb, var(--color-panel), var(--color-background) 10%);
- box-shadow: 0 14px 34px rgba(0, 0, 0, 0.34);
- }
-
- .office-new-menu[hidden] {
- display: none;
+ z-index: 15;
+ display: grid;
+ min-width: 172px;
+ padding: 6px;
+ border: 1px solid var(--color-border);
+ border-radius: 6px;
+ background: var(--color-background);
+ box-shadow: 0 16px 36px rgba(0, 0, 0, 0.18);
}
.office-new-menu-item {
- appearance: none;
display: flex;
align-items: center;
gap: 8px;
width: 100%;
- height: 32px;
- padding: 0 8px;
- border: 1px solid transparent;
- border-radius: 6px;
+ border: 0;
+ border-radius: 5px;
background: transparent;
color: var(--color-text);
- cursor: pointer;
- font: inherit;
- font-size: 12px;
- font-weight: 650;
- letter-spacing: 0;
- line-height: 1;
+ padding: 8px;
text-align: left;
- white-space: nowrap;
+ cursor: pointer;
}
.office-new-menu-item:hover {
- border-color: color-mix(in srgb, var(--color-primary) 22%, transparent);
- background: color-mix(in srgb, var(--color-background-hover) 76%, transparent);
+ background: var(--color-surface);
}
- .office-new-menu-item:disabled {
- cursor: default;
- opacity: 0.46;
- }
-
- .office-new-menu-item .material-symbols-outlined {
- flex: 0 0 auto;
- width: 18px;
- font-size: 18px;
- line-height: 1;
- text-align: center;
- }
-
- .office-icon-button,
- .office-tab,
- .office-tab-close {
- border: 1px solid color-mix(in srgb, var(--color-border), transparent 12%);
- border-radius: 8px;
- background: color-mix(in srgb, var(--color-panel), var(--color-background) 16%);
- color: inherit;
- transition: border-color 120ms ease, background 120ms ease, transform 120ms ease;
- }
-
- .office-icon-button {
- display: inline-grid;
- place-items: center;
- width: 32px;
- height: 32px;
- min-width: 32px;
- padding: 0;
- }
-
- .office-command-button {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- gap: 5px;
- width: auto;
- max-width: 126px;
- padding: 0 8px;
- white-space: nowrap;
- }
-
- .office-command-button .office-button-label {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- font-size: 11px;
- font-weight: 700;
- line-height: 1;
- }
-
- .office-icon-button.is-primary {
- border-color: color-mix(in srgb, #2c7be5, var(--color-border) 20%);
- background: color-mix(in srgb, #2c7be5, var(--color-panel) 82%);
- }
-
- .office-icon-button.is-active {
- border-color: color-mix(in srgb, #2ca58d, var(--color-border) 24%);
- background: color-mix(in srgb, #2ca58d, var(--color-panel) 84%);
- }
-
- .office-icon-button:hover:not(:disabled),
- .office-tab:hover,
- .office-tab-close:hover {
- border-color: color-mix(in srgb, #2c7be5, var(--color-border) 45%);
- background: color-mix(in srgb, var(--color-panel), #2c7be5 8%);
- }
-
- .office-icon-button:disabled {
- cursor: default;
- opacity: 0.42;
- }
-
- .office-icon-button .material-symbols-outlined,
- .office-tab-icon {
- font-size: 19px;
- line-height: 1;
- }
-
- .office-tabs {
+ .office-toolbar-row {
display: flex;
- gap: 6px;
- min-height: 42px;
- padding: 7px 10px;
- overflow-x: auto;
- border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 22%);
- background: color-mix(in srgb, var(--color-panel), var(--color-background) 28%);
- }
-
- .office-tab-shell {
- display: grid;
- grid-template-columns: minmax(0, 1fr) 28px;
align-items: center;
- min-width: 150px;
- max-width: 240px;
- }
-
- .office-tab-shell.is-system {
- grid-template-columns: minmax(0, 1fr);
- min-width: 172px;
- }
-
- .office-tab,
- .office-tab-close {
- height: 28px;
- min-height: 28px;
- border-radius: 7px;
+ gap: 8px;
+ width: 100%;
+ min-width: 0;
}
- .office-tab {
+ .office-tool-group,
+ .office-empty-actions {
display: flex;
align-items: center;
+ flex-wrap: wrap;
gap: 6px;
- min-width: 0;
- border-top-right-radius: 0;
- border-bottom-right-radius: 0;
- padding: 0 8px;
- text-align: left;
- }
-
- .office-tab-shell.is-system .office-tab {
- border-radius: 7px;
- }
-
- .office-tab-close {
- display: grid;
- place-items: center;
- border-left: 0;
- border-top-left-radius: 0;
- border-bottom-left-radius: 0;
- padding: 0;
- }
-
- .office-tab-close .material-symbols-outlined {
- font-size: 17px;
- }
-
- .office-tab-shell.is-active .office-tab,
- .office-tab-shell.is-active .office-tab-close {
- border-color: color-mix(in srgb, #2c7be5, var(--color-border) 36%);
- background: color-mix(in srgb, #2c7be5, var(--color-panel) 88%);
}
- .office-tab-shell.is-dirty .office-tab-title::after {
- content: " *";
- color: #2ca58d;
- }
-
- .office-tab-title {
- min-width: 0;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- font-size: 12px;
- line-height: 1;
+ .office-toolbar-spacer {
+ flex: 1 1 auto;
}
.office-state-line {
- display: flex;
- align-items: center;
- gap: 8px;
- min-height: 34px;
- padding: 6px 12px;
- border-bottom: 1px solid color-mix(in srgb, var(--color-border), transparent 28%);
- color: var(--color-text-secondary);
- font-size: 12px;
+ font-size: 13px;
+ color: var(--color-muted);
}
.office-body {
- position: relative;
display: flex;
flex: 1 1 auto;
min-height: 0;
- overflow: hidden;
- background: var(--color-background);
- }
-
- .office-body.is-source {
- background: transparent;
}
- .office-editor-wrap {
+ .office-editor-wrap,
+ .office-editor-scroll {
display: flex;
flex: 1 1 auto;
- flex-direction: column;
min-width: 0;
min-height: 0;
}
- .office-editor-scroll {
- flex: 1 1 auto;
- min-height: 0;
- overflow: auto;
- padding: 30px 24px;
- }
-
- .office-editor-scroll.is-source {
- display: flex;
- overflow: hidden;
- padding: var(--spacing-md);
- background: transparent;
- }
-
- .office-editor-scroll.is-desktop {
- display: flex;
- overflow: hidden;
- padding: 0;
- background: #1f2329;
- }
-
- .office-desktop-wrap {
- display: flex;
+ .office-source-editor {
flex: 1 1 auto;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
- aspect-ratio: auto;
- background: #1f2329;
+ resize: none;
+ border: 0;
+ outline: none;
+ padding: 16px;
+ background: var(--color-background);
+ color: var(--color-text);
+ font: 14px/1.55 var(--font-mono, monospace);
}
- .office-desktop-empty {
- display: grid;
+ .office-empty {
+ display: flex;
flex: 1 1 auto;
- place-items: center;
- align-content: center;
- gap: 12px;
- min-width: 0;
- min-height: 0;
+ align-items: center;
+ justify-content: center;
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%;
- height: 100%;
- min-height: 0;
- aspect-ratio: auto;
- border: 0;
- background: #20242a;
- }
-
- .office-source-editor {
- box-sizing: border-box;
- flex: 1 1 auto;
- width: 100%;
- height: 100%;
- min-width: 0;
- min-height: 0;
- margin: 0;
- padding: 0;
- border: 0;
- outline: none;
- background: transparent;
- box-shadow: none;
- font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
- font-size: 13px;
- line-height: 1.65;
- resize: none;
+ .office-command-button {
+ min-width: 108px;
+ justify-content: flex-start;
+ padding: 0 10px;
}
- textarea:focus {
- background: transparent;
- filter: brightness(1) !important;
+ .office-header-actions {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
}
- .office-panel .spinning {
- animation: office-spin 0.8s linear infinite;
+ .office-header-new-button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 32px;
+ border: 1px solid var(--color-border);
+ border-radius: 6px;
+ background: var(--color-background);
+ color: var(--color-text);
+ padding: 0 9px;
+ cursor: pointer;
}
- @keyframes office-spin {
- to { transform: rotate(360deg); }
+ .office-header-actions .office-new-menu {
+ right: 0;
}
- @container (max-width: 680px) {
- .office-toolbar {
- padding-inline: 8px;
+ @container (max-width: 560px) {
+ .office-document-header,
+ .office-toolbar,
+ .office-state-line {
+ padding: 7px;
}
- .office-toolbar-row {
- gap: 5px;
+ .office-button-label,
+ .office-header-new-button span:not(.material-symbols-outlined) {
+ display: none;
}
.office-command-button {
- width: 32px;
- max-width: 32px;
- padding-inline: 0;
- }
-
- .office-command-button .office-button-label {
- position: absolute;
- width: 1px;
- height: 1px;
- overflow: hidden;
- clip: rect(0 0 0 0);
- white-space: nowrap;
+ min-width: 32px;
+ justify-content: center;
}
-
}
</style>
</body>
diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.js
index 1beb1777f..3e7f5d7a5 100644
--- a/plugins/_office/webui/office-store.js
+++ b/plugins/_office/webui/office-store.js
@@ -2,25 +2,15 @@ import { createStore } from "/js/AlpineStore.js";
import { callJsonApi } from "/js/api.js";
import { getNamespacedClient } from "/js/websocket.js";
import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";
-import { store as rightCanvasStore } from "/components/canvas/right-canvas-store.js";
-import { store as browserStore } from "/plugins/_browser/webui/browser-store.js";
+import { open as openSurface } from "/js/surfaces.js";
const officeSocket = getNamespacedClient("/ws");
officeSocket.addHandlers(["ws_webui"]);
const SAVE_MESSAGE_MS = 1800;
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 XPRA_DESKTOP_PRIME_INTERVAL_MS = 220;
-const XPRA_DESKTOP_PRIME_ATTEMPTS = 120;
-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;
+const DESKTOP_DOCUMENT_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);
function currentContextId() {
try {
@@ -57,55 +47,6 @@ function editorContainsFocus(element) {
return Boolean(element && active && (element === active || element.contains(active)));
}
-function isEditableInputTarget(target) {
- const element = target?.nodeType === 1 ? target : target?.parentElement;
- const editable = element?.closest?.("input, textarea, select, [contenteditable='true'], [contenteditable=''], [role='textbox']");
- if (!editable) return false;
- if (editable.tagName !== "INPUT") return true;
- const type = String(editable.getAttribute("type") || "text").toLowerCase();
- return !["button", "checkbox", "color", "file", "image", "radio", "range", "reset", "submit"].includes(type);
-}
-
-function normalizeModalPath(path = "") {
- return String(path || "").replace(/^\/+/, "");
-}
-
-function isModalPathOpen(path = "") {
- const normalized = normalizeModalPath(path);
- return Boolean(
- globalThis.isModalOpen?.(path)
- || globalThis.isModalOpen?.(`/${normalized}`)
- || globalThis.isModalOpen?.(normalized)
- );
-}
-
-function waitForElementByPredicate(predicate, timeoutMs = URL_INTENT_PANEL_TIMEOUT_MS) {
- const found = predicate();
- if (found) return Promise.resolve(found);
- return new Promise((resolve) => {
- const timeout = globalThis.setTimeout(() => {
- observer.disconnect();
- resolve(predicate());
- }, timeoutMs);
- const observer = new MutationObserver(() => {
- const element = predicate();
- if (!element) return;
- globalThis.clearTimeout(timeout);
- observer.disconnect();
- resolve(element);
- });
- observer.observe(document.body, { childList: true, subtree: true });
- });
-}
-
-function browserPanelForMode(mode = "modal") {
- const panels = Array.from(document.querySelectorAll(".browser-panel"));
- if (mode === "canvas") {
- return panels.find((panel) => panel.closest?.('[data-surface-id="browser"]')) || null;
- }
- return panels.find((panel) => panel.closest?.(".modal")) || null;
-}
-
function placeCaretAtEnd(element) {
if (!element) return;
if (element.tagName === "TEXTAREA" || element.tagName === "INPUT") {
@@ -137,22 +78,23 @@ function normalizeDocument(doc = {}) {
function normalizeSession(payload = {}) {
const document = normalizeDocument(payload.document || payload);
- const extension = String(payload.extension || document.extension || "").toLowerCase();
return {
...payload,
document,
- extension,
+ extension: String(payload.extension || document.extension || "").toLowerCase(),
file_id: payload.file_id || document.file_id || "",
path: document.path || payload.path || "",
title: payload.title || document.title || document.basename || basename(document.path),
tab_id: uniqueTabId(payload),
text: String(payload.text || ""),
- desktop: payload.desktop || null,
- desktop_session_id: payload.desktop_session_id || payload.desktop?.session_id || "",
dirty: false,
};
}
+function documentLabel(document = {}) {
+ return document.title || document.basename || basename(document.path);
+}
+
async function callOffice(action, payload = {}) {
return await callJsonApi("/plugins/_office/office_session", {
action,
@@ -187,8 +129,6 @@ function isOfficeSocketData(data) {
|| Object.prototype.hasOwnProperty.call(data, "ok")
|| Object.prototype.hasOwnProperty.call(data, "session_id")
|| Object.prototype.hasOwnProperty.call(data, "document")
- || Object.prototype.hasOwnProperty.call(data, "desktop")
- || Object.prototype.hasOwnProperty.call(data, "closed")
);
}
@@ -204,7 +144,8 @@ const model = {
message: "",
editorText: "",
_root: null,
- _mode: "canvas",
+ _mode: "modal",
+ _initialized: false,
_saveMessageTimer: null,
_inputTimer: null,
_history: [],
@@ -212,57 +153,24 @@ const model = {
_pendingFocus: false,
_pendingFocusEnd: true,
_focusAttempts: 0,
- _floatingCleanup: null,
- _desktopHeartbeatTimer: null,
- _desktopHeartbeatSessionId: "",
- _desktopHeartbeatTabId: "",
- _desktopHeartbeatMisses: 0,
- _desktopResizeCleanup: null,
- _desktopResizeTarget: null,
- _desktopResizeTimer: null,
- _desktopResizeKey: "",
- _desktopResizePendingKey: "",
- _desktopResizeSuspended: false,
- _desktopResizePending: false,
- _desktopViewportSyncTimers: [],
- _desktopHostVisible: false,
- _desktopPrimeTimer: null,
- _desktopPrimeAttempts: 0,
- _desktopKeyboardActive: false,
- _desktopFocusInProgress: false,
- _desktopBridgeReady: false,
- _desktopKeyboardCaptureState: { ready: false, active: false, capture: false, focused: false },
- _desktopLastState: null,
- _desktopKeyboardCleanup: null,
- _desktopClipboardCleanup: null,
- _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" });
+ _headerCleanup: null,
+
+ async init() {
+ if (this._initialized) return;
+ this._initialized = true;
+ await this.refresh();
},
async onMount(element = null, options = {}) {
+ await this.init();
if (element) this._root = element;
- this._mode = options?.mode === "modal" ? "modal" : "canvas";
- if (this._mode === "modal") {
- this._desktopHostVisible = true;
- this.setupFloatingModal(element);
- await this.onOpen({ source: "modal" });
- return;
- }
+ this._mode = options?.mode === "canvas" ? "canvas" : "modal";
+ if (this._mode === "modal") this.setupDocumentModal(element);
this.queueRender();
},
async onOpen(payload = {}) {
- this.restoreDesktopShutdownState();
+ await this.init();
await this.refresh();
if (payload?.path || payload?.file_id) {
await this.openSession({
@@ -271,39 +179,17 @@ const model = {
refresh: payload.refresh === true,
source: payload.source || "",
});
- } else if (this._desktopIntentionalShutdown) {
- this.session = null;
- this.activeTabId = "";
- this.editorText = "";
- this.dirty = false;
- } else {
- await this.ensureDesktopSession({ select: !this.session });
}
- this.restoreDesktopFrames();
- this.requestDesktopViewportSync({ force: true });
},
- beforeHostHidden(options = {}) {
- this._desktopHostVisible = false;
+ beforeHostHidden() {
this.flushInput();
- this.clearDesktopViewportSyncTimers();
- this.stopDesktopMonitor();
- this.stopDesktopKeyboardBridge();
- this.stopDesktopClipboardBridge();
- this.unloadDesktopFrames();
},
cleanup() {
this.flushInput();
- this.stopDesktopMonitor();
- this.stopDesktopResizeObserver();
- this.clearDesktopViewportSyncTimers();
- this.stopXpraDesktopPrime();
- this.stopDesktopKeyboardBridge();
- this.stopDesktopClipboardBridge();
- if (!this._desktopIntentionalShutdown) this.moveDesktopFrameToKeepalive();
- this._floatingCleanup?.();
- this._floatingCleanup = null;
+ this._headerCleanup?.();
+ this._headerCleanup = null;
if (this._mode === "modal") this._root = null;
},
@@ -317,176 +203,6 @@ 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 });
- this.updateDesktopMonitor();
- return existing;
- }
- const showProgress = options.progress !== false;
- const progressMessage = String(options.message || DESKTOP_START_MESSAGE);
- if (this._desktopStarting) {
- if (showProgress) {
- this.loading = true;
- this.message = progressMessage;
- }
- return await this._desktopStarting;
- }
-
- this._desktopStarting = (async () => {
- try {
- if (showProgress) {
- this.loading = true;
- this.message = progressMessage;
- this.error = "";
- }
- 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;
- if (existingIndex >= 0) {
- desktopTabId = this.tabs[existingIndex].tab_id;
- this.tabs.splice(existingIndex, 1, { ...this.tabs[existingIndex], ...session, tab_id: desktopTabId });
- } else {
- this.tabs.unshift(session);
- }
- this.tabs = this.tabs.map((tab) => (
- this.hasOfficialOffice(tab)
- ? {
- ...tab,
- desktop: session.desktop,
- desktop_session_id: session.desktop_session_id,
- session_id: this.isDesktopSession(tab) ? session.session_id : tab.session_id,
- }
- : tab
- ));
- if (options.select || !this.session) {
- this.selectTab(desktopTabId, { focus: false });
- } else {
- this.updateDesktopMonitor();
- }
- this.restoreDesktopFrames();
- return { ...session, tab_id: desktopTabId };
- } catch (error) {
- this.error = error instanceof Error ? error.message : String(error);
- return null;
- } finally {
- if (showProgress) {
- this.loading = false;
- if (this.message === progressMessage) this.message = "";
- }
- this._desktopStarting = null;
- }
- })();
- return await this._desktopStarting;
- },
-
async create(kind = "document", format = "") {
const fmt = String(format || (kind === "spreadsheet" ? "ods" : kind === "presentation" ? "odp" : "md")).toLowerCase();
const title = this.defaultTitle(kind, fmt);
@@ -527,6 +243,12 @@ const model = {
this.error = response.error || "Document could not be opened.";
return null;
}
+ if (response?.requires_desktop || this.isDesktopDocument(response)) {
+ const document = normalizeDocument(response.document || response);
+ this.setMessage(`${documentLabel(document)} is ready. Use Open in Desktop to edit it.`);
+ await this.refresh();
+ return response;
+ }
const session = normalizeSession(response);
this.installSession(session);
await this.refresh();
@@ -540,10 +262,6 @@ const model = {
},
installSession(session) {
- if (this.isDesktopOfficeDocument(session)) {
- this.installDesktopDocumentSession(session);
- return;
- }
const existingIndex = this.tabs.findIndex((tab) => (
(session.file_id && tab.file_id === session.file_id)
|| (session.path && tab.path === session.path)
@@ -558,67 +276,14 @@ const model = {
this.selectTab(this.activeTabId);
},
- installDesktopDocumentSession(session) {
- this.setDesktopIntentionalShutdown(false);
- this.tabs = this.tabs.filter((tab) => !this.isDesktopOfficeDocument(tab));
- let desktopTab = this.tabs.find((tab) => this.isDesktopSession(tab));
- if (!desktopTab) {
- desktopTab = {
- ...session,
- tab_id: SYSTEM_DESKTOP_FILE_ID,
- file_id: SYSTEM_DESKTOP_FILE_ID,
- extension: "desktop",
- title: "Desktop",
- path: session.desktop?.desktop_path || "/desktop/session",
- mode: "desktop",
- document: {
- file_id: SYSTEM_DESKTOP_FILE_ID,
- path: session.desktop?.desktop_path || "/desktop/session",
- basename: "Desktop",
- title: "Desktop",
- extension: "desktop",
- },
- dirty: false,
- };
- this.tabs.unshift(desktopTab);
- }
- const documentSession = { ...session, tab_id: session.tab_id || uniqueTabId(session) };
- const existingIndex = this.tabs.findIndex((tab) => (
- (documentSession.file_id && tab.file_id === documentSession.file_id)
- || (documentSession.path && tab.path === documentSession.path)
- ));
- if (existingIndex >= 0) {
- this.tabs.splice(existingIndex, 1, documentSession);
- } else {
- this.tabs.push(documentSession);
- }
- this.session = documentSession;
- this.activeTabId = documentSession.tab_id;
- this.editorText = "";
- this.dirty = false;
- this.resetHistory("");
- this.queueRender({ focus: true });
- this.restoreDesktopFrames();
- this.requestDesktopViewportSync({ force: true });
- this.updateDesktopMonitor();
- },
-
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();
},
ensureActiveTab() {
@@ -633,21 +298,12 @@ const model = {
async closeTab(tabId) {
const tab = this.tabs.find((item) => item.tab_id === tabId);
if (!tab) return;
- if (this.isDesktopSession(tab)) {
- this.selectTab(tab.tab_id, { focus: false });
- return;
- }
- if (!this.hasOfficialOffice(tab) && (tab.dirty || (this.isActiveTab(tab) && this.dirty))) {
+ if (tab.dirty || (this.isActiveTab(tab) && this.dirty)) {
const shouldSave = globalThis.confirm?.("Save changes?") ?? true;
if (shouldSave) await this.save();
}
try {
- if (this.hasOfficialOffice(tab)) {
- await callOffice("desktop_save", {
- desktop_session_id: tab.desktop_session_id || tab.session_id,
- file_id: tab.file_id || "",
- }).catch(() => null);
- } else if (tab.session_id) {
+ if (tab.session_id) {
await requestOffice("office_close", { session_id: tab.session_id }, 2500).catch(() => null);
}
await callOffice("close", {
@@ -665,48 +321,17 @@ const model = {
this.dirty = false;
this.ensureActiveTab();
}
- this.updateDesktopMonitor();
this.ensureActiveTab();
await this.refresh();
},
async closeActiveFile() {
- if (!this.session || this.isDesktopSession() || this.loading) return;
+ if (!this.session || this.loading) return;
await this.closeTab(this.session.tab_id);
},
async save() {
- if (!this.session || this.saving) return;
- if (this.isDesktopSession()) return;
- if (this.hasOfficialOffice()) {
- this.saving = true;
- this.error = "";
- try {
- const response = await callOffice("desktop_save", {
- desktop_session_id: this.session.desktop_session_id || this.session.session_id,
- file_id: this.session.file_id || "",
- });
- if (response?.ok === false) throw new Error(response.error || "Save failed.");
- const document = normalizeDocument(response.document || this.session.document || {});
- const updated = {
- ...this.session,
- dirty: false,
- document,
- path: document.path || this.session.path,
- file_id: document.file_id || this.session.file_id,
- version: document.version || response.version || this.session.version,
- };
- this.replaceActiveSession(updated);
- this.dirty = false;
- this.setMessage("Saved");
- await this.refresh();
- } catch (error) {
- this.error = error instanceof Error ? error.message : String(error);
- } finally {
- this.saving = false;
- }
- return;
- }
+ if (!this.session || this.saving || !this.isMarkdown()) return;
this.syncEditorText();
this.saving = true;
this.error = "";
@@ -741,8 +366,7 @@ const model = {
},
async renameActiveFile() {
- if (!this.session || this.isDesktopSession() || this.saving) return;
-
+ if (!this.session || this.saving) return;
const session = this.session;
const path = session.path || session.document?.path || "";
if (!path) {
@@ -800,7 +424,6 @@ const model = {
extension: document.extension || session.extension,
file_id: document.file_id || session.file_id,
version: document.version || response.version || session.version,
- desktop: response.desktop?.desktop || session.desktop,
text: this.session?.tab_id === session.tab_id ? this.editorText : session.text,
dirty: false,
};
@@ -820,7 +443,6 @@ const model = {
const index = this.tabs.findIndex((tab) => tab.tab_id === (previous?.tab_id || next.tab_id));
if (index >= 0) this.tabs.splice(index, 1, next);
this.queueRender();
- this.updateDesktopMonitor();
},
setMessage(value) {
@@ -889,12 +511,11 @@ const model = {
syncEditorText() {
if (!this.session) return;
- if (this.hasOfficialOffice()) return;
this.session.text = this.editorText;
},
scheduleInputPush() {
- if (!this.session?.session_id) return;
+ if (!this.session?.session_id || !this.isMarkdown()) return;
if (this._inputTimer) globalThis.clearTimeout(this._inputTimer);
this._inputTimer = globalThis.setTimeout(() => {
this._inputTimer = null;
@@ -903,8 +524,7 @@ const model = {
},
flushInput() {
- if (!this.session?.session_id) return;
- if (this.hasOfficialOffice()) return;
+ if (!this.session?.session_id || !this.isMarkdown()) return;
this.syncEditorText();
requestOffice("office_input", {
session_id: this.session.session_id,
@@ -913,12 +533,7 @@ const model = {
},
format(command) {
- if (!this.session) return;
- if (!this.isMarkdown()) return;
- this.applySourceFormat(command);
- },
-
- applySourceFormat(command) {
+ if (!this.session || !this.isMarkdown()) return;
const textarea = this._root?.querySelector?.("[data-office-source]");
if (!textarea) return;
const start = textarea.selectionStart || 0;
@@ -941,7 +556,6 @@ const model = {
},
queueRender(options = {}) {
- const force = Boolean(options.force);
if (options.focus) {
this._pendingFocus = true;
this._pendingFocusEnd = options.end !== false;
@@ -964,12 +578,9 @@ const model = {
},
focusEditor(options = {}) {
- if (!this.session) return false;
- if (this.hasOfficialOffice()) {
- return this.focusDesktopFrame(this.desktopFrame(), { arm: true });
- }
+ if (!this.session || !this.isMarkdown()) return false;
const source = this._root?.querySelector?.("[data-office-source]");
- if (!this.isMarkdown() || !source) return false;
+ if (!source) return false;
source.focus?.({ preventScroll: true });
if (!editorContainsFocus(source)) return false;
if (options.end !== false) placeCaretAtEnd(source);
@@ -981,1275 +592,17 @@ const model = {
return ext === "md";
},
- isBinaryOffice(tab = this.session) {
+ isDesktopDocument(tab = this.session) {
const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
- return ["odt", "ods", "odp", "docx", "xlsx", "pptx"].includes(ext);
- },
-
- hasOfficialOffice(tab = this.session) {
- return Boolean(tab?.desktop?.available && tab.desktop.url);
- },
-
- isDesktopSession(tab = this.session) {
- return Boolean(
- tab
- && (
- tab.file_id === SYSTEM_DESKTOP_FILE_ID
- || tab.extension === "desktop"
- || tab.mode === "desktop"
- )
- );
- },
-
- isDesktopOfficeDocument(tab = this.session) {
- return Boolean(tab && this.hasOfficialOffice(tab) && !this.isDesktopSession(tab) && this.isBinaryOffice(tab));
+ return DESKTOP_DOCUMENT_EXTENSIONS.has(ext);
},
hasActiveFile(tab = this.session) {
- return Boolean(tab && !this.isDesktopSession(tab) && (this.isMarkdown(tab) || this.isDesktopOfficeDocument(tab)));
- },
-
- isVisibleOfficeTab(tab = {}) {
- return Boolean(this.hasActiveFile(tab));
+ return Boolean(tab && this.isMarkdown(tab));
},
visibleTabs() {
- return this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));
- },
-
- officialOfficeUrl(tab = this.session) {
- const url = tab?.desktop?.url || "";
- if (!url) return "";
- try {
- const parsed = new URL(url, window.location.href);
- const secureContext = globalThis.isSecureContext === true;
- parsed.searchParams.set("offscreen", secureContext ? "true" : "false");
- parsed.searchParams.set("clipboard_poll", secureContext ? "true" : "false");
- if (parsed.origin === window.location.origin) return `${parsed.pathname}${parsed.search}${parsed.hash}`;
- return parsed.href;
- } catch {
- return url;
- }
- },
-
- isDesktopHostVisible() {
- if (this._mode === "modal") return true;
- const canvas = rightCanvasStore;
- return Boolean(canvas?.isOpen && (canvas.isSurfaceMounted?.("office") ?? canvas.activeSurfaceId === "office"));
- },
-
- setDesktopHostVisible(visible) {
- const next = Boolean(visible);
- if (!next && this._mode === "modal") return;
- if (this._desktopHostVisible === next) return;
- this._desktopHostVisible = next;
- if (next) {
- this.afterDesktopHostShown({ source: "canvas-visibility" });
- } else {
- this.beforeHostHidden({ reason: "hidden" });
- }
- },
-
- desktopFrames() {
- 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;
- },
-
- isUsableDesktopFrame(frame) {
- if (!frame?.contentWindow) return false;
- const rect = frame.getBoundingClientRect?.();
- return Boolean(rect && rect.width >= 120 && rect.height >= 80);
- },
-
- desktopFrame(preferred = null) {
- if (this.isUsableDesktopFrame(preferred)) return preferred;
- const rootFrame = this._root?.querySelector?.("[data-office-desktop-frame]");
- if (this.isUsableDesktopFrame(rootFrame)) return rootFrame;
- const frames = this.desktopFrames();
- return frames
- .filter((frame) => this.isUsableDesktopFrame(frame))
- .sort((left, right) => {
- const leftRect = left.getBoundingClientRect();
- const rightRect = right.getBoundingClientRect();
- return (rightRect.width * rightRect.height) - (leftRect.width * leftRect.height);
- })[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();
- this.moveDesktopFrameToKeepalive();
- },
-
- restoreDesktopFrames() {
- if (!this.isDesktopHostVisible()) return;
- this.attachDesktopFrame();
- },
-
- afterDesktopHostShown() {
- if (!this.hasOfficialOffice()) return;
- this._desktopHostVisible = true;
- this._desktopResizeKey = "";
- this._desktopResizePendingKey = "";
- this._desktopResizeSuspended = false;
- this._desktopResizePending = false;
- this.restoreDesktopFrames();
- this.requestDesktopViewportSync({ force: true, frame: this.desktopFrame() });
- },
-
- beforeDesktopHostHandoff() {
- this.stopDesktopResizeObserver();
- this.clearDesktopViewportSyncTimers();
- this.stopXpraDesktopPrime();
- this._desktopResizeKey = "";
- this._desktopResizePendingKey = "";
- this._desktopResizeSuspended = true;
- this._desktopResizePending = true;
- },
-
- cancelDesktopHostHandoff() {
- this._desktopResizeSuspended = false;
- this._desktopResizePending = false;
- this.requestDesktopViewportSync({ force: true, frame: this.desktopFrame() });
- },
-
- onDesktopFrameLoaded(event = null) {
- if (event?.target?.getAttribute?.("src") === "about:blank") return;
- if (!this.isDesktopHostVisible()) return;
- this.error = "";
- this.queueDesktopFrameFocus(event?.target || null);
- this.requestDesktopViewportSync({ force: true, frame: event?.target || null });
- },
-
- queueDesktopFrameFocus(frame = null) {
- for (const delay of [0, 80, 260]) {
- globalThis.setTimeout(() => {
- if (!this.hasOfficialOffice()) return;
- if (isEditableInputTarget(document.activeElement)) return;
- this.focusDesktopFrame(frame || this.desktopFrame(), { arm: true });
- }, delay);
- }
- },
-
- focusDesktopFrame(frame = null, options = {}) {
- if (this._desktopFocusInProgress) return false;
- const target = this.desktopFrame(frame);
- if (!target) return false;
- if (options.arm !== false) this._desktopKeyboardActive = true;
- this._desktopFocusInProgress = true;
- try {
- target.setAttribute("tabindex", "0");
- target.focus?.({ preventScroll: true });
- target.contentWindow?.focus?.();
- if (target.contentDocument?.body && !target.contentDocument.body.hasAttribute("tabindex")) {
- target.contentDocument.body.tabIndex = -1;
- }
- target.contentDocument?.body?.focus?.({ preventScroll: true });
- if (target.contentWindow?.client) target.contentWindow.client.capture_keyboard = true;
- } catch {
- target.focus?.({ preventScroll: true });
- } finally {
- this._desktopFocusInProgress = false;
- }
- const focused = Boolean(document.activeElement === target || target.contentDocument?.hasFocus?.());
- this.updateDesktopKeyboardCaptureState(target);
- return focused;
- },
-
- updateDesktopMonitor() {
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) {
- this.stopDesktopMonitor();
- this.stopDesktopResizeObserver();
- this._desktopKeyboardActive = false;
- this._desktopBridgeReady = false;
- this.updateDesktopKeyboardCaptureState();
- return;
- }
- const sessionId = this.session?.desktop_session_id || this.session?.session_id || "";
- const tabId = this.session?.tab_id || "";
- if (
- sessionId
- && tabId
- && this._desktopHeartbeatTimer
- && this._desktopHeartbeatSessionId === sessionId
- && this._desktopHeartbeatTabId === tabId
- ) return;
- this.startDesktopMonitor();
- this.startDesktopResizeObserver();
- },
-
- startDesktopResizeObserver() {
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) {
- this.stopDesktopResizeObserver();
- return;
- }
- const frame = this.desktopFrame();
- const target = frame?.parentElement || frame;
- if (!target) {
- this.stopDesktopResizeObserver();
- return;
- }
- if (this._desktopResizeCleanup && this._desktopResizeTarget === target) return;
- this.stopDesktopResizeObserver();
-
- const resize = () => this.queueDesktopResize();
- const resizeStart = () => this.suspendDesktopResize();
- const resizeEnd = () => this.resumeDesktopResize();
- const cleanup = [];
- if (typeof ResizeObserver !== "undefined") {
- const observer = new ResizeObserver(resize);
- observer.observe(target);
- cleanup.push(() => observer.disconnect());
- }
- globalThis.addEventListener?.("resize", resize);
- cleanup.push(() => globalThis.removeEventListener?.("resize", resize));
- globalThis.addEventListener?.("right-canvas-resize-start", resizeStart);
- cleanup.push(() => globalThis.removeEventListener?.("right-canvas-resize-start", resizeStart));
- globalThis.addEventListener?.("right-canvas-resize-end", resizeEnd);
- cleanup.push(() => globalThis.removeEventListener?.("right-canvas-resize-end", resizeEnd));
- this._desktopResizeTarget = target;
- this._desktopResizeCleanup = () => cleanup.splice(0).reverse().forEach((entry) => entry());
- resize();
- },
-
- stopDesktopResizeObserver() {
- if (this._desktopResizeTimer) {
- globalThis.clearTimeout(this._desktopResizeTimer);
- }
- this._desktopResizeTimer = null;
- this._desktopResizeCleanup?.();
- this._desktopResizeCleanup = null;
- this._desktopResizeTarget = null;
- this._desktopResizeKey = "";
- this._desktopResizePendingKey = "";
- this._desktopResizeSuspended = false;
- this._desktopResizePending = false;
- },
-
- suspendDesktopResize() {
- this._desktopResizeSuspended = true;
- if (this._desktopResizeTimer) {
- globalThis.clearTimeout(this._desktopResizeTimer);
- this._desktopResizeTimer = null;
- }
- this._desktopResizePendingKey = "";
- },
-
- resumeDesktopResize() {
- const hadPendingResize = this._desktopResizePending;
- this._desktopResizeSuspended = false;
- this._desktopResizePending = false;
- if (hadPendingResize || this.hasOfficialOffice()) {
- this.queueDesktopResize({ force: true });
- }
- },
-
- shouldDeferDesktopResize() {
- return Boolean(
- this._desktopResizeSuspended
- || document.body?.classList?.contains("right-canvas-resizing")
- || document.querySelector?.(".modal-inner.office-modal.is-resizing")
- );
- },
-
- clearDesktopViewportSyncTimers() {
- for (const timer of this._desktopViewportSyncTimers.splice(0)) {
- globalThis.clearTimeout(timer);
- }
- },
-
- requestDesktopViewportSync(options = {}) {
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) return;
- if (options.force) this.clearDesktopViewportSyncTimers();
- const run = (force = false) => {
- this.syncDesktopViewport({ ...options, force });
- };
- if (globalThis.requestAnimationFrame) {
- globalThis.requestAnimationFrame(() => run(Boolean(options.force)));
- } else {
- globalThis.setTimeout(() => run(Boolean(options.force)), 0);
- }
- if (options.followup === false) return;
- const timer = globalThis.setTimeout(() => {
- this._desktopViewportSyncTimers = this._desktopViewportSyncTimers.filter((item) => item !== timer);
- run(false);
- }, options.force ? 260 : 180);
- this._desktopViewportSyncTimers.push(timer);
- },
-
- syncDesktopViewport(options = {}) {
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) return false;
- const frame = this.desktopFrame(options.frame || null);
- if (!frame) return false;
- this.startDesktopResizeObserver();
- this.primeXpraDesktopFrame({ reset: true, frame });
- this.queueDesktopResize({
- force: Boolean(options.force),
- serverResize: options.serverResize !== false,
- frame,
- });
- this.updateDesktopMonitor();
- return true;
- },
-
- primeXpraDesktopFrame(options = {}) {
- if (options.reset) {
- this.stopXpraDesktopPrime();
- this._desktopPrimeAttempts = 0;
- }
- if (this.applyXpraDesktopFrameMode(options.frame || null)) return;
- if (this._desktopPrimeAttempts >= XPRA_DESKTOP_PRIME_ATTEMPTS) return;
- this._desktopPrimeAttempts += 1;
- if (this._desktopPrimeTimer) globalThis.clearTimeout(this._desktopPrimeTimer);
- this._desktopPrimeTimer = globalThis.setTimeout(() => {
- this._desktopPrimeTimer = null;
- this.primeXpraDesktopFrame();
- }, XPRA_DESKTOP_PRIME_INTERVAL_MS);
- },
-
- stopXpraDesktopPrime() {
- if (this._desktopPrimeTimer) globalThis.clearTimeout(this._desktopPrimeTimer);
- this._desktopPrimeTimer = null;
- },
-
- applyXpraDesktopFrameMode(preferredFrame = null, options = {}) {
- const frame = this.desktopFrame(preferredFrame);
- const remoteWindow = frame?.contentWindow;
- if (!remoteWindow) return false;
- const requestServerResize = options.requestServerResize === true;
- const requestRefresh = options.requestRefresh !== false;
- try {
- const remoteDocument = frame.contentDocument || remoteWindow.document;
- this.installXpraDesktopFrameCss(remoteDocument);
- this.installXpraDesktopFramePatches(remoteWindow, remoteDocument);
- const client = remoteWindow.client;
- if (!client) return false;
- this.installXpraDesktopClientPatches(remoteWindow, client);
- this.installXpraDesktopCursorPatches(remoteWindow, remoteDocument, client);
- this.installXpraDesktopKeyboardBridge(frame, remoteWindow, remoteDocument, client);
- this.installXpraDesktopClipboardBridge(frame, remoteWindow, remoteDocument, client);
- const container = client.container || remoteDocument?.querySelector?.("#screen");
- if (!container) return false;
-
- client.server_is_desktop = true;
- client.server_resize_exact = true;
- remoteDocument?.body?.classList?.add("desktop");
-
- const windows = Object.values(client.id_to_window || {});
- if (!client.connected || !windows.length) return false;
-
- const width = Math.round(container.clientWidth || remoteWindow.innerWidth || 0);
- const height = Math.round(container.clientHeight || remoteWindow.innerHeight || 0);
- if (width > 0 && height > 0) {
- client.desktop_width = width;
- client.desktop_height = height;
- }
- if (requestServerResize && width > 0 && height > 0 && typeof client._screen_resized === "function") {
- client.desktop_width = 0;
- client.desktop_height = 0;
- client.__a0AllowScreenResize = true;
- try {
- client._screen_resized(new remoteWindow.Event("resize"));
- } finally {
- client.__a0AllowScreenResize = false;
- }
- }
-
- for (const xpraWindow of windows) {
- this.normalizeXpraDesktopWindow(xpraWindow, width, height);
- xpraWindow.screen_resized?.();
- this.normalizeXpraDesktopWindow(xpraWindow, width, height);
- xpraWindow.updateCSSGeometry?.();
- this.fitXpraDesktopWindowElement(xpraWindow, width, height);
- this.installXpraDesktopWheelBridge(remoteWindow, xpraWindow);
- if (requestRefresh && xpraWindow.wid != null) client.request_refresh?.(xpraWindow.wid);
- }
- this.installXpraDesktopAgentBridge(frame, remoteWindow, remoteDocument, client, container);
- return true;
- } catch (error) {
- console.warn("Xpra desktop viewport prime skipped", error);
- return false;
- }
- },
-
- installXpraDesktopAgentBridge(frame, remoteWindow, remoteDocument, client, container) {
- if (!frame || !remoteWindow || !remoteDocument || !client) return null;
- const store = this;
- const finite = (value, fallback = 0) => {
- const number = Number(value);
- return Number.isFinite(number) ? number : fallback;
- };
- const metrics = () => {
- const desktopWidth = Math.max(1, finite(client.desktop_width || container?.clientWidth || remoteWindow.innerWidth, 1));
- const desktopHeight = Math.max(1, finite(client.desktop_height || container?.clientHeight || remoteWindow.innerHeight, 1));
- const clientWidth = Math.max(1, finite(container?.clientWidth || remoteWindow.innerWidth, desktopWidth));
- const clientHeight = Math.max(1, finite(container?.clientHeight || remoteWindow.innerHeight, desktopHeight));
- return {
- desktopWidth,
- desktopHeight,
- clientWidth,
- clientHeight,
- scaleX: clientWidth / desktopWidth,
- scaleY: clientHeight / desktopHeight,
- };
- };
- const bridge = frame.__agentZeroDesktopBridge || {};
- Object.assign(bridge, {
- ready: true,
- state: async (options = {}) => {
- const result = await callOffice("desktop_state", {
- include_screenshot: options.includeScreenshot === true || options.include_screenshot === true,
- });
- store._desktopLastState = result;
- return result;
- },
- focus: (options = {}) => store.focusDesktopFrame(frame, { ...options, arm: options.arm !== false }),
- requestRefresh: () => {
- for (const xpraWindow of Object.values(client.id_to_window || {})) {
- if (xpraWindow?.wid != null) client.request_refresh?.(xpraWindow.wid);
- }
- return true;
- },
- desktopToClient: (x, y) => {
- const value = metrics();
- return {
- x: Math.round(finite(x) * value.scaleX),
- y: Math.round(finite(y) * value.scaleY),
- scale_x: value.scaleX,
- scale_y: value.scaleY,
- };
- },
- clientToDesktop: (x, y) => {
- const value = metrics();
- return {
- x: Math.round(finite(x) / value.scaleX),
- y: Math.round(finite(y) / value.scaleY),
- scale_x: value.scaleX,
- scale_y: value.scaleY,
- };
- },
- diagnostics: () => store.desktopBridgeDiagnostics(frame),
- });
- frame.agentZeroDesktop = bridge;
- frame.__agentZeroDesktopBridge = bridge;
- remoteWindow.agentZeroDesktop = bridge;
- remoteWindow.__agentZeroDesktopBridge = bridge;
- this._desktopBridgeReady = true;
- this.updateDesktopKeyboardCaptureState(frame);
- return bridge;
- },
-
- desktopBridgeDiagnostics(frame = null) {
- return {
- ready: this._desktopBridgeReady,
- keyboard: this.updateDesktopKeyboardCaptureState(frame),
- lastStateOk: this._desktopLastState?.ok ?? null,
- };
- },
-
- updateDesktopKeyboardCaptureState(frame = null) {
- const target = this.desktopFrame(frame);
- const client = target?.contentWindow?.client;
- const state = {
- ready: Boolean(target?.__agentZeroDesktopBridge || target?.contentWindow?.__agentZeroDesktopBridge),
- active: Boolean(this._desktopKeyboardActive),
- capture: Boolean(client?.capture_keyboard),
- focused: Boolean(target && (document.activeElement === target || target.contentDocument?.hasFocus?.())),
- };
- this._desktopKeyboardCaptureState = state;
- return state;
- },
-
- normalizeXpraDesktopWindow(xpraWindow, width, height) {
- if (!xpraWindow) return;
- const normalizedWidth = Math.max(1, Math.round(Number(width || 0)));
- const normalizedHeight = Math.max(1, Math.round(Number(height || 0)));
- xpraWindow.x = 0;
- xpraWindow.y = 0;
- xpraWindow.w = normalizedWidth;
- xpraWindow.h = normalizedHeight;
- xpraWindow.resizable = false;
- xpraWindow.decorations = false;
- xpraWindow.decorated = false;
- xpraWindow.metadata = { ...(xpraWindow.metadata || {}), decorations: false };
- xpraWindow._set_decorated?.(false);
- xpraWindow.configure_border_class?.();
- xpraWindow.leftoffset = 0;
- xpraWindow.rightoffset = 0;
- xpraWindow.topoffset = 0;
- xpraWindow.bottomoffset = 0;
- },
-
- fitXpraDesktopWindowElement(xpraWindow, width, height) {
- const cssWidth = `${Math.max(1, Number(width || 0))}px`;
- const cssHeight = `${Math.max(1, Number(height || 0))}px`;
- const windowElement = xpraWindow?.div;
- const canvas = xpraWindow?.canvas;
- windowElement?.style?.setProperty("left", "0px", "important");
- windowElement?.style?.setProperty("top", "0px", "important");
- windowElement?.style?.setProperty("position", "absolute", "important");
- windowElement?.style?.setProperty("width", cssWidth, "important");
- windowElement?.style?.setProperty("height", cssHeight, "important");
- windowElement?.style?.setProperty("transform", "none", "important");
- windowElement?.style?.setProperty("margin", "0", "important");
- canvas?.style?.setProperty("width", cssWidth, "important");
- canvas?.style?.setProperty("height", cssHeight, "important");
- canvas?.style?.setProperty("display", "block", "important");
- canvas?.style?.setProperty("margin", "0", "important");
- },
-
- installXpraDesktopWheelBridge(remoteWindow, xpraWindow) {
- const canvas = xpraWindow?.canvas;
- if (!remoteWindow || !canvas || canvas.__a0XpraWheelBridgeInstalled) return;
- if (typeof xpraWindow.mouse_scroll_cb !== "function") return;
- canvas.__a0XpraWheelBridgeInstalled = true;
- canvas.addEventListener("wheel", (event) => {
- event.stopImmediatePropagation?.();
- event.stopPropagation?.();
- event.preventDefault?.();
- const normalizedEvent = this.xpraDesktopWheelEvent(remoteWindow, canvas, event);
- xpraWindow.mouse_scroll_cb(normalizedEvent, xpraWindow);
- }, { passive: false, capture: true });
- },
-
- xpraDesktopWheelEvent(remoteWindow, canvas, event) {
- const finite = (value, fallback = 0) => {
- const number = Number(value);
- return Number.isFinite(number) ? number : fallback;
- };
- const deltaMode = finite(event.deltaMode, 0);
- const lineHeight = 16;
- const pageHeight = Math.max(1, remoteWindow.innerHeight || canvas.clientHeight || 800);
- const deltaScale = deltaMode === 1 ? lineHeight : deltaMode === 2 ? pageHeight : 1;
- const deltaX = finite(event.deltaX) * deltaScale;
- const deltaY = finite(event.deltaY) * deltaScale;
- const deltaZ = finite(event.deltaZ) * deltaScale;
- const wheelDeltaX = finite(event.wheelDeltaX, -deltaX);
- const wheelDeltaY = finite(event.wheelDeltaY, -deltaY);
- const wheelDelta = finite(event.wheelDelta, wheelDeltaY || wheelDeltaX);
- const getModifierState = (key) => {
- if (typeof event.getModifierState === "function") return event.getModifierState(key);
- const normalizedKey = String(key || "").toLowerCase();
- if (normalizedKey === "alt") return Boolean(event.altKey);
- if (normalizedKey === "control") return Boolean(event.ctrlKey);
- if (normalizedKey === "meta") return Boolean(event.metaKey);
- if (normalizedKey === "shift") return Boolean(event.shiftKey);
- return false;
- };
- const normalizedEvent = Object.create(event);
- Object.defineProperties(normalizedEvent, {
- target: { value: event.target || canvas },
- currentTarget: { value: canvas },
- clientX: { value: finite(event.clientX) },
- clientY: { value: finite(event.clientY) },
- pageX: { value: finite(event.pageX, finite(event.clientX)) },
- pageY: { value: finite(event.pageY, finite(event.clientY)) },
- screenX: { value: finite(event.screenX) },
- screenY: { value: finite(event.screenY) },
- offsetX: { value: finite(event.offsetX) },
- offsetY: { value: finite(event.offsetY) },
- movementX: { value: finite(event.movementX) },
- movementY: { value: finite(event.movementY) },
- button: { value: finite(event.button) },
- buttons: { value: finite(event.buttons) },
- which: { value: finite(event.which) },
- detail: { value: finite(event.detail) },
- deltaX: { value: deltaX },
- deltaY: { value: deltaY },
- deltaZ: { value: deltaZ },
- deltaMode: { value: 0 },
- wheelDeltaX: { value: wheelDeltaX },
- wheelDeltaY: { value: wheelDeltaY },
- wheelDelta: { value: wheelDelta },
- altKey: { value: Boolean(event.altKey) },
- ctrlKey: { value: Boolean(event.ctrlKey) },
- metaKey: { value: Boolean(event.metaKey) },
- shiftKey: { value: Boolean(event.shiftKey) },
- getModifierState: { value: getModifierState },
- preventDefault: { value: () => event.preventDefault?.() },
- stopPropagation: { value: () => event.stopPropagation?.() },
- stopImmediatePropagation: { value: () => event.stopImmediatePropagation?.() },
- });
- return normalizedEvent;
- },
-
- installXpraDesktopFrameCss(remoteDocument) {
- if (!remoteDocument || remoteDocument.getElementById("a0-xpra-desktop-frame-css")) return;
- const style = remoteDocument.createElement("style");
- style.id = "a0-xpra-desktop-frame-css";
- style.textContent = `
- html, body, #screen {
- width: 100% !important;
- height: 100% !important;
- overflow: hidden !important;
- }
- #float_menu,
- .windowhead,
- .windowbuttons {
- display: none !important;
- }
- #shadow_pointer {
- display: none !important;
- visibility: hidden !important;
- opacity: 0 !important;
- }
- .window,
- .window.border,
- .window.desktop,
- .undecorated,
- .undecorated.border,
- .undecorated.desktop {
- left: 0 !important;
- top: 0 !important;
- position: absolute !important;
- width: 100% !important;
- height: 100% !important;
- transform: none !important;
- margin: 0 !important;
- border: 0 !important;
- border-radius: 0 !important;
- box-shadow: none !important;
- }
- .window canvas,
- .undecorated canvas {
- display: block !important;
- width: 100% !important;
- height: 100% !important;
- margin: 0 !important;
- border: 0 !important;
- border-radius: 0 !important;
- box-shadow: none !important;
- }
- `;
- remoteDocument.head?.appendChild(style);
- },
-
- installXpraDesktopCursorPatches(remoteWindow, remoteDocument, client) {
- if (!remoteWindow || !remoteDocument || !client) return;
- const hideShadowPointer = () => {
- const pointer = remoteDocument.getElementById?.("shadow_pointer");
- pointer?.style?.setProperty("display", "none", "important");
- pointer?.style?.setProperty("visibility", "hidden", "important");
- pointer?.style?.setProperty("opacity", "0", "important");
- };
- hideShadowPointer();
-
- const pointerPacket = remoteWindow.PACKET_TYPES?.pointer_position || "pointer-position";
- if (!client.__a0XpraDesktopCursorPatched) {
- if (typeof client._process_pointer_position === "function") {
- client.__a0OriginalProcessPointerPosition = client._process_pointer_position;
- }
- client._process_pointer_position = function patchedProcessPointerPosition(packet) {
- hideShadowPointer();
- this.__a0LastPointerPosition = packet;
- return false;
- };
- client.__a0XpraDesktopCursorPatched = true;
- }
- if (client.packet_handlers && pointerPacket) {
- client.packet_handlers[pointerPacket] = client._process_pointer_position;
- }
- },
-
- installXpraDesktopFramePatches(remoteWindow, remoteDocument) {
- if (!remoteWindow || !remoteDocument) return;
- remoteWindow.__a0XpraDesktopFramePatches ||= {};
- const patches = remoteWindow.__a0XpraDesktopFramePatches;
- if (!patches.noWindowList && typeof remoteWindow.noWindowList === "function") {
- const originalNoWindowList = remoteWindow.noWindowList;
- remoteWindow.noWindowList = function patchedNoWindowList(...args) {
- if (!remoteDocument.querySelector("#open_windows")) return undefined;
- return originalNoWindowList.apply(this, args);
- };
- patches.noWindowList = true;
- }
- if (!patches.addWindowListItem && typeof remoteWindow.addWindowListItem === "function") {
- const originalAddWindowListItem = remoteWindow.addWindowListItem;
- remoteWindow.addWindowListItem = function patchedAddWindowListItem(...args) {
- if (!remoteDocument.querySelector("#open_windows_list")) return undefined;
- return originalAddWindowListItem.apply(this, args);
- };
- patches.addWindowListItem = true;
- }
- },
-
- installXpraDesktopClientPatches(remoteWindow, client) {
- if (!remoteWindow || !client || client.__a0XpraDesktopClientPatched) return;
- if (typeof client._screen_resized === "function") {
- const originalScreenResized = client._screen_resized.bind(client);
- client.__a0OriginalScreenResized = originalScreenResized;
- client._screen_resized = function patchedScreenResized(event) {
- if (client.__a0AllowScreenResize === true) return originalScreenResized(event);
- return false;
- };
- }
- client.__a0XpraDesktopClientPatched = true;
- },
-
- installXpraDesktopClipboardBridge(frame, remoteWindow, remoteDocument, client) {
- if (!frame || !remoteWindow || !remoteDocument || !client) return;
- this.ensureDesktopClipboardBridge();
- if (remoteWindow.__a0XpraDesktopClipboardBridgeInstalled) return;
-
- const onPaste = (event) => {
- this.handleDesktopPasteEvent(event, frame, remoteWindow, client);
- };
- const onKeydown = (event) => {
- if (this.isDesktopPasteShortcut(event)) {
- void this.syncHostClipboardToDesktop(frame);
- }
- };
- remoteWindow.addEventListener("paste", onPaste, true);
- remoteDocument.addEventListener("paste", onPaste, true);
- remoteWindow.addEventListener("keydown", onKeydown, true);
- remoteDocument.addEventListener("keydown", onKeydown, true);
- remoteWindow.__a0XpraDesktopClipboardBridgeInstalled = true;
- remoteWindow.__a0XpraDesktopClipboardBridgeCleanup = () => {
- remoteWindow.removeEventListener("paste", onPaste, true);
- remoteDocument.removeEventListener("paste", onPaste, true);
- remoteWindow.removeEventListener("keydown", onKeydown, true);
- remoteDocument.removeEventListener("keydown", onKeydown, true);
- remoteWindow.__a0XpraDesktopClipboardBridgeInstalled = false;
- };
- },
-
- ensureDesktopClipboardBridge() {
- if (this._desktopClipboardCleanup) return;
-
- const onPaste = (event) => {
- if (!this._desktopKeyboardActive || !this.hasOfficialOffice()) return;
- if (isEditableInputTarget(event.target)) return;
- const frame = this.desktopFrame();
- const remoteWindow = frame?.contentWindow;
- const client = remoteWindow?.client;
- if (!frame || !remoteWindow || !client) return;
- this.handleDesktopPasteEvent(event, frame, remoteWindow, client);
- };
-
- document.addEventListener("paste", onPaste, true);
- this._desktopClipboardCleanup = () => {
- document.removeEventListener("paste", onPaste, true);
- this._desktopClipboardCleanup = null;
- };
- },
-
- stopDesktopClipboardBridge() {
- this._desktopClipboardCleanup?.();
- },
-
- handleDesktopPasteEvent(event, frame, remoteWindow, client) {
- const text = this.desktopClipboardTextFromEvent(event);
- if (!text) return false;
- if (!this.syncXpraClipboardText(client, text, remoteWindow)) return false;
- event.preventDefault?.();
- event.stopImmediatePropagation?.();
- event.stopPropagation?.();
- this.focusDesktopFrame(frame, { arm: true });
- return true;
- },
-
- desktopClipboardTextFromEvent(event) {
- const data = (event?.originalEvent || event)?.clipboardData;
- if (!data?.getData) return "";
- for (const type of ["text/plain", "text", "Text", "STRING", "UTF8_STRING"]) {
- const value = data.getData(type);
- if (value) return value;
- }
- return "";
- },
-
- syncXpraClipboardText(client, text, remoteWindow = null) {
- const value = String(text ?? "");
- if (!client || !value || typeof client.send_clipboard_token !== "function") return false;
- const textPlain = remoteWindow?.TEXT_PLAIN || "text/plain";
- const utf8String = remoteWindow?.UTF8_STRING || "UTF8_STRING";
- const utilities = remoteWindow?.Utilities;
- const payload = utilities?.StringToUint8 ? utilities.StringToUint8(value) : value;
- client.clipboard_enabled = true;
- client.clipboard_direction = "both";
- client.clipboard_buffer = value;
- client.clipboard_pending = false;
- client.send_clipboard_token(payload, [textPlain, utf8String, "TEXT", "STRING"]);
- return true;
- },
-
- async syncHostClipboardToDesktop(frame = null) {
- const target = this.desktopFrame(frame);
- const remoteWindow = target?.contentWindow;
- const client = remoteWindow?.client;
- if (!client || !navigator.clipboard?.readText) return false;
- try {
- const text = await navigator.clipboard.readText();
- return this.syncXpraClipboardText(client, text, remoteWindow);
- } catch {
- return false;
- }
- },
-
- isDesktopPasteShortcut(event) {
- const key = String(event?.key || "").toLowerCase();
- return key === "v" && (event?.ctrlKey || event?.metaKey) && !event?.altKey;
- },
-
- installXpraDesktopKeyboardBridge(frame, remoteWindow, remoteDocument, client) {
- if (!frame || !remoteWindow || !remoteDocument || !client) return;
- this.ensureDesktopKeyboardBridge();
- frame.setAttribute("tabindex", "0");
- if (remoteWindow.__a0XpraDesktopKeyboardBridgeInstalled) return;
-
- const activate = () => {
- if (this._desktopFocusInProgress) return;
- this.focusDesktopFrame(frame, { arm: true });
- };
- const events = ["pointerdown", "mousedown", "touchstart", "focusin"];
- for (const eventName of events) {
- remoteDocument.addEventListener(eventName, activate, true);
- }
- remoteWindow.addEventListener("focus", activate, true);
- remoteWindow.__a0XpraDesktopKeyboardBridgeInstalled = true;
- remoteWindow.__a0XpraDesktopKeyboardBridgeCleanup = () => {
- for (const eventName of events) {
- remoteDocument.removeEventListener(eventName, activate, true);
- }
- remoteWindow.removeEventListener("focus", activate, true);
- remoteWindow.__a0XpraDesktopKeyboardBridgeInstalled = false;
- };
- },
-
- ensureDesktopKeyboardBridge() {
- if (this._desktopKeyboardCleanup) return;
-
- const deactivateWhenOutsideDesktop = (event) => {
- const target = event.target;
- if (target?.closest?.(".office-desktop-wrap") || target?.matches?.("[data-office-desktop-frame]")) return;
- this._desktopKeyboardActive = false;
- };
- const forwardKeyboardEvent = (event, pressed) => {
- if (!this._desktopKeyboardActive || !this.hasOfficialOffice()) return;
- if (event.defaultPrevented || isEditableInputTarget(event.target)) return;
-
- const frame = this.desktopFrame();
- if (!frame || document.activeElement === frame) return;
- const client = frame.contentWindow?.client;
- const handler = pressed ? client?._keyb_onkeydown : client?._keyb_onkeyup;
- if (!client?.capture_keyboard || typeof handler !== "function") return;
- if (pressed && this.isDesktopPasteShortcut(event)) {
- void this.syncHostClipboardToDesktop(frame);
- }
-
- const allowDefault = handler.call(client, event);
- if (!allowDefault) {
- event.preventDefault();
- event.stopPropagation();
- }
- };
- const onKeydown = (event) => forwardKeyboardEvent(event, true);
- const onKeyup = (event) => forwardKeyboardEvent(event, false);
-
- document.addEventListener("pointerdown", deactivateWhenOutsideDesktop, true);
- document.addEventListener("keydown", onKeydown, true);
- document.addEventListener("keyup", onKeyup, true);
- this._desktopKeyboardCleanup = () => {
- document.removeEventListener("pointerdown", deactivateWhenOutsideDesktop, true);
- document.removeEventListener("keydown", onKeydown, true);
- document.removeEventListener("keyup", onKeyup, true);
- this._desktopKeyboardActive = false;
- this._desktopKeyboardCleanup = null;
- };
- },
-
- stopDesktopKeyboardBridge() {
- this._desktopKeyboardCleanup?.();
- },
-
- queueDesktopResize(options = {}) {
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) return;
- const token = this.session?.desktop?.token || "";
- const frame = this.desktopFrame(options.frame || null);
- const target = frame?.parentElement || frame;
- if (!token || !target) return;
- const force = Boolean(options.force);
- const serverResize = options.serverResize !== false;
- const rect = target.getBoundingClientRect();
- const width = Math.round(rect.width);
- const height = Math.round(rect.height);
- if (width < 320 || height < 220) return;
- const key = `${token}:${width}x${height}`;
- const refreshFrameOnly = () => {
- this.applyXpraDesktopFrameMode(frame, { requestServerResize: false, requestRefresh: false });
- };
- if (!serverResize) {
- refreshFrameOnly();
- return;
- }
- if (key === this._desktopResizeKey || key === this._desktopResizePendingKey) {
- refreshFrameOnly();
- return;
- }
- refreshFrameOnly();
- if (!force && this.shouldDeferDesktopResize()) {
- this._desktopResizePending = true;
- return;
- }
- if (this._desktopResizeTimer) globalThis.clearTimeout(this._desktopResizeTimer);
- this._desktopResizePendingKey = key;
- this._desktopResizeTimer = globalThis.setTimeout(async () => {
- this._desktopResizeTimer = null;
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) {
- if (this._desktopResizePendingKey === key) this._desktopResizePendingKey = "";
- return;
- }
- if (!force && this.shouldDeferDesktopResize()) {
- if (this._desktopResizePendingKey === key) this._desktopResizePendingKey = "";
- this._desktopResizePending = true;
- return;
- }
- try {
- const params = new URLSearchParams({ token, width: String(width), height: String(height) });
- const response = await fetch(`/desktop/resize?${params.toString()}`, { credentials: "same-origin" });
- if (response.ok) {
- const result = await response.json().catch(() => ({}));
- this._desktopResizeKey = key;
- const activeFrame = this.desktopFrame(frame);
- const activeTarget = activeFrame?.parentElement || activeFrame;
- const activeRect = activeTarget?.getBoundingClientRect?.();
- const activeWidth = Math.round(activeRect?.width || 0);
- const activeHeight = Math.round(activeRect?.height || 0);
- if (activeWidth >= 320 && activeHeight >= 220) {
- const activeKey = `${token}:${activeWidth}x${activeHeight}`;
- if (activeKey !== key) {
- this.queueDesktopResize({ force: true, serverResize: true, frame: activeFrame });
- return;
- }
- }
- if (result?.reload) this.reloadDesktopFrame(activeFrame || frame);
- this.primeXpraDesktopFrame({ reset: true, frame: activeFrame || frame });
- }
- } catch (error) {
- console.warn("Desktop resize skipped", error);
- } finally {
- if (this._desktopResizePendingKey === key) this._desktopResizePendingKey = "";
- }
- }, DESKTOP_RESIZE_DELAY_MS);
- },
-
- reloadDesktopFrame(frame = null) {
- const target = this.desktopFrame(frame);
- if (!target) return;
- const current = target.getAttribute("src") || target.src || this.officialOfficeUrl();
- if (!current) return;
- try {
- const url = new URL(current, window.location.href);
- url.searchParams.set("a0_reload", String(Date.now()));
- target.setAttribute("src", `${url.pathname}${url.search}`);
- } catch {
- target.setAttribute("src", current);
- }
- },
-
- async handleDesktopUrlIntents(intents = []) {
- const incoming = Array.isArray(intents)
- ? intents.filter((intent) => intent && typeof intent === "object")
- : [];
- if (!incoming.length) return;
- this._desktopUrlIntentQueue.push(...incoming);
- if (this._desktopUrlIntentBusy) return;
-
- this._desktopUrlIntentBusy = true;
- try {
- while (this._desktopUrlIntentQueue.length) {
- const intent = this._desktopUrlIntentQueue.shift();
- await this.openDesktopUrlIntent(intent);
- }
- } finally {
- this._desktopUrlIntentBusy = false;
- }
- },
-
- async openDesktopUrlIntent(intent = {}) {
- const url = String(intent?.url || "").trim();
- const destination = this.browserDestinationForDesktopUrl();
- if (destination === "canvas") {
- await this.openBrowserCanvasForDesktopUrl(url);
- } else {
- await this.openBrowserModalForDesktopUrl(url);
- }
- this.setMessage(url ? "Opened link in Browser" : "Opened Browser");
- },
-
- browserDestinationForDesktopUrl() {
- if (this.isDesktopInModal()) return "canvas";
- return "modal";
- },
-
- isDesktopInModal() {
- if (isModalPathOpen(OFFICE_MODAL_PATH)) return true;
- const modalDesktop = Array.from(document.querySelectorAll(".office-panel"))
- .some((panel) => panel.closest?.(".modal") && panel.querySelector?.("[data-office-desktop-frame]"));
- if (modalDesktop) return true;
- if (rightCanvasStore?.isOpen && rightCanvasStore.activeSurfaceId === "office") return false;
- return this._mode === "modal";
- },
-
- async openBrowserCanvasForDesktopUrl(url = "") {
- if (rightCanvasStore?.isMobileMode) {
- await this.openBrowserModalForDesktopUrl(url);
- return;
- }
- const payload = { url, source: "desktop-url" };
- let opened = false;
- if (isModalPathOpen(BROWSER_MODAL_PATH)) {
- opened = await rightCanvasStore.dockSurface?.("browser", {
- ...payload,
- modalPath: BROWSER_MODAL_PATH,
- sourceModalPath: BROWSER_MODAL_PATH,
- });
- } else {
- opened = await rightCanvasStore.open?.("browser", payload);
- }
- if (!opened) {
- await this.openBrowserModalForDesktopUrl(url);
- return;
- }
- if (browserStore?.openUrlIntent) {
- await browserStore.openUrlIntent(url);
- }
- },
-
- async openBrowserModalForDesktopUrl(url = "") {
- if (rightCanvasStore?.isOpen && rightCanvasStore.activeSurfaceId === "browser") {
- await rightCanvasStore.openModalSurface?.("browser", { modalPath: BROWSER_MODAL_PATH });
- } else {
- const openModal = globalThis.ensureModalOpen || globalThis.openModal;
- const modalPromise = openModal?.(BROWSER_MODAL_PATH);
- if (modalPromise?.catch) {
- modalPromise.catch((error) => console.error("Browser modal open failed", error));
- }
- }
- const panel = await waitForElementByPredicate(() => browserPanelForMode("modal"));
- if (panel && browserStore?.onOpen) {
- await browserStore.onOpen(panel, { mode: "modal" });
- }
- if (browserStore?.openUrlIntent) {
- await browserStore.openUrlIntent(url);
- }
- },
-
- startDesktopMonitor() {
- this.stopDesktopMonitor();
- if (!this.hasOfficialOffice() || !this.isDesktopHostVisible()) return;
- const tabId = this.session?.tab_id || "";
- const sessionId = this.session?.desktop_session_id || this.session?.session_id || "";
- if (!tabId || !sessionId) return;
- this._desktopHeartbeatSessionId = sessionId;
- this._desktopHeartbeatTabId = tabId;
- this._desktopHeartbeatMisses = 0;
-
- const tick = async () => {
- if (!this.session || this.session.tab_id !== tabId || !this.hasOfficialOffice() || !this.isDesktopHostVisible()) return;
- try {
- const response = await callOffice("desktop_sync", {
- 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);
- if (response?.document) {
- const document = normalizeDocument(response.document);
- this.replaceActiveSession({
- ...this.session,
- document,
- path: document.path || this.session.path,
- file_id: document.file_id || this.session.file_id,
- version: document.version || this.session.version,
- });
- }
- } catch {
- if (!this.session || this.session.tab_id !== tabId) return;
- this._desktopHeartbeatMisses += 1;
- if (this._desktopHeartbeatMisses >= 2) {
- await this.handleOfficialOfficeClosed(tabId);
- }
- }
- };
-
- this._desktopHeartbeatTimer = globalThis.setInterval(tick, DESKTOP_HEARTBEAT_MS);
- globalThis.setTimeout(tick, Math.min(1200, DESKTOP_HEARTBEAT_MS));
- },
-
- stopDesktopMonitor() {
- if (this._desktopHeartbeatTimer) {
- globalThis.clearInterval(this._desktopHeartbeatTimer);
- }
- this._desktopHeartbeatTimer = null;
- this._desktopHeartbeatSessionId = "";
- this._desktopHeartbeatTabId = "";
- this._desktopHeartbeatMisses = 0;
- },
-
- 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.session
- : null;
- const target = tab || hiddenDesktopDocument;
- if (!target || target._desktopClosed) return;
- target._desktopClosed = true;
- this.stopDesktopMonitor();
- this.stopDesktopResizeObserver();
- this.stopXpraDesktopPrime();
- this.message = "Desktop is restarting";
- await this.ensureDesktopSession({
- force: true,
- select: this.activeTabId === tabId || Boolean(hiddenDesktopDocument),
- message: "Desktop is restarting",
- });
- target._desktopClosed = false;
- await this.refresh();
+ return this.tabs.filter((tab) => this.hasActiveFile(tab));
},
defaultTitle(kind, fmt) {
@@ -2276,7 +629,6 @@ const model = {
tabIcon(tab = {}) {
tab = tab || {};
const ext = String(tab.extension || tab.document?.extension || "").toLowerCase();
- if (this.isDesktopSession(tab)) return "desktop_windows";
if (ext === "md") return "article";
if (ext === "odt" || ext === "docx") return "description";
if (ext === "ods" || ext === "xlsx") return "table_chart";
@@ -2284,6 +636,17 @@ const model = {
return "draft";
},
+ async openActiveInDesktop() {
+ const target = this.session?.document || this.session;
+ if (!target?.path && !target?.file_id) return;
+ await openSurface("desktop", {
+ path: target.path || "",
+ file_id: target.file_id || "",
+ refresh: true,
+ source: "office-explicit-action",
+ });
+ },
+
async runNewMenuAction(action = "") {
const normalized = String(action || "").trim().toLowerCase();
if (normalized === "open") return await this.openFileBrowser();
@@ -2297,7 +660,7 @@ const model = {
installHeaderNewMenu(header = null) {
if (!header || header.querySelector(".office-header-actions")) return () => {};
- const root = globalThis.document.createElement("div");
+ const root = document.createElement("div");
root.className = "office-header-actions";
root.innerHTML = `
<button type="button" class="office-header-new-button" aria-haspopup="menu" aria-expanded="false">
@@ -2358,12 +721,10 @@ const model = {
await this.runNewMenuAction(action);
});
}
- globalThis.document.addEventListener("click", onDocumentClick);
- globalThis.document.addEventListener("keydown", onDocumentKeydown);
+ document.addEventListener("click", onDocumentClick);
+ document.addEventListener("keydown", onDocumentKeydown);
- const firstHeaderAction = header.querySelector(
- ".modal-surface-switcher, .modal-dock-button, .office-modal-focus-button, .modal-close",
- );
+ const firstHeaderAction = header.querySelector(".modal-close");
if (firstHeaderAction) {
firstHeaderAction.insertAdjacentElement("beforebegin", root);
} else {
@@ -2373,278 +734,28 @@ const model = {
setOpen(false);
return () => {
button?.removeEventListener("click", onButtonClick);
- globalThis.document.removeEventListener("click", onDocumentClick);
- globalThis.document.removeEventListener("keydown", onDocumentKeydown);
+ document.removeEventListener("click", onDocumentClick);
+ document.removeEventListener("keydown", onDocumentKeydown);
root.remove();
};
},
- setupFloatingModal(element = null) {
- const root = element || globalThis.document?.querySelector(".office-panel");
- const modal = root?.closest?.(".modal");
+ setupDocumentModal(element = null) {
+ const root = element || document.querySelector(".office-panel");
const inner = root?.closest?.(".modal-inner");
- const body = root?.closest?.(".modal-bd");
const header = inner?.querySelector?.(".modal-header");
- if (!inner || !body || !header || inner.dataset.officeModalReady === "1") return;
-
+ if (!inner || !header || inner.dataset.officeModalReady === "1") return;
inner.dataset.officeModalReady = "1";
- modal?.classList?.add("modal-floating", "modal-no-backdrop");
- inner.classList.add("office-modal", "modal-no-backdrop");
- body.classList.add("office-modal-body");
- header.style.cursor = "move";
-
- const inset = 8;
- const minWidth = 720;
- const minHeight = 520;
- const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
- const cleanup = [];
- let beforeFocusBounds = null;
- let dragging = false;
- let resizing = false;
- let pointerId = 0;
- let startX = 0;
- let startY = 0;
- let startLeft = 0;
- let startTop = 0;
- let startWidth = 0;
- let startHeight = 0;
- let resizeMode = "";
-
- const newMenuCleanup = this.installHeaderNewMenu(header);
-
- const currentBounds = () => {
- const rect = inner.getBoundingClientRect();
- return {
- left: rect.left,
- top: rect.top,
- width: rect.width,
- height: rect.height,
- };
- };
-
- const normalizedBounds = (bounds) => {
- const maxWidth = Math.max(320, globalThis.innerWidth - inset * 2);
- const maxHeight = Math.max(320, globalThis.innerHeight - inset * 2);
- const safeMinWidth = Math.min(minWidth, maxWidth);
- const safeMinHeight = Math.min(minHeight, maxHeight);
- const width = clamp(bounds.width, safeMinWidth, maxWidth);
- const height = clamp(bounds.height, safeMinHeight, maxHeight);
- return {
- width,
- height,
- left: clamp(bounds.left, inset, Math.max(inset, globalThis.innerWidth - width - inset)),
- top: clamp(bounds.top, inset, Math.max(inset, globalThis.innerHeight - height - inset)),
- };
- };
-
- const setBounds = (bounds) => {
- const next = normalizedBounds(bounds);
- inner.style.position = "fixed";
- inner.style.transform = "none";
- inner.style.left = `${Math.round(next.left)}px`;
- inner.style.top = `${Math.round(next.top)}px`;
- inner.style.width = `${Math.round(next.width)}px`;
- inner.style.height = `${Math.round(next.height)}px`;
- inner.style.right = "auto";
- inner.style.bottom = "auto";
- inner.style.margin = "0";
- };
-
- const ensurePosition = () => {
- setBounds(currentBounds());
- };
-
- const shield = globalThis.document.createElement("div");
- shield.className = "office-modal-input-shield";
- inner.appendChild(shield);
- cleanup.push(() => shield.remove());
-
- const setShield = (visible, cursor = "") => {
- shield.style.display = visible ? "block" : "none";
- shield.style.cursor = cursor;
- };
-
- const focusButton = globalThis.document.createElement("button");
- focusButton.type = "button";
- focusButton.className = "modal-dock-button office-modal-focus-button";
- focusButton.innerHTML = '<span class="material-symbols-outlined" aria-hidden="true">fullscreen</span>';
- const updateFocusButton = (active) => {
- const label = active ? "Restore size" : "Focus mode";
- focusButton.setAttribute("aria-label", label);
- focusButton.querySelector(".material-symbols-outlined").textContent = active ? "fullscreen_exit" : "fullscreen";
- };
- updateFocusButton(false);
- const closeButton = inner.querySelector(".modal-close");
- if (closeButton) {
- closeButton.insertAdjacentElement("beforebegin", focusButton);
- } else {
- header.appendChild(focusButton);
- }
- cleanup.push(() => focusButton.remove());
-
- const setFocusMode = (enabled) => {
- ensurePosition();
- if (enabled) {
- beforeFocusBounds = currentBounds();
- inner.classList.add("is-focus-mode");
- setBounds({
- left: inset,
- top: inset,
- width: globalThis.innerWidth - inset * 2,
- height: globalThis.innerHeight - inset * 2,
- });
- updateFocusButton(true);
- return;
- }
- inner.classList.remove("is-focus-mode");
- setBounds(beforeFocusBounds || currentBounds());
- beforeFocusBounds = null;
- updateFocusButton(false);
- };
-
- const onFocusClick = () => setFocusMode(!inner.classList.contains("is-focus-mode"));
- focusButton.addEventListener("click", onFocusClick);
- cleanup.push(() => focusButton.removeEventListener("click", onFocusClick));
-
- const onPointerDown = (event) => {
- if (event.button !== 0) return;
- if (event.target?.closest?.("button,a,input,textarea,select")) return;
- if (inner.classList.contains("is-focus-mode")) return;
- ensurePosition();
- const rect = inner.getBoundingClientRect();
- dragging = true;
- pointerId = event.pointerId;
- startX = event.clientX;
- startY = event.clientY;
- startLeft = rect.left;
- startTop = rect.top;
- startWidth = rect.width;
- startHeight = rect.height;
- inner.classList.add("is-dragging");
- setShield(true, "move");
- header.setPointerCapture?.(pointerId);
- event.preventDefault();
- };
-
- const onPointerMove = (event) => {
- if (!dragging || event.pointerId !== pointerId) return;
- setBounds({
- left: startLeft + event.clientX - startX,
- top: startTop + event.clientY - startY,
- width: startWidth,
- height: startHeight,
- });
- };
-
- const onPointerUp = (event) => {
- if (!dragging || event.pointerId !== pointerId) return;
- dragging = false;
- inner.classList.remove("is-dragging");
- setShield(false);
- header.releasePointerCapture?.(pointerId);
- };
-
- const createResizeHandle = (mode) => {
- const handle = globalThis.document.createElement("div");
- handle.className = `office-modal-resizer is-${mode}`;
- handle.dataset.officeResize = mode;
- inner.appendChild(handle);
- cleanup.push(() => handle.remove());
- return handle;
- };
-
- const onResizeDown = (event) => {
- if (event.button !== 0 || inner.classList.contains("is-focus-mode")) return;
- ensurePosition();
- const rect = inner.getBoundingClientRect();
- resizing = true;
- resizeMode = event.currentTarget.dataset.officeResize || "";
- pointerId = event.pointerId;
- startX = event.clientX;
- startY = event.clientY;
- startLeft = rect.left;
- startTop = rect.top;
- startWidth = rect.width;
- startHeight = rect.height;
- inner.classList.add("is-resizing");
- this.suspendDesktopResize();
- setShield(true, resizeMode === "right" ? "ew-resize" : resizeMode === "bottom" ? "ns-resize" : "nwse-resize");
- event.currentTarget.setPointerCapture?.(pointerId);
- event.preventDefault();
- event.stopPropagation();
- };
-
- const onResizeMove = (event) => {
- if (!resizing || event.pointerId !== pointerId) return;
- const dx = event.clientX - startX;
- const dy = event.clientY - startY;
- setBounds({
- left: startLeft,
- top: startTop,
- width: resizeMode === "bottom" ? startWidth : startWidth + dx,
- height: resizeMode === "right" ? startHeight : startHeight + dy,
- });
- };
-
- const onResizeUp = (event) => {
- if (!resizing || event.pointerId !== pointerId) return;
- resizing = false;
- resizeMode = "";
- inner.classList.remove("is-resizing");
- setShield(false);
- event.currentTarget.releasePointerCapture?.(pointerId);
- this.resumeDesktopResize();
- };
-
- header.addEventListener("pointerdown", onPointerDown);
- header.addEventListener("pointermove", onPointerMove);
- header.addEventListener("pointerup", onPointerUp);
- header.addEventListener("pointercancel", onPointerUp);
- cleanup.push(() => header.removeEventListener("pointerdown", onPointerDown));
- cleanup.push(() => header.removeEventListener("pointermove", onPointerMove));
- cleanup.push(() => header.removeEventListener("pointerup", onPointerUp));
- cleanup.push(() => header.removeEventListener("pointercancel", onPointerUp));
-
- for (const mode of ["right", "bottom", "corner"]) {
- const handle = createResizeHandle(mode);
- handle.addEventListener("pointerdown", onResizeDown);
- handle.addEventListener("pointermove", onResizeMove);
- handle.addEventListener("pointerup", onResizeUp);
- handle.addEventListener("pointercancel", onResizeUp);
- cleanup.push(() => handle.removeEventListener("pointerdown", onResizeDown));
- cleanup.push(() => handle.removeEventListener("pointermove", onResizeMove));
- cleanup.push(() => handle.removeEventListener("pointerup", onResizeUp));
- cleanup.push(() => handle.removeEventListener("pointercancel", onResizeUp));
- }
-
- const onWindowResize = () => {
- if (inner.classList.contains("is-focus-mode")) {
- setBounds({
- left: inset,
- top: inset,
- width: globalThis.innerWidth - inset * 2,
- height: globalThis.innerHeight - inset * 2,
- });
- return;
- }
- ensurePosition();
- };
- globalThis.addEventListener("resize", onWindowResize);
- cleanup.push(() => globalThis.removeEventListener("resize", onWindowResize));
-
- if (globalThis.requestAnimationFrame) {
- globalThis.requestAnimationFrame(ensurePosition);
- } else {
- globalThis.setTimeout(ensurePosition, 0);
- }
- this._floatingCleanup = () => {
- newMenuCleanup?.();
- cleanup.splice(0).reverse().forEach((entry) => entry());
- modal?.classList?.remove("modal-floating", "modal-no-backdrop");
- inner.classList.remove("is-dragging", "is-resizing", "is-focus-mode");
- this._desktopResizeSuspended = false;
- this._desktopResizePending = false;
+ inner.classList.add("office-modal");
+ this._headerCleanup = () => {
delete inner.dataset.officeModalReady;
+ inner.classList.remove("office-modal");
+ };
+ const menuCleanup = this.installHeaderNewMenu(header);
+ const previousCleanup = this._headerCleanup;
+ this._headerCleanup = () => {
+ menuCleanup?.();
+ previousCleanup?.();
};
},
};
diff --git a/plugins/_office/webui/thumbnail.jpg b/plugins/_office/webui/thumbnail.jpg
index 2f02c2195..e5fe998e0 100644
Binary files a/plugins/_office/webui/thumbnail.jpg and b/plugins/_office/webui/thumbnail.jpg differ