Agent Zero AI framework
Add Office document rename action
Alessandro27b3624a9728
diff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.pyindex 1092912bb..8d812bae0 100644--- a/plugins/_office/api/office_session.py+++ b/plugins/_office/api/office_session.py@@ -51,6 +51,8 @@ class OfficeSession(ApiHandler):return await self._open_document(doc, input, request)if action == "save":return self._save(input)+ if action == "renamed":+ return self._renamed(input, context_id)if action == "desktop_save":return self._desktop_save(input)if action == "desktop_sync":@@ -108,6 +110,27 @@ class OfficeSession(ApiHandler):return {"ok": False, "error": "session_id is required."}return markdown_sessions.get_manager().save(session_id, text=input.get("text"))+ def _renamed(self, input: dict, context_id: str = "") -> dict:+ file_id = str(input.get("file_id") or "").strip()+ path = str(input.get("path") or "").strip()+ if not file_id:+ return {"ok": False, "error": "file_id is required."}+ if not path:+ return {"ok": False, "error": "path is required."}+ try:+ updated = document_store.update_document_path(file_id, path, context_id=context_id)+ except Exception as exc:+ return {"ok": False, "error": str(exc)}+ desktop = None+ if str(updated.get("extension") or "").lower() in libreoffice_desktop.OFFICIAL_EXTENSIONS:+ desktop = libreoffice_desktop.get_manager().retarget_document(file_id, updated)+ return {+ "ok": True,+ "document": _public_doc(updated),+ "version": document_store.item_version(updated),+ "desktop": desktop,+ }+def _desktop(self) -> dict:desktop = libreoffice_desktop.get_manager().ensure_system_desktop()if not desktop.get("available"):diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.pyindex 994361e2d..303714290 100644--- a/plugins/_office/helpers/document_store.py+++ b/plugins/_office/helpers/document_store.py@@ -268,6 +268,41 @@ def get_document(file_id: str, conn: sqlite3.Connection | None = None) -> dict[sreturn _fetch(active)+def update_document_path(file_id: str, path: str | Path, context_id: str = "") -> dict[str, Any]:+ resolved = normalize_path(path, context_id=context_id)+ 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()+ changed_at = now()++ with connect() as conn:+ doc = get_document(file_id, conn=conn)+ row = conn.execute("SELECT file_id FROM documents WHERE path = ?", (str(resolved),)).fetchone()+ if row and row["file_id"] != file_id:+ raise ValueError(f"Document path is already registered: {display_path(resolved)}")+ conn.execute(+ """+ UPDATE documents+ SET path=?, basename=?, extension=?, size=?, sha256=?, last_modified=?, updated_at=?+ WHERE file_id=?+ """,+ (str(resolved), resolved.name, ext, stat.st_size, digest, now_iso(), changed_at, file_id),+ )+ conn.execute(+ "INSERT INTO events (file_id, event_type, payload, created_at) VALUES (?, ?, ?, ?)",+ (+ file_id,+ "renamed",+ json.dumps({"from": display_path(doc["path"]), "to": display_path(resolved)}),+ changed_at,+ ),+ )+ return get_document(file_id, conn=conn)++def get_open_documents(limit: int = 6) -> list[dict[str, Any]]:with connect() as conn:_clear_expired_sessions(conn)diff --git a/plugins/_office/helpers/libreoffice_desktop.py b/plugins/_office/helpers/libreoffice_desktop.pyindex de31d6c62..dc591c0a9 100644--- a/plugins/_office/helpers/libreoffice_desktop.py+++ b/plugins/_office/helpers/libreoffice_desktop.py@@ -185,6 +185,17 @@ class LibreOfficeDesktopManager:updated = document_store.register_document(doc["path"])return {"ok": True, "session_id": session.session_id, "document": _public_doc(updated)}+ 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:+ return {"ok": True, "updated": False}+ with self._lock:+ session.path = str(doc["path"])+ session.title = str(doc["basename"])+ session.extension = str(doc["extension"])+ self._write_manifest(session)+ return {"ok": True, "updated": True, "desktop": session.public(doc)}+def close(self, session_id: str, save_first: bool = True) -> dict[str, Any]:with self._lock:normalized = str(session_id or "").strip()diff --git a/plugins/_office/webui/office-panel.html b/plugins/_office/webui/office-panel.htmlindex 90d51b63f..9c9b3dd2c 100644--- a/plugins/_office/webui/office-panel.html+++ b/plugins/_office/webui/office-panel.html@@ -38,6 +38,9 @@<span class="office-toolbar-spacer"></span><div class="office-tool-group office-tool-actions" x-show="$store.office.session && !$store.office.isDesktopSession()" style="display: none;">+ <button type="button" class="office-icon-button" title="Rename" aria-label="Rename" :disabled="$store.office.saving" @click="$store.office.renameActiveFile()">+ <span class="material-symbols-outlined">edit</span>+ </button><button type="button" class="office-icon-button" title="Save" aria-label="Save" :class="{ 'is-primary': $store.office.dirty }" :disabled="$store.office.saving" @click="$store.office.save()"><span class="material-symbols-outlined" :class="{ spinning: $store.office.saving }" x-text="$store.office.saving ? 'progress_activity' : 'save'"></span></button>diff --git a/plugins/_office/webui/office-store.js b/plugins/_office/webui/office-store.jsindex 7c2408635..2fcee590e 100644--- a/plugins/_office/webui/office-store.js+++ b/plugins/_office/webui/office-store.js@@ -34,6 +34,13 @@ function extensionOf(path = "") {return index >= 0 ? name.slice(index + 1) : "";}+function parentPath(path = "") {+ const normalized = String(path || "").split("?")[0].split("#")[0].replace(/\/+$/, "");+ const index = normalized.lastIndexOf("/");+ if (index <= 0) return "/";+ return normalized.slice(0, index);+}+function uniqueTabId(session = {}) {return String(session.file_id || session.session_id || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`);}@@ -508,10 +515,76 @@ const model = {}},+ async renameActiveFile() {+ if (!this.session || this.isDesktopSession() || this.saving) return;+ if (this.dirty || this.session.dirty) {+ await this.save();+ if (this.error) return;+ }++ const session = this.session;+ const path = session.path || session.document?.path || "";+ if (!path) {+ this.error = "This document does not have a file path to rename.";+ return;+ }+ const name = basename(path || session.title || "");+ const extension = extensionOf(name);+ await fileBrowserStore.openRenameModal(+ {+ name,+ path,+ is_dir: false,+ size: session.document?.size || 0,+ modified: session.document?.last_modified || "",+ type: "document",+ },+ {+ currentPath: parentPath(path),+ validateName: (newName) => {+ if (!extension) return true;+ return extensionOf(newName) === extension || `Keep the .${extension} extension for this open document.`;+ },+ onRenamed: async ({ path: renamedPath }) => {+ await this.handleActiveFileRenamed(session, renamedPath);+ },+ },+ );+ },++ async handleActiveFileRenamed(session, renamedPath) {+ const response = await callOffice("renamed", {+ file_id: session.file_id || "",+ path: renamedPath,+ });+ if (response?.ok === false) throw new Error(response.error || "Rename failed.");++ const document = normalizeDocument(response.document || session.document || {});+ const updated = {+ ...session,+ document,+ title: document.title || document.basename || basename(document.path),+ path: document.path || renamedPath,+ extension: document.extension || session.extension,+ file_id: document.file_id || session.file_id,+ version: document.version || response.version || session.version,+ desktop: response.desktop?.desktop || session.desktop,+ dirty: false,+ };+ this.replaceSession(session, updated);+ this.dirty = false;+ this.setMessage("Renamed");+ await this.refresh();+ },+replaceActiveSession(next) {if (!this.session) return;+ this.replaceSession(this.session, next);+ },++ replaceSession(previous, next) {this.session = next;- const index = this.tabs.findIndex((tab) => tab.tab_id === next.tab_id);+ const index = this.tabs.findIndex((tab) => tab.tab_id === (previous?.tab_id || next.tab_id));if (index >= 0 && this.isVisibleOfficeTab(next)) this.tabs.splice(index, 1, next);this.queueRender();this.updateDesktopMonitor();diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.pyindex e0ebcd4d9..71c80d935 100644--- a/tests/test_office_canvas_setup.py+++ b/tests/test_office_canvas_setup.py@@ -34,8 +34,13 @@ def test_document_canvas_uses_markdown_editor_and_official_libreoffice_desktop_fassert "format_align_center" not in panelassert "is-native-tile" not in panelassert "hasOfficialOffice()" in panel+ assert 'title="Rename"' in panel+ assert "@click=\"$store.office.renameActiveFile()\"" in panelassert "office_save" in storeassert "desktop_save" in store+ assert "openRenameModal" in store+ assert 'callOffice("renamed"' in store+ assert "handleActiveFileRenamed" in storeassert "--office-zoom" not in panelassert "zoom: 1" not in storeassert 'callOffice("desktop")' in store@@ -137,6 +142,15 @@ def test_office_surface_filters_tabs_to_desktop_and_markdown_without_dashboard()assert "isVisibleOfficeTab" in storeassert "return this.tabs.filter((tab) => this.isVisibleOfficeTab(tab));" in store+ file_browser_store = (+ PROJECT_ROOT / "webui" / "components" / "modals" / "file-browser" / "file-browser-store.js"+ ).read_text(encoding="utf-8")++ assert "renameAfterConfirm" in file_browser_store+ assert "renameValidateName" in file_browser_store+ assert "options.onRenamed" in file_browser_store+ assert "options.validateName" in file_browser_store+def test_right_canvas_surface_is_branded_as_desktop():surface = (diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex b93a9aa99..4c13d8157 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -263,6 +263,20 @@ def test_markdown_save_tracks_version_history(office_state):assert Path(updated["path"]).read_text(encoding="utf-8").endswith("Second\n")+def test_document_path_update_preserves_file_id_after_rename(office_state):+ doc = document_store.create_document("document", "Rename Me", "md", "Body")+ original = Path(doc["path"])+ renamed = original.with_name("Renamed.md")+ original.rename(renamed)++ updated = document_store.update_document_path(doc["file_id"], renamed)++ assert updated["file_id"] == doc["file_id"]+ assert updated["basename"] == "Renamed.md"+ assert updated["path"] == str(renamed)+ assert document_store.get_document(doc["file_id"])["path"] == str(renamed)++def test_direct_markdown_edits_refresh_open_canvas_session(office_state, monkeypatch):manager = markdown_sessions.MarkdownSessionManager()monkeypatch.setattr(markdown_sessions, "_manager", manager, raising=False)diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex 6acb2706a..32008d005 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -23,6 +23,8 @@ const model = {renameMode: "rename",isRenaming: false,renameError: null,+ renameAfterConfirm: null,+ renameValidateName: null,openDropdownPath: null, // Track which dropdown is currently open// --- Lifecycle -----------------------------------------------------------@@ -148,12 +150,26 @@ const model = {return `${trimmedBase}/${name}`;},+ parentPath(path) {+ const normalized = this.normalizePath(String(path || "")).replace(/\/+$/, "");+ const index = normalized.lastIndexOf("/");+ if (index <= 0) return "/";+ return normalized.slice(0, index);+ },++ siblingPath(path, name) {+ const parent = this.parentPath(path);+ return parent === "/" ? `/${name}` : `${parent}/${name}`;+ },+resetRenameState() {this.renameTarget = null;this.renameName = "";this.renameMode = "rename";this.isRenaming = false;this.renameError = null;+ this.renameAfterConfirm = null;+ this.renameValidateName = null;},// --- Sorting -------------------------------------------------------------@@ -258,12 +274,20 @@ const model = {},// --- Rename / Create ------------------------------------------------------ async openRenameModal(file) {+ async openRenameModal(file, options = {}) {this.resetRenameState();this.renameTarget = file;this.renameName = file?.name || "";this.renameMode = "rename";this.renameError = null;+ this.renameAfterConfirm = typeof options.onRenamed === "function" ? options.onRenamed : null;+ this.renameValidateName = typeof options.validateName === "function" ? options.validateName : null;+ if (typeof options.currentPath === "string" && options.currentPath) {+ this.browser.currentPath = options.currentPath;+ }+ if (Array.isArray(options.entries)) {+ this.browser.entries = options.entries;+ }window.openModal("modals/file-browser/rename-modal.html");},@@ -299,6 +323,13 @@ const model = {this.renameError = "No item selected for rename.";return;}+ if (this.renameValidateName) {+ const validation = this.renameValidateName(newName, this.renameTarget);+ if (validation !== true) {+ this.renameError = typeof validation === "string" ? validation : "Name is not valid.";+ return;+ }+ }// UX: pre-validate duplicates so we can show a clean inline error (no toast spam)const duplicate = (this.browser.entries || []).some((entry) => {@@ -317,6 +348,11 @@ const model = {this.renameError = null;try {+ const previousPath = this.renameTarget?.path || "";+ const renamedPath =+ this.renameMode === "create-folder"+ ? this.buildChildPath(newName)+ : this.siblingPath(previousPath, newName);const payload =this.renameMode === "create-folder"? {@@ -344,6 +380,16 @@ const model = {}await this.fetchFiles(this.browser.currentPath);+ if (this.renameAfterConfirm) {+ await this.renameAfterConfirm({+ action: this.renameMode,+ previousPath,+ path: renamedPath,+ name: newName,+ target: this.renameTarget,+ response: data,+ });+ }this.closeRenameModal();} catch (error) {const message = error?.message || "Rename failed";