Agent Zero AI framework
Add Office Collabora canvas integration
Alessandrobf02987d5782
diff --git a/plugins/_office/api/collabora_logs.py b/plugins/_office/api/collabora_logs.pynew file mode 100644index 000000000..3708a801e--- /dev/null+++ b/plugins/_office/api/collabora_logs.py@@ -0,0 +1,13 @@+from __future__ import annotations++from helpers.api import ApiHandler, Request+from plugins._office.helpers import collabora_status+++class CollaboraLogs(ApiHandler):+ async def process(self, input: dict, request: Request) -> dict:+ return {+ "ok": True,+ "bootstrap": collabora_status.tail_file(collabora_status.BOOTSTRAP_LOG),+ "wrapper": collabora_status.tail_file(collabora_status.WRAPPER_LOG),+ }diff --git a/plugins/_office/api/collabora_status.py b/plugins/_office/api/collabora_status.pynew file mode 100644index 000000000..f2603abc6--- /dev/null+++ b/plugins/_office/api/collabora_status.py@@ -0,0 +1,11 @@+from __future__ import annotations++from helpers.api import ApiHandler, Request+from plugins._office.helpers.collabora_status import collect_status, read_status+++class CollaboraStatus(ApiHandler):+ async def process(self, input: dict, request: Request) -> dict:+ if input.get("fresh"):+ return collect_status()+ return read_status()diff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.pynew file mode 100644index 000000000..8a15f68ca--- /dev/null+++ b/plugins/_office/api/office_session.py@@ -0,0 +1,129 @@+from __future__ import annotations++import xml.etree.ElementTree as ET+from urllib.parse import quote, urlparse++import httpx+from helpers.api import ApiHandler, Request+from plugins._office.helpers import collabora_runtime, collabora_status, wopi_store+++DISCOVERY_URLS = (+ "http://127.0.0.1:9980/office/hosting/discovery",+ "http://127.0.0.1:9980/hosting/discovery",+)+++class OfficeSession(ApiHandler):+ async def process(self, input: dict, request: Request) -> dict:+ action = str(input.get("action") or "open").lower()+ if action == "status":+ return collabora_status.collect_status()+ if action == "retry":+ collabora_runtime.retry_bootstrap()+ return {"ok": True, **collabora_status.read_status()}+ if action == "recent":+ return {"ok": True, "documents": wopi_store.get_recent_documents()}+ if action == "create":+ doc = wopi_store.create_document(+ kind=str(input.get("kind") or "document"),+ title=str(input.get("title") or "Untitled"),+ fmt=str(input.get("format") or "docx"),+ content=str(input.get("content") or ""),+ path=str(input.get("path") or ""),+ )+ return await self._open_document(doc, input, request)+ if action == "open":+ doc = wopi_store.register_document(str(input.get("path") or ""))+ return await self._open_document(doc, input, request)+ 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"+ permission = "write" if mode == "edit" else "read"+ origin = self._origin(request)+ session = wopi_store.create_session(+ doc["file_id"],+ user_id=str(input.get("user_id") or "agent-zero-user"),+ permission=permission,+ origin=origin,+ )+ discovery = await self._discover()+ if not discovery.get("ok"):+ return {+ "ok": False,+ "error": discovery.get("error") or "Collabora discovery is unavailable",+ "file_id": doc["file_id"],+ "title": doc["basename"],+ "extension": doc["extension"],+ "status": collabora_status.collect_status(),+ }++ action_url = self._select_action(discovery["xml"], doc["extension"], mode)+ if not action_url:+ return {+ "ok": False,+ "error": f"Collabora does not advertise {mode} support for .{doc['extension']}",+ "file_id": doc["file_id"],+ "title": doc["basename"],+ "extension": doc["extension"],+ }++ wopi_src = f"http://127.0.0.1:80/wopi/files/{doc['file_id']}"+ iframe_action = self._same_origin_action(action_url, wopi_src, session["session_id"])+ return {+ "ok": True,+ "file_id": doc["file_id"],+ "iframe_action": iframe_action,+ "access_token": session["access_token"],+ "access_token_ttl": session["access_token_ttl"],+ "post_message_origin": origin,+ "title": doc["basename"],+ "extension": doc["extension"],+ "path": doc["path"],+ "version": wopi_store.item_version(doc),+ }++ def _origin(self, request: Request) -> str:+ origin = request.headers.get("Origin") or request.host_url.rstrip("/")+ return origin.rstrip("/")++ async def _discover(self) -> dict:+ for url in DISCOVERY_URLS:+ try:+ async with httpx.AsyncClient(timeout=8.0) as client:+ response = await client.get(url)+ if response.status_code == 200 and "wopi-discovery" in response.text.lower():+ return {"ok": True, "xml": response.text}+ except Exception:+ continue+ return {"ok": False, "error": "Collabora discovery is not reachable yet"}++ def _select_action(self, discovery_xml: str, extension: str, mode: str) -> str:+ root = ET.fromstring(discovery_xml)+ best = ""+ fallback = ""+ for action in root.findall(".//{*}action"):+ if action.attrib.get("ext", "").lower() != extension.lower():+ continue+ name = action.attrib.get("name", "").lower()+ urlsrc = action.attrib.get("urlsrc", "")+ if not urlsrc:+ continue+ if name == mode:+ best = urlsrc+ break+ if name == "view":+ fallback = urlsrc+ return best or fallback++ def _same_origin_action(self, urlsrc: str, wopi_src: str, session_id: str) -> str:+ parsed = urlparse(urlsrc)+ path = parsed.path or "/office/browser/cool.html"+ if not path.startswith("/office"):+ path = "/office" + path+ query = parsed.query+ base = path + (f"?{query}" if query else ("?" if urlsrc.endswith("?") else ""))+ separator = "" if base.endswith("?") or base.endswith("&") else ("&" if "?" in base else "?")+ base = f"{base}{separator}a0_session={quote(session_id, safe='')}"+ return f"{base}&WOPISrc={quote(wopi_src, safe='')}"diff --git a/plugins/_office/extensions/python/_functions/run_ui/init_a0/end/_20_collabora_bootstrap.py b/plugins/_office/extensions/python/_functions/run_ui/init_a0/end/_20_collabora_bootstrap.pynew file mode 100644index 000000000..8725346c0--- /dev/null+++ b/plugins/_office/extensions/python/_functions/run_ui/init_a0/end/_20_collabora_bootstrap.py@@ -0,0 +1,9 @@+from __future__ import annotations++from helpers.extension import Extension+from plugins._office.helpers.collabora_runtime import start_bootstrap_worker+++class CollaboraBootstrap(Extension):+ def execute(self, **kwargs):+ start_bootstrap_worker(force=False)diff --git a/plugins/_office/extensions/python/job_loop/_20_collabora_reconcile.py b/plugins/_office/extensions/python/job_loop/_20_collabora_reconcile.pynew file mode 100644index 000000000..0cc206b6a--- /dev/null+++ b/plugins/_office/extensions/python/job_loop/_20_collabora_reconcile.py@@ -0,0 +1,9 @@+from __future__ import annotations++from helpers.extension import Extension+from plugins._office.helpers.collabora_runtime import reconcile+++class CollaboraReconcile(Extension):+ async def execute(self, **kwargs):+ reconcile()diff --git a/plugins/_office/extensions/python/startup_migration/_20_office_routes.py b/plugins/_office/extensions/python/startup_migration/_20_office_routes.pynew file mode 100644index 000000000..71857a720--- /dev/null+++ b/plugins/_office/extensions/python/startup_migration/_20_office_routes.py@@ -0,0 +1,9 @@+from __future__ import annotations++from helpers.extension import Extension+from plugins._office.helpers.route_bootstrap import install_route_hooks+++class OfficeRoutesStartup(Extension):+ def execute(self, **kwargs):+ install_route_hooks()diff --git a/plugins/_office/extensions/webui/get_tool_message_handler/document-artifact-handler.js b/plugins/_office/extensions/webui/get_tool_message_handler/document-artifact-handler.jsnew file mode 100644index 000000000..76b349a1a--- /dev/null+++ b/plugins/_office/extensions/webui/get_tool_message_handler/document-artifact-handler.js@@ -0,0 +1,81 @@+import {+ createActionButton,+ copyToClipboard,+} from "/components/messages/action-buttons/simple-action-buttons.js";+import { store as stepDetailStore } from "/components/modals/process-step-detail/step-detail-store.js";+import { store as speechStore } from "/components/chat/speech/speech-store.js";+import {+ buildDetailPayload,+ cleanStepTitle,+ drawProcessStep,+} from "/js/messages.js";++export default async function registerDocumentArtifactHandler(extData) {+ if (extData?.tool_name === "document_artifact") {+ extData.handler = drawDocumentArtifactTool;+ }+}++async function openOfficeCanvas(kvps = {}) {+ const canvas = globalThis.Alpine?.store?.("rightCanvas")+ || (await import("/components/canvas/right-canvas-store.js")).store;+ await canvas?.open?.("office", {+ path: kvps.path || "",+ file_id: kvps.file_id || "",+ source: "tool",+ });+}++function drawDocumentArtifactTool({+ id,+ type,+ heading,+ content,+ kvps,+ timestamp,+ agentno = 0,+ ...additional+}) {+ const args = arguments[0];+ const title = cleanStepTitle(heading);+ const displayKvps = { ...kvps };+ const contentText = String(content ?? "");+ const headerLabels = [+ kvps?._tool_name && { label: kvps._tool_name, class: "tool-name-badge" },+ kvps?.format && { label: String(kvps.format).toUpperCase(), class: "tool-name-badge" },+ ].filter(Boolean);++ const actionButtons = [+ createActionButton("description", "Office", () => openOfficeCanvas(kvps)),+ ];++ if (kvps?.path) {+ actionButtons.push(+ createActionButton("content_copy", "Path", () => copyToClipboard(kvps.path)),+ );+ }++ if (contentText.trim()) {+ actionButtons.push(+ createActionButton("history", "Versions", () =>+ stepDetailStore.showStepDetail(buildDetailPayload(args, { headerLabels })),+ ),+ createActionButton("detail", "", () =>+ stepDetailStore.showStepDetail(buildDetailPayload(args, { headerLabels })),+ ),+ createActionButton("speak", "", () => speechStore.speak(contentText)),+ createActionButton("copy", "", () => copyToClipboard(contentText)),+ );+ }++ return drawProcessStep({+ id,+ title,+ code: "DOC",+ classes: undefined,+ kvps: displayKvps,+ content,+ actionButtons: actionButtons.filter(Boolean),+ log: args,+ });+}diff --git a/plugins/_office/extensions/webui/right-canvas-panels/office-panel.html b/plugins/_office/extensions/webui/right-canvas-panels/office-panel.htmlnew file mode 100644index 000000000..7c15b4f2e--- /dev/null+++ b/plugins/_office/extensions/webui/right-canvas-panels/office-panel.html@@ -0,0 +1,8 @@+<div+ class="right-canvas-surface-panel office-canvas-surface"+ data-surface-id="office"+ x-show="$store.rightCanvas && $store.rightCanvas.isOpen && $store.rightCanvas.activeSurfaceId === 'office'"+ style="display: none;"+>+ <x-component path="/plugins/_office/webui/office-panel.html"></x-component>+</div>diff --git a/plugins/_office/extensions/webui/right_canvas_register_surfaces/register-office.js b/plugins/_office/extensions/webui/right_canvas_register_surfaces/register-office.jsnew file mode 100644index 000000000..746384b2f--- /dev/null+++ b/plugins/_office/extensions/webui/right_canvas_register_surfaces/register-office.js@@ -0,0 +1,38 @@+function waitForElement(selector, timeoutMs = 3000) {+ const found = document.querySelector(selector);+ if (found) return Promise.resolve(found);+ return new Promise((resolve) => {+ const timeout = globalThis.setTimeout(() => {+ observer.disconnect();+ resolve(document.querySelector(selector));+ }, timeoutMs);+ const observer = new MutationObserver(() => {+ const element = document.querySelector(selector);+ if (!element) return;+ globalThis.clearTimeout(timeout);+ observer.disconnect();+ resolve(element);+ });+ observer.observe(document.body, { childList: true, subtree: true });+ });+}++export default async function registerOfficeSurface(canvas) {+ canvas.registerSurface({+ id: "office",+ title: "Office",+ icon: "description",+ order: 20,+ modalPath: "/plugins/_office/webui/main.html",+ async open(payload = {}) {+ const panel = await waitForElement('[data-surface-id="office"] .office-panel');+ const office = globalThis.Alpine?.store?.("office");+ await office?.onMount?.(panel, { mode: "canvas" });+ await office?.onOpen?.(payload);+ },+ async close() {+ const office = globalThis.Alpine?.store?.("office");+ office?.beforeHostHidden?.();+ },+ });+}diff --git a/plugins/_office/helpers/collabora_runtime.py b/plugins/_office/helpers/collabora_runtime.pynew file mode 100644index 000000000..4c66b35a4--- /dev/null+++ b/plugins/_office/helpers/collabora_runtime.py@@ -0,0 +1,348 @@+from __future__ import annotations++import fcntl+import os+import shutil+import subprocess+import threading+import time+from pathlib import Path++from plugins._office.helpers import collabora_status as status+++LOCK_FILE = status.RUNTIME_DIR / "bootstrap.lock"+WRAPPER_FILE = status.RUNTIME_DIR / "run_coolwsd.sh"+SUPERVISOR_CONF = Path("/etc/supervisor/conf.d/a0_office_collabora.conf")+SUPERVISOR_INCLUDE_PATTERN = "/etc/supervisor/conf.d/a0_office_*.conf"+SOURCES_FILE = Path("/etc/apt/sources.list.d/collaboraonline.sources")+KEYRING_FILE = Path("/etc/apt/keyrings/collaboraonline-release-keyring.gpg")++_worker_lock = threading.Lock()+_worker: threading.Thread | None = None+++def start_bootstrap_worker(force: bool = False) -> bool:+ global _worker+ with _worker_lock:+ if _worker and _worker.is_alive():+ return False+ _worker = threading.Thread(target=bootstrap, kwargs={"force": force}, name="a0-office-collabora-bootstrap", daemon=True)+ _worker.start()+ return True+++def bootstrap(force: bool = False) -> None:+ status.ensure_dirs()+ with LOCK_FILE.open("w", encoding="utf-8") as lock:+ try:+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)+ except BlockingIOError:+ status.append_log("bootstrap already running")+ return++ try:+ _bootstrap_locked(force=force)+ except Exception as exc:+ status.append_log(f"bootstrap failed: {exc}")+ status.write_status("failed", healthy=False, installing=False, message=str(exc))+++def _bootstrap_locked(force: bool = False) -> None:+ status.write_status("installing", healthy=False, installing=True, message="Preparing Collabora Online")+ status.append_log("bootstrap start")++ _write_wrapper()+ _write_supervisor_conf()+ _reread_supervisor()++ if status.packages_installed() and not force:+ status.append_log("coolwsd and code-brand already installed")+ _restart_supervisor()+ _finish_status()+ return++ if not _can_install():+ status.write_status("degraded", healthy=False, installing=False, message="Container does not support automatic apt installation")+ _restart_supervisor()+ return++ _ensure_code_repo()+ _wait_for_apt_locks()+ _run(["apt-get", "update"], timeout=600)+ _run([+ "apt-get",+ "install",+ "-y",+ "--no-install-recommends",+ "coolwsd",+ "coolwsd-deprecated",+ "code-brand",+ ], timeout=1800, env={**os.environ, "DEBIAN_FRONTEND": "noninteractive"})++ _restart_supervisor()+ _finish_status()+++def reconcile() -> None:+ wrapper_changed = _write_wrapper()+ supervisor_changed = _write_supervisor_conf()+ if supervisor_changed:+ _reread_supervisor()+ current = status.collect_status()+ if current.get("healthy"):+ if wrapper_changed or supervisor_changed:+ status.append_log("Collabora runtime configuration changed; restarting service")+ _restart_supervisor()+ time.sleep(1)+ current = status.collect_status()+ status.write_status("healthy", healthy=True, installed=True, installing=False, degraded=False, message="Collabora Online is healthy")+ return+ if current.get("installed"):+ _reread_supervisor()+ _restart_supervisor()+ status.write_status("degraded", healthy=False, installing=False, message="Collabora is installed but not healthy")+ return+ start_bootstrap_worker(force=False)+++def retry_bootstrap() -> None:+ start_bootstrap_worker(force=True)+++def _finish_status() -> None:+ for _ in range(12):+ current = status.collect_status()+ if current.get("healthy"):+ status.write_status("healthy", healthy=True, installed=True, installing=False, degraded=False, message="Collabora Online is healthy")+ return+ time.sleep(2)+ current = status.collect_status()+ state = "degraded" if current.get("installed") else "failed"+ status.write_status(+ state,+ healthy=False,+ installed=bool(current.get("installed")),+ installing=False,+ degraded=bool(current.get("installed")),+ message="Collabora did not become healthy yet",+ )+++def _can_install() -> bool:+ return os.geteuid() == 0 and shutil.which("apt-get") is not None and shutil.which("dpkg") is not None+++def _ensure_code_repo() -> None:+ KEYRING_FILE.parent.mkdir(parents=True, exist_ok=True)+ if not KEYRING_FILE.exists():+ _run([+ "wget",+ "-O",+ str(KEYRING_FILE),+ "https://collaboraoffice.com/downloads/gpg/collaboraonline-release-keyring.gpg",+ ], timeout=300)+ SOURCES_FILE.write_text(+ "\n".join([+ "Types: deb",+ "URIs: https://www.collaboraoffice.com/repos/CollaboraOnline/CODE-deb",+ "Suites: ./",+ f"Signed-By: {KEYRING_FILE}",+ "",+ ]),+ encoding="utf-8",+ )+++def _wait_for_apt_locks(timeout: int = 180) -> None:+ locks = [+ "/var/lib/dpkg/lock-frontend",+ "/var/lib/dpkg/lock",+ "/var/lib/apt/lists/lock",+ "/var/cache/apt/archives/lock",+ ]+ deadline = time.time() + timeout+ while time.time() < deadline:+ busy = False+ for lock_path in locks:+ try:+ fd = os.open(lock_path, os.O_RDWR | os.O_CREAT, 0o644)+ try:+ fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)+ fcntl.lockf(fd, fcntl.LOCK_UN)+ except OSError:+ busy = True+ finally:+ os.close(fd)+ except OSError:+ continue+ if not busy:+ return+ status.append_log("waiting for apt/dpkg locks")+ time.sleep(3)+ raise TimeoutError("Timed out waiting for apt/dpkg locks")+++def _write_wrapper() -> bool:+ status.ensure_dirs()+ changed = _write_text_if_changed(+ WRAPPER_FILE,+ """#!/usr/bin/env bash+set -u+LOG="/a0/tmp/_office/collabora/coolwsd-wrapper.log"+LOG_DIR="$(dirname "$LOG")"+mkdir -p "$LOG_DIR" /opt/cool/cache /opt/cool/child-roots+while true; do+ if ! command -v coolwsd >/dev/null 2>&1; then+ echo "$(date -u +%FT%TZ) coolwsd missing; sleeping" >> "$LOG"+ sleep 20+ continue+ fi+ if ! id cool >/dev/null 2>&1; then+ echo "$(date -u +%FT%TZ) cool user missing; sleeping" >> "$LOG"+ sleep 20+ continue+ fi+ chown -R cool:cool "$LOG_DIR" /opt/cool/cache /opt/cool/child-roots 2>/dev/null || true+ args=(+ --o:sys_template_path=/opt/cool/systemplate+ --o:child_root_path=/opt/cool/child-roots+ --o:file_server_root_path=/usr/share/coolwsd+ --o:cache_files.path=/opt/cool/cache+ --o:ssl.enable=false+ --o:ssl.termination=false+ --o:net.listen=loopback+ --o:net.proto=IPv4+ --o:net.service_root=/office+ --o:home_mode.enable=true+ )+ if command -v runuser >/dev/null 2>&1; then+ runuser -u cool -- /usr/bin/coolwsd "${args[@]}" >> "$LOG" 2>&1 &+ else+ su -s /bin/bash cool -c 'exec /usr/bin/coolwsd "$@"' coolwsd "${args[@]}" >> "$LOG" 2>&1 &+ fi+ child=$!+ trap 'kill -TERM "$child" 2>/dev/null; wait "$child" 2>/dev/null; exit 0' TERM INT+ wait "$child"+ code=$?+ echo "$(date -u +%FT%TZ) coolwsd exited with ${code}; restarting after backoff" >> "$LOG"+ sleep 5+done+""",+ )+ WRAPPER_FILE.chmod(0o755)+ return changed+++def _write_supervisor_conf() -> bool:+ include_changed = _ensure_supervisor_include()+ if not os.access("/etc/supervisor/conf.d", os.W_OK):+ status.append_log("supervisor conf directory is not writable")+ return include_changed+ conf_changed = _write_text_if_changed(+ SUPERVISOR_CONF,+ f"""[program:{status.SUPERVISOR_PROGRAM}]+command={WRAPPER_FILE}+autostart=true+autorestart=true+startsecs=0+startretries=999999+stopsignal=TERM+stdout_logfile=/a0/tmp/_office/collabora/supervisor.log+stderr_logfile=/a0/tmp/_office/collabora/supervisor.err.log+""",+ )+ return include_changed or conf_changed+++def _ensure_supervisor_include() -> bool:+ active_config = _active_supervisor_config()+ if not active_config or not active_config.exists() or not os.access(active_config, os.W_OK):+ return False+ try:+ text = active_config.read_text(encoding="utf-8")+ except OSError:+ return False+ if SUPERVISOR_INCLUDE_PATTERN in text:+ return False+ if "\n[include]\n" in f"\n{text}":+ updated = _append_to_include_files(text, SUPERVISOR_INCLUDE_PATTERN)+ else:+ updated = text.rstrip() + "\n\n[include]\nfiles = " + SUPERVISOR_INCLUDE_PATTERN + "\n"+ if updated != text:+ active_config.write_text(updated, encoding="utf-8")+ return True+ return False+++def _active_supervisor_config() -> Path | None:+ cmdline = Path("/proc/1/cmdline")+ try:+ parts = [part for part in cmdline.read_text(encoding="utf-8").split("\x00") if part]+ except OSError:+ return None+ for index, part in enumerate(parts):+ if part == "-c" and index + 1 < len(parts):+ return Path(parts[index + 1])+ if part.startswith("-c") and len(part) > 2:+ return Path(part[2:])+ return Path("/etc/supervisor/supervisord.conf")+++def _append_to_include_files(text: str, pattern: str) -> str:+ lines = text.splitlines()+ in_include = False+ for index, line in enumerate(lines):+ stripped = line.strip()+ if stripped.startswith("[") and stripped.endswith("]"):+ in_include = stripped.lower() == "[include]"+ continue+ if in_include and stripped.startswith("files"):+ separator = " " if line.rstrip().endswith("=") else " "+ lines[index] = line.rstrip() + separator + pattern+ return "\n".join(lines) + ("\n" if text.endswith("\n") else "")+ return text.rstrip() + "\nfiles = " + pattern + "\n"+++def _write_text_if_changed(path: Path, text: str) -> bool:+ try:+ if path.exists() and path.read_text(encoding="utf-8") == text:+ return False+ except OSError:+ pass+ path.write_text(text, encoding="utf-8")+ return True+++def _reread_supervisor() -> None:+ if not shutil.which("supervisorctl"):+ return+ _run(["supervisorctl", "reread"], timeout=20, check=False)+ _run(["supervisorctl", "update", status.SUPERVISOR_PROGRAM], timeout=30, check=False)+++def _restart_supervisor() -> None:+ if not shutil.which("supervisorctl"):+ return+ _run(["supervisorctl", "restart", status.SUPERVISOR_PROGRAM], timeout=30, check=False)+++def _run(args: list[str], timeout: int, env: dict[str, str] | None = None, check: bool = True) -> subprocess.CompletedProcess[str]:+ status.append_log("$ " + " ".join(args))+ result = subprocess.run(+ args,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=timeout,+ env=env,+ check=False,+ )+ if result.stdout:+ with status.BOOTSTRAP_LOG.open("a", encoding="utf-8") as handle:+ handle.write(result.stdout)+ if not result.stdout.endswith("\n"):+ handle.write("\n")+ if check and result.returncode != 0:+ raise RuntimeError(f"{' '.join(args)} failed with exit {result.returncode}")+ return resultdiff --git a/plugins/_office/helpers/collabora_status.py b/plugins/_office/helpers/collabora_status.pynew file mode 100644index 000000000..f087537e7--- /dev/null+++ b/plugins/_office/helpers/collabora_status.py@@ -0,0 +1,181 @@+from __future__ import annotations++import json+import os+import shutil+import subprocess+import time+from pathlib import Path+from typing import Any+from urllib.request import Request, urlopen++from helpers import files+++PLUGIN_NAME = "_office"+RUNTIME_DIR = Path(files.get_abs_path("tmp", PLUGIN_NAME, "collabora"))+STATE_DIR = Path(files.get_abs_path("usr", "plugins", PLUGIN_NAME, "collabora"))+STATUS_FILE = RUNTIME_DIR / "status.json"+BOOTSTRAP_LOG = RUNTIME_DIR / "bootstrap.log"+WRAPPER_LOG = RUNTIME_DIR / "coolwsd-wrapper.log"+SUPERVISOR_PROGRAM = "a0_office_collabora"+++def ensure_dirs() -> None:+ RUNTIME_DIR.mkdir(parents=True, exist_ok=True)+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ (STATE_DIR / "backups").mkdir(parents=True, exist_ok=True)+++def now_ts() -> float:+ return time.time()+++def read_status() -> dict[str, Any]:+ ensure_dirs()+ if not STATUS_FILE.exists():+ return default_status("idle")+ try:+ data = json.loads(STATUS_FILE.read_text(encoding="utf-8"))+ if isinstance(data, dict):+ return {**default_status("idle"), **data}+ except Exception:+ pass+ return default_status("idle")+++def write_status(state: str, **extra: Any) -> dict[str, Any]:+ ensure_dirs()+ payload = {+ **read_status(),+ "state": state,+ "updated_at": now_ts(),+ **extra,+ }+ STATUS_FILE.write_text(json.dumps(payload, indent=2, sort_keys=True), encoding="utf-8")+ return payload+++def default_status(state: str = "idle") -> dict[str, Any]:+ return {+ "plugin": PLUGIN_NAME,+ "state": state,+ "healthy": False,+ "installed": False,+ "installing": False,+ "degraded": False,+ "message": "",+ "updated_at": 0,+ "runtime_dir": str(RUNTIME_DIR),+ "state_dir": str(STATE_DIR),+ "status_file": str(STATUS_FILE),+ "bootstrap_log": str(BOOTSTRAP_LOG),+ "wrapper_log": str(WRAPPER_LOG),+ }+++def append_log(message: str) -> None:+ ensure_dirs()+ line = f"{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())} {message}\n"+ with BOOTSTRAP_LOG.open("a", encoding="utf-8") as handle:+ handle.write(line)+++def tail_file(path: Path, max_bytes: int = 16000) -> str:+ try:+ with path.open("rb") as handle:+ handle.seek(0, os.SEEK_END)+ size = handle.tell()+ handle.seek(max(0, size - max_bytes))+ return handle.read().decode("utf-8", errors="replace")+ except FileNotFoundError:+ return ""+ except Exception as exc:+ return f"Could not read log: {exc}"+++def run_command(args: list[str], timeout: int = 10) -> subprocess.CompletedProcess[str]:+ return subprocess.run(+ args,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.STDOUT,+ timeout=timeout,+ check=False,+ )+++def command_exists(name: str) -> bool:+ return shutil.which(name) is not None+++def package_installed(name: str) -> bool:+ if not command_exists("dpkg-query"):+ return False+ result = run_command(["dpkg-query", "-W", "-f=${Status}", name], timeout=8)+ return result.returncode == 0 and "install ok installed" in result.stdout+++def packages_installed() -> bool:+ return (+ command_exists("coolwsd")+ and command_exists("coolforkit-caps")+ and package_installed("coolwsd")+ and package_installed("coolwsd-deprecated")+ and package_installed("code-brand")+ )+++def supervisor_status() -> str:+ if not command_exists("supervisorctl"):+ return "supervisorctl unavailable"+ result = run_command(["supervisorctl", "status", SUPERVISOR_PROGRAM], timeout=8)+ return (result.stdout or "").strip() or f"exit {result.returncode}"+++def process_status() -> str:+ if not command_exists("pgrep"):+ return ""+ result = run_command(["pgrep", "-a", "coolwsd"], timeout=8)+ return (result.stdout or "").strip()+++def discovery_ok() -> bool:+ for url in (+ "http://127.0.0.1:9980/office/hosting/discovery",+ "http://127.0.0.1:9980/hosting/discovery",+ ):+ try:+ request = Request(url, headers={"User-Agent": "Agent-Zero-Office/1.0"})+ with urlopen(request, timeout=5) as response:+ body = response.read(256)+ if response.status == 200 and b"wopi-discovery" in body.lower():+ return True+ except Exception:+ continue+ return False+++def collect_status() -> dict[str, Any]:+ ensure_dirs()+ installed = packages_installed()+ supervisor = supervisor_status()+ process = process_status()+ http_ok = discovery_ok()+ healthy = installed and http_ok+ saved = read_status()+ installing = saved.get("state") == "installing"+ state = "healthy" if healthy else ("installing" if installing else ("degraded" if installed else saved.get("state") or "idle"))+ return {+ **saved,+ "state": state,+ "healthy": healthy,+ "installed": installed,+ "installing": installing and not healthy,+ "degraded": installed and not healthy,+ "coolwsd_path": shutil.which("coolwsd") or "",+ "supervisor": supervisor,+ "process": process,+ "discovery_ok": http_ok,+ "updated_at": now_ts(),+ }diff --git a/plugins/_office/helpers/office_proxy.py b/plugins/_office/helpers/office_proxy.pynew file mode 100644index 000000000..555c406fd--- /dev/null+++ b/plugins/_office/helpers/office_proxy.py@@ -0,0 +1,261 @@+from __future__ import annotations++import asyncio+from http.cookies import SimpleCookie+from urllib.parse import parse_qs, unquote++import httpx+from flask.sessions import SecureCookieSessionInterface+from starlette.responses import PlainTextResponse, Response+from starlette.types import Receive, Scope, Send+from starlette.websockets import WebSocket++from helpers import login+from plugins._office.helpers import wopi_store+++UPSTREAM_HTTP = "http://127.0.0.1:9980"+UPSTREAM_WS = "ws://127.0.0.1:9980"+HTTP_PROXY_ATTEMPTS = 4+HTTP_PROXY_RETRY_DELAYS = (0.2, 0.5, 1.0)+TRANSIENT_HTTP_ERRORS = (+ httpx.ConnectError,+ httpx.ConnectTimeout,+ httpx.ReadError,+ httpx.ReadTimeout,+ httpx.RemoteProtocolError,+ httpx.WriteError,+ httpx.WriteTimeout,+)+++class OfficeProxy:+ def __init__(self, flask_app=None) -> None:+ self.flask_app = flask_app++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ if scope["type"] == "websocket":+ await self.websocket(scope, receive, send)+ return+ if scope["type"] == "http":+ await self.http(scope, receive, send)+ return+ await PlainTextResponse("Unsupported scope", status_code=500)(scope, receive, send)++ def upstream_path(self, scope: Scope) -> str:+ raw_path = scope.get("raw_path")+ if raw_path:+ path = raw_path.decode("latin-1")+ else:+ path = scope.get("path", "")+ if not path.startswith("/office"):+ path = "/office" + (path if path.startswith("/") else "/" + path)+ query = scope.get("query_string", b"").decode("latin-1")+ return path + (f"?{query}" if query else "")++ async def http(self, scope: Scope, receive: Receive, send: Send) -> None:+ if not self.is_authorized(scope):+ await PlainTextResponse("Authentication required", status_code=401)(scope, receive, send)+ return++ body = b""+ more = True+ while more:+ message = await receive()+ if message["type"] != "http.request":+ break+ body += message.get("body", b"")+ more = bool(message.get("more_body"))++ method = scope.get("method", "GET")+ headers = self.forward_headers(scope)+ url = UPSTREAM_HTTP + self.upstream_path(scope)+ try:+ upstream, attempts = await self.request_upstream_http(method, url, body, headers)+ disable_cache = self.should_disable_cache(scope, upstream.status_code)+ omitted_headers = {"content-encoding", "content-length", "transfer-encoding", "connection"}+ if disable_cache:+ omitted_headers.update({"cache-control", "pragma", "expires"})+ response_headers = {+ key: value+ for key, value in upstream.headers.items()+ if key.lower() not in omitted_headers+ }+ response_headers["X-A0-Office-Proxy-Attempts"] = str(attempts)+ if disable_cache:+ response_headers["Cache-Control"] = "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0"+ response_headers["Pragma"] = "no-cache"+ response_headers["Expires"] = "0"+ await Response(upstream.content, status_code=upstream.status_code, headers=response_headers)(scope, receive, send)+ except Exception as exc:+ await PlainTextResponse(+ f"Collabora is unavailable after {HTTP_PROXY_ATTEMPTS} attempts: {exc}",+ status_code=503,+ headers={+ "Cache-Control": "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0",+ "Pragma": "no-cache",+ "Expires": "0",+ },+ )(scope, receive, send)++ async def request_upstream_http(+ self,+ method: str,+ url: str,+ body: bytes,+ headers: dict[str, str],+ ) -> tuple[httpx.Response, int]:+ for attempt in range(1, HTTP_PROXY_ATTEMPTS + 1):+ try:+ async with httpx.AsyncClient(timeout=httpx.Timeout(60.0, read=36000.0), follow_redirects=False) as client:+ response = await client.request(method, url, content=body, headers=headers)+ return response, attempt+ except TRANSIENT_HTTP_ERRORS:+ if attempt >= HTTP_PROXY_ATTEMPTS:+ raise+ delay_index = min(attempt - 1, len(HTTP_PROXY_RETRY_DELAYS) - 1)+ await asyncio.sleep(HTTP_PROXY_RETRY_DELAYS[delay_index])+ raise RuntimeError("Collabora proxy retry loop exited unexpectedly")++ def should_disable_cache(self, scope: Scope, status_code: int) -> bool:+ path = self.upstream_path(scope).split("?", 1)[0]+ return status_code >= 500 or path.endswith("/cool.html")++ async def websocket(self, scope: Scope, receive: Receive, send: Send) -> None:+ import websockets++ websocket = WebSocket(scope, receive=receive, send=send)+ if not self.is_authorized(scope):+ await websocket.close(code=1008)+ return++ await websocket.accept()+ url = self.upstream_websocket_url(scope)+ headers = self.websocket_headers(scope)+ origin = self.header_value(scope, b"origin", "")+ try:+ async with websockets.connect(+ url,+ host="127.0.0.1",+ port=9980,+ origin=origin or None,+ additional_headers=headers,+ open_timeout=10,+ ping_interval=None,+ ) as upstream:+ async def browser_to_upstream():+ while True:+ msg = await websocket.receive()+ if msg["type"] == "websocket.disconnect":+ await upstream.close()+ return+ if "bytes" in msg and msg["bytes"] is not None:+ await upstream.send(msg["bytes"])+ elif "text" in msg and msg["text"] is not None:+ await upstream.send(msg["text"])++ async def upstream_to_browser():+ async for msg in upstream:+ if isinstance(msg, bytes):+ await websocket.send_bytes(msg)+ else:+ await websocket.send_text(msg)++ await asyncio.gather(browser_to_upstream(), upstream_to_browser())+ except Exception:+ await websocket.close(code=1011)++ def forward_headers(self, scope: Scope) -> dict[str, str]:+ headers: dict[str, str] = {}+ for key_b, value_b in scope.get("headers", []):+ key = key_b.decode("latin-1")+ value = value_b.decode("latin-1")+ if key.lower() in {"host", "content-length", "connection"}:+ continue+ headers[key] = value+ host = dict(scope.get("headers", [])).get(b"host", b"localhost:32080").decode("latin-1")+ headers["Host"] = host+ headers["X-Forwarded-Proto"] = scope.get("scheme", "http")+ return headers++ def upstream_websocket_url(self, scope: Scope) -> str:+ host = self.header_value(scope, b"host", "localhost:32080")+ return f"ws://{host}{self.upstream_path(scope)}"++ def websocket_headers(self, scope: Scope) -> list[tuple[str, str]]:+ hop_by_hop = {+ b"host",+ b"connection",+ b"upgrade",+ b"origin",+ b"sec-websocket-key",+ b"sec-websocket-version",+ b"sec-websocket-extensions",+ }+ headers = [+ (key.decode("latin-1"), value.decode("latin-1"))+ for key, value in scope.get("headers", [])+ if key.lower() not in hop_by_hop+ ]+ return headers++ def header_value(self, scope: Scope, name: bytes, default: str = "") -> str:+ value = dict(scope.get("headers", [])).get(name, default.encode("latin-1"))+ return value.decode("latin-1") if isinstance(value, bytes) else str(value)++ def is_authorized(self, scope: Scope) -> bool:+ if self._has_valid_wopi_token(scope):+ return True+ credentials_hash = login.get_credentials_hash()+ if not credentials_hash:+ return True+ if not self.flask_app:+ return False+ serializer = SecureCookieSessionInterface().get_signing_serializer(self.flask_app)+ if not serializer:+ return False+ cookie_header = dict(scope.get("headers", [])).get(b"cookie", b"").decode("latin-1")+ if not cookie_header:+ return False+ cookies = SimpleCookie()+ cookies.load(cookie_header)+ session_cookie = cookies.get(self.flask_app.config.get("SESSION_COOKIE_NAME", "session"))+ if not session_cookie:+ return False+ try:+ session_data = serializer.loads(session_cookie.value)+ except Exception:+ return False+ return session_data.get("authentication") == credentials_hash++ def _has_valid_wopi_token(self, scope: Scope) -> bool:+ if not self._is_collabora_editor_channel(scope):+ return False+ path = self.upstream_path(scope)+ decoded = unquote(path)+ marker = "/wopi/files/"+ marker_index = decoded.find(marker)+ if marker_index == -1:+ return False+ file_part = decoded[marker_index + len(marker):]+ file_id, separator, query_text = file_part.partition("?")+ if not separator or not file_id:+ return False+ file_id = file_id.strip("/")+ if "/" in file_id:+ file_id = file_id.split("/", 1)[0]+ token = (parse_qs(query_text, keep_blank_values=True).get("access_token") or [""])[0]+ if not token:+ return False+ try:+ wopi_store.validate_token(token, file_id, require_write=False)+ except Exception:+ return False+ return True++ def _is_collabora_editor_channel(self, scope: Scope) -> bool:+ path = scope.get("path", "")+ raw_path = scope.get("raw_path")+ if raw_path:+ path = raw_path.decode("latin-1", errors="ignore")+ return path.startswith("/office/cool/")diff --git a/plugins/_office/helpers/route_bootstrap.py b/plugins/_office/helpers/route_bootstrap.pynew file mode 100644index 000000000..6419374bd--- /dev/null+++ b/plugins/_office/helpers/route_bootstrap.py@@ -0,0 +1,61 @@+from __future__ import annotations+++def install_route_hooks() -> None:+ from helpers.ui_server import UiServerRuntime++ if getattr(UiServerRuntime, "_a0_office_route_hooks_installed", False):+ return++ original_register_http_routes = UiServerRuntime.register_http_routes+ original_build_asgi_app = UiServerRuntime.build_asgi_app++ def register_http_routes(self):+ result = original_register_http_routes(self)+ from plugins._office.helpers.wopi_routes import register_wopi_routes++ register_wopi_routes(self.webapp)+ return result++ def build_asgi_app(self, startup_monitor):+ from socketio import ASGIApp+ from starlette.applications import Starlette+ from starlette.routing import Mount+ from uvicorn.middleware.wsgi import WSGIMiddleware++ from helpers import fasta2a_server, mcp_server+ from plugins._office.helpers.office_proxy import OfficeProxy++ with startup_monitor.stage("wsgi.middleware.create"):+ wsgi_app = WSGIMiddleware(self.webapp)++ with startup_monitor.stage("mcp.proxy.init"):+ mcp_app = mcp_server.DynamicMcpProxy.get_instance()++ with startup_monitor.stage("a2a.proxy.init"):+ a2a_app = fasta2a_server.DynamicA2AProxy.get_instance()++ with startup_monitor.stage("starlette.app.create"):+ starlette_app = Starlette(+ routes=[+ Mount("/office", app=OfficeProxy(self.webapp)),+ Mount("/mcp", app=mcp_app),+ Mount("/a2a", app=a2a_app),+ Mount("/", app=wsgi_app),+ ],+ lifespan=startup_monitor.lifespan(),+ )++ with startup_monitor.stage("socketio.asgi.create"):+ return ASGIApp(self.socketio_server, other_asgi_app=starlette_app)++ UiServerRuntime.register_http_routes = register_http_routes+ UiServerRuntime.build_asgi_app = build_asgi_app+ UiServerRuntime._a0_office_route_hooks_installed = True+ UiServerRuntime._a0_office_original_build_asgi_app = original_build_asgi_app+++def is_installed() -> bool:+ from helpers.ui_server import UiServerRuntime++ return bool(getattr(UiServerRuntime, "_a0_office_route_hooks_installed", False))diff --git a/plugins/_office/helpers/wopi_routes.py b/plugins/_office/helpers/wopi_routes.pynew file mode 100644index 000000000..2772ad2d9--- /dev/null+++ b/plugins/_office/helpers/wopi_routes.py@@ -0,0 +1,133 @@+from __future__ import annotations++import json+import mimetypes+from pathlib import Path+from typing import Any++from flask import Flask, Response, request, send_file++from plugins._office.helpers import wopi_store+++def register_wopi_routes(app: Flask) -> None:+ if getattr(app, "_a0_office_wopi_routes_registered", False):+ return+ app._a0_office_wopi_routes_registered = True++ app.add_url_rule("/wopi/files/<file_id>", "office_wopi_file", wopi_file, methods=["GET", "POST"])+ app.add_url_rule("/wopi/files/<file_id>/contents", "office_wopi_contents", wopi_contents, methods=["GET", "POST"])+++def token_from_request() -> str:+ auth = request.headers.get("Authorization", "")+ if auth.lower().startswith("bearer "):+ return auth.split(" ", 1)[1].strip()+ return request.args.get("access_token", "") or request.form.get("access_token", "")+++def validate(file_id: str, require_write: bool = False) -> dict[str, Any] | Response:+ try:+ return wopi_store.validate_token(token_from_request(), file_id, require_write=require_write)+ except PermissionError as exc:+ return Response(str(exc), status=401)+ except Exception as exc:+ return Response(str(exc), status=404)+++def json_response(data: dict[str, Any], status: int = 200, headers: dict[str, str] | None = None) -> Response:+ return Response(+ json.dumps(data, separators=(",", ":"), ensure_ascii=False),+ status=status,+ mimetype="application/json",+ headers=headers or {},+ )+++def conflict(current_lock: str, reason: str = "Lock mismatch") -> Response:+ return Response(+ "",+ status=409,+ headers={+ "X-WOPI-Lock": current_lock or "",+ "X-WOPI-LockFailureReason": reason,+ },+ )+++def wopi_file(file_id: str):+ if request.method == "GET":+ token_info = validate(file_id)+ if isinstance(token_info, Response):+ return token_info+ try:+ return json_response(wopi_store.check_file_info(file_id, token_info))+ except FileNotFoundError:+ return Response("File not found", status=404)+ except Exception as exc:+ return Response(str(exc), status=500)++ override = request.headers.get("X-WOPI-Override", "").upper().replace("-", "_")+ require_write = override in {"LOCK", "REFRESH_LOCK", "UNLOCK"}+ token_info = validate(file_id, require_write=require_write)+ if isinstance(token_info, Response):+ return token_info++ lock_value = request.headers.get("X-WOPI-Lock", "")+ old_lock = request.headers.get("X-WOPI-OldLock", "")+ timeout = request.headers.get("X-WOPI-LockExpirationTimeout")+ session_id = (token_info.get("token") or {}).get("session_id", "")++ try:+ if override == "GET_LOCK":+ return Response("", status=200, headers={"X-WOPI-Lock": wopi_store.get_lock(file_id)})+ if override == "LOCK" and old_lock:+ ok, current = wopi_store.unlock_and_relock(file_id, old_lock, lock_value, session_id, timeout)+ return Response("", status=200) if ok else conflict(current)+ if override == "LOCK":+ ok, current = wopi_store.lock(file_id, lock_value, session_id, timeout)+ return Response("", status=200) if ok else conflict(current)+ if override == "REFRESH_LOCK":+ ok, current = wopi_store.refresh_lock(file_id, lock_value, timeout)+ return Response("", status=200) if ok else conflict(current)+ if override == "UNLOCK":+ ok, current = wopi_store.unlock(file_id, lock_value)+ return Response("", status=200) if ok else conflict(current)+ return Response("Unsupported WOPI override", status=501)+ except Exception as exc:+ return Response(str(exc), status=500)+++def wopi_contents(file_id: str):+ if request.method == "GET":+ token_info = validate(file_id)+ if isinstance(token_info, Response):+ return token_info+ try:+ doc = wopi_store.get_document(file_id)+ path = Path(doc["path"])+ mimetype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"+ return send_file(path, mimetype=mimetype, as_attachment=False, download_name=doc["basename"])+ except FileNotFoundError:+ return Response("File not found", status=404)+ except Exception as exc:+ return Response(str(exc), status=500)++ override = request.headers.get("X-WOPI-Override", "").upper().replace("-", "_")+ if override != "PUT":+ return Response("Unsupported WOPI override", status=501)+ token_info = validate(file_id, require_write=True)+ if isinstance(token_info, Response):+ return token_info++ try:+ version = wopi_store.put_file(file_id, request.get_data() or b"", request.headers.get("X-WOPI-Lock", ""))+ return Response("", status=200, headers={"X-WOPI-ItemVersion": version})+ except wopi_store.LockMismatch as exc:+ return conflict(exc.current_lock)+ except OverflowError as exc:+ return Response(str(exc), status=413)+ except FileNotFoundError:+ return Response("File not found", status=404)+ except Exception as exc:+ return Response(str(exc), status=500)diff --git a/plugins/_office/helpers/wopi_store.py b/plugins/_office/helpers/wopi_store.pynew file mode 100644index 000000000..2897e91c8--- /dev/null+++ b/plugins/_office/helpers/wopi_store.py@@ -0,0 +1,552 @@+from __future__ import annotations++import hashlib+import json+import os+import secrets+import shutil+import sqlite3+import time+import uuid+import zipfile+from contextlib import contextmanager+from pathlib import Path+from typing import Any+from xml.sax.saxutils import escape++from helpers import files+++PLUGIN_NAME = "_office"+SUPPORTED_EXTENSIONS = {"docx", "xlsx", "pptx", "odt", "ods", "odp"}+DEFAULT_TTL_SECONDS = 8 * 60 * 60+DEFAULT_LOCK_SECONDS = 30 * 60+MAX_LOCK_SECONDS = 3600+MIN_LOCK_SECONDS = 60+MAX_SAVE_BYTES = 512 * 1024 * 1024++STATE_DIR = Path(files.get_abs_path("usr", "plugins", PLUGIN_NAME, "collabora"))+DB_PATH = STATE_DIR / "documents.sqlite3"+BACKUP_DIR = STATE_DIR / "backups"+DOCUMENTS_DIR = Path(files.get_abs_path("usr", "workdir", "documents"))+WORKDIR = Path(files.get_abs_path("usr", "workdir"))+++def now() -> float:+ return time.time()+++def now_iso() -> str:+ return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+++def ensure_dirs() -> None:+ STATE_DIR.mkdir(parents=True, exist_ok=True)+ BACKUP_DIR.mkdir(parents=True, exist_ok=True)+ DOCUMENTS_DIR.mkdir(parents=True, exist_ok=True)+++def sha256_bytes(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def token_hash(token: str) -> str:+ return hashlib.sha256(token.encode("utf-8")).hexdigest()+++def safe_title(title: str, fallback: str = "Document") -> str:+ cleaned = "".join(ch if ch.isalnum() or ch in " ._-" else "_" for ch in title).strip(" ._")+ return cleaned or fallback+++def normalize_extension(value: str) -> str:+ ext = value.lower().strip().lstrip(".")+ if ext not in SUPPORTED_EXTENSIONS:+ raise ValueError(f"Unsupported Office format: {ext}")+ return ext+++def normalize_path(path: str | Path) -> Path:+ raw = str(path)+ if raw.startswith("/a0/") and not files.get_base_dir().startswith("/a0"):+ raw = files.get_abs_path(raw.removeprefix("/a0/"))+ candidate = Path(raw if os.path.isabs(raw) else files.get_abs_path(raw))+ resolved = candidate.expanduser().resolve(strict=False)+ allowed_roots = [WORKDIR.resolve(strict=False)]+ if not any(os.path.commonpath([str(resolved), str(root)]) == str(root) for root in allowed_roots):+ raise PermissionError("Office documents must be inside /a0/usr/workdir")+ if candidate.exists():+ real = candidate.resolve(strict=True)+ if not any(os.path.commonpath([str(real), str(root)]) == str(root) for root in allowed_roots):+ raise PermissionError("Office document symlink escapes the workdir")+ return resolved+++@contextmanager+def connect() -> Any:+ ensure_dirs()+ conn = sqlite3.connect(DB_PATH, timeout=30)+ conn.row_factory = sqlite3.Row+ conn.execute("PRAGMA journal_mode=WAL")+ conn.execute("PRAGMA foreign_keys=ON")+ init_db(conn)+ try:+ yield conn+ conn.commit()+ finally:+ conn.close()+++def init_db(conn: sqlite3.Connection) -> None:+ conn.executescript(+ """+ CREATE TABLE IF NOT EXISTS documents (+ file_id TEXT PRIMARY KEY,+ path TEXT NOT NULL UNIQUE,+ basename TEXT NOT NULL,+ extension TEXT NOT NULL,+ owner_id TEXT NOT NULL,+ size INTEGER NOT NULL,+ version INTEGER NOT NULL,+ sha256 TEXT NOT NULL,+ last_modified TEXT NOT NULL,+ created_at REAL NOT NULL,+ updated_at REAL NOT NULL+ );+ CREATE TABLE IF NOT EXISTS sessions (+ session_id TEXT PRIMARY KEY,+ file_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ permission TEXT NOT NULL,+ origin TEXT NOT NULL,+ created_at REAL NOT NULL,+ expires_at REAL NOT NULL+ );+ CREATE TABLE IF NOT EXISTS tokens (+ token_hash TEXT PRIMARY KEY,+ file_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ user_id TEXT NOT NULL,+ permission TEXT NOT NULL,+ source_path TEXT NOT NULL,+ created_at REAL NOT NULL,+ expires_at REAL NOT NULL+ );+ CREATE TABLE IF NOT EXISTS locks (+ file_id TEXT PRIMARY KEY,+ lock_value TEXT NOT NULL,+ expires_at REAL NOT NULL,+ session_id TEXT NOT NULL,+ updated_at REAL NOT NULL+ );+ CREATE TABLE IF NOT EXISTS versions (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ file_id TEXT NOT NULL,+ version TEXT NOT NULL,+ path TEXT NOT NULL,+ size INTEGER NOT NULL,+ sha256 TEXT NOT NULL,+ created_at REAL NOT NULL+ );+ CREATE TABLE IF NOT EXISTS events (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ file_id TEXT,+ event_type TEXT NOT NULL,+ payload TEXT NOT NULL,+ created_at REAL NOT NULL+ );+ """+ )+++def register_document(path: str | Path, owner_id: str = "a0") -> dict[str, Any]:+ resolved = normalize_path(path)+ if not resolved.exists():+ raise FileNotFoundError(str(resolved))+ ext = normalize_extension(resolved.suffix.lstrip("."))+ data = resolved.read_bytes()+ digest = sha256_bytes(data)+ stat = resolved.stat()+ current_time = now()+ with connect() as conn:+ row = conn.execute("SELECT * FROM documents WHERE path = ?", (str(resolved),)).fetchone()+ if row:+ conn.execute(+ """+ UPDATE documents+ SET basename=?, extension=?, size=?, sha256=?, last_modified=?, updated_at=?+ WHERE file_id=?+ """,+ (resolved.name, ext, stat.st_size, digest, now_iso(), current_time, row["file_id"]),+ )+ return get_document(row["file_id"], conn=conn)++ file_id = uuid.uuid4().hex+ conn.execute(+ """+ INSERT INTO documents+ (file_id, path, basename, extension, owner_id, size, version, sha256, last_modified, created_at, updated_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (file_id, str(resolved), resolved.name, ext, owner_id, stat.st_size, 1, digest, now_iso(), current_time, current_time),+ )+ _record_version(conn, file_id, resolved, "1", data)+ return get_document(file_id, conn=conn)+++def get_document(file_id: str, conn: sqlite3.Connection | None = None) -> dict[str, Any]:+ def _fetch(active: sqlite3.Connection) -> dict[str, Any]:+ row = active.execute("SELECT * FROM documents WHERE file_id = ?", (file_id,)).fetchone()+ if not row:+ raise FileNotFoundError(file_id)+ return dict(row)++ if conn is not None:+ return _fetch(conn)+ with connect() as active:+ return _fetch(active)+++def get_recent_documents(limit: int = 12) -> list[dict[str, Any]]:+ with connect() as conn:+ rows = conn.execute(+ "SELECT * FROM documents ORDER BY updated_at DESC LIMIT ?",+ (limit,),+ ).fetchall()+ return [dict(row) for row in rows]+++def create_session(file_id: str, user_id: str, permission: str, origin: str, ttl_seconds: int = DEFAULT_TTL_SECONDS) -> dict[str, Any]:+ permission = "write" if permission == "write" else "read"+ token = secrets.token_urlsafe(32)+ created = now()+ expires = created + ttl_seconds+ doc = get_document(file_id)+ session_id = uuid.uuid4().hex+ with connect() as conn:+ conn.execute(+ "INSERT INTO sessions (session_id, file_id, user_id, permission, origin, created_at, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?)",+ (session_id, file_id, user_id, permission, origin, created, expires),+ )+ conn.execute(+ """+ INSERT INTO tokens+ (token_hash, file_id, session_id, user_id, permission, source_path, created_at, expires_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (token_hash(token), file_id, session_id, user_id, permission, doc["path"], created, expires),+ )+ return {+ "session_id": session_id,+ "file_id": file_id,+ "access_token": token,+ "access_token_ttl": int(expires * 1000),+ "expires_at": expires,+ "permission": permission,+ "origin": origin,+ }+++def validate_token(raw_token: str, file_id: str, require_write: bool = False) -> dict[str, Any]:+ if not raw_token:+ raise PermissionError("Missing WOPI access token")+ with connect() as conn:+ row = conn.execute("SELECT * FROM tokens WHERE token_hash = ?", (token_hash(raw_token),)).fetchone()+ if not row or row["file_id"] != file_id:+ raise PermissionError("Invalid WOPI access token")+ if row["expires_at"] < now():+ raise PermissionError("Expired WOPI access token")+ if require_write and row["permission"] != "write":+ raise PermissionError("WOPI token is read-only")+ session = conn.execute("SELECT * FROM sessions WHERE session_id = ?", (row["session_id"],)).fetchone()+ return {"token": dict(row), "session": dict(session) if session else {}}+++def check_file_info(file_id: str, token_info: dict[str, Any]) -> dict[str, Any]:+ doc = get_document(file_id)+ session = token_info.get("session") or {}+ can_write = (token_info.get("token") or {}).get("permission") == "write"+ origin = session.get("origin") or "http://localhost:32080"+ info = {+ "BaseFileName": doc["basename"],+ "OwnerId": doc["owner_id"],+ "Size": int(doc["size"]),+ "Version": item_version(doc),+ "UserId": session.get("user_id") or "agent-zero-user",+ "UserFriendlyName": "Agent Zero",+ "UserCanWrite": bool(can_write),+ "ReadOnly": not bool(can_write),+ "SupportsLocks": True,+ "SupportsUpdate": True,+ "SupportsExtendedLockLength": True,+ "SupportsGetLock": True,+ "UserCanNotWriteRelative": True,+ "PostMessageOrigin": origin,+ "ClosePostMessage": True,+ "CloseUrl": origin.rstrip("/") + "/",+ "LastModifiedTime": doc["last_modified"],+ }+ return {key: value for key, value in info.items() if value is not None}+++def item_version(doc: dict[str, Any]) -> str:+ return f"{int(doc['version'])}-{str(doc['sha256'])[:12]}"+++def get_lock(file_id: str) -> str:+ with connect() as conn:+ _clear_expired_locks(conn)+ row = conn.execute("SELECT lock_value FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ return row["lock_value"] if row else ""+++def lock(file_id: str, lock_value: str, session_id: str, timeout_seconds: int) -> tuple[bool, str]:+ timeout_seconds = clamp_lock_timeout(timeout_seconds)+ with connect() as conn:+ _clear_expired_locks(conn)+ row = conn.execute("SELECT * FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ if row and row["lock_value"] != lock_value:+ return False, row["lock_value"]+ expires = now() + timeout_seconds+ conn.execute(+ """+ INSERT INTO locks (file_id, lock_value, expires_at, session_id, updated_at)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(file_id) DO UPDATE SET lock_value=excluded.lock_value, expires_at=excluded.expires_at, session_id=excluded.session_id, updated_at=excluded.updated_at+ """,+ (file_id, lock_value, expires, session_id, now()),+ )+ return True, lock_value+++def refresh_lock(file_id: str, lock_value: str, timeout_seconds: int) -> tuple[bool, str]:+ timeout_seconds = clamp_lock_timeout(timeout_seconds)+ with connect() as conn:+ _clear_expired_locks(conn)+ row = conn.execute("SELECT * FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ if not row or row["lock_value"] != lock_value:+ return False, row["lock_value"] if row else ""+ conn.execute(+ "UPDATE locks SET expires_at = ?, updated_at = ? WHERE file_id = ?",+ (now() + timeout_seconds, now(), file_id),+ )+ return True, lock_value+++def unlock(file_id: str, lock_value: str) -> tuple[bool, str]:+ with connect() as conn:+ _clear_expired_locks(conn)+ row = conn.execute("SELECT * FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ if not row:+ return True, ""+ if row["lock_value"] != lock_value:+ return False, row["lock_value"]+ conn.execute("DELETE FROM locks WHERE file_id = ?", (file_id,))+ return True, ""+++def unlock_and_relock(file_id: str, old_lock: str, new_lock: str, session_id: str, timeout_seconds: int) -> tuple[bool, str]:+ with connect() as conn:+ _clear_expired_locks(conn)+ row = conn.execute("SELECT * FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ if row and row["lock_value"] != old_lock:+ return False, row["lock_value"]+ expires = now() + clamp_lock_timeout(timeout_seconds)+ conn.execute(+ """+ INSERT INTO locks (file_id, lock_value, expires_at, session_id, updated_at)+ VALUES (?, ?, ?, ?, ?)+ ON CONFLICT(file_id) DO UPDATE SET lock_value=excluded.lock_value, expires_at=excluded.expires_at, session_id=excluded.session_id, updated_at=excluded.updated_at+ """,+ (file_id, new_lock, expires, session_id, now()),+ )+ return True, new_lock+++def put_file(file_id: str, data: bytes, lock_value: str) -> str:+ if len(data) > MAX_SAVE_BYTES:+ raise OverflowError("Office save exceeds maximum size")+ with connect() as conn:+ _clear_expired_locks(conn)+ doc = get_document(file_id, conn=conn)+ current_lock = conn.execute("SELECT lock_value FROM locks WHERE file_id = ?", (file_id,)).fetchone()+ current = current_lock["lock_value"] if current_lock else ""+ path = Path(doc["path"])+ if current and current != lock_value:+ raise LockMismatch(current)+ if not current and int(doc["size"]) > 0:+ raise LockMismatch("")++ previous = path.read_bytes() if path.exists() else b""+ _record_version(conn, file_id, path, item_version(doc), previous)+ tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ with tmp_path.open("wb") as handle:+ handle.write(data)+ handle.flush()+ os.fsync(handle.fileno())+ os.replace(tmp_path, path)+ digest = sha256_bytes(data)+ next_version = int(doc["version"]) + 1+ conn.execute(+ """+ UPDATE documents+ SET size=?, version=?, sha256=?, last_modified=?, updated_at=?+ WHERE file_id=?+ """,+ (len(data), next_version, digest, now_iso(), now(), file_id),+ )+ return f"{next_version}-{digest[:12]}"+++class LockMismatch(Exception):+ def __init__(self, current_lock: str) -> None:+ super().__init__("WOPI lock mismatch")+ self.current_lock = current_lock+++def clamp_lock_timeout(value: int | str | None) -> int:+ try:+ seconds = int(value or DEFAULT_LOCK_SECONDS)+ except (TypeError, ValueError):+ seconds = DEFAULT_LOCK_SECONDS+ return max(MIN_LOCK_SECONDS, min(MAX_LOCK_SECONDS, seconds))+++def _clear_expired_locks(conn: sqlite3.Connection) -> None:+ conn.execute("DELETE FROM locks WHERE expires_at < ?", (now(),))+++def _record_version(conn: sqlite3.Connection, file_id: str, path: Path, version: str, data: bytes) -> None:+ if not data:+ return+ BACKUP_DIR.mkdir(parents=True, exist_ok=True)+ backup_path = BACKUP_DIR / f"{file_id}-{int(time.time() * 1000)}-{version.replace('/', '_')}"+ backup_path.write_bytes(data)+ conn.execute(+ "INSERT INTO versions (file_id, version, path, size, sha256, created_at) VALUES (?, ?, ?, ?, ?, ?)",+ (file_id, version, str(backup_path), len(data), sha256_bytes(data), now()),+ )+++def version_history(file_id: str) -> list[dict[str, Any]]:+ with connect() as conn:+ rows = conn.execute(+ "SELECT id, file_id, version, path, size, sha256, created_at FROM versions WHERE file_id = ? ORDER BY id DESC",+ (file_id,),+ ).fetchall()+ return [dict(row) for row in rows]+++def restore_version(file_id: str, version_id: int) -> dict[str, Any]:+ with connect() as conn:+ doc = get_document(file_id, conn=conn)+ row = conn.execute("SELECT * FROM versions WHERE id = ? AND file_id = ?", (version_id, file_id)).fetchone()+ if not row:+ raise FileNotFoundError(f"Version {version_id} not found")+ data = Path(row["path"]).read_bytes()+ path = Path(doc["path"])+ _record_version(conn, file_id, path, item_version(doc), path.read_bytes() if path.exists() else b"")+ path.write_bytes(data)+ digest = sha256_bytes(data)+ next_version = int(doc["version"]) + 1+ conn.execute(+ "UPDATE documents SET size=?, version=?, sha256=?, last_modified=?, updated_at=? WHERE file_id=?",+ (len(data), next_version, digest, now_iso(), now(), file_id),+ )+ return get_document(file_id, conn=conn)+++def create_document(kind: str, title: str, fmt: str, content: str = "", path: str = "") -> dict[str, Any]:+ ext = normalize_extension(fmt)+ target = normalize_path(path) if path else _unique_document_path(title, ext)+ target.parent.mkdir(parents=True, exist_ok=True)+ if target.exists():+ raise FileExistsError(str(target))+ data = template_bytes(kind, ext, title, content)+ target.write_bytes(data)+ return register_document(target)+++def _unique_document_path(title: str, ext: str) -> Path:+ base = safe_title(title, "Document")+ candidate = DOCUMENTS_DIR / f"{base}.{ext}"+ index = 2+ while candidate.exists():+ candidate = DOCUMENTS_DIR / f"{base} {index}.{ext}"+ index += 1+ return candidate.resolve(strict=False)+++def template_bytes(kind: str, ext: str, title: str, content: str) -> bytes:+ if ext == "docx":+ return _docx(title, content)+ if ext == "xlsx":+ return _xlsx(title, content)+ if ext == "pptx":+ return _pptx(title, content)+ if ext in {"odt", "ods", "odp"}:+ return _odf(ext, title, content)+ raise ValueError(ext)+++def _zip_bytes(files_map: dict[str, str | bytes], stored: set[str] | None = None) -> bytes:+ import io++ buffer = io.BytesIO()+ with zipfile.ZipFile(buffer, "w", compression=zipfile.ZIP_DEFLATED) as archive:+ for name, value in files_map.items():+ data = value.encode("utf-8") if isinstance(value, str) else value+ info = zipfile.ZipInfo(name)+ info.compress_type = zipfile.ZIP_STORED if stored and name in stored else zipfile.ZIP_DEFLATED+ archive.writestr(info, data)+ return buffer.getvalue()+++def _docx(title: str, content: str) -> bytes:+ lines = [title] + [line for line in content.splitlines() if line.strip()]+ body = "".join(f"<w:p><w:r><w:t>{escape(line)}</w:t></w:r></w:p>" for line in lines)+ return _zip_bytes({+ "[Content_Types].xml": """<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/></Types>""",+ "_rels/.rels": """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/></Relationships>""",+ "word/document.xml": f"""<?xml version="1.0" encoding="UTF-8"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"><w:body>{body}<w:sectPr/></w:body></w:document>""",+ })+++def _xlsx(title: str, content: str) -> bytes:+ rows = [title] + [line for line in content.splitlines() if line.strip()]+ sheet_rows = "".join(+ f'<row r="{idx}"><c r="A{idx}" t="inlineStr"><is><t>{escape(line)}</t></is></c></row>'+ for idx, line in enumerate(rows, start=1)+ )+ return _zip_bytes({+ "[Content_Types].xml": """<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/></Types>""",+ "_rels/.rels": """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>""",+ "xl/_rels/workbook.xml.rels": """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/></Relationships>""",+ "xl/workbook.xml": """<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="Sheet1" sheetId="1" r:id="rId1"/></sheets></workbook>""",+ "xl/worksheets/sheet1.xml": f"""<?xml version="1.0" encoding="UTF-8"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>{sheet_rows}</sheetData></worksheet>""",+ })+++def _pptx(title: str, content: str) -> bytes:+ subtitle = content.splitlines()[0] if content.splitlines() else ""+ return _zip_bytes({+ "[Content_Types].xml": """<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/><Override PartName="/ppt/slides/slide1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/></Types>""",+ "_rels/.rels": """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="ppt/presentation.xml"/></Relationships>""",+ "ppt/_rels/presentation.xml.rels": """<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide1.xml"/></Relationships>""",+ "ppt/presentation.xml": """<?xml version="1.0" encoding="UTF-8"?><p:presentation xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><p:sldIdLst><p:sldId id="256" r:id="rId1"/></p:sldIdLst><p:sldSz cx="9144000" cy="5143500"/></p:presentation>""",+ "ppt/slides/slide1.xml": f"""<?xml version="1.0" encoding="UTF-8"?><p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr/><p:sp><p:nvSpPr><p:cNvPr id="2" name="Title"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr><p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:r><a:t>{escape(title)}</a:t></a:r></a:p><a:p><a:r><a:t>{escape(subtitle)}</a:t></a:r></a:p></p:txBody></p:sp></p:spTree></p:cSld></p:sld>""",+ })+++def _odf(ext: str, title: str, content: str) -> bytes:+ mime = {+ "odt": "application/vnd.oasis.opendocument.text",+ "ods": "application/vnd.oasis.opendocument.spreadsheet",+ "odp": "application/vnd.oasis.opendocument.presentation",+ }[ext]+ body = f"<text:p>{escape(title)}</text:p><text:p>{escape(content)}</text:p>"+ return _zip_bytes({+ "mimetype": mime,+ "META-INF/manifest.xml": f"""<?xml version="1.0" encoding="UTF-8"?><manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"><manifest:file-entry manifest:media-type="{mime}" manifest:full-path="/"/><manifest:file-entry manifest:media-type="text/xml" manifest:full-path="content.xml"/></manifest:manifest>""",+ "content.xml": f"""<?xml version="1.0" encoding="UTF-8"?><office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.2"><office:body><office:text>{body}</office:text></office:body></office:document-content>""",+ }, stored={"mimetype"})diff --git a/plugins/_office/plugin.yaml b/plugins/_office/plugin.yamlnew file mode 100644index 000000000..b6cbe218d--- /dev/null+++ b/plugins/_office/plugin.yaml@@ -0,0 +1,8 @@+name: _office+title: Office+description: Universal Canvas office documents with Collabora Online, WOPI, and document artifacts.+version: "0.1"+settings_sections:+ - developer+per_project_config: false+per_agent_config: falsediff --git a/plugins/_office/prompts/agent.system.tool.document_artifact.md b/plugins/_office/prompts/agent.system.tool.document_artifact.mdnew file mode 100644index 000000000..112a7f8bb--- /dev/null+++ b/plugins/_office/prompts/agent.system.tool.document_artifact.md@@ -0,0 +1,37 @@+### document_artifact+create/open/inspect reusable Office artifacts in the Agent Zero canvas+use when producing substantial documents, spreadsheets, or presentations that should stay editable+do not dump long office-style artifacts only into chat when this tool is available++formats: docx xlsx pptx odt ods odp+actions: create open inspect export version_history restore_version status+common args: action kind title format content path file_id version_id++storage:+- generated files default to `/a0/usr/workdir/documents/`+- existing files must be under `/a0/usr/workdir`+- tool results include `canvas_surface: office`; open the Office canvas when collaborating on the artifact++examples:+~~~json+{+ "tool_name": "document_artifact",+ "tool_args": {+ "action": "create",+ "kind": "document",+ "title": "Project Brief",+ "format": "docx",+ "content": "Draft the brief here."+ }+}+~~~++~~~json+{+ "tool_name": "document_artifact",+ "tool_args": {+ "action": "open",+ "path": "/a0/usr/workdir/documents/Project Brief.docx"+ }+}+~~~diff --git a/plugins/_office/tools/document_artifact.py b/plugins/_office/tools/document_artifact.pynew file mode 100644index 000000000..5bec39ec5--- /dev/null+++ b/plugins/_office/tools/document_artifact.py@@ -0,0 +1,115 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Any++from helpers.tool import Response, Tool+from plugins._office.helpers import collabora_status, wopi_store+++class DocumentArtifact(Tool):+ async def execute(+ self,+ action: str = "",+ kind: str = "document",+ title: str = "Untitled",+ format: str = "docx",+ content: str = "",+ path: str = "",+ file_id: str = "",+ version_id: int | str | None = None,+ **kwargs: Any,+ ) -> Response:+ action = str(action or self.method or "status").strip().lower().replace("-", "_")+ try:+ if action == "create":+ doc = wopi_store.create_document(kind=kind, title=title, fmt=format, content=content, path=path)+ return self._document_response("Created document artifact.", doc)+ if action == "open":+ doc = self._document_from_input(file_id=file_id, path=path)+ return self._document_response("Opened document artifact.", doc)+ if action == "inspect":+ doc = self._document_from_input(file_id=file_id, path=path)+ return self._json_response({"ok": True, "document": self._public_doc(doc)}, doc=doc)+ if action == "version_history":+ doc = self._document_from_input(file_id=file_id, path=path)+ versions = wopi_store.version_history(doc["file_id"])+ return self._json_response({"ok": True, "versions": versions}, doc=doc)+ 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 = wopi_store.restore_version(doc["file_id"], int(version_id))+ return self._document_response("Restored document artifact version.", restored)+ 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(".")+ if target_format and target_format != doc["extension"]:+ return Response(+ message=f"Export to .{target_format} is not available yet. The source file remains unchanged at {doc['path']}.",+ break_loop=False,+ additional=self._additional(doc),+ )+ return self._document_response("Document artifact export path is ready.", doc)+ if action == "status":+ return self._json_response({"ok": True, "status": collabora_status.collect_status()})+ return Response(message=f"Unknown document_artifact action: {action}", break_loop=False)+ except Exception as exc:+ return Response(message=f"document_artifact {action} failed: {exc}", break_loop=False)++ def get_log_object(self):+ return self.agent.context.log.log(+ type="tool",+ heading=f"icon://description {self.agent.agent_name}: Using document artifact",+ content="",+ kvps={**self.args, "_tool_name": self.name},+ _tool_name=self.name,+ )++ def _document_from_input(self, file_id: str = "", path: str = "") -> dict[str, Any]:+ if file_id:+ return wopi_store.get_document(file_id)+ if path:+ return wopi_store.register_document(path)+ raise ValueError("file_id or path is required")++ def _document_response(self, message: str, doc: dict[str, Any]) -> Response:+ payload = {"ok": True, "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),+ )++ def _json_response(self, payload: dict[str, Any], doc: dict[str, Any] | None = None) -> Response:+ return Response(+ message=json.dumps(payload, indent=2, ensure_ascii=False, default=str),+ break_loop=False,+ additional=self._additional(doc) if doc else {"_tool_name": self.name, "canvas_surface": "office"},+ )++ def _additional(self, doc: dict[str, Any] | None) -> dict[str, Any]:+ if not doc:+ return {"_tool_name": self.name, "canvas_surface": "office"}+ return {+ "_tool_name": self.name,+ "canvas_surface": "office",+ "file_id": doc["file_id"],+ "title": doc["basename"],+ "format": doc["extension"],+ "path": doc["path"],+ "version": wopi_store.item_version(doc),+ }++ def _public_doc(self, doc: dict[str, Any]) -> dict[str, Any]:+ return {+ "file_id": doc["file_id"],+ "path": doc["path"],+ "basename": doc["basename"],+ "extension": doc["extension"],+ "size": doc["size"],+ "version": wopi_store.item_version(doc),+ "last_modified": doc["last_modified"],+ "exists": Path(doc["path"]).exists(),+ }diff --git a/plugins/_office/webui/main.html b/plugins/_office/webui/main.htmlnew file mode 100644index 000000000..d9f9701d1--- /dev/null+++ b/plugins/_office/webui/main.html@@ -0,0 +1,14 @@+<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 Office in canvas"+ data-canvas-dock-icon="dock_to_right"+>+<head>+ <title>Office</title>+</head>+<body class="office-modal-body">+ <x-component path="/plugins/_office/webui/office-panel.html" mode="modal"></x-component>+</body>+</html>diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.htmlnew file mode 100644index 000000000..510142c74--- /dev/null+++ b/plugins/_office/webui/office-panel.html@@ -0,0 +1,464 @@+<html>+<head>+ <script type="module">+ import { store } from "/plugins/_office/webui/office-store.js";+ </script>+</head>+<body>+ <div class="office-panel" x-data x-create="$store.office.onMount($el, xAttrs($el) || {})" x-destroy="$store.office.cleanup()">+ <template x-if="$store.office">+ <div class="office-shell">+ <div class="office-toolbar">+ <button type="button" class="office-button" title="Open" @click="$store.office.openPrompt()">+ <span class="material-symbols-outlined">folder_open</span>+ <span>Open</span>+ </button>+ <button type="button" class="office-button" title="New document" @click="$store.office.create('document')">+ <span class="material-symbols-outlined">note_add</span>+ <span>Doc</span>+ </button>+ <button type="button" class="office-button" title="New spreadsheet" @click="$store.office.create('spreadsheet')">+ <span class="material-symbols-outlined">table</span>+ <span>Sheet</span>+ </button>+ <button type="button" class="office-button" title="New presentation" @click="$store.office.create('presentation')">+ <span class="material-symbols-outlined">slideshow</span>+ <span>Presentation</span>+ </button>+ <span class="office-toolbar-spacer"></span>+ <span+ class="office-health-pill"+ :class="`is-${$store.office.status?.state || 'unknown'}`"+ :title="$store.office.status?.message || 'Office status'"+ >+ <span class="office-health-dot"></span>+ <span x-text="$store.office.status?.state || 'status'"></span>+ </span>+ <button type="button" class="office-icon-button" title="Save" @click="$store.office.save()" :disabled="!$store.office.session">+ <span class="material-symbols-outlined">save</span>+ </button>+ <button type="button" class="office-icon-button" title="Versions" @click="$store.office.showVersions()" :disabled="!$store.office.session">+ <span class="material-symbols-outlined">history</span>+ </button>+ <button type="button" class="office-icon-button" title="Refresh status" @click="$store.office.refresh()">+ <span class="material-symbols-outlined">refresh</span>+ </button>+ </div>++ <div class="office-status-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">+ <div class="office-bootstrap" x-show="!$store.office.session && (!$store.office.status || !$store.office.status.healthy)">+ <div class="office-bootstrap-header">+ <span class="material-symbols-outlined">description</span>+ <div>+ <strong x-text="$store.office.status?.state || 'Preparing Office'"></strong>+ <span x-text="$store.office.status?.message || 'Collabora Online is being prepared in the background.'"></span>+ </div>+ </div>+ <div class="office-bootstrap-actions">+ <button type="button" class="office-button" @click="$store.office.retry()">+ <span class="material-symbols-outlined">restart_alt</span>+ <span>Retry</span>+ </button>+ <button type="button" class="office-button" @click="$store.office.refresh()">+ <span class="material-symbols-outlined">sync</span>+ <span>Status</span>+ </button>+ </div>+ <pre class="office-log" x-text="$store.office.logs?.bootstrap || $store.office.logs?.wrapper || ''"></pre>+ </div>++ <div class="office-start" x-show="!$store.office.session && $store.office.status?.healthy" style="display: none;">+ <div class="office-start-actions">+ <button type="button" class="office-create-tile" @click="$store.office.create('document')">+ <span class="material-symbols-outlined">article</span>+ <span>Document</span>+ </button>+ <button type="button" class="office-create-tile" @click="$store.office.create('spreadsheet')">+ <span class="material-symbols-outlined">table_chart</span>+ <span>Spreadsheet</span>+ </button>+ <button type="button" class="office-create-tile" @click="$store.office.create('presentation')">+ <span class="material-symbols-outlined">co_present</span>+ <span>Presentation</span>+ </button>+ </div>+ <div class="office-recent" x-show="$store.office.recent.length">+ <template x-for="doc in $store.office.recent" :key="doc.file_id">+ <button type="button" class="office-recent-row" :title="doc.path" @click="$store.office.openPath(doc.path)">+ <span class="material-symbols-outlined">description</span>+ <span x-text="doc.basename"></span>+ </button>+ </template>+ </div>+ </div>++ <div class="office-frame-wrap" x-show="$store.office.session" style="display: none;">+ <iframe+ data-office-frame+ allow="clipboard-read *; clipboard-write *; fullscreen *"+ allowfullscreen+ ></iframe>+ </div>+ </div>+ </div>+ </template>+ </div>++ <style>+ .office-panel,+ .office-shell {+ display: flex;+ flex: 1 1 auto;+ flex-direction: column;+ width: 100%;+ height: 100%;+ min-width: 0;+ min-height: 0;+ background: var(--color-background);+ }++ .office-panel {+ container-type: inline-size;+ }++ .modal-inner.office-modal {+ box-sizing: border-box;+ container-type: inline-size;+ width: min(82vw, 1180px);+ height: min(88vh, 900px);+ min-width: min(340px, calc(100vw - 16px));+ min-height: min(500px, calc(100vh - 16px));+ max-width: calc(100vw - 16px);+ max-height: calc(100vh - 16px);+ resize: both;+ border: 1px solid color-mix(in srgb, var(--color-border) 75%, transparent);+ border-radius: 7px;+ box-shadow: 0 18px 48px rgba(0, 0, 0, 0.32);+ background: color-mix(in srgb, var(--color-background) 94%, #000 6%);+ }++ .modal-inner.office-modal .modal-header {+ min-height: 34px;+ padding: 0.35rem 0.75rem 0.35rem 1rem;+ cursor: move;+ user-select: none;+ background: color-mix(in srgb, var(--color-background) 92%, #000 8%);+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 70%, transparent);+ }++ .modal-inner.office-modal .modal-title {+ font-size: 0.95rem;+ letter-spacing: 0;+ }++ .modal-inner.office-modal .modal-close {+ font-size: 1.35rem;+ line-height: 1;+ }++ .modal-inner.office-modal .modal-scroll {+ display: flex;+ flex-direction: column;+ flex: 1 1 auto;+ min-height: 0;+ overflow: hidden;+ padding: 0;+ }++ .modal-inner.office-modal .modal-bd.office-modal-body {+ box-sizing: border-box;+ display: flex;+ flex-direction: column;+ flex: 1 1 auto;+ width: 100%;+ height: 100%;+ min-height: 0;+ padding: 0;+ }++ .modal-inner.office-modal .modal-bd.office-modal-body > x-component,+ .modal-inner.office-modal .modal-bd.office-modal-body > div[x-data] {+ display: flex;+ flex: 1 1 auto;+ width: 100%;+ height: 100%;+ min-height: 0;+ }++ .modal-inner.office-modal .modal-bd.office-modal-body > x-component > .office-panel {+ flex: 1 1 auto;+ height: 100%;+ min-height: 0;+ }++ .office-toolbar {+ display: flex;+ align-items: center;+ gap: 6px;+ min-height: 44px;+ padding: 7px 9px;+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 66%, transparent);+ background: color-mix(in srgb, var(--color-background) 92%, #000 8%);+ overflow-x: auto;+ }++ .office-toolbar-spacer {+ flex: 1 1 auto;+ min-width: 8px;+ }++ .office-button,+ .office-icon-button,+ .office-health-pill,+ .office-create-tile,+ .office-recent-row {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 7px;+ border: 1px solid color-mix(in srgb, var(--color-border) 64%, transparent);+ border-radius: 7px;+ background: color-mix(in srgb, var(--color-panel) 80%, transparent);+ color: var(--color-text);+ font: inherit;+ cursor: pointer;+ }++ .office-button {+ min-height: 32px;+ padding: 5px 9px;+ font-size: 0.8rem;+ white-space: nowrap;+ }++ .office-icon-button {+ width: 32px;+ height: 32px;+ min-width: 32px;+ padding: 0;+ }++ .office-health-pill {+ min-height: 28px;+ padding: 4px 8px;+ cursor: default;+ font-size: 0.75rem;+ text-transform: capitalize;+ white-space: nowrap;+ color: var(--color-text-muted);+ background: color-mix(in srgb, var(--color-panel) 64%, transparent);+ }++ .office-health-dot {+ width: 7px;+ height: 7px;+ border-radius: 999px;+ background: color-mix(in srgb, var(--color-text-muted) 70%, transparent);+ }++ .office-health-pill.is-healthy .office-health-dot {+ background: #31c48d;+ }++ .office-health-pill.is-installing .office-health-dot {+ background: #f6ad55;+ }++ .office-health-pill.is-degraded .office-health-dot,+ .office-health-pill.is-failed .office-health-dot {+ background: #f05252;+ }++ .office-button:hover:not(:disabled),+ .office-icon-button:hover:not(:disabled),+ .office-create-tile:hover,+ .office-recent-row:hover {+ background: color-mix(in srgb, var(--color-background-hover) 70%, transparent);+ border-color: color-mix(in srgb, var(--color-primary) 28%, var(--color-border));+ }++ .office-button:disabled,+ .office-icon-button:disabled {+ cursor: not-allowed;+ opacity: 0.42;+ }++ .office-button .material-symbols-outlined,+ .office-icon-button .material-symbols-outlined {+ font-size: 18px;+ }++ .office-status-line {+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 32px;+ padding: 5px 10px;+ border-bottom: 1px solid color-mix(in srgb, var(--color-border) 44%, transparent);+ font-size: 0.82rem;+ color: var(--color-text);+ }++ .office-body {+ position: relative;+ display: flex;+ flex: 1 1 auto;+ min-width: 0;+ min-height: 0;+ overflow: hidden;+ }++ .office-bootstrap,+ .office-start {+ display: flex;+ flex: 1 1 auto;+ min-width: 0;+ min-height: 0;+ flex-direction: column;+ gap: 14px;+ padding: 18px;+ overflow: auto;+ }++ .office-bootstrap-header {+ display: grid;+ grid-template-columns: auto minmax(0, 1fr);+ gap: 10px;+ align-items: start;+ max-width: 720px;+ }++ .office-bootstrap-header > .material-symbols-outlined {+ font-size: 24px;+ color: color-mix(in srgb, var(--color-primary) 70%, var(--color-text));+ }++ .office-bootstrap-header div {+ display: flex;+ min-width: 0;+ flex-direction: column;+ gap: 3px;+ font-size: 0.9rem;+ line-height: 1.35;+ }++ .office-bootstrap-header span {+ color: var(--color-text-muted);+ }++ .office-bootstrap-actions,+ .office-start-actions {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ }++ .office-log {+ min-height: 140px;+ max-height: 260px;+ overflow: auto;+ margin: 0;+ padding: 10px;+ border: 1px solid color-mix(in srgb, var(--color-border) 60%, transparent);+ border-radius: 7px;+ background: color-mix(in srgb, var(--color-panel) 78%, transparent);+ color: var(--color-text-muted);+ font-family: var(--font-family-code);+ font-size: 0.72rem;+ white-space: pre-wrap;+ }++ .office-create-tile {+ min-width: 132px;+ min-height: 88px;+ flex-direction: column;+ padding: 12px;+ font-weight: 650;+ }++ .office-create-tile .material-symbols-outlined {+ font-size: 28px;+ }++ .office-recent {+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-width: 720px;+ }++ .office-recent-row {+ justify-content: flex-start;+ min-height: 36px;+ padding: 7px 9px;+ text-align: left;+ }++ .office-recent-row span:last-child {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }++ .office-frame-wrap {+ display: flex;+ position: absolute;+ inset: 0;+ flex: 1 1 auto;+ width: 100%;+ height: 100%;+ min-width: 0;+ min-height: 0;+ background: #fff;+ }++ .office-frame-wrap iframe {+ flex: 1 1 auto;+ width: 100%;+ height: 100%;+ min-width: 0;+ min-height: 0;+ border: 0;+ background: #fff;+ }++ .office-panel .spinning {+ display: inline-block;+ animation: office-spin 0.8s linear infinite;+ }++ @keyframes office-spin {+ to { transform: rotate(360deg); }+ }++ @media (max-width: 520px) {+ .office-button span:last-child {+ display: none;+ }+ .office-health-pill span:last-child {+ display: none;+ }+ .office-create-tile {+ min-width: 104px;+ }+ }++ @container (max-width: 560px) {+ .office-button span:last-child {+ display: none;+ }+ .office-health-pill span:last-child {+ display: none;+ }+ .office-create-tile {+ min-width: 104px;+ }+ }+ </style>+</body>+</html>diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.jsnew file mode 100644index 000000000..69b9dcd2a--- /dev/null+++ b/plugins/_office/webui/office-store.js@@ -0,0 +1,449 @@+import { createStore } from "/js/AlpineStore.js";+import { callJsonApi } from "/js/api.js";++const FRAME_NAME_PREFIX = "a0-office-frame";++function makeFrameName() {+ const id = globalThis.crypto?.randomUUID?.()+ || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;+ return `${FRAME_NAME_PREFIX}-${id}`;+}++function parseMessage(data) {+ if (typeof data === "string") {+ try {+ return JSON.parse(data);+ } catch {+ return { MessageId: data };+ }+ }+ return data && typeof data === "object" ? data : {};+}++const model = {+ status: null,+ logs: null,+ recent: [],+ session: null,+ loading: false,+ error: "",+ message: "",+ frameReady: false,+ frameName: FRAME_NAME_PREFIX,+ _root: null,+ _messageBound: false,+ _frameTimer: null,+ _frameRecoveryTimer: null,+ _frameAttempt: 0,+ _frameRecoveryTried: false,+ _frameOrigin: "",+ _mode: "canvas",+ _floatingCleanup: null,++ async init(element = null) {+ return await this.onMount(element, { mode: "canvas" });+ },++ async onMount(element = null, options = {}) {+ if (element) this._root = element;+ this.assignFrameName(element);+ globalThis.requestAnimationFrame?.(() => this.assignFrameName(element));+ if (!this._messageBound) {+ globalThis.addEventListener("message", (event) => this.onPostMessage(event));+ this._messageBound = true;+ }+ this._mode = options?.mode === "modal" ? "modal" : "canvas";+ if (this._mode === "modal") {+ this.setupFloatingModal(element);+ } else {+ this.setupCanvasSurface(element);+ }+ await this.refresh();+ if (this.session && this._root) {+ await this.restartFrameLoad();+ }+ },++ async onOpen(payload = {}) {+ await this.refresh();+ if (payload?.path) {+ await this.openPath(payload.path);+ } else if (this.session && !this.frameReady) {+ await this.restartFrameLoad();+ }+ },++ cleanup() {+ this._floatingCleanup?.();+ this._floatingCleanup = null;+ if (this._mode === "modal") {+ this._root = null;+ }+ },++ async refresh() {+ try {+ this.status = await callJsonApi("/plugins/_office/office_session", { action: "status" });+ const recent = await callJsonApi("/plugins/_office/office_session", { action: "recent" });+ this.recent = recent?.documents || [];+ if (!this.status?.healthy) {+ const logs = await callJsonApi("/plugins/_office/collabora_logs", {});+ this.logs = logs;+ }+ } catch (error) {+ this.error = error instanceof Error ? error.message : String(error);+ }+ },++ async retry() {+ this.message = "Retrying Collabora setup...";+ this.status = await callJsonApi("/plugins/_office/office_session", { action: "retry" });+ },++ async create(kind = "document") {+ const defaults = {+ document: ["Document", "docx"],+ spreadsheet: ["Spreadsheet", "xlsx"],+ presentation: ["Presentation", "pptx"],+ };+ const [title, format] = defaults[kind] || defaults.document;+ await this.openSession({+ action: "create",+ kind,+ title,+ format,+ content: "",+ });+ },++ async openPrompt() {+ const path = globalThis.prompt?.("Open Office file path", "/a0/usr/workdir/documents/");+ if (!path) return;+ await this.openPath(path);+ },++ async openPath(path) {+ await this.openSession({ action: "open", path, mode: "edit" });+ },++ async openSession(payload) {+ this.loading = true;+ this.error = "";+ this.message = "";+ try {+ const response = await callJsonApi("/plugins/_office/office_session", payload);+ if (!response?.ok) {+ this.error = response?.error || "Office session could not be opened.";+ if (response?.status) this.status = response.status;+ return;+ }+ this.clearFrameTimers();+ this.session = response;+ this.frameReady = false;+ this._frameOrigin = "";+ this._frameAttempt = 0;+ this._frameRecoveryTried = false;+ await this.submitFrame();+ this.scheduleFrameWatch();+ await this.refresh();+ } catch (error) {+ this.error = error instanceof Error ? error.message : String(error);+ } finally {+ this.loading = false;+ }+ },++ async submitFrame() {+ await new Promise((resolve) => requestAnimationFrame(resolve));+ const session = this.session;+ const frame = this.activeFrame();+ if (!session || !frame?.name) return;+ const form = document.createElement("form");+ form.method = "post";+ form.action = this.frameAction(session.iframe_action);+ form.target = frame.name;+ form.style.display = "none";+ const fields = {+ access_token: session.access_token,+ access_token_ttl: String(session.access_token_ttl),+ ui_defaults: "UIMode=notebookbar;TextRuler=false",+ };+ for (const [name, value] of Object.entries(fields)) {+ const input = document.createElement("input");+ input.type = "hidden";+ input.name = name;+ input.value = value;+ form.appendChild(input);+ }+ document.body.appendChild(form);+ form.submit();+ form.remove();+ },++ async restartFrameLoad() {+ this.frameReady = false;+ this._frameOrigin = "";+ this._frameAttempt = 0;+ this._frameRecoveryTried = false;+ this.clearFrameTimers();+ await this.submitFrame();+ this.scheduleFrameWatch();+ },++ frameAction(action) {+ const url = new URL(action, globalThis.location.origin);+ url.searchParams.set("a0_frame_attempt", String(this._frameAttempt));+ return url.pathname + url.search;+ },++ scheduleFrameWatch() {+ this.clearFrameTimers();+ this._frameTimer = setTimeout(() => {+ if (this.session && !this.frameReady) {+ this.message = "Still opening the editor...";+ this._frameRecoveryTimer = setTimeout(() => this.recoverFrameLoad(), 3000);+ }+ }, 20000);+ },++ async recoverFrameLoad() {+ if (!this.session || this.frameReady || this._frameRecoveryTried) return;+ this._frameRecoveryTried = true;+ this._frameAttempt += 1;+ this.message = "Still opening the editor... trying a fresh editor load.";+ await this.submitFrame();+ this._frameTimer = setTimeout(() => {+ if (this.session && !this.frameReady) {+ this.message = "Still opening the editor...";+ }+ }, 25000);+ },++ clearFrameTimers() {+ if (this._frameTimer) {+ clearTimeout(this._frameTimer);+ this._frameTimer = null;+ }+ if (this._frameRecoveryTimer) {+ clearTimeout(this._frameRecoveryTimer);+ this._frameRecoveryTimer = null;+ }+ },++ beforeHostHidden() {+ if (this.session) {+ this.save();+ }+ this.frameReady = false;+ this._frameOrigin = "";+ this.clearFrameTimers();+ const frame = this.activeFrame();+ if (frame) {+ frame.src = "about:blank";+ }+ },++ postToFrame(message) {+ const frame = this.activeFrame();+ const targetOrigin = this._frameOrigin || this.session?.post_message_origin || globalThis.location.origin;+ frame?.contentWindow?.postMessage(JSON.stringify(message), targetOrigin);+ },++ save() {+ this.postToFrame({+ MessageId: "Action_Save",+ Values: {+ DontTerminateEdit: true,+ DontSaveIfUnmodified: true,+ },+ });+ },++ closeFile() {+ this.save();+ this.session = null;+ this.frameReady = false;+ this._frameOrigin = "";+ this._frameAttempt = 0;+ this._frameRecoveryTried = false;+ this.clearFrameTimers();+ },++ async showVersions() {+ if (!this.session?.file_id) return;+ this.message = "Version history is available through the document_artifact tool.";+ },++ onPostMessage(event) {+ if (!this.session) return;+ if (!this.isAllowedFrameOrigin(event.origin)) return;+ this._frameOrigin = event.origin;+ const message = parseMessage(event.data);+ const id = message.MessageId || message.messageId || "";+ if (id === "App_LoadingStatus" && message.Values?.Status === "Frame_Ready") {+ this.frameReady = true;+ this.clearFrameTimers();+ if (this.message === "Still opening the editor...") this.message = "";+ if (this.message === "Still opening the editor... trying a fresh editor load.") this.message = "";+ this.postToFrame({ MessageId: "Host_PostmessageReady" });+ } else if (id === "UI_Close") {+ this.session = null;+ } else if (id === "Action_Save_Resp") {+ this.message = message.Values?.success === false ? "Save did not complete." : "Saved";+ }+ },++ isAllowedFrameOrigin(origin) {+ const allowed = new Set([+ globalThis.location.origin,+ this.session?.post_message_origin,+ this.loopbackCounterpart(globalThis.location.origin),+ this.loopbackCounterpart(this.session?.post_message_origin),+ ].filter(Boolean));+ return allowed.has(origin);+ },++ loopbackCounterpart(origin) {+ if (!origin) return "";+ try {+ const url = new URL(origin);+ if (url.hostname === "127.0.0.1") {+ url.hostname = "localhost";+ return url.origin;+ }+ if (url.hostname === "localhost") {+ url.hostname = "127.0.0.1";+ return url.origin;+ }+ } catch {+ return "";+ }+ return "";+ },++ assignFrameName(element = null) {+ const root = element || this._root;+ if (!root) return this.frameName || FRAME_NAME_PREFIX;+ if (!root.dataset.officeFrameName) {+ root.dataset.officeFrameName = makeFrameName();+ }+ const frame = root.querySelector?.("iframe[data-office-frame]");+ if (frame) {+ frame.setAttribute("name", root.dataset.officeFrameName);+ frame.name = root.dataset.officeFrameName;+ try {+ frame.contentWindow.name = root.dataset.officeFrameName;+ } catch {}+ }+ this.frameName = root.dataset.officeFrameName;+ return this.frameName;+ },++ activeFrame() {+ this.assignFrameName();+ return this._root?.querySelector?.("iframe[data-office-frame]") || null;+ },++ setupFloatingModal(element = null) {+ this._floatingCleanup?.();+ const root = element || globalThis.document?.querySelector(".office-panel");+ const modal = root?.closest?.(".modal");+ const inner = modal?.querySelector?.(".modal-inner");+ const body = modal?.querySelector?.(".modal-bd");+ const header = modal?.querySelector?.(".modal-header");+ if (!modal || !inner || !header) return;+ modal.classList.add("modal-floating");+ inner.classList.add("office-modal", "modal-no-backdrop");+ body?.classList?.add("office-modal-body");++ const rect = inner.getBoundingClientRect();+ inner.style.left = `${Math.max(8, rect.left)}px`;+ inner.style.top = `${Math.max(8, rect.top)}px`;+ inner.style.transform = "none";++ let drag = null;+ let resizeObserver = null;+ const viewportGap = 8;+ const clampPosition = (left, top) => {+ const bounds = inner.getBoundingClientRect();+ const maxLeft = Math.max(viewportGap, globalThis.innerWidth - bounds.width - viewportGap);+ const maxTop = Math.max(viewportGap, globalThis.innerHeight - bounds.height - viewportGap);+ return {+ left: Math.min(Math.max(viewportGap, left), maxLeft),+ top: Math.min(Math.max(viewportGap, top), maxTop),+ };+ };+ const clampGeometry = () => {+ const bounds = inner.getBoundingClientRect();+ const left = Math.max(viewportGap, bounds.left);+ const top = Math.max(viewportGap, bounds.top);+ const maxWidth = Math.max(340, globalThis.innerWidth - viewportGap * 2);+ const maxHeight = Math.max(360, globalThis.innerHeight - viewportGap * 2);+ if (bounds.width > maxWidth) inner.style.width = `${maxWidth}px`;+ if (bounds.height > maxHeight) inner.style.height = `${maxHeight}px`;+ const next = clampPosition(left, top);+ inner.style.left = `${next.left}px`;+ inner.style.top = `${next.top}px`;+ inner.style.maxWidth = `${Math.max(340, globalThis.innerWidth - next.left - viewportGap)}px`;+ inner.style.maxHeight = `${Math.max(360, globalThis.innerHeight - next.top - viewportGap)}px`;+ };+ clampGeometry();+ globalThis.addEventListener("resize", clampGeometry);+ if (globalThis.ResizeObserver) {+ resizeObserver = new ResizeObserver(clampGeometry);+ resizeObserver.observe(inner);+ }++ const onPointerMove = (event) => {+ if (!drag) return;+ const next = clampPosition(+ drag.left + event.clientX - drag.x,+ drag.top + event.clientY - drag.y,+ );+ inner.style.left = `${next.left}px`;+ inner.style.top = `${next.top}px`;+ clampGeometry();+ };+ const onPointerUp = () => {+ drag = null;+ globalThis.removeEventListener("pointermove", onPointerMove);+ globalThis.removeEventListener("pointerup", onPointerUp);+ try {+ header.releasePointerCapture?.(header.__officePanelPointerId || 0);+ } catch {}+ };+ const onPointerDown = (event) => {+ if (event.button !== 0) return;+ if (event.target?.closest?.("button, input, select, textarea, a")) return;+ const current = inner.getBoundingClientRect();+ drag = {+ x: event.clientX,+ y: event.clientY,+ left: current.left,+ top: current.top,+ };+ header.__officePanelPointerId = event.pointerId;+ header.setPointerCapture?.(event.pointerId);+ globalThis.addEventListener("pointermove", onPointerMove);+ globalThis.addEventListener("pointerup", onPointerUp);+ event.preventDefault();+ };+ header.addEventListener("pointerdown", onPointerDown);++ this._floatingCleanup = () => {+ header.removeEventListener("pointerdown", onPointerDown);+ globalThis.removeEventListener("pointermove", onPointerMove);+ globalThis.removeEventListener("pointerup", onPointerUp);+ globalThis.removeEventListener("resize", clampGeometry);+ resizeObserver?.disconnect?.();+ };+ },++ setupCanvasSurface(element = null) {+ this._floatingCleanup?.();+ this._floatingCleanup = null;+ if (element) this._root = element;+ },+};++export const store = createStore("office", model);diff --git a/tests/test_office_wopi_store.py b/tests/test_office_wopi_store.pynew file mode 100644index 000000000..b0774f493--- /dev/null+++ b/tests/test_office_wopi_store.py@@ -0,0 +1,161 @@+from __future__ import annotations++import sys+from pathlib import Path++import pytest+from flask import Flask++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))++from plugins._office.helpers import wopi_routes, wopi_store+++def office_state(tmp_path, monkeypatch):+ workdir = tmp_path / "workdir"+ state = tmp_path / "state"+ documents = workdir / "documents"+ monkeypatch.setattr(wopi_store, "STATE_DIR", state)+ monkeypatch.setattr(wopi_store, "DB_PATH", state / "documents.sqlite3")+ monkeypatch.setattr(wopi_store, "BACKUP_DIR", state / "backups")+ monkeypatch.setattr(wopi_store, "DOCUMENTS_DIR", documents)+ monkeypatch.setattr(wopi_store, "WORKDIR", workdir)+ wopi_store.ensure_dirs()+ return {"workdir": workdir, "state": state, "documents": documents}+++def test_check_file_info_has_no_nulls_and_token_is_scoped(office_state):+ doc = wopi_store.create_document("document", "Scope Test", "docx", "hello")+ session = wopi_store.create_session(doc["file_id"], "user-a", "write", "http://localhost:32080")++ token_info = wopi_store.validate_token(session["access_token"], doc["file_id"], require_write=True)+ info = wopi_store.check_file_info(doc["file_id"], token_info)++ assert all(value is not None for value in info.values())+ assert info["UserCanWrite"] is True+ assert info["ReadOnly"] is False+ assert info["SupportsLocks"] is True++ other = wopi_store.create_document("document", "Other", "docx", "")+ with pytest.raises(PermissionError):+ wopi_store.validate_token(session["access_token"], other["file_id"])+++def test_path_traversal_and_symlink_escape_are_rejected(office_state, tmp_path):+ outside = tmp_path / "outside.docx"+ outside.write_bytes(wopi_store.template_bytes("document", "docx", "Outside", ""))++ with pytest.raises(PermissionError):+ wopi_store.register_document(outside)++ link = office_state["workdir"] / "escape.docx"+ link.symlink_to(outside)+ with pytest.raises(PermissionError):+ wopi_store.register_document(link)+++def test_lock_conflicts_refresh_unlock_and_relock(office_state):+ doc = wopi_store.create_document("document", "Lock Test", "docx", "")+ session = wopi_store.create_session(doc["file_id"], "user-a", "write", "http://localhost:32080")++ ok, current = wopi_store.lock(doc["file_id"], "lock-a", session["session_id"], 120)+ assert ok is True+ assert current == "lock-a"++ ok, current = wopi_store.lock(doc["file_id"], "lock-b", session["session_id"], 120)+ assert ok is False+ assert current == "lock-a"++ ok, current = wopi_store.refresh_lock(doc["file_id"], "lock-a", 120)+ assert ok is True+ assert current == "lock-a"++ ok, current = wopi_store.unlock_and_relock(doc["file_id"], "lock-a", "lock-c", session["session_id"], 120)+ assert ok is True+ assert current == "lock-c"++ ok, current = wopi_store.unlock(doc["file_id"], "lock-b")+ assert ok is False+ assert current == "lock-c"++ ok, current = wopi_store.unlock(doc["file_id"], "lock-c")+ assert ok is True+ assert current == ""+++def test_put_file_requires_lock_and_updates_version_history(office_state):+ doc = wopi_store.create_document("document", "Save Test", "docx", "before")+ session = wopi_store.create_session(doc["file_id"], "user-a", "write", "http://localhost:32080")++ with pytest.raises(wopi_store.LockMismatch):+ wopi_store.put_file(doc["file_id"], b"after", "")++ ok, _ = wopi_store.lock(doc["file_id"], "save-lock", session["session_id"], 120)+ assert ok is True+ next_version = wopi_store.put_file(doc["file_id"], b"after", "save-lock")+ saved = wopi_store.get_document(doc["file_id"])++ assert next_version == wopi_store.item_version(saved)+ assert saved["size"] == len(b"after")+ assert (office_state["documents"] / "Save Test.docx").read_bytes() == b"after"+ assert wopi_store.version_history(doc["file_id"])+++def test_wopi_routes_return_conflict_lock_header(office_state):+ app = Flask(__name__)+ wopi_routes.register_wopi_routes(app)+ doc = wopi_store.create_document("document", "Route Test", "docx", "")+ session = wopi_store.create_session(doc["file_id"], "user-a", "write", "http://localhost:32080")++ with app.test_client() as client:+ first = client.post(+ f"/wopi/files/{doc['file_id']}?access_token={session['access_token']}",+ headers={"X-WOPI-Override": "LOCK", "X-WOPI-Lock": "route-lock"},+ )+ assert first.status_code == 200++ conflict = client.post(+ f"/wopi/files/{doc['file_id']}?access_token={session['access_token']}",+ headers={"X-WOPI-Override": "LOCK", "X-WOPI-Lock": "other-lock"},+ )+ assert conflict.status_code == 409+ assert conflict.headers["X-WOPI-Lock"] == "route-lock"+++def test_office_proxy_accepts_encoded_wopi_socket_token_without_session_cookie(office_state):+ pytest.importorskip("starlette")+ from plugins._office.helpers import office_proxy++ doc = wopi_store.create_document("document", "Socket Token", "docx", "")+ session = wopi_store.create_session(doc["file_id"], "user-a", "write", "http://127.0.0.1:32080")+ encoded_wopi = (+ f"http%3A%2F%2F127.0.0.1%3A80%2Fwopi%2Ffiles%2F{doc['file_id']}"+ f"%3Faccess_token%3D{session['access_token']}"+ f"%26access_token_ttl%3D{session['access_token_ttl']}"+ )+ scope = {+ "type": "websocket",+ "path": f"/office/cool/{encoded_wopi}/ws",+ "raw_path": f"/office/cool/{encoded_wopi}/ws".encode("latin-1"),+ "query_string": b"",+ "headers": [],+ }++ proxy = office_proxy.OfficeProxy()++ assert proxy._has_valid_wopi_token(scope) is True++ headers = proxy.websocket_headers({+ "headers": [+ (b"host", b"127.0.0.1:32080"),+ (b"origin", b"http://127.0.0.1:32080"),+ (b"user-agent", b"qa"),+ (b"sec-websocket-key", b"ignored"),+ ],+ })+ assert proxy.upstream_websocket_url(scope).startswith("ws://127.0.0.1:32080/office/cool/")+ assert all(key.lower() not in {"host", "origin", "sec-websocket-key"} for key, _ in headers)+ assert ("user-agent", "qa") in headers