Skip to content

Agent Zero AI framework

Improve Office desktop integration

Alessandro739c0a18a31e
diff --git a/helpers/virtual_desktop.py b/helpers/virtual_desktop.py
index a5ae2e371..3e2cf5f3a 100644
--- a/helpers/virtual_desktop.py
+++ b/helpers/virtual_desktop.py
@@ -122,6 +122,9 @@ def session_url(token: str, *, title: str = "Desktop") -> str:
"title": title,
"sharing": "true",
"clipboard": "true",
+ "clipboard_direction": "both",
+ "clipboard_poll": "true",
+ "clipboard_preferred_format": "text/plain",
"printing": "true",
"file_transfer": "true",
"sound": "true",
diff --git a/plugins/_office/helpers/libreoffice_desktop.py b/plugins/_office/helpers/libreoffice_desktop.py
index 75fd49214..de31d6c62 100644
--- a/plugins/_office/helpers/libreoffice_desktop.py
+++ b/plugins/_office/helpers/libreoffice_desktop.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import atexit
+import hashlib
import json
import os
import shutil
@@ -44,12 +45,14 @@ HIDDEN_XPRA_DESKTOP_ENTRIES = (
"xpra-start.desktop",
)
DESKTOP_FOLDER_LINKS = (
- ("Workdir", ("usr", "workdir")),
("Projects", ("usr", "projects")),
("Skills", ("usr", "skills")),
("Agents", ("usr", "agents")),
("Downloads", ("usr", "downloads")),
)
+OOR_NS = "http://openoffice.org/2001/registry"
+XS_NS = "http://www.w3.org/2001/XMLSchema"
+XSI_NS = "http://www.w3.org/2001/XMLSchema-instance"
@dataclass
@@ -431,27 +434,18 @@ class LibreOfficeDesktopManager:
user_dir = session.profile_dir / "user"
user_dir.mkdir(parents=True, exist_ok=True)
registry = user_dir / "registrymodifications.xcu"
- if registry.exists():
- return
- registry.write_text(
- """<?xml version="1.0" encoding="UTF-8"?>
-<oor:items xmlns:oor="http://openoffice.org/2001/registry" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
-<item oor:path="/org.openoffice.Office.Common/Misc"><prop oor:name="FirstRun" oor:op="fuse"><value>false</value></prop></item>
-<item oor:path="/org.openoffice.Setup/Office"><prop oor:name="ooSetupInstCompleted" oor:op="fuse"><value>true</value></prop></item>
-<item oor:path="/org.openoffice.Setup/Office"><prop oor:name="MigrationCompleted" oor:op="fuse"><value>true</value></prop></item>
-<item oor:path="/org.openoffice.Setup/Office"><prop oor:name="OfficeRestartInProgress" oor:op="fuse"><value>false</value></prop></item>
-<item oor:path="/org.openoffice.Setup/L10N"><prop oor:name="ooLocale" oor:op="fuse"><value>en-US</value></prop></item>
-</oor:items>
-""",
- encoding="utf-8",
- )
+ _write_libreoffice_registry_defaults(registry, document_store.document_home())
def _prepare_desktop_launchers(self, session: DesktopSession) -> None:
soffice = libreoffice.find_soffice()
if not soffice:
raise RuntimeError("LibreOffice is not installed in this runtime.")
+ workdir_home = document_store.document_home()
+ workdir_home.mkdir(parents=True, exist_ok=True)
documents_home = document_store.document_binary_home()
documents_home.mkdir(parents=True, exist_ok=True)
+ downloads_home = Path(files.get_abs_path("usr", "downloads"))
+ downloads_home.mkdir(parents=True, exist_ok=True)
desktop_dir = session.profile_dir / "Desktop"
desktop_dir.mkdir(parents=True, exist_ok=True)
@@ -470,13 +464,13 @@ class LibreOfficeDesktopManager:
"\n".join(
[
'XDG_DESKTOP_DIR="$HOME/Desktop"',
- f'XDG_DOCUMENTS_DIR="{documents_home}"',
- f'XDG_DOWNLOAD_DIR="{files.get_abs_path("usr", "downloads")}"',
- f'XDG_TEMPLATES_DIR="{documents_home}"',
- f'XDG_PUBLICSHARE_DIR="{document_store.document_home()}"',
- f'XDG_MUSIC_DIR="{document_store.document_home()}"',
- f'XDG_PICTURES_DIR="{document_store.document_home()}"',
- f'XDG_VIDEOS_DIR="{document_store.document_home()}"',
+ f'XDG_DOCUMENTS_DIR="{workdir_home}"',
+ f'XDG_DOWNLOAD_DIR="{downloads_home}"',
+ f'XDG_TEMPLATES_DIR="{workdir_home}"',
+ f'XDG_PUBLICSHARE_DIR="{workdir_home}"',
+ f'XDG_MUSIC_DIR="{workdir_home}"',
+ f'XDG_PICTURES_DIR="{downloads_home}"',
+ f'XDG_VIDEOS_DIR="{workdir_home}"',
"",
],
),
@@ -485,10 +479,17 @@ class LibreOfficeDesktopManager:
xfce_conf_dir = config_dir / "xfce4" / "xfconf" / "xfce-perchannel-xml"
xfce_conf_dir.mkdir(parents=True, exist_ok=True)
(xfce_conf_dir / "xfce4-desktop.xml").write_text(
- """<?xml version="1.1" encoding="UTF-8"?>
+ f"""<?xml version="1.1" encoding="UTF-8"?>
<channel name="xfce4-desktop" version="1.0">
<property name="last-settings-migration-version" type="uint" value="1"/>
+ <property name="backdrop" type="empty">
+ <property name="screen0" type="empty">
+ <property name="monitor0" type="empty">
+ <property name="image-path" type="string" value="{_xml_attr(str(downloads_home))}"/>
+ </property>
+ </property>
+ </property>
<property name="desktop-icons" type="empty">
<property name="style" type="int" value="2"/>
<property name="file-icons" type="empty">
@@ -536,16 +537,16 @@ class LibreOfficeDesktopManager:
icon=icon,
categories=categories,
try_exec=soffice,
+ working_dir=workdir_home,
)
terminal = shutil.which("xfce4-terminal") or "xfce4-terminal"
settings = shutil.which("xfce4-settings-manager") or "xfce4-settings-manager"
- workdir = document_store.document_home()
desktop_apps = (
{
"filename": "Terminal.desktop",
"name": "Terminal",
- "exec": _desktop_exec(terminal, f"--working-directory={workdir}"),
+ "exec": _desktop_exec(terminal, f"--working-directory={workdir_home}"),
"try_exec": terminal,
"icon": _desktop_icon(
"/usr/share/icons/hicolor/128x128/apps/org.xfce.terminal.png",
@@ -578,9 +579,11 @@ class LibreOfficeDesktopManager:
categories=str(app["categories"]),
try_exec=str(app["try_exec"]),
)
+ _ensure_desktop_folder_link(desktop_dir, "Workdir", workdir_home)
for label, target_parts in DESKTOP_FOLDER_LINKS:
_ensure_desktop_folder_link(desktop_dir, label, Path(files.get_abs_path(*target_parts)))
+ self._trust_desktop_launchers(session, desktop_dir)
self._prepare_xfce_panel_config(session)
self._prepare_xfce_profile_autostart(session)
@@ -823,6 +826,33 @@ fi
except (OSError, subprocess.TimeoutExpired):
return
+ def _trust_desktop_launchers(self, session: DesktopSession, desktop_dir: Path) -> None:
+ gio = shutil.which("gio")
+ if not gio:
+ return
+ env = self._xfce_process_env(session, "xfdesktop")
+ for launcher in desktop_dir.glob("*.desktop"):
+ try:
+ launcher.chmod(0o755)
+ checksum = hashlib.sha256(launcher.read_bytes()).hexdigest()
+ except OSError:
+ continue
+ for command in (
+ [gio, "set", str(launcher), "metadata::trusted", "true"],
+ [gio, "set", "-t", "string", str(launcher), "metadata::xfce-exe-checksum", checksum],
+ ):
+ try:
+ subprocess.run(
+ command,
+ check=False,
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ timeout=4,
+ env=env,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ continue
+
def _xfce_process_env(self, session: DesktopSession, command_name: str) -> dict[str, str]:
env = self._display_env(session)
proc = Path("/proc")
@@ -1102,6 +1132,8 @@ def _xpra_shadow_command(xpra: str, session: DesktopSession) -> list[str]:
"--tray=no",
"--system-tray=no",
"--notifications=no",
+ "--clipboard=yes",
+ "--clipboard-direction=both",
"--file-transfer=yes",
"--open-files=no",
"--open-url=no",
@@ -1160,6 +1192,86 @@ def _desktop_exec_arg(value: str) -> str:
return f'"{escaped}"'
+def _xml_attr(value: str) -> str:
+ return (
+ str(value)
+ .replace("&", "&amp;")
+ .replace('"', "&quot;")
+ .replace("<", "&lt;")
+ .replace(">", "&gt;")
+ )
+
+
+def _oor(name: str) -> str:
+ return f"{{{OOR_NS}}}{name}"
+
+
+def _file_uri(path: str | Path) -> str:
+ return Path(path).resolve(strict=False).as_uri()
+
+
+def _write_libreoffice_registry_defaults(registry: Path, workdir: str | Path) -> None:
+ Path(workdir).mkdir(parents=True, exist_ok=True)
+ ET.register_namespace("oor", OOR_NS)
+ ET.register_namespace("xs", XS_NS)
+ ET.register_namespace("xsi", XSI_NS)
+ root = _read_libreoffice_registry(registry)
+ workdir_uri = _file_uri(workdir)
+ for path, prop, value in (
+ ("/org.openoffice.Office.Common/Misc", "FirstRun", "false"),
+ ("/org.openoffice.Setup/Office", "ooSetupInstCompleted", "true"),
+ ("/org.openoffice.Setup/Office", "MigrationCompleted", "true"),
+ ("/org.openoffice.Setup/Office", "OfficeRestartInProgress", "false"),
+ ("/org.openoffice.Setup/L10N", "ooLocale", "en-US"),
+ ("/org.openoffice.Office.Paths/Variables", "Work", workdir_uri),
+ (
+ "/org.openoffice.Office.Paths/Paths/org.openoffice.Office.Paths:NamedPath['Work']",
+ "WritePath",
+ workdir_uri,
+ ),
+ ):
+ _set_registry_prop(root, path, prop, value)
+ registry.parent.mkdir(parents=True, exist_ok=True)
+ ET.ElementTree(root).write(registry, encoding="utf-8", xml_declaration=True)
+
+
+def _read_libreoffice_registry(registry: Path) -> ET.Element:
+ if registry.exists():
+ try:
+ return ET.parse(registry).getroot()
+ except ET.ParseError:
+ pass
+ return ET.Element(
+ _oor("items"),
+ {
+ "xmlns:xs": XS_NS,
+ "xmlns:xsi": XSI_NS,
+ },
+ )
+
+
+def _set_registry_prop(root: ET.Element, item_path: str, prop_name: str, value: str) -> None:
+ item = _find_registry_item(root, item_path)
+ if item is None:
+ item = ET.SubElement(root, "item", {_oor("path"): item_path})
+ prop = next((child for child in item.findall("prop") if child.get(_oor("name")) == prop_name), None)
+ if prop is None:
+ prop = ET.SubElement(item, "prop", {_oor("name"): prop_name, _oor("op"): "fuse"})
+ else:
+ prop.set(_oor("op"), "fuse")
+ value_node = prop.find("value")
+ if value_node is None:
+ value_node = ET.SubElement(prop, "value")
+ value_node.text = str(value)
+
+
+def _find_registry_item(root: ET.Element, item_path: str) -> ET.Element | None:
+ for item in root.findall("item"):
+ if item.get(_oor("path")) == item_path:
+ return item
+ return None
+
+
def _write_desktop_launcher(
path: Path,
*,
@@ -1168,6 +1280,7 @@ def _write_desktop_launcher(
icon: str,
categories: str,
try_exec: str = "",
+ working_dir: str | Path | None = None,
) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
lines = [
@@ -1179,6 +1292,8 @@ def _write_desktop_launcher(
]
if try_exec:
lines.append(f"TryExec={try_exec}")
+ if working_dir:
+ lines.append(f"Path={working_dir}")
lines.extend(
[
f"Icon={icon}",
diff --git a/plugins/_office/skills/linux-desktop/SKILL.md b/plugins/_office/skills/linux-desktop/SKILL.md
index 5392968a6..10e66b236 100644
--- a/plugins/_office/skills/linux-desktop/SKILL.md
+++ b/plugins/_office/skills/linux-desktop/SKILL.md
@@ -85,7 +85,7 @@ When browser automation is available, the higher-level QA flow is:
The Desktop exposes stable folders for common user work:
-- `Workdir` -> `/a0/usr/workdir`
+- `Workdir` -> configured Agent Zero workdir (default `/a0/usr/workdir`)
- `Projects` -> `/a0/usr/projects`
- `Skills` -> `/a0/usr/skills`
- `Agents` -> `/a0/usr/agents`
@@ -98,7 +98,7 @@ Use these folders when the user asks to inspect or manipulate project files, ski
- `LibreOffice Writer`: word processing and DOCX layout.
- `LibreOffice Calc`: spreadsheets, formulas, tables, charts.
- `LibreOffice Impress`: presentations and slide polish.
-- `Workdir`: graphical file management with Thunar at `/a0/usr/workdir`.
+- `Workdir`: graphical file management with Thunar at the configured Agent Zero workdir (default `/a0/usr/workdir`).
- `Terminal`: shell work inside the Agent Zero runtime.
- `Settings`: XFCE system settings.
diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.html
index de991fe25..1c02e972c 100644
--- a/plugins/_office/webui/office-panel.html
+++ b/plugins/_office/webui/office-panel.html
@@ -105,8 +105,8 @@
</div>
</div>
- <div class="office-tabs" x-show="$store.office.tabs.length" role="tablist" aria-label="Open documents" style="display: none;">
- <template x-for="tab in $store.office.tabs" :key="tab.tab_id">
+ <div class="office-tabs" x-show="$store.office.visibleTabs().length" role="tablist" aria-label="Open documents" style="display: none;">
+ <template x-for="tab in $store.office.visibleTabs()" :key="tab.tab_id">
<div class="office-tab-shell" :class="{ 'is-active': $store.office.isActiveTab(tab), 'is-dirty': tab.dirty, 'is-system': $store.office.isDesktopSession(tab) }">
<button type="button" class="office-tab" role="tab" :aria-selected="$store.office.isActiveTab(tab).toString()" :title="$store.office.tabLabel(tab)" @click="$store.office.selectTab(tab.tab_id)">
<span class="material-symbols-outlined office-tab-icon" aria-hidden="true" x-text="$store.office.tabIcon(tab)"></span>
diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.js
index 2b04a2291..449ac2458 100644
--- a/plugins/_office/webui/office-store.js
+++ b/plugins/_office/webui/office-store.js
@@ -356,6 +356,7 @@ const model = {
_desktopPrimeAttempts: 0,
_desktopKeyboardActive: false,
_desktopKeyboardCleanup: null,
+ _desktopClipboardCleanup: null,
_desktopStarting: null,
async init(element = null) {
@@ -397,6 +398,7 @@ const model = {
this.stopDesktopResizeObserver();
this.stopXpraDesktopPrime();
this.stopDesktopKeyboardBridge();
+ this.stopDesktopClipboardBridge();
this._floatingCleanup?.();
this._floatingCleanup = null;
if (this._mode === "modal") this._root = null;
@@ -522,6 +524,10 @@ const model = {
},
installSession(session) {
+ if (this.isDesktopOfficeDocument(session)) {
+ this.installDesktopDocumentSession(session);
+ return;
+ }
const existingIndex = this.tabs.findIndex((tab) => (
(session.file_id && tab.file_id === session.file_id)
|| (session.path && tab.path === session.path)
@@ -536,6 +542,41 @@ const model = {
this.selectTab(this.activeTabId);
},
+ installDesktopDocumentSession(session) {
+ this.tabs = this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));
+ let desktopTab = this.tabs.find((tab) => this.isDesktopSession(tab));
+ if (!desktopTab) {
+ desktopTab = {
+ ...session,
+ tab_id: SYSTEM_DESKTOP_FILE_ID,
+ file_id: SYSTEM_DESKTOP_FILE_ID,
+ extension: "desktop",
+ title: "Desktop",
+ path: session.desktop?.desktop_path || "/desktop/session",
+ mode: "desktop",
+ document: {
+ file_id: SYSTEM_DESKTOP_FILE_ID,
+ path: session.desktop?.desktop_path || "/desktop/session",
+ basename: "Desktop",
+ title: "Desktop",
+ extension: "desktop",
+ preview: {},
+ },
+ dirty: false,
+ };
+ this.tabs.unshift(desktopTab);
+ }
+ const desktopTabId = desktopTab.tab_id;
+ this.session = { ...session, tab_id: session.tab_id || uniqueTabId(session) };
+ this.activeTabId = desktopTabId;
+ this.sourceMode = false;
+ this.editorText = "";
+ this.dirty = false;
+ this.resetHistory("");
+ this.queueRender({ focus: true });
+ this.updateDesktopMonitor();
+ },
+
selectTab(tabId, options = {}) {
const tab = this.tabs.find((item) => item.tab_id === tabId) || this.tabs[0] || null;
this.session = tab;
@@ -559,9 +600,39 @@ const model = {
async closeFile() {
if (!this.session) return;
+ if (this.isDesktopOfficeDocument(this.session) && !this.tabs.some((tab) => tab.tab_id === this.session.tab_id)) {
+ await this.closeDesktopDocumentSession(this.session);
+ return;
+ }
await this.closeTab(this.session.tab_id);
},
+ async closeDesktopDocumentSession(session) {
+ try {
+ await callOffice("desktop_save", {
+ desktop_session_id: session.desktop_session_id || session.session_id,
+ file_id: session.file_id || "",
+ }).catch(() => null);
+ await callOffice("close", {
+ session_id: session.store_session_id || "",
+ file_id: session.file_id || "",
+ });
+ } catch (error) {
+ console.warn("Desktop document close skipped", error);
+ }
+ this.session = null;
+ this.activeTabId = "";
+ this.editorText = "";
+ this.dirty = false;
+ const desktopTab = this.tabs.find((tab) => this.isDesktopSession(tab));
+ if (desktopTab) {
+ this.selectTab(desktopTab.tab_id, { focus: false });
+ } else {
+ await this.ensureDesktopSession({ select: true });
+ }
+ await this.refresh();
+ },
+
async closeTab(tabId) {
const tab = this.tabs.find((item) => item.tab_id === tabId);
if (!tab) return;
@@ -695,7 +766,7 @@ const model = {
if (!this.session) return;
this.session = next;
const index = this.tabs.findIndex((tab) => tab.tab_id === next.tab_id);
- if (index >= 0) this.tabs.splice(index, 1, next);
+ if (index >= 0 && this.isVisibleOfficeTab(next)) this.tabs.splice(index, 1, next);
this.queueRender();
this.updateDesktopMonitor();
},
@@ -996,12 +1067,14 @@ const model = {
return true;
},
- isMarkdown() {
- return this.session?.extension === "md";
+ isMarkdown(tab = this.session) {
+ const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
+ return ext === "md";
},
- isDocx() {
- return this.session?.extension === "docx";
+ isDocx(tab = this.session) {
+ const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
+ return ext === "docx";
},
isBinaryOffice(tab = this.session) {
@@ -1024,6 +1097,18 @@ const model = {
);
},
+ isDesktopOfficeDocument(tab = this.session) {
+ return Boolean(tab && this.hasOfficialOffice(tab) && !this.isDesktopSession(tab) && this.isBinaryOffice(tab));
+ },
+
+ isVisibleOfficeTab(tab = {}) {
+ return Boolean(this.isDesktopSession(tab) || this.isMarkdown(tab));
+ },
+
+ visibleTabs() {
+ return this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));
+ },
+
officialOfficeUrl(tab = this.session) {
return tab?.desktop?.url || "";
},
@@ -1299,6 +1384,7 @@ const model = {
this.installXpraDesktopClientPatches(remoteWindow, client);
this.installXpraDesktopCursorPatches(remoteWindow, remoteDocument, client);
this.installXpraDesktopKeyboardBridge(frame, remoteWindow, remoteDocument, client);
+ this.installXpraDesktopClipboardBridge(frame, remoteWindow, remoteDocument, client);
const container = client.container || remoteDocument?.querySelector?.("#screen");
if (!container) return false;
@@ -1568,6 +1654,111 @@ const model = {
client.__a0XpraDesktopClientPatched = true;
},
+ installXpraDesktopClipboardBridge(frame, remoteWindow, remoteDocument, client) {
+ if (!frame || !remoteWindow || !remoteDocument || !client) return;
+ this.ensureDesktopClipboardBridge();
+ if (remoteWindow.__a0XpraDesktopClipboardBridgeInstalled) return;
+
+ const onPaste = (event) => {
+ this.handleDesktopPasteEvent(event, frame, remoteWindow, client);
+ };
+ const onKeydown = (event) => {
+ if (this.isDesktopPasteShortcut(event)) {
+ void this.syncHostClipboardToDesktop(frame);
+ }
+ };
+ remoteWindow.addEventListener("paste", onPaste, true);
+ remoteDocument.addEventListener("paste", onPaste, true);
+ remoteWindow.addEventListener("keydown", onKeydown, true);
+ remoteDocument.addEventListener("keydown", onKeydown, true);
+ remoteWindow.__a0XpraDesktopClipboardBridgeInstalled = true;
+ remoteWindow.__a0XpraDesktopClipboardBridgeCleanup = () => {
+ remoteWindow.removeEventListener("paste", onPaste, true);
+ remoteDocument.removeEventListener("paste", onPaste, true);
+ remoteWindow.removeEventListener("keydown", onKeydown, true);
+ remoteDocument.removeEventListener("keydown", onKeydown, true);
+ remoteWindow.__a0XpraDesktopClipboardBridgeInstalled = false;
+ };
+ },
+
+ ensureDesktopClipboardBridge() {
+ if (this._desktopClipboardCleanup) return;
+
+ const onPaste = (event) => {
+ if (!this._desktopKeyboardActive || !this.hasOfficialOffice()) return;
+ if (isEditableInputTarget(event.target)) return;
+ const frame = this.desktopFrame();
+ const remoteWindow = frame?.contentWindow;
+ const client = remoteWindow?.client;
+ if (!frame || !remoteWindow || !client) return;
+ this.handleDesktopPasteEvent(event, frame, remoteWindow, client);
+ };
+
+ document.addEventListener("paste", onPaste, true);
+ this._desktopClipboardCleanup = () => {
+ document.removeEventListener("paste", onPaste, true);
+ this._desktopClipboardCleanup = null;
+ };
+ },
+
+ stopDesktopClipboardBridge() {
+ this._desktopClipboardCleanup?.();
+ },
+
+ handleDesktopPasteEvent(event, frame, remoteWindow, client) {
+ const text = this.desktopClipboardTextFromEvent(event);
+ if (!text) return false;
+ if (!this.syncXpraClipboardText(client, text, remoteWindow)) return false;
+ event.preventDefault?.();
+ event.stopImmediatePropagation?.();
+ event.stopPropagation?.();
+ this.focusDesktopFrame(frame, { arm: true });
+ return true;
+ },
+
+ desktopClipboardTextFromEvent(event) {
+ const data = (event?.originalEvent || event)?.clipboardData;
+ if (!data?.getData) return "";
+ for (const type of ["text/plain", "text", "Text", "STRING", "UTF8_STRING"]) {
+ const value = data.getData(type);
+ if (value) return value;
+ }
+ return "";
+ },
+
+ syncXpraClipboardText(client, text, remoteWindow = null) {
+ const value = String(text ?? "");
+ if (!client || !value || typeof client.send_clipboard_token !== "function") return false;
+ const textPlain = remoteWindow?.TEXT_PLAIN || "text/plain";
+ const utf8String = remoteWindow?.UTF8_STRING || "UTF8_STRING";
+ const utilities = remoteWindow?.Utilities;
+ const payload = utilities?.StringToUint8 ? utilities.StringToUint8(value) : value;
+ client.clipboard_enabled = true;
+ client.clipboard_direction = "both";
+ client.clipboard_buffer = value;
+ client.clipboard_pending = false;
+ client.send_clipboard_token(payload, [textPlain, utf8String, "TEXT", "STRING"]);
+ return true;
+ },
+
+ async syncHostClipboardToDesktop(frame = null) {
+ const target = this.desktopFrame(frame);
+ const remoteWindow = target?.contentWindow;
+ const client = remoteWindow?.client;
+ if (!client || !navigator.clipboard?.readText) return false;
+ try {
+ const text = await navigator.clipboard.readText();
+ return this.syncXpraClipboardText(client, text, remoteWindow);
+ } catch {
+ return false;
+ }
+ },
+
+ isDesktopPasteShortcut(event) {
+ const key = String(event?.key || "").toLowerCase();
+ return key === "v" && (event?.ctrlKey || event?.metaKey) && !event?.altKey;
+ },
+
installXpraDesktopKeyboardBridge(frame, remoteWindow, remoteDocument, client) {
if (!frame || !remoteWindow || !remoteDocument || !client) return;
this.ensureDesktopKeyboardBridge();
@@ -1607,6 +1798,9 @@ const model = {
const client = frame.contentWindow?.client;
const handler = pressed ? client?._keyb_onkeydown : client?._keyb_onkeyup;
if (!client?.capture_keyboard || typeof handler !== "function") return;
+ if (pressed && this.isDesktopPasteShortcut(event)) {
+ void this.syncHostClipboardToDesktop(frame);
+ }
const allowDefault = handler.call(client, event);
if (!allowDefault) {
@@ -1755,14 +1949,18 @@ const model = {
async handleOfficialOfficeClosed(tabId) {
const tab = this.tabs.find((item) => item.tab_id === tabId);
- if (!tab || tab._desktopClosed) return;
- tab._desktopClosed = true;
+ const hiddenDesktopDocument = !tab && this.session?.tab_id === tabId && this.isDesktopOfficeDocument(this.session)
+ ? this.session
+ : null;
+ const target = tab || hiddenDesktopDocument;
+ if (!target || target._desktopClosed) return;
+ target._desktopClosed = true;
this.stopDesktopMonitor();
this.stopDesktopResizeObserver();
this.stopXpraDesktopPrime();
this.setMessage("Desktop is restarting");
- await this.ensureDesktopSession({ force: true, select: this.activeTabId === tabId });
- tab._desktopClosed = false;
+ await this.ensureDesktopSession({ force: true, select: this.activeTabId === tabId || Boolean(hiddenDesktopDocument) });
+ target._desktopClosed = false;
await this.refresh();
},
@@ -1921,7 +2119,7 @@ const model = {
},
openCards() {
- return this.tabs
+ return this.visibleTabs()
.filter((tab) => !this.isDesktopSession(tab))
.map((tab) => normalizeDocument({
...tab.document,
diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.py
index 7fe9378f5..b142945fe 100644
--- a/tests/test_office_canvas_setup.py
+++ b/tests/test_office_canvas_setup.py
@@ -112,7 +112,7 @@ def test_desktop_xpra_canvas_scroll_is_forwarded_to_the_remote_session():
assert "getModifierState: { value: getModifierState }" in store
-def test_office_dashboard_uses_cards_and_visible_tabs_for_open_files():
+def test_office_dashboard_uses_cards_and_filters_tabs_to_desktop_and_markdown():
panel = (PROJECT_ROOT / "plugins" / "_office" / "webui" / "office-panel.html").read_text(
encoding="utf-8",
)
@@ -122,11 +122,16 @@ def test_office_dashboard_uses_cards_and_visible_tabs_for_open_files():
assert "office-card-grid" in panel
assert "office-document-card" in panel
+ assert "visibleTabs()" in panel
assert "openCards()" in panel
assert "recentCards()" in panel
assert "office-editor-head" not in panel
assert "office-recent-row" not in panel
assert "open_documents" in store
+ assert "installDesktopDocumentSession" in store
+ assert "isDesktopOfficeDocument" in store
+ assert "isVisibleOfficeTab" in store
+ assert "return this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));" in store
def test_right_canvas_surface_is_branded_as_desktop():
diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.py
index 7aea3a49a..dd10b8bad 100644
--- a/tests/test_office_document_store.py
+++ b/tests/test_office_document_store.py
@@ -430,11 +430,17 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,
assert payload["extension"] == "xlsx"
assert payload["url"].startswith("/desktop/session/")
registry = tmp_path / "desktop" / "profiles" / payload["session_id"] / "user" / "registrymodifications.xcu"
- assert "ooSetupInstCompleted" in registry.read_text(encoding="utf-8")
- assert "FirstRun" in registry.read_text(encoding="utf-8")
+ registry_text = registry.read_text(encoding="utf-8")
+ assert "ooSetupInstCompleted" in registry_text
+ assert "FirstRun" in registry_text
+ assert "Office.Paths/Variables" in registry_text
+ assert "Office.Paths:NamedPath['Work']" in registry_text
+ assert office_state.workdir.as_uri() in registry_text
writer_launcher = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "LibreOffice Writer.desktop"
- assert "--writer" in writer_launcher.read_text(encoding="utf-8")
- assert "X-XFCE-Trusted=true" in writer_launcher.read_text(encoding="utf-8")
+ writer_text = writer_launcher.read_text(encoding="utf-8")
+ assert "--writer" in writer_text
+ assert f"Path={office_state.workdir}" in writer_text
+ assert "X-XFCE-Trusted=true" in writer_text
terminal_launcher = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "Terminal.desktop"
files_launcher = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "Files.desktop"
settings_launcher = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "Settings.desktop"
@@ -446,13 +452,16 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,
assert not (tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "Browser.desktop").exists()
assert "xfce4-settings-manager" in settings_text
assert "org.xfce.settings.manager" in settings_text
- for link_name, target in {
- "Workdir": "usr/workdir",
+ link_targets = {
"Projects": "usr/projects",
"Skills": "usr/skills",
"Agents": "usr/agents",
"Downloads": "usr/downloads",
- }.items():
+ }
+ workdir_link = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / "Workdir"
+ assert workdir_link.is_symlink()
+ assert workdir_link.resolve() == office_state.workdir
+ for link_name, target in link_targets.items():
link = tmp_path / "desktop" / "profiles" / payload["session_id"] / "Desktop" / link_name
assert link.is_symlink()
assert str(link.resolve()).endswith(target)
@@ -478,7 +487,21 @@ def test_official_libreoffice_desktop_manager_opens_binary_session(office_state,
/ "xfce-perchannel-xml"
/ "xfce4-desktop.xml"
)
- assert "desktop-icons" in desktop_profile.read_text(encoding="utf-8")
+ desktop_profile_text = desktop_profile.read_text(encoding="utf-8")
+ assert "desktop-icons" in desktop_profile_text
+ assert "image-path" in desktop_profile_text
+ assert "usr/downloads" in desktop_profile_text
+ user_dirs = (
+ tmp_path
+ / "desktop"
+ / "profiles"
+ / payload["session_id"]
+ / ".config"
+ / "user-dirs.dirs"
+ ).read_text(encoding="utf-8")
+ assert 'XDG_PICTURES_DIR="' in user_dirs
+ assert "usr/downloads" in user_dirs
+ assert f'XDG_DOCUMENTS_DIR="{office_state.workdir}"' in user_dirs
panel_profile = (
tmp_path
/ "desktop"