Skip to content

Agent Zero AI framework

Keep LibreOffice saves on the renamed document

Alessandro6dd3ef4ee354
diff --git a/plugins/_desktop/AGENTS.md b/plugins/_desktop/AGENTS.md
index 7a1db2d6c..ae6e3b7bd 100644
--- a/plugins/_desktop/AGENTS.md
+++ b/plugins/_desktop/AGENTS.md
@@ -19,6 +19,7 @@
- Keep the Xpra server, client modules, and GTK introspection runtime present as one compatible stack; Xpra shadow sessions import all three even when users connect only through HTML5.
- Route APT commands through `system_packages.run_runtime_apt` so existing Kali containers repair from the build's snapshot. Preserve the installed Xpra component version. If GTK needs a missing ATK typelib, align ATK's version-locked libraries and any installed optional components with the build's pinned snapshot version; do not fetch dependencies from rolling.
- Keep desktop state injected into prompts accurate and bounded.
+- Rename open LibreOffice documents through native Save As so unsaved edits and subsequent WebUI/native saves follow the new path. `helpers/rename_office_document.py` runs with system Python/UNO, connects to the existing profile through a local named pipe, and matches the full document URL; never select a document by basename alone. Retain the document's format/filter and encryption properties, and disallow target overwrite. Closed documents retain filesystem rename behavior.
- Do not expose desktop routes without the expected auth protections.
- Keep Desktop host visibility tied to an attached modal or canvas host; modal cleanup may preserve the iframe in keepalive, but must not leave stale modal mode behind.
- Keep LibreOffice Writer as the default handler for Markdown and plain text files; keep Agent Zero Editor available as a secondary Open With target through the desktop intent bridge.
diff --git a/plugins/_desktop/helpers/desktop_session.py b/plugins/_desktop/helpers/desktop_session.py
index bf66a8228..7a2f81b56 100644
--- a/plugins/_desktop/helpers/desktop_session.py
+++ b/plugins/_desktop/helpers/desktop_session.py
@@ -377,6 +377,34 @@ class DesktopSessionManager:
"save": save_result,
}
+ def rename_open_document(self, source: Path, target: Path) -> bool:
+ with self._lock:
+ session = self.get(SYSTEM_SESSION_ID)
+ if not session:
+ session = self._load_system_desktop_from_manifest_locked()
+ if session:
+ self._sessions[session.session_id] = session
+ self._register_virtual_desktop(session)
+ if not session or not self._office_window_id_locked(session, title=source.name, fallback=False):
+ return False
+ result = subprocess.run(
+ [
+ "/usr/bin/python3",
+ str(Path(__file__).with_name("rename_office_document.py")),
+ libreoffice.find_soffice(),
+ str(session.profile_dir),
+ str(source),
+ str(target),
+ ],
+ env=self._display_env(session),
+ capture_output=True,
+ text=True,
+ timeout=30,
+ )
+ if result.returncode:
+ raise RuntimeError(result.stderr.strip() or "LibreOffice could not rename the open document.")
+ return json.loads(result.stdout)["renamed"]
+
def retarget_document(self, file_id: str, doc: dict[str, Any]) -> dict[str, Any]:
session = self._find_by_file_id(file_id)
if not session:
diff --git a/plugins/_desktop/helpers/rename_office_document.py b/plugins/_desktop/helpers/rename_office_document.py
new file mode 100644
index 000000000..e62ec3c5a
--- /dev/null
+++ b/plugins/_desktop/helpers/rename_office_document.py
@@ -0,0 +1,59 @@
+"""Run with the system Python that owns python3-uno, outside the framework venv."""
+from __future__ import annotations
+
+import hashlib
+import json
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+
+def rename_document(soffice: str, profile: Path, source: Path, target: Path) -> bool:
+ import uno
+
+ # Forward an acceptor to the existing profile; never expose a TCP listener.
+ pipe = "a0-rename-" + hashlib.sha256(str(profile.resolve()).encode()).hexdigest()[:16]
+ process = subprocess.Popen(
+ [soffice, f"-env:UserInstallation={profile.resolve().as_uri()}",
+ f"--accept=pipe,name={pipe};urp;StarOffice.ComponentContext", "--norestore", "--nodefault"],
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ )
+ try:
+ context = uno.getComponentContext()
+ resolver = context.ServiceManager.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", context)
+ for attempt in range(50):
+ try:
+ context = resolver.resolve(f"uno:pipe,name={pipe};urp;StarOffice.ComponentContext")
+ break
+ except uno.getClass("com.sun.star.connection.NoConnectException"):
+ if attempt == 49:
+ raise RuntimeError("Could not connect to the open LibreOffice document.") from None
+ time.sleep(0.1)
+ desktop = context.ServiceManager.createInstanceWithContext("com.sun.star.frame.Desktop", context)
+ components = desktop.getComponents().createEnumeration()
+ while components.hasMoreElements():
+ document = components.nextElement()
+ if not hasattr(document, "getURL") or document.getURL() != source.resolve().as_uri():
+ continue
+ overwrite = uno.createUnoStruct("com.sun.star.beans.PropertyValue")
+ overwrite.Name, overwrite.Value = "Overwrite", False
+ properties = tuple(prop for prop in document.getArgs() if prop.Name in {
+ "FilterName", "FilterOptions", "FilterData", "EncryptionData", "Password",
+ })
+ document.storeAsURL(target.resolve().as_uri(), (*properties, overwrite))
+ return True
+ return False
+ finally:
+ # The forwarded command normally exits immediately; do not leave a launcher behind.
+ if process.poll() is None:
+ process.terminate()
+ process.wait(timeout=5)
+
+
+if __name__ == "__main__":
+ try:
+ print(json.dumps({"renamed": rename_document(sys.argv[1], *(Path(arg) for arg in sys.argv[2:]))}))
+ except Exception as error:
+ print(str(error), file=sys.stderr)
+ sys.exit(1)
diff --git a/plugins/_office/AGENTS.md b/plugins/_office/AGENTS.md
index e55db1e34..9ba457142 100644
--- a/plugins/_office/AGENTS.md
+++ b/plugins/_office/AGENTS.md
@@ -14,6 +14,7 @@
## Local Contracts
- Preserve document storage integrity and live session synchronization.
+- `rename_document` validates scope, extension, and destination before calling an optional native-document rename handler. Preserve source mode/ownership, retain the source on native failure, and update stored paths and version history after a successful native save. Office routes supply the Desktop handler; Editor text renames keep their existing atomic-write path.
- Atomic writes preserve the existing file mode and owner/group; Rename and Save As inherit them from the source. Temporary files and new files from atomic writes start private (0600). Metadata failures must leave the original untouched.
- Version backups use private files (0600) inside a process-owned private directory (0700); `ensure_dirs` also restricts existing backup directories.
- Keep LibreOffice operations bounded to intended workspaces and artifact paths.
diff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.py
index 49225b6d7..768cebb96 100644
--- a/plugins/_office/api/office_session.py
+++ b/plugins/_office/api/office_session.py
@@ -131,6 +131,7 @@ class OfficeSession(ApiHandler):
path,
content=input.get("text") if "text" in input else None,
context_id=context_id,
+ rename_open_document=desktop_session.get_manager().rename_open_document,
)
except Exception as exc:
return {"ok": False, "error": str(exc)}
diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.py
index fe6e867d8..d6ff4718a 100644
--- a/plugins/_office/helpers/document_store.py
+++ b/plugins/_office/helpers/document_store.py
@@ -13,7 +13,7 @@ import uuid
import zipfile
from contextlib import contextmanager
from pathlib import Path
-from typing import Any
+from typing import Any, Callable
from xml.sax.saxutils import escape
from helpers import files
@@ -342,6 +342,7 @@ def rename_document(
content: str | None = None,
context_id: str = "",
file_browser: bool = False,
+ rename_open_document: Callable[[Path, Path], bool] | None = None,
) -> dict[str, Any]:
resolved = normalize_path(path, context_id=context_id, file_browser=file_browser)
ext = resolved.suffix.lstrip(".").lower()
@@ -375,8 +376,21 @@ def rename_document(
if changed_path and data is None:
resolved.parent.mkdir(parents=True, exist_ok=True)
- source.rename(resolved)
+ renamed_open = rename_open_document and rename_open_document(source, resolved)
+ if renamed_open:
+ metadata = source.stat()
+ current = resolved.stat()
+ if (current.st_uid, current.st_gid) != (metadata.st_uid, metadata.st_gid):
+ os.chown(resolved, metadata.st_uid, metadata.st_gid)
+ os.chmod(resolved, stat.S_IMODE(metadata.st_mode))
+ else:
+ source.rename(resolved)
final_data = resolved.read_bytes()
+ content_changed = final_data != previous
+ if content_changed:
+ _record_version(conn, file_id, source_resolved, item_version(doc), previous)
+ if renamed_open:
+ source.unlink()
elif data is not None:
if content_changed:
_record_version(conn, file_id, source_resolved, item_version(doc), previous)
@@ -387,7 +401,7 @@ def rename_document(
else:
final_data = previous
- stat = resolved.stat()
+ file_stat = resolved.stat()
next_version = int(doc["version"]) + 1 if content_changed else int(doc["version"])
conn.execute(
"""
@@ -399,7 +413,7 @@ def rename_document(
str(resolved),
resolved.name,
ext,
- stat.st_size,
+ file_stat.st_size,
next_version,
sha256_bytes(final_data),
now_iso(),
diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.py
index 0cbbab123..99223f841 100644
--- a/tests/test_office_document_store.py
+++ b/tests/test_office_document_store.py
@@ -544,6 +544,102 @@ def test_document_rename_saves_dirty_markdown_and_removes_original(office_state)
assert renamed.read_text(encoding="utf-8") == "# Clean Rename\n\nFresh text"
+def test_native_office_rename_preserves_unsaved_content_and_metadata(office_state):
+ import stat
+
+ doc = document_store.create_document("document", "Native Rename", "odt", "Saved text")
+ source = Path(doc["path"])
+ source.chmod(0o640)
+ original = source.read_bytes()
+ metadata = source.stat()
+ target = source.with_name("Renamed.odt")
+ dirty = document_store.odt_bytes("Native Rename", "Unsaved Writer text")
+
+ def native_rename(old, new):
+ assert old == source and new == target
+ assert old.read_bytes() == original and not new.exists()
+ new.write_bytes(dirty)
+ return True
+
+ updated = document_store.rename_document(doc["file_id"], target, rename_open_document=native_rename)
+
+ assert not source.exists()
+ assert target.read_bytes() == dirty
+ assert stat.S_IMODE(target.stat().st_mode) == 0o640
+ assert (target.stat().st_uid, target.stat().st_gid) == (metadata.st_uid, metadata.st_gid)
+ assert updated["file_id"] == doc["file_id"]
+ assert updated["version"] == doc["version"] + 1
+ assert updated["sha256"] == document_store.sha256_bytes(dirty)
+
+
+def test_native_office_rename_rejects_collisions_and_keeps_source_on_failure(office_state):
+ doc = document_store.create_document("document", "Failed Rename", "odt", "Original")
+ source = Path(doc["path"])
+ original = source.read_bytes()
+ target = source.with_name("Taken.odt")
+ target.write_bytes(b"collision sentinel")
+
+ def fail_rename(old, new):
+ raise RuntimeError("Native rename failed")
+
+ with pytest.raises(FileExistsError):
+ document_store.rename_document(doc["file_id"], target, rename_open_document=fail_rename)
+ assert target.read_bytes() == b"collision sentinel"
+ target.unlink()
+ with pytest.raises(RuntimeError, match="Native rename failed"):
+ document_store.rename_document(doc["file_id"], target, rename_open_document=fail_rename)
+ assert source.read_bytes() == original
+ assert not target.exists()
+ assert document_store.get_document(doc["file_id"])["path"] == str(source)
+
+ updated = document_store.rename_document(doc["file_id"], target, rename_open_document=lambda *_: False)
+ assert updated["path"] == str(target)
+ assert target.read_bytes() == original
+ assert not source.exists()
+
+
+def test_native_office_bridge_matches_full_url_and_disallows_overwrite(tmp_path, monkeypatch):
+ from plugins._desktop.helpers import rename_office_document
+
+ source = tmp_path / "source" / "Same name.odt"
+ target = source.with_name("Renamed.odt")
+ calls = []
+ other = types.SimpleNamespace(
+ getURL=lambda: (tmp_path / "other" / source.name).as_uri(),
+ storeAsURL=lambda *_: pytest.fail("Renamed a different document with the same basename"),
+ )
+ document = types.SimpleNamespace(
+ getURL=lambda: source.as_uri(),
+ getArgs=lambda: (types.SimpleNamespace(Name="FilterName", Value="Office Open XML Text"),
+ types.SimpleNamespace(Name="URL", Value=source.as_uri())),
+ storeAsURL=lambda url, properties: calls.append((url, [(p.Name, p.Value) for p in properties])),
+ )
+ items = [other, document]
+ enumeration = types.SimpleNamespace(hasMoreElements=lambda: bool(items), nextElement=lambda: items.pop(0))
+ desktop = types.SimpleNamespace(getComponents=lambda: types.SimpleNamespace(createEnumeration=lambda: enumeration))
+ context = types.SimpleNamespace()
+ resolver = types.SimpleNamespace(resolve=lambda url: context)
+ context.ServiceManager = types.SimpleNamespace(createInstanceWithContext=lambda name, _: resolver if name.endswith("UnoUrlResolver") else desktop)
+ monkeypatch.setitem(sys.modules, "uno", types.SimpleNamespace(
+ getComponentContext=lambda: context,
+ createUnoStruct=lambda _: types.SimpleNamespace(),
+ ))
+ commands = []
+
+ def launch(command, **kwargs):
+ commands.append(command)
+ return types.SimpleNamespace(poll=lambda: 0, wait=lambda timeout: 0)
+
+ monkeypatch.setattr(rename_office_document.subprocess, "Popen", launch)
+ assert rename_office_document.rename_document("soffice", tmp_path / "profile", source, target)
+ assert calls == [(target.as_uri(), [("FilterName", "Office Open XML Text"), ("Overwrite", False)])]
+ assert any(arg.startswith("--accept=pipe,name=") for arg in commands[0])
+
+ items[:] = [other]
+ assert not rename_office_document.rename_document("soffice", tmp_path / "profile", source, target)
+ assert len(calls) == 1
+
+
def test_text_session_save_as_creates_new_file_without_mutating_original(office_state):
manager = editor_markdown_sessions.MarkdownSessionManager()
doc = document_store.create_document("document", "Original Note", "md", "# Original Note\n")