Agent Zero AI framework
Improve Editor text file workflows
Alessandrobd584da2f4b8
diff --git a/plugins/_desktop/AGENTS.md b/plugins/_desktop/AGENTS.mdindex 2f2b300fd..e7bdef438 100644--- a/plugins/_desktop/AGENTS.md+++ b/plugins/_desktop/AGENTS.md@@ -16,6 +16,7 @@- Preserve session startup, cleanup, and route protection for desktop access.- Keep desktop state injected into prompts accurate and bounded.- Do not expose desktop routes without the expected auth protections.+- Keep Markdown and plain text file open-with handling routed to the Editor surface through the desktop intent bridge; Desktop owns the Xfce launcher/MIME setup, while Editor owns `.md` and `.txt` editing.## Work Guidancediff --git a/plugins/_desktop/api/desktop_session.py b/plugins/_desktop/api/desktop_session.pyindex e0eead095..7b1120311 100644--- a/plugins/_desktop/api/desktop_session.py+++ b/plugins/_desktop/api/desktop_session.py@@ -74,10 +74,10 @@ class DesktopSession(ApiHandler):return {"ok": False, "error": str(exc)}ext = str(doc.get("extension") or "").lower()- if ext == "md":+ if ext in document_store.EDITOR_TEXT_EXTENSIONS:return {"ok": False,- "error": "Markdown documents use the Editor surface.",+ "error": "Text documents use the Editor surface.","requires_editor": True,"document": _public_doc(doc),}diff --git a/plugins/_desktop/helpers/desktop_session.py b/plugins/_desktop/helpers/desktop_session.pyindex 0545a5684..efacb2c41 100644--- a/plugins/_desktop/helpers/desktop_session.py+++ b/plugins/_desktop/helpers/desktop_session.py@@ -23,7 +23,7 @@ from plugins._desktop.helpers import desktop_statefrom plugins._office.helpers import document_store, libreoffice-OFFICIAL_EXTENSIONS = {"odt", "ods", "odp", "docx", "xlsx", "pptx", "txt"}+OFFICIAL_EXTENSIONS = {"odt", "ods", "odp", "docx", "xlsx", "pptx"}PLUGIN_NAME = "_desktop"SYSTEM_SESSION_ID = "agent-zero-desktop"SYSTEM_FILE_ID = "system-desktop"@@ -78,6 +78,7 @@ DESKTOP_FOLDER_LINKS = (URL_INTENT_MAX_ITEMS = 50URL_INTENT_MAX_LENGTH = 8192URL_HANDLER_DESKTOP_ID = "agent-zero-browser.desktop"+EDITOR_HANDLER_DESKTOP_ID = "agent-zero-editor.desktop"SHUTDOWN_HANDLER_DESKTOP_ID = "agent-zero-shutdown.desktop"SHUTDOWN_PANEL_LAUNCHER_ID = SHUTDOWN_HANDLER_DESKTOP_IDSHUTDOWN_CONFIRM_SECONDS = 8@@ -1135,6 +1136,7 @@ class DesktopSessionManager:applications_dir.mkdir(parents=True, exist_ok=True)browser_bridge = _write_url_bridge_script(session)+ editor_bridge = _write_editor_bridge_script(session)shutdown_bridge = _write_shutdown_bridge_script(session)helpers_rc = config_dir / "xfce4" / "helpers.rc"helpers_rc.parent.mkdir(parents=True, exist_ok=True)@@ -1153,8 +1155,12 @@ class DesktopSessionManager:config_dir / "xfce4" / "helpers" / "agent-zero-browser.desktop",browser_bridge,)- _write_mimeapps_defaults(config_dir / "mimeapps.list", URL_HANDLER_DESKTOP_ID)- _write_mimeapps_defaults(data_dir / "applications" / "mimeapps.list", URL_HANDLER_DESKTOP_ID)+ _write_mimeapps_defaults(config_dir / "mimeapps.list", URL_HANDLER_DESKTOP_ID, EDITOR_HANDLER_DESKTOP_ID)+ _write_mimeapps_defaults(+ data_dir / "applications" / "mimeapps.list",+ URL_HANDLER_DESKTOP_ID,+ EDITOR_HANDLER_DESKTOP_ID,+ )_write_desktop_launcher(applications_dir / URL_HANDLER_DESKTOP_ID,name="Agent Zero Browser",@@ -1165,6 +1171,15 @@ class DesktopSessionManager:mime_types=_url_handler_mime_types(),no_display=True,)+ _write_desktop_launcher(+ applications_dir / EDITOR_HANDLER_DESKTOP_ID,+ name="Agent Zero Editor",+ exec_line=_desktop_exec(editor_bridge, "%F"),+ icon="accessories-text-editor",+ categories="Utility;TextEditor;",+ try_exec=str(editor_bridge),+ mime_types=_editor_text_handler_mime_types(),+ )_write_desktop_launcher(applications_dir / SHUTDOWN_HANDLER_DESKTOP_ID,name="Shutdown Desktop",@@ -1190,6 +1205,14 @@ class DesktopSessionManager:categories="Network;WebBrowser;",try_exec=str(browser_bridge),)+ _write_desktop_launcher(+ desktop_dir / "Editor.desktop",+ name="Editor",+ exec_line=_desktop_exec(editor_bridge),+ icon="accessories-text-editor",+ categories="Utility;TextEditor;",+ try_exec=str(editor_bridge),+ )self._trust_desktop_launchers(session, desktop_dir)def _hide_xpra_desktop_entries(self, applications_dir: Path) -> None:@@ -1830,6 +1853,10 @@ def _url_bridge_script_path(session: DesktopSession) -> Path:return _url_bridge_dir(session) / "open-url"+def _editor_bridge_script_path(session: DesktopSession) -> Path:+ return _url_bridge_dir(session) / "open-editor"++def _url_bridge_queue_path(session: DesktopSession) -> Path:return _url_bridge_dir(session) / "browser-url-intents.jsonl"@@ -1900,6 +1927,64 @@ if __name__ == "__main__":return script+def _write_editor_bridge_script(session: DesktopSession) -> Path:+ bridge_dir = _url_bridge_dir(session)+ bridge_dir.mkdir(parents=True, exist_ok=True)+ script = _editor_bridge_script_path(session)+ queue = _url_bridge_queue_path(session)+ lock = _url_bridge_lock_path(session)+ script.write_text(+ f"""#!/usr/bin/env python3+import fcntl+import json+import os+import sys+import time+from urllib.parse import quote++QUEUE_PATH = {str(queue)!r}+LOCK_PATH = {str(lock)!r}+MAX_URL_LENGTH = {URL_INTENT_MAX_LENGTH}+++def editor_url(path):+ path = str(path or "").strip()+ if not path:+ return "a0-editor://open"+ return "a0-editor://open?path=" + quote(path[:MAX_URL_LENGTH], safe="/:")+++def main():+ urls = [editor_url(arg) for arg in sys.argv[1:] if str(arg or "").strip()]+ if not urls:+ urls = [editor_url("")]+ os.makedirs(os.path.dirname(QUEUE_PATH), exist_ok=True)+ with open(LOCK_PATH, "a+", encoding="utf-8") as lock_file:+ fcntl.flock(lock_file, fcntl.LOCK_EX)+ with open(QUEUE_PATH, "a", encoding="utf-8") as queue_file:+ for url in urls:+ queue_file.write(json.dumps({{+ "url": url,+ "created_at": time.time(),+ "source": "desktop-editor",+ }}, ensure_ascii=True) + "\\n")+ queue_file.flush()+ os.fsync(queue_file.fileno())+ fcntl.flock(lock_file, fcntl.LOCK_UN)+++if __name__ == "__main__":+ main()+""",+ encoding="utf-8",+ )+ try:+ script.chmod(0o755)+ except OSError:+ pass+ return script++def _write_shutdown_bridge_script(session: DesktopSession) -> Path:bridge_dir = _url_bridge_dir(session)bridge_dir.mkdir(parents=True, exist_ok=True)@@ -2102,14 +2187,25 @@ def _url_handler_mime_types() -> tuple[str, ...]:)-def _write_mimeapps_defaults(path: Path, desktop_id: str) -> None:- associations = ";".join([desktop_id, ""])+def _editor_text_handler_mime_types() -> tuple[str, ...]:+ return (+ "text/markdown",+ "text/x-markdown",+ "text/plain",+ )+++def _write_mimeapps_defaults(path: Path, url_desktop_id: str, editor_desktop_id: str) -> None:+ url_associations = ";".join([url_desktop_id, ""])+ editor_associations = ";".join([editor_desktop_id, ""])lines = ["[Default Applications]",- *(f"{mime_type}={desktop_id}" for mime_type in _url_handler_mime_types()),+ *(f"{mime_type}={url_desktop_id}" for mime_type in _url_handler_mime_types()),+ *(f"{mime_type}={editor_desktop_id}" for mime_type in _editor_text_handler_mime_types()),"","[Added Associations]",- *(f"{mime_type}={associations}" for mime_type in _url_handler_mime_types()),+ *(f"{mime_type}={url_associations}" for mime_type in _url_handler_mime_types()),+ *(f"{mime_type}={editor_associations}" for mime_type in _editor_text_handler_mime_types()),"",]path.parent.mkdir(parents=True, exist_ok=True)diff --git a/plugins/_desktop/webui/desktop-store.js b/plugins/_desktop/webui/desktop-store.jsindex 1408ecad6..9c793da90 100644--- a/plugins/_desktop/webui/desktop-store.js+++ b/plugins/_desktop/webui/desktop-store.js@@ -2239,7 +2239,12 @@ const model = {async openDesktopUrlIntent(intent = {}) {const url = String(intent?.url || "").trim();const handled = await handleUrlIntent({ url, source: "desktop-url" });- this.setMessage(handled ? "Opened link in Browser" : "Browser is not available");+ const isEditorIntent = url.startsWith("a0-editor:");+ this.setMessage(+ handled+ ? (isEditorIntent ? "Opened text in Editor" : "Opened link in Browser")+ : (isEditorIntent ? "Editor is not available" : "Browser is not available"),+ );},browserDestinationForDesktopUrl() {diff --git a/plugins/_editor/AGENTS.md b/plugins/_editor/AGENTS.mdindex 19d823537..f7c2f25b9 100644--- a/plugins/_editor/AGENTS.md+++ b/plugins/_editor/AGENTS.md@@ -2,12 +2,12 @@## Purpose-- Own the native Markdown editor surface for canvas and floating modal workflows.+- Own the native Markdown and plain text editor surface for canvas and floating modal workflows.## Ownership- `api/` owns editor session and WebSocket handlers.-- `helpers/` owns markdown session and open-file context helpers.+- `helpers/` owns editor text session and open-file context helpers.- `prompts/` owns agent-visible open-file context.- `webui/` owns editor panel, preview, store, and main surface.- `extensions/` owns editor hook contributions.@@ -17,6 +17,8 @@- Keep editor session state synchronized across API, WebSocket, and WebUI panel behavior.- Do not expose unsaved content or local paths beyond intended chat/context surfaces.- Keep the floating Editor modal on the shared surface modal chrome so the header remains draggable while existing Focus mode continues to work.+- Keep Editor Open wired through the File Browser text picker so users can open one or more Markdown or plain text files with an obvious confirmation action.+- Keep Save As distinct from Rename: Save As writes the current editor text to a chosen `.md` or `.txt` path and retargets the active session without removing the original file.## Work Guidancediff --git a/plugins/_editor/api/editor_session.py b/plugins/_editor/api/editor_session.pyindex 5ef197648..60dbf4578 100644--- a/plugins/_editor/api/editor_session.py+++ b/plugins/_editor/api/editor_session.py@@ -38,13 +38,13 @@ class EditorSession(ApiHandler):return closedif action == "create":fmt = str(input.get("format") or "md").lower().lstrip(".")- if fmt != "md":- return {"ok": False, "error": "Editor can only create Markdown documents."}+ if fmt not in document_store.EDITOR_TEXT_EXTENSIONS:+ return {"ok": False, "error": "Editor can only create Markdown (.md) and text (.txt) documents."}try:doc = document_store.create_document(kind="document",title=str(input.get("title") or "Untitled"),- fmt="md",+ fmt=fmt,content=str(input.get("content") or ""),path=str(input.get("path") or ""),context_id=context_id,@@ -72,6 +72,28 @@ class EditorSession(ApiHandler):if not session_id:return {"ok": False, "error": "session_id is required."}return markdown_sessions.get_manager().save(session_id, text=input.get("text"))+ if action == "save_as":+ session_id = str(input.get("session_id") or "").strip()+ path = str(input.get("path") or "").strip()+ if not session_id:+ return {"ok": False, "error": "session_id is required."}+ if not path:+ return {"ok": False, "error": "path is required."}+ try:+ result = markdown_sessions.get_manager().save_as(session_id, path, text=input.get("text"))+ except Exception as exc:+ return {"ok": False, "error": str(exc)}+ document_store.close_session(session_id=str(input.get("store_session_id") or "").strip())+ store_session = document_store.create_session(+ result["document"]["file_id"],+ user_id=str(input.get("user_id") or "agent-zero-user"),+ permission="write",+ origin=self._origin(request),+ )+ return {+ **result,+ "store_session_id": store_session["session_id"],+ }if action == "renamed":return self._renamed(input, context_id)if action == "refresh":@@ -85,7 +107,7 @@ class EditorSession(ApiHandler):request: Request,context_id: str = "",) -> dict:- if str(doc.get("extension") or "").lower() != "md":+ if str(doc.get("extension") or "").lower() not in document_store.EDITOR_TEXT_EXTENSIONS:return {"ok": False,"error": f".{doc.get('extension', '')} documents use the Desktop surface.",diff --git a/plugins/_editor/api/ws_editor.py b/plugins/_editor/api/ws_editor.pyindex 7c8e6e446..8adf31d1c 100644--- a/plugins/_editor/api/ws_editor.py+++ b/plugins/_editor/api/ws_editor.py@@ -53,10 +53,17 @@ class WsEditor(WsHandler):elif path:doc = document_store.register_document(path, context_id=context_id)else:+ fmt = str(data.get("format") or "md").lower().strip().lstrip(".")+ if fmt not in document_store.EDITOR_TEXT_EXTENSIONS:+ return WsResult.error(+ code="UNSUPPORTED_EDITOR_DOCUMENT",+ message=f"Editor can only create Markdown (.md) and text (.txt) documents, not .{fmt}.",+ correlation_id=data.get("correlationId"),+ )doc = document_store.create_document(kind="document",title=str(data.get("title") or "Untitled"),- fmt="md",+ fmt=fmt,content=str(data.get("content") or ""),context_id=context_id,)diff --git a/plugins/_editor/helpers/markdown_sessions.py b/plugins/_editor/helpers/markdown_sessions.pyindex 64eb39f43..0347fa3cb 100644--- a/plugins/_editor/helpers/markdown_sessions.py+++ b/plugins/_editor/helpers/markdown_sessions.py@@ -31,7 +31,7 @@ class MarkdownSession:class MarkdownSessionManager:- """Owns native Editor sessions for Markdown documents."""+ """Owns native Editor sessions for Markdown and plain text documents."""def __init__(self) -> None:self._sessions: dict[str, MarkdownSession] = {}@@ -39,8 +39,8 @@ class MarkdownSessionManager:def open(self, doc: dict[str, Any], sid: str = "", context_id: str = "", refresh: bool = False) -> dict[str, Any]:ext = str(doc["extension"]).lower()- if ext != "md":- raise ValueError(f"Editor is only available for Markdown. Open .{ext} files in the Desktop.")+ if ext not in document_store.EDITOR_TEXT_EXTENSIONS:+ raise ValueError(f"Editor is only available for Markdown and text files. Open .{ext} files in the Desktop.")normalized_context = str(context_id or "")if refresh:@@ -64,6 +64,7 @@ class MarkdownSessionManager:_mark_session_external(session, doc)session.path = doc["path"]session.title = doc["basename"]+ session.extension = extsession.updated_at = time.time()self.activate(session.session_id)return self._payload(session, doc)@@ -103,11 +104,12 @@ class MarkdownSessionManager:if conflict is not None:return conflict- updated = document_store.write_markdown(session.file_id, session.text)+ updated = document_store.write_text_document(session.file_id, session.text)session.updated_at = time.time()session.dirty = Falsesession.path = updated["path"]session.title = updated["basename"]+ session.extension = str(updated.get("extension") or session.extension).lower()_set_session_base(session, updated)self._refresh_file_sessions(updated,@@ -121,6 +123,32 @@ class MarkdownSessionManager:"version": document_store.item_version(updated),}+ def save_as(self, session_id: str, path: str, text: str | None = None) -> dict[str, Any]:+ session = self._require(session_id)+ if text is not None:+ session.text = str(text)++ updated = document_store.save_text_document_as(+ session.file_id,+ path,+ session.text,+ context_id=session.context_id,+ )+ old_file_id = session.file_id+ session.file_id = updated["file_id"]+ session.updated_at = time.time()+ session.dirty = False+ session.path = updated["path"]+ session.title = updated["basename"]+ session.extension = str(updated.get("extension") or session.extension).lower()+ _set_session_base(session, updated)+ return {+ "ok": True,+ "previous_file_id": old_file_id,+ "document": _public_doc(updated),+ "version": document_store.item_version(updated),+ }+def activate(self, session_id: str) -> dict[str, Any]:session = self._require(session_id)now = time.time()@@ -145,7 +173,7 @@ class MarkdownSessionManager:doc = document_store.get_document(normalized)except Exception:return {"ok": False, "refreshed": 0, "sessions": []}- if str(doc.get("extension") or "").lower() != "md":+ if str(doc.get("extension") or "").lower() not in document_store.EDITOR_TEXT_EXTENSIONS:return {"ok": True, "refreshed": 0, "sessions": []}refreshed = self._refresh_file_sessions(@@ -342,6 +370,7 @@ class MarkdownSessionManager:session.text = str(text)session.path = doc["path"]session.title = doc["basename"]+ session.extension = str(doc.get("extension") or session.extension).lower()if dirty is not None and (can_replace_text or refresh_dirty or not session.dirty):session.dirty = dirtyif can_replace_text or not session.dirty:diff --git a/plugins/_editor/helpers/open_files_context.py b/plugins/_editor/helpers/open_files_context.pyindex eaa6e1481..54d45e1c3 100644--- a/plugins/_editor/helpers/open_files_context.py+++ b/plugins/_editor/helpers/open_files_context.py@@ -11,7 +11,7 @@ def build_context(context_id: str = "", max_items: int = 20) -> str:return ""lines = [- "These Markdown files are open in the Editor for the active Agent Zero context. Content is omitted; use `text_editor` with action `read` before content-sensitive edits.",+ "These Markdown or plain text files are open in the Editor for the active Agent Zero context. Content is omitted; use `text_editor` with action `read` before content-sensitive edits.",]for item in files:lines.append(format_open_file_line(item))diff --git a/plugins/_editor/webui/editor-panel.html b/plugins/_editor/webui/editor-panel.htmlindex 310a8f7a3..309c5cb27 100644--- a/plugins/_editor/webui/editor-panel.html+++ b/plugins/_editor/webui/editor-panel.html@@ -9,7 +9,7 @@<template x-if="$store.editor"><div class="editor-panel" x-create="$store.editor.onMount($el, xAttrs($el) || {})" x-destroy="$store.editor.cleanup()"><div class="editor-shell" @keydown="$store.editor.handleEditorKeydown($event)">- <div class="editor-tabs" x-show="$store.editor.visibleTabs().length > 0" style="display: none;" role="tablist" aria-label="Open Markdown files">+ <div class="editor-tabs" x-show="$store.editor.visibleTabs().length > 0" style="display: none;" role="tablist" aria-label="Open text files"><template x-for="tab in $store.editor.visibleTabs()" :key="tab.tab_id"><divclass="editor-tab-shell"@@ -82,6 +82,8 @@<buttontype="button"class="editor-icon-button editor-mode-toggle"+ x-show="$store.editor.isMarkdown()"+ style="display: none;":title="$store.editor.viewModeTitle()":aria-label="$store.editor.viewModeTitle()"@click="$store.editor.toggleViewMode()"@@ -89,30 +91,30 @@<span class="material-symbols-outlined" aria-hidden="true" x-text="$store.editor.viewModeIcon()"></span></button>- <div class="editor-tool-group editor-source-tools" x-show="$store.editor.isMarkdown() && $store.editor.isSourceMode()" style="display: none;">+ <div class="editor-tool-group editor-source-tools" x-show="$store.editor.isTextDocument() && $store.editor.isSourceMode()" style="display: none;"><button type="button" class="editor-icon-button" title="Undo" aria-label="Undo" :disabled="!$store.editor.canUndo()" @click="$store.editor.undo()"><span class="material-symbols-outlined">undo</span></button><button type="button" class="editor-icon-button" title="Redo" aria-label="Redo" :disabled="!$store.editor.canRedo()" @click="$store.editor.redo()"><span class="material-symbols-outlined">redo</span></button>- <button type="button" class="editor-icon-button" title="Bold" aria-label="Bold" @click="$store.editor.format('bold')">+ <button type="button" class="editor-icon-button" title="Bold" aria-label="Bold" x-show="$store.editor.isMarkdown()" @click="$store.editor.format('bold')"><span class="material-symbols-outlined">format_bold</span></button>- <button type="button" class="editor-icon-button" title="Italic" aria-label="Italic" @click="$store.editor.format('italic')">+ <button type="button" class="editor-icon-button" title="Italic" aria-label="Italic" x-show="$store.editor.isMarkdown()" @click="$store.editor.format('italic')"><span class="material-symbols-outlined">format_italic</span></button>- <button type="button" class="editor-icon-button" title="List" aria-label="List" @click="$store.editor.format('list')">+ <button type="button" class="editor-icon-button" title="List" aria-label="List" x-show="$store.editor.isMarkdown()" @click="$store.editor.format('list')"><span class="material-symbols-outlined">format_list_bulleted</span></button>- <button type="button" class="editor-icon-button" title="Numbered list" aria-label="Numbered list" @click="$store.editor.format('numbered')">+ <button type="button" class="editor-icon-button" title="Numbered list" aria-label="Numbered list" x-show="$store.editor.isMarkdown()" @click="$store.editor.format('numbered')"><span class="material-symbols-outlined">format_list_numbered</span></button>- <button type="button" class="editor-icon-button" title="Table" aria-label="Table" @click="$store.editor.format('table')">+ <button type="button" class="editor-icon-button" title="Table" aria-label="Table" x-show="$store.editor.isMarkdown()" @click="$store.editor.format('table')"><span class="material-symbols-outlined">table</span></button></div>- <div class="editor-tool-group editor-preview-tools" x-show="$store.editor.isPreviewMode()" style="display: none;">+ <div class="editor-tool-group editor-preview-tools" x-show="$store.editor.isMarkdown() && $store.editor.isPreviewMode()" style="display: none;"><button type="button" class="editor-icon-button" title="Previous page" aria-label="Previous page" :disabled="$store.editor.previewEditing || $store.editor.activePageIndex <= 0" @click="$store.editor.previousPage()"><span class="material-symbols-outlined">chevron_left</span></button>@@ -147,6 +149,17 @@<span class="material-symbols-outlined" :class="{ spinning: $store.editor.saving }" x-text="$store.editor.saving ? 'progress_activity' : 'save'"></span></button>+ <button+ type="button"+ class="editor-icon-button editor-save-as-button"+ title="Save As"+ aria-label="Save As"+ :disabled="$store.editor.saving"+ @click="$store.editor.saveAs()"+ >+ <span class="material-symbols-outlined">save_as</span>+ </button>+<div class="editor-file-actions" x-data="{ open: false }" @click.outside="open = false" @keydown.escape.window="open = false"><buttontype="button"@@ -213,7 +226,7 @@<textareaclass="editor-source-editor"data-editor-source- aria-label="Markdown source"+ aria-label="Text source"x-show="$store.editor.aceUnavailable"x-model="$store.editor.editorText"@input="$store.editor.onSourceInput()"@@ -224,7 +237,7 @@</div></div>- <div class="editor-preview-shell" x-show="$store.editor.session && $store.editor.isPreviewMode()" style="display: none;">+ <div class="editor-preview-shell" x-show="$store.editor.session && $store.editor.isMarkdown() && $store.editor.isPreviewMode()" style="display: none;"><div class="editor-preview-title"><h1 x-text="$store.editor.pageTitle()"></h1></div>@@ -261,6 +274,10 @@<span class="material-symbols-outlined" aria-hidden="true">article</span><span class="editor-button-label">Markdown</span></button>+ <button type="button" class="editor-icon-button editor-command-button" @click="$store.editor.runNewMenuAction('text')">+ <span class="material-symbols-outlined" aria-hidden="true">description</span>+ <span class="editor-button-label">Text</span>+ </button></div></div></div>diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.jsindex c62195113..a5997e387 100644--- a/plugins/_editor/webui/editor-store.js+++ b/plugins/_editor/webui/editor-store.js@@ -3,7 +3,9 @@ import { callJsonApi } from "/js/api.js";import { getNamespacedClient } from "/js/websocket.js";import { store as fileBrowserStore } from "/components/modals/file-browser/file-browser-store.js";import {+ openLatest as openLatestSurface,placeSurfaceModalHeaderAction,+ registerUrlHandler,setupFloatingSurfaceModalChrome,} from "/js/surfaces.js";import {@@ -24,6 +26,7 @@ const INPUT_PUSH_DELAY_MS = 650;const MAX_HISTORY = 80;const SOURCE_MODE = "source";const PREVIEW_MODE = "preview";+const EDITOR_TEXT_EXTENSIONS = new Set(["md", "txt"]);function currentContextId() {try {@@ -51,6 +54,33 @@ function parentPath(path = "") {return normalized.slice(0, index);}+function textDocumentFilename(path = "", fallback = "Untitled.md") {+ const name = basename(path || fallback || "Untitled.md");+ const ext = extensionOf(name);+ if (EDITOR_TEXT_EXTENSIONS.has(ext)) return name;+ return `${name.replace(/\.+$/, "") || "Untitled"}.md`;+}++function textDocumentDefaultExtension(path = "") {+ const ext = extensionOf(path);+ return EDITOR_TEXT_EXTENSIONS.has(ext) ? ext : "md";+}++function editorIntent(url = "") {+ const raw = String(url || "").trim();+ if (!raw) return null;+ try {+ const parsed = new URL(raw);+ if (parsed.protocol !== "a0-editor:") return null;+ if (parsed.hostname === "open") {+ return { path: parsed.searchParams.get("path") || "" };+ }+ return null;+ } catch {+ return null;+ }+}+function uniqueTabId(session = {}) {return String(session.file_id || session.session_id || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`);}@@ -77,7 +107,7 @@ function placeCaretAtEnd(element) {selection.addRange(range);}-function normalizeMarkdown(doc = {}) {+function normalizeTextDocument(doc = {}) {const path = doc.path || "";const extension = String(doc.extension || extensionOf(path)).toLowerCase();return {@@ -90,7 +120,7 @@ function normalizeMarkdown(doc = {}) {}function normalizeSession(payload = {}) {- const document = normalizeMarkdown(payload.document || payload);+ const document = normalizeTextDocument(payload.document || payload);return {...payload,document,@@ -301,7 +331,7 @@ const model = {},async setViewMode(mode) {- const next = mode === PREVIEW_MODE ? PREVIEW_MODE : SOURCE_MODE;+ const next = mode === PREVIEW_MODE && this.isMarkdown() ? PREVIEW_MODE : SOURCE_MODE;if (this.viewMode === next) return;this.applyPreviewEdit({ silent: true });this.syncEditorText();@@ -319,6 +349,7 @@ const model = {},async toggleViewMode() {+ if (!this.isMarkdown()) return;await this.setViewMode(this.isPreviewMode() ? SOURCE_MODE : PREVIEW_MODE);},@@ -331,6 +362,7 @@ const model = {},pages() {+ if (!this.isMarkdown()) return [];return buildMarkdownPages(this.editorText, this.tabTitle(this.session || {}));},@@ -351,6 +383,7 @@ const model = {},previewHtml() {+ if (!this.isMarkdown()) return "";return renderEditorPreviewMarkdown(this.currentPage().markdown || "", this.editorText);},@@ -476,7 +509,7 @@ const model = {},schedulePreviewEnhance() {- if (!this.isPreviewMode()) return;+ if (!this.isMarkdown() || !this.isPreviewMode()) return;if (this._previewEnhanceTimer) globalThis.clearTimeout(this._previewEnhanceTimer);this._previewEnhanceTimer = globalThis.setTimeout(() => {this._previewEnhanceTimer = null;@@ -669,6 +702,7 @@ const model = {},openSearch() {+ if (!this.isMarkdown()) return;if (!this.isPreviewMode()) {this.setViewMode(PREVIEW_MODE);}@@ -832,13 +866,15 @@ const model = {handleEditorKeydown(event) {if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "f") {+ if (!this.isMarkdown()) return;event.preventDefault();this.openSearch();}},async create(kind = "document", format = "") {- const fmt = "md";+ const requested = String(format || "md").toLowerCase().replace(/^\./, "");+ const fmt = EDITOR_TEXT_EXTENSIONS.has(requested) ? requested : "md";const title = this.defaultTitle(kind, fmt);return await this.openSession({action: "create",@@ -866,7 +902,17 @@ const model = {// The file browser can still open with the static fallback.}}- await fileBrowserStore.open(workdirPath);+ await fileBrowserStore.openTextPicker(workdirPath, async ({ selectedFiles = [] } = {}) => {+ const files = selectedFiles.filter((file) => file?.path);+ if (!files.length) return false;+ for (const file of files) {+ const session = await this.openPath(file.path, { source: "file-browser", refresh: true });+ if (!session || session.ok === false) {+ throw new Error(this.error || `Could not open ${file.name || file.path}`);+ }+ }+ return true;+ });},async openPath(path, options = {}) {@@ -883,11 +929,11 @@ const model = {try {const response = await callEditor(payload.action || "open", payload);if (response?.ok === false) {- this.error = response.error || "Markdown could not be opened.";+ this.error = response.error || "Text document could not be opened.";return null;}if (response?.requires_desktop) {- const document = normalizeMarkdown(response.document || response);+ const document = normalizeTextDocument(response.document || response);this.setMessage(`${documentLabel(document)} uses the Desktop surface.`);await this.refresh();return response;@@ -931,6 +977,11 @@ const model = {this.activeTabId = tab?.tab_id || "";this.editorText = String(tab?.text || "");this.dirty = Boolean(tab?.dirty);+ if (!this.isMarkdown(tab) && this.isPreviewMode()) {+ this.viewMode = SOURCE_MODE;+ this.searchOpen = false;+ this.searchQuery = "";+ }if (this.previewEditing) this.cancelPreviewEdit();if (!options.preservePage) {this.activePageIndex = 0;@@ -941,6 +992,7 @@ const model = {this.searchIndex = -1;this.resetHistory(this.editorText);this.setSourceEditorText(this.editorText);+ this.updateSourceEditorMode();if (tab?.session_id) {requestEditor("editor_activate", { session_id: tab.session_id }, 2500).catch(() => {});}@@ -994,7 +1046,7 @@ const model = {if (!pending) return "";const dirtyCount = Number(pending.dirtyCount || 0);if (pending.kind === "all") {- if (dirtyCount === 0) return "All open Markdown files will be closed.";+ if (dirtyCount === 0) return "All open text files will be closed.";return `${dirtyCount} open ${dirtyCount === 1 ? "file has" : "files have"} unsaved changes.`;}if (dirtyCount > 0) return "This file has unsaved changes.";@@ -1069,7 +1121,7 @@ const model = {file_id: tab.file_id || "",});} catch (error) {- console.warn("Markdown close skipped", error);+ console.warn("Editor close skipped", error);}this.tabs = this.tabs.filter((item) => item.tab_id !== tabId);if (this.pendingClose?.tabId === tabId || this.pendingClose?.tabIds?.includes(tabId)) {@@ -1140,7 +1192,7 @@ const model = {const darkMode = globalThis.localStorage?.getItem("darkMode");const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/github";editor.setTheme(theme);- editor.session.setMode("ace/mode/markdown");+ editor.session.setMode(this.sourceEditorMode());editor.session.setUseWrapMode(true);editor.setOptions({fontSize: "13px",@@ -1159,9 +1211,20 @@ const model = {editor.session.on("change", this._sourceEditorChangeHandler);this.sourceEditor = editor;this.aceUnavailable = false;+ this.updateSourceEditorMode();this.queueRender({ focus: Boolean(this.session), end: false });},+ sourceEditorMode(tab = this.session) {+ return this.isMarkdown(tab) ? "ace/mode/markdown" : "ace/mode/text";+ },++ updateSourceEditorMode(tab = this.session) {+ try {+ this.sourceEditor?.session?.setMode(this.sourceEditorMode(tab));+ } catch {}+ },+destroySourceEditor() {if (this.sourceEditor?.session && this._sourceEditorChangeHandler) {this.sourceEditor.session.off?.("change", this._sourceEditorChangeHandler);@@ -1199,7 +1262,7 @@ const model = {},async save() {- if (!this.session || this.saving || !this.isMarkdown()) return;+ if (!this.session || this.saving || !this.isTextDocument()) return;this.applyPreviewEdit({ silent: true });this.syncEditorText();this.saving = true;@@ -1213,7 +1276,7 @@ const model = {response = await callEditor("save", payload);}if (response?.ok === false) throw new Error(response.error || "Save failed.");- const document = normalizeMarkdown(response.document || this.session.document || {});+ const document = normalizeTextDocument(response.document || this.session.document || {});const updated = {...this.session,text: this.editorText,@@ -1221,6 +1284,7 @@ const model = {document,path: document.path || this.session.path,file_id: document.file_id || this.session.file_id,+ extension: document.extension || this.session.extension,version: document.version || response.version || this.session.version,};this.replaceActiveSession(updated);@@ -1234,8 +1298,73 @@ const model = {}},+ async saveAs() {+ if (!this.session || this.saving || !this.isTextDocument()) return;+ this.applyPreviewEdit({ silent: true });+ this.syncEditorText();++ let startPath = parentPath(this.session.path || this.session.document?.path || "");+ if (!startPath || startPath === "/") {+ try {+ const home = await callEditor("home");+ startPath = home?.path || startPath || "/a0/usr/workdir";+ } catch {+ startPath = "/a0/usr/workdir";+ }+ }++ await fileBrowserStore.openSaveAsPicker(startPath, {+ filename: textDocumentFilename(this.session.path || this.session.title || "Untitled.md"),+ defaultExtension: textDocumentDefaultExtension(this.session.path || this.session.title || "Untitled.md"),+ onConfirm: async ({ path } = {}) => {+ if (!path) return false;+ await this.saveAsPath(path);+ return true;+ },+ });+ },++ async saveAsPath(path) {+ if (!this.session || this.saving || !this.isTextDocument()) return null;+ this.saving = true;+ this.error = "";+ try {+ const payload = {+ session_id: this.session.session_id,+ store_session_id: this.session.store_session_id || "",+ path,+ text: this.editorText,+ };+ const response = await callEditor("save_as", payload);+ if (response?.ok === false) throw new Error(response.error || "Save As failed.");+ const document = normalizeTextDocument(response.document || this.session.document || {});+ const updated = {+ ...this.session,+ text: this.editorText,+ dirty: false,+ document,+ title: document.title || document.basename || basename(document.path),+ path: document.path || path,+ file_id: document.file_id || this.session.file_id,+ extension: document.extension || this.session.extension,+ store_session_id: response.store_session_id || this.session.store_session_id,+ version: document.version || response.version || this.session.version,+ };+ this.replaceActiveSession(updated);+ this.dirty = false;+ this.setMessage("Saved As");+ await this.refresh();+ return updated;+ } catch (error) {+ this.error = error instanceof Error ? error.message : String(error);+ throw error;+ } finally {+ this.saving = false;+ }+ },+async saveTab(tab) {- if (!tab || this.saving || !this.isMarkdown(tab)) return false;+ if (!tab || this.saving || !this.isTextDocument(tab)) return false;if (this.isActiveTab(tab)) {this.applyPreviewEdit({ silent: true });this.syncEditorText();@@ -1254,7 +1383,7 @@ const model = {response = await callEditor("save", payload);}if (response?.ok === false) throw new Error(response.error || "Save failed.");- const document = normalizeMarkdown(response.document || tab.document || {});+ const document = normalizeTextDocument(response.document || tab.document || {});const updated = {...tab,text: payload.text,@@ -1262,6 +1391,7 @@ const model = {document,path: document.path || tab.path,file_id: document.file_id || tab.file_id,+ extension: document.extension || tab.extension,version: document.version || response.version || tab.version,};this.replaceSession(tab, updated);@@ -1310,7 +1440,7 @@ const model = {file_id: session.file_id || "",path: renamedPath,};- if (this.isMarkdown(session)) {+ if (this.isTextDocument(session)) {this.syncEditorText();payload.text = this.session?.tab_id === session.tab_id ? this.editorText : session.text || "";}@@ -1330,7 +1460,7 @@ const model = {});if (response?.ok === false) throw new Error(response.error || "Rename failed.");- const document = normalizeMarkdown(response.document || session.document || {});+ const document = normalizeTextDocument(response.document || session.document || {});const updated = {...session,document,@@ -1355,7 +1485,11 @@ const model = {replaceSession(previous, next) {const wasActive = this.activeTabId === (previous?.tab_id || next.tab_id);- if (wasActive) this.session = next;+ if (wasActive) {+ this.session = next;+ if (!this.isMarkdown(next) && this.isPreviewMode()) this.viewMode = SOURCE_MODE;+ this.updateSourceEditorMode(next);+ }const index = this.tabs.findIndex((tab) => tab.tab_id === (previous?.tab_id || next.tab_id));if (index >= 0) this.tabs.splice(index, 1, next);},@@ -1447,7 +1581,7 @@ const model = {},scheduleInputPush() {- if (!this.session?.session_id || !this.isMarkdown()) return;+ if (!this.session?.session_id || !this.isTextDocument()) return;if (this._inputTimer) globalThis.clearTimeout(this._inputTimer);this._inputTimer = globalThis.setTimeout(() => {this._inputTimer = null;@@ -1456,7 +1590,7 @@ const model = {},flushInput() {- if (!this.session?.session_id || !this.isMarkdown()) return;+ if (!this.session?.session_id || !this.isTextDocument()) return;if (this.previewEditing) return;this.syncEditorText();requestEditor("editor_input", {@@ -1525,7 +1659,7 @@ const model = {},focusEditor(options = {}) {- if (!this.session || !this.isMarkdown()) return false;+ if (!this.session || !this.isTextDocument()) return false;if (this.sourceEditor && this.isSourceMode()) {this.sourceEditor.focus();if (options.end !== false) {@@ -1549,8 +1683,13 @@ const model = {return ext === "md";},+ isTextDocument(tab = this.session) {+ const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();+ return EDITOR_TEXT_EXTENSIONS.has(ext);+ },+hasActiveFile(tab = this.session) {- return Boolean(tab && this.isMarkdown(tab));+ return Boolean(tab && this.isTextDocument(tab));},visibleTabs() {@@ -1560,7 +1699,8 @@ const model = {defaultTitle(kind, fmt) {const date = new Date().toISOString().slice(0, 10);if (fmt === "md") return `Markdown ${date}`;- return `Markdown ${date}`;+ if (fmt === "txt") return `Text ${date}`;+ return `Text ${date}`;},tabTitle(tab = {}) {@@ -1578,6 +1718,7 @@ const model = {tab = tab || {};const ext = String(tab.extension || tab.document?.extension || "").toLowerCase();if (ext === "md") return "article";+ if (ext === "txt") return "description";return "draft";},@@ -1585,6 +1726,7 @@ const model = {const normalized = String(action || "").trim().toLowerCase();if (normalized === "open") return await this.openFileBrowser();if (normalized === "markdown") return await this.create("document", "md");+ if (normalized === "text") return await this.create("document", "txt");return null;},@@ -1608,6 +1750,10 @@ const model = {<span class="material-symbols-outlined" aria-hidden="true">article</span><span>Markdown</span></button>+ <button type="button" class="editor-new-menu-item" role="menuitem" data-editor-new-action="text">+ <span class="material-symbols-outlined" aria-hidden="true">description</span>+ <span>Text</span>+ </button></div>`;@@ -1678,6 +1824,19 @@ const model = {inner.classList.remove("editor-modal", "is-focus-mode");};},++ async handleEditorUrlIntent(intent = {}) {+ const editor = editorIntent(intent?.url || "");+ if (!editor) return false;+ await openLatestSurface("editor", {+ path: editor.path,+ refresh: true,+ source: intent?.source || "desktop-open",+ });+ return true;+ },};export const store = createStore("editor", model);++registerUrlHandler((intent) => model.handleEditorUrlIntent(intent));diff --git a/plugins/_office/AGENTS.md b/plugins/_office/AGENTS.mdindex 2e0c54b0e..7fba34633 100644--- a/plugins/_office/AGENTS.md+++ b/plugins/_office/AGENTS.md@@ -16,6 +16,7 @@- Preserve document storage integrity and live session synchronization.- Keep LibreOffice operations bounded to intended workspaces and artifact paths.- Do not expose document contents or temporary files beyond intended UI/tool flows.+- Editor text Save As storage helpers must preserve exact `.md` or `.txt` text and create a new registered document without mutating or deleting the source document.## Work Guidancediff --git a/plugins/_office/api/office_session.py b/plugins/_office/api/office_session.pyindex 7a07dd347..49225b6d7 100644--- a/plugins/_office/api/office_session.py+++ b/plugins/_office/api/office_session.py@@ -63,10 +63,10 @@ class OfficeSession(ApiHandler):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"- if str(doc.get("extension") or "").lower() == "md":+ if str(doc.get("extension") or "").lower() in document_store.EDITOR_TEXT_EXTENSIONS:return {"ok": False,- "error": "Markdown documents use the Editor surface.",+ "error": "Text documents use the Editor surface.","document": _public_doc(doc),}if str(doc.get("extension") or "").lower() in desktop_session.OFFICIAL_EXTENSIONS:@@ -116,7 +116,7 @@ class OfficeSession(ApiHandler):return {"ok": False, "error": f".{doc.get('extension', '')} documents are not supported by LibreOffice."}def _save(self, input: dict) -> dict:- return {"ok": False, "error": "Markdown saves use /plugins/_editor/editor_session."}+ return {"ok": False, "error": "Text document saves use /plugins/_editor/editor_session."}def _renamed(self, input: dict, context_id: str = "") -> dict:file_id = str(input.get("file_id") or "").strip()diff --git a/plugins/_office/api/ws_office.py b/plugins/_office/api/ws_office.pyindex 7afd8498d..100b7a2b3 100644--- a/plugins/_office/api/ws_office.py+++ b/plugins/_office/api/ws_office.py@@ -22,7 +22,7 @@ class WsOffice(WsHandler):if event in {"office_input", "office_save", "office_close"}:return {"ok": False,- "error": "Office WebSocket editing is not available for Markdown; use the Editor surface.",+ "error": "Office WebSocket editing is not available for text documents; use the Editor surface.",}except FileNotFoundError as exc:return WsResult.error(code="OFFICE_SESSION_NOT_FOUND", message=str(exc), correlation_id=data.get("correlationId"))@@ -59,10 +59,10 @@ class WsOffice(WsHandler):context_id=context_id,)ext = str(doc.get("extension") or "").lower()- if ext == "md":+ if ext in document_store.EDITOR_TEXT_EXTENSIONS:return WsResult.error(code="UNSUPPORTED_OFFICE_DOCUMENT",- message="Markdown documents use the Editor surface.",+ message="Text documents use the Editor surface.",correlation_id=data.get("correlationId"),)if ext in desktop_session.OFFICIAL_EXTENSIONS:diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.pyindex adcea0c8e..f73077afd 100644--- a/plugins/_office/helpers/document_store.py+++ b/plugins/_office/helpers/document_store.py@@ -23,8 +23,8 @@ from plugins._office.helpers import pptx_writerPLUGIN_NAME = "_office"OPEN_DOCUMENT_EXTENSIONS = {"odt", "ods", "odp"}OOXML_EXTENSIONS = {"docx", "xlsx", "pptx"}-DESKTOP_TEXT_EXTENSIONS = {"txt"}-SUPPORTED_EXTENSIONS = {"md", *OPEN_DOCUMENT_EXTENSIONS, *OOXML_EXTENSIONS, *DESKTOP_TEXT_EXTENSIONS}+EDITOR_TEXT_EXTENSIONS = {"md", "txt"}+SUPPORTED_EXTENSIONS = {*EDITOR_TEXT_EXTENSIONS, *OPEN_DOCUMENT_EXTENSIONS, *OOXML_EXTENSIONS}DEFAULT_TTL_SECONDS = 8 * 60 * 60MAX_SAVE_BYTES = 512 * 1024 * 1024ODF_OFFICE_NS = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"@@ -336,8 +336,8 @@ def rename_document(ext = normalize_extension(resolved.suffix.lstrip("."))data = Noneif content is not None:- if ext != "md":- raise ValueError("Inline content can only be provided for Markdown documents.")+ if ext not in EDITOR_TEXT_EXTENSIONS:+ raise ValueError("Inline content can only be provided for Editor text documents.")data = str(content or "").encode("utf-8")if len(data) > MAX_SAVE_BYTES:raise OverflowError("Document save exceeds maximum size")@@ -495,13 +495,91 @@ def close_session(session_id: str = "", file_id: str = "") -> int:def read_text_for_editor(doc: dict[str, Any]) -> str:path = Path(doc["path"])ext = str(doc["extension"]).lower()- if ext == "md":+ if ext in EDITOR_TEXT_EXTENSIONS:return path.read_text(encoding="utf-8", errors="replace")raise ValueError(f"Text editing is not available for .{ext}.")+def write_text_document(file_id: str, content: str) -> dict[str, Any]:+ doc = get_document(file_id)+ ext = str(doc.get("extension") or "").lower()+ if ext not in EDITOR_TEXT_EXTENSIONS:+ raise ValueError(f"Editor text saves are not available for .{ext}.")+ return replace_document_bytes(file_id, str(content or "").encode("utf-8"), actor=f"editor:{ext}")++def write_markdown(file_id: str, content: str) -> dict[str, Any]:- return replace_document_bytes(file_id, str(content or "").encode("utf-8"), actor="editor:markdown")+ return write_text_document(file_id, content)+++def save_text_document_as(+ file_id: str,+ path: str | Path,+ content: str,+ context_id: str = "",+) -> dict[str, Any]:+ target = normalize_path(path, context_id=context_id)+ ext = normalize_extension(target.suffix.lstrip("."))+ if ext not in EDITOR_TEXT_EXTENSIONS:+ raise ValueError("Editor Save As only supports Markdown (.md) and text (.txt) files.")+ if target.exists():+ raise FileExistsError(f"Target already exists: {display_path(target)}")++ data = str(content or "").encode("utf-8")+ if len(data) > MAX_SAVE_BYTES:+ raise OverflowError("Document save exceeds maximum size")++ with connect() as conn:+ source = get_document(file_id, conn=conn)+ source_ext = str(source.get("extension") or "").lower()+ if source_ext not in EDITOR_TEXT_EXTENSIONS:+ raise ValueError(f"Editor Save As is not available for .{source_ext}.")+ changed_at = now()+ target.parent.mkdir(parents=True, exist_ok=True)+ _write_atomic(target, data)+ digest = sha256_bytes(data)+ stat = target.stat()+ new_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ """,+ (+ new_file_id,+ str(target),+ target.name,+ ext,+ str(source.get("owner_id") or "a0"),+ stat.st_size,+ 1,+ digest,+ now_iso(),+ changed_at,+ changed_at,+ ),+ )+ _record_version(conn, new_file_id, target, "1", data)+ conn.execute(+ "INSERT INTO events (file_id, event_type, payload, created_at) VALUES (?, ?, ?, ?)",+ (+ file_id,+ "saved_as",+ json.dumps({"from": display_path(source["path"]), "to": display_path(target)}),+ changed_at,+ ),+ )+ conn.execute(+ "INSERT INTO events (file_id, event_type, payload, created_at) VALUES (?, ?, ?, ?)",+ (+ new_file_id,+ "created_from_save_as",+ json.dumps({"from": display_path(source["path"])}),+ changed_at,+ ),+ )+ return get_document(new_file_id, conn=conn)def replace_document_bytes(@@ -623,7 +701,7 @@ def create_document(def _unique_document_path(title: str, ext: str, context_id: str = "") -> Path:base = safe_document_stem(title, ext, "Document")- root = document_home(context_id) if ext == "md" else document_binary_home(context_id)+ root = document_home(context_id) if ext in EDITOR_TEXT_EXTENSIONS else document_binary_home(context_id)candidate = root / f"{base}.{ext}"index = 2while candidate.exists():diff --git a/tests/test_file_browser_navigation.py b/tests/test_file_browser_navigation.pyindex e2285e071..be18e04e8 100644--- a/tests/test_file_browser_navigation.py+++ b/tests/test_file_browser_navigation.py@@ -81,7 +81,7 @@ def test_file_browser_compact_controls_and_narrow_layout_contract() -> None:assert "container: file-browser / inline-size;" in htmlassert "@container file-browser (max-width: 620px)" in html- assert "grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 5.25rem;" in html+ assert "grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 8rem;" in htmlassert ".file-cell-date,\n .file-date {\n display: none;" in htmlassert ".file-cell-size,\n .file-size" not in html@@ -89,6 +89,45 @@ def test_file_browser_compact_controls_and_narrow_layout_contract() -> None:assert "New file and New folder controls icon-only" in dox+def test_file_browser_editor_picker_modes_have_primary_footer_actions() -> None:+ html = read("webui", "components", "modals", "file-browser", "file-browser.html")+ store = read("webui", "components", "modals", "file-browser", "file-browser-store.js")+ dox = read("webui", "components", "modals", "file-browser", "AGENTS.md")++ assert "PICKER_MODE_TEXT_OPEN" in store+ assert "PICKER_MODE_SAVE_AS" in store+ assert "openTextPicker" in store+ assert "openSaveAsPicker" in store+ assert 'new Set(["md", "txt"])' in store+ assert "pickerSelectedFiles()" in store+ assert "validatePickerFilename" in store+ assert "handleFileNameClick(file = {})" in store+ assert "fileSurfaceTarget(file) === \"editor\"" in store+ assert "isEditorSurface(file = {})" in store+ assert "canOpenInActionMenu(file = {})" in store++ assert "file-browser-picker-actions" in html+ assert "file-editor-open-action" in html+ assert 'aria-label="Open in Editor"' in html+ assert "picker-filename-input" in html+ assert "Open Selected" in store+ assert "Save Here" in store+ assert "$store.fileBrowser.confirmPicker()" in html+ assert "$store.fileBrowser.pickerSelectionLabel()" in html+ assert "$store.fileBrowser.isPickerMode()" in html+ assert "$store.fileBrowser.isTextOpenPicker()" in html+ assert "picker-confirm-button" in html++ assert "picker modes for Editor Open and Save As" in dox+ assert "Markdown or plain text files" in dox+ assert "Open in Editor action visible outside the overflow menu" in dox++ editor_button_index = html.index("file-editor-open-action")+ dropdown_menu_index = html.index('class="dropdown-menu"')+ assert editor_button_index < dropdown_menu_index+ assert 'x-show="$store.fileBrowser.canOpenInActionMenu(file)"' in html++def test_file_browser_empty_api_path_uses_default_workdir_contract() -> None:api_source = read("api", "get_work_dir_files.py")api_dox = read("api", "get_work_dir_files.py.dox.md")diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.pyindex 515b340d9..35fc39fd6 100644--- a/tests/test_office_canvas_setup.py+++ b/tests/test_office_canvas_setup.py@@ -285,8 +285,8 @@ def test_desktop_plugin_owns_routes_runtime_surface_and_state_paths():assert "virtual_desktop_routes.install_route_hooks()" in desktop_startupassert 'action in {"open_document", "document"}' in desktop_api- assert 'if ext == "md":' in desktop_api- assert "Markdown documents use the Editor surface." in desktop_api+ assert "document_store.EDITOR_TEXT_EXTENSIONS" in desktop_api+ assert "Text documents use the Editor surface." in desktop_apiassert "return self._open_markdown(doc, input, request)" not in desktop_apiassert "markdown_sessions" not in desktop_apiassert '"status": desktop.get("status") or {}' in desktop_api@@ -466,7 +466,7 @@ def test_office_artifacts_only_open_desktop_from_explicit_document_ui_requests()assert 'action == "desktop"' not in office_apiassert 'action == "desktop_state"' not in office_apiassert 'action == "desktop_shutdown"' not in office_api- assert "Markdown documents use the Editor surface." in office_api+ assert "Text documents use the Editor surface." in office_apiassert '"requires_editor": True' not in office_api@@ -529,7 +529,7 @@ def test_editor_plugin_owns_markdown_sessions_and_active_context_extras():assert "editor_open_files" in editor_extrasassert "desktop_state" in desktop_contextassert 'pop("office_canvas"' in office_context- assert "Office WebSocket editing is not available for Markdown; use the Editor surface." in office_ws+ assert "Office WebSocket editing is not available for text documents; use the Editor surface." in office_wsassert "from plugins._office.helpers import document_store, markdown_sessions" not in office_wsassert not (PROJECT_ROOT / "plugins" / "_office" / "helpers" / "markdown_sessions.py").exists()assert "syncTextEditorResultsIntoOpenEditor" in editor_result_sync@@ -547,10 +547,13 @@ def test_editor_open_file_browser_prefers_context_home_before_workdir_fallback()assert home_lookup < settings_fallbackassert "workdirPath = home.path;" in open_file_browserassert "workdirPath = response?.settings?.workdir_path || workdirPath;" in open_file_browser+ assert "fileBrowserStore.openTextPicker" in open_file_browser+ assert "selectedFiles" in open_file_browserdef test_editor_toolbar_places_preview_toggle_left_and_save_on_right():editor_panel = read("plugins", "_editor", "webui", "editor-panel.html")+ editor_store = read("plugins", "_editor", "webui", "editor-store.js")toolbar_start = editor_panel.index('<div class="editor-toolbar"')toolbar_end = editor_panel.index('<div class="editor-search-bar"', toolbar_start)toolbar = editor_panel[toolbar_start:toolbar_end]@@ -560,13 +563,20 @@ def test_editor_toolbar_places_preview_toggle_left_and_save_on_right():preview_tools = toolbar.index("editor-preview-tools")spacer = toolbar.index("editor-toolbar-spacer")save_button = toolbar.index("editor-save-button")+ save_as_button = toolbar.index("editor-save-as-button")file_actions = toolbar.index("editor-file-actions")file_menu = toolbar.index("editor-file-menu")assert mode_toggle < source_toolsassert mode_toggle < preview_tools- assert spacer < save_button < file_actions < file_menu+ assert spacer < save_button < save_as_button < file_actions < file_menuassert "@click=\"$store.editor.save()\"" in toolbar+ assert "@click=\"$store.editor.saveAs()\"" in toolbar+ assert "async saveAs()" in editor_store+ assert "fileBrowserStore.openSaveAsPicker" in editor_store+ assert 'callEditor("save_as"' in editor_store+ assert "isTextDocument()" in toolbar+ assert 'data-editor-new-action="text"' in editor_storefile_menu_markup = toolbar[file_menu:]assert "<span>Save</span>" not in file_menu_markup@@ -574,6 +584,26 @@ def test_editor_toolbar_places_preview_toggle_left_and_save_on_right():assert "<span>Close File</span>" in file_menu_markup+def test_desktop_text_open_with_routes_to_editor_surface():+ desktop_session = read("plugins", "_desktop", "helpers", "desktop_session.py")+ desktop_store = read("plugins", "_desktop", "webui", "desktop-store.js")+ editor_store = read("plugins", "_editor", "webui", "editor-store.js")++ assert 'EDITOR_HANDLER_DESKTOP_ID = "agent-zero-editor.desktop"' in desktop_session+ assert "def _write_editor_bridge_script" in desktop_session+ assert "a0-editor://open?path=" in desktop_session+ assert "_editor_text_handler_mime_types()" in desktop_session+ assert '"text/markdown"' in desktop_session+ assert '"text/x-markdown"' in desktop_session+ assert '"text/plain"' in desktop_session+ assert "applications_dir / EDITOR_HANDLER_DESKTOP_ID" in desktop_session+ assert 'desktop_dir / "Editor.desktop"' in desktop_session+ assert "Opened text in Editor" in desktop_store+ assert "registerUrlHandler" in editor_store+ assert "handleEditorUrlIntent" in editor_store+ assert 'openLatestSurface("editor"' in editor_store++def test_office_and_desktop_skills_are_rehomed_and_renamed():office_skills = PROJECT_ROOT / "plugins" / "_office" / "skills"desktop_skills = PROJECT_ROOT / "plugins" / "_desktop" / "skills"diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex 9e4daa87e..011e619ed 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -84,15 +84,15 @@ def test_document_store_create_defaults_to_markdown(office_state):assert Path(doc["path"]).read_text(encoding="utf-8").startswith("# Research Note")-def test_text_files_register_as_desktop_documents(office_state):+def test_text_files_register_as_editor_documents(office_state):path = office_state.workdir / "plain-note.txt"- path.write_text("Plain text belongs on the Desktop surface.\n", encoding="utf-8")+ path.write_text("Plain text belongs in the Editor surface.\n", encoding="utf-8")doc = document_store.register_document(path)assert doc["extension"] == "txt"- assert "txt" in document_store.DESKTOP_TEXT_EXTENSIONS- assert "txt" in desktop_session.OFFICIAL_EXTENSIONS+ assert "txt" in document_store.EDITOR_TEXT_EXTENSIONS+ assert "txt" not in desktop_session.OFFICIAL_EXTENSIONSdef test_file_browser_can_register_runtime_root_markdown(office_state, monkeypatch):@@ -521,6 +521,46 @@ 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_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")+ original = Path(doc["path"])+ session = manager.open(doc, context_id="ctx-a")+ target = office_state.workdir / "notes" / "Saved Copy.txt"++ result = manager.save_as(+ session["session_id"],+ str(target),+ text="Saved Copy\n\nExact body\n",+ )++ saved_session = manager._sessions[session["session_id"]]+ assert result["ok"] is True+ assert result["document"]["file_id"] != doc["file_id"]+ assert result["previous_file_id"] == doc["file_id"]+ assert saved_session.file_id == result["document"]["file_id"]+ assert saved_session.path == str(target)+ assert saved_session.extension == "txt"+ assert saved_session.dirty is False+ assert original.read_text(encoding="utf-8") == "# Original Note"+ assert target.read_text(encoding="utf-8") == "Saved Copy\n\nExact body\n"+++def test_editor_session_opens_and_saves_txt_documents(office_state):+ manager = editor_markdown_sessions.MarkdownSessionManager()+ doc = document_store.create_document("document", "Plain Note", "txt", "First line")+ session = manager.open(doc, context_id="ctx-a")++ assert session["extension"] == "txt"+ assert session["text"] == "First line"++ result = manager.save(session["session_id"], text="Second line\n")++ assert result["ok"] is True+ assert result["document"]["extension"] == "txt"+ assert Path(result["document"]["path"]).read_text(encoding="utf-8") == "Second line\n"++def test_refresh_open_markdown_session_reloads_external_file_edits(office_state):manager = editor_markdown_sessions.MarkdownSessionManager()doc = document_store.create_document("document", "External Refresh", "md", "First")diff --git a/webui/components/modals/file-browser/AGENTS.md b/webui/components/modals/file-browser/AGENTS.mdindex 15f82de4f..f1dcb53f6 100644--- a/webui/components/modals/file-browser/AGENTS.md+++ b/webui/components/modals/file-browser/AGENTS.md@@ -17,6 +17,8 @@- The floating file-browser modal must use the shared surface modal chrome so it remains draggable/resizable and exposes Focus mode.- Preserve remembered-directory behavior: explicit paths win, then remembered path, then `$WORK_DIR`.- Empty mounted startup states must self-heal to the `$WORK_DIR` default instead of rendering a blank path and empty list.+- Preserve picker modes for Editor Open and Save As: Editor Open selects one or more Markdown or plain text files with a pinned primary action, and Save As selects the current folder plus a `.md` or `.txt` file name.+- Keep the row-level Open in Editor action visible outside the overflow menu for Editor-owned `.md` and `.txt` files.- Keep the file list readable in narrow canvas/modal containers by hiding the Modified date column before sacrificing the Name or Size columns.- Keep New file and New folder controls icon-only across canvas and modal modes while preserving accessible labels.- Keep narrow mobile controls compact: Up shares the path row, and New file/New folder share the search row.diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex d142bfba5..74c8c1277 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -10,8 +10,11 @@ import {const FILE_BROWSER_MODAL_PATH = "modals/file-browser/file-browser.html";const FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY = "fileBrowser.lastDirectory";const DEFAULT_REMEMBER_LAST_DIRECTORY = true;-const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdown"]);-const DESKTOP_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx", "txt"]);+const PICKER_MODE_NONE = "";+const PICKER_MODE_TEXT_OPEN = "text-open";+const PICKER_MODE_SAVE_AS = "save-as";+const EDITOR_TEXT_EXTENSIONS = new Set(["md", "txt"]);+const DESKTOP_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx"]);const BROWSER_EXTENSIONS = new Set(["html","htm",@@ -32,7 +35,7 @@ const SURFACE_ACTIONS = {editor: {label: "Open in Editor",icon: "article",- title: "Open Markdown in Editor",+ title: "Open text in Editor",},desktop: {label: "Open in Desktop",@@ -87,6 +90,12 @@ const model = {openDropdownPath: null, // Track which dropdown is currently opensearchQuery: "",isBulkBusy: false,+ pickerMode: PICKER_MODE_NONE,+ pickerConfirmLabel: "",+ pickerFilename: "",+ pickerDefaultExtension: "md",+ pickerFilenameError: "",+ pickerOnConfirm: null,// --- Lifecycle -----------------------------------------------------------init() {@@ -118,9 +127,9 @@ const model = {},// --- Public API (called from button/link) --------------------------------- async open(path = "") {+ async open(path = "", options = {}) {if (this.isLoading) return; // Prevent double-open- this.resetOpenState();+ this.resetOpenState(options);try {// Open modal FIRST (immediate UI feedback)@@ -164,6 +173,24 @@ const model = {window.closeModal(FILE_BROWSER_MODAL_PATH);},+ async openTextPicker(path = "", onConfirm = null) {+ return await this.open(path, {+ pickerMode: PICKER_MODE_TEXT_OPEN,+ confirmLabel: "Open Selected",+ onConfirm,+ });+ },++ async openSaveAsPicker(path = "", options = {}) {+ return await this.open(path, {+ pickerMode: PICKER_MODE_SAVE_AS,+ confirmLabel: "Save Here",+ filename: options.filename || "Untitled.md",+ defaultExtension: options.defaultExtension || "",+ onConfirm: options.onConfirm,+ });+ },+destroy() {this._floatingCleanup?.();this._floatingCleanup = null;@@ -184,6 +211,7 @@ const model = {this.pathInput = "";this.pathError = "";this.isPathSubmitting = false;+ this.resetPickerState();this.resetRenameState();},@@ -223,7 +251,7 @@ const model = {},// --- Helpers -------------------------------------------------------------- resetOpenState() {+ resetOpenState(options = {}) {this.cancelMountedDefaultLoad();this.isLoading = true;this.error = null;@@ -232,6 +260,32 @@ const model = {this.isBulkBusy = false;this.pathError = "";this.isPathSubmitting = false;+ this.configurePicker(options);+ },++ configurePicker(options = {}) {+ const mode = String(options?.pickerMode || PICKER_MODE_NONE).trim();+ this.pickerMode = [PICKER_MODE_TEXT_OPEN, PICKER_MODE_SAVE_AS].includes(mode)+ ? mode+ : PICKER_MODE_NONE;+ this.pickerConfirmLabel = String(options?.confirmLabel || "").trim()+ || (this.pickerMode === PICKER_MODE_SAVE_AS ? "Save Here" : "Open Selected");+ this.pickerFilename = String(options?.filename || "").trim();+ this.pickerDefaultExtension = this.normalizedEditorTextExtension(+ options?.defaultExtension || this.fileExtension({ name: this.pickerFilename }) || "md",+ );+ this.pickerFilenameError = "";+ this.pickerOnConfirm = typeof options?.onConfirm === "function" ? options.onConfirm : null;+ if (this.pickerMode) this.clearSelection();+ },++ resetPickerState() {+ this.pickerMode = PICKER_MODE_NONE;+ this.pickerConfirmLabel = "";+ this.pickerFilename = "";+ this.pickerDefaultExtension = "md";+ this.pickerFilenameError = "";+ this.pickerOnConfirm = null;},async loadOpeningPath(path = "") {@@ -328,9 +382,9 @@ const model = {get filteredEntries() {const query = this.searchQuery.trim().toLowerCase();- if (!query) return this.browser.entries;-return this.browser.entries.filter((file) => {+ if (!this.pickerAllowsEntry(file)) return false;+ if (!query) return true;const searchable = [file.name,file.path,@@ -354,7 +408,11 @@ const model = {},get selectedFiles() {- return this.browser.entries.filter((file) => file.selected);+ return this.browser.entries.filter((file) => file.selected && this.isSelectableEntry(file));+ },++ get selectableEntries() {+ return this.filteredEntries.filter((file) => this.isSelectableEntry(file));},get selectedCount() {@@ -367,18 +425,18 @@ const model = {get allVisibleSelected() {return (- this.filteredEntries.length > 0 &&- this.filteredEntries.every((file) => file.selected)+ this.selectableEntries.length > 0 &&+ this.selectableEntries.every((file) => file.selected));},get someVisibleSelected() {- return this.filteredEntries.some((file) => file.selected);+ return this.selectableEntries.some((file) => file.selected);},toggleSelectAllVisible() {const shouldSelect = !this.allVisibleSelected;- this.filteredEntries.forEach((file) => {+ this.selectableEntries.forEach((file) => {file.selected = shouldSelect;});},@@ -389,6 +447,24 @@ const model = {});},+ isPickerMode() {+ return this.pickerMode !== PICKER_MODE_NONE;+ },++ isTextOpenPicker() {+ return this.pickerMode === PICKER_MODE_TEXT_OPEN;+ },++ isSaveAsPicker() {+ return this.pickerMode === PICKER_MODE_SAVE_AS;+ },++ isSelectableEntry(file = {}) {+ if (this.isSaveAsPicker()) return false;+ if (this.isTextOpenPicker()) return !file?.is_dir && this.fileSurfaceTarget(file) === "editor";+ return true;+ },+normalizeOpeningPath(path) {return String(path || "").trim();},@@ -483,16 +559,138 @@ const model = {fileSurfaceTarget(file = {}) {if (!file || file.is_dir) return "";const ext = this.fileExtension(file);- if (MARKDOWN_EXTENSIONS.has(ext)) return "editor";+ if (EDITOR_TEXT_EXTENSIONS.has(ext)) return "editor";if (BROWSER_EXTENSIONS.has(ext)) return "browser";if (DESKTOP_EXTENSIONS.has(ext)) return "desktop";return "";},+ pickerAllowsEntry(file = {}) {+ if (!this.isTextOpenPicker()) return true;+ return Boolean(file?.is_dir || this.fileSurfaceTarget(file) === "editor");+ },++ pickerSelectedFiles() {+ if (!this.isTextOpenPicker()) return [];+ return this.selectedFiles.filter((file) => !file.is_dir && this.fileSurfaceTarget(file) === "editor");+ },++ pickerSelectionLabel() {+ if (!this.isTextOpenPicker()) return "";+ const count = this.pickerSelectedFiles().length;+ if (!count) return "No text files selected";+ return `${count} text ${count === 1 ? "file" : "files"} selected`;+ },++ normalizedEditorTextExtension(value = "") {+ const ext = String(value || "").toLowerCase().trim().replace(/^\./, "");+ return EDITOR_TEXT_EXTENSIONS.has(ext) ? ext : "md";+ },++ pickerFilenameValue() {+ const raw = String(this.pickerFilename || "").trim();+ if (!raw) return "";+ const ext = this.fileExtension({ name: raw });+ return ext ? raw : `${raw}.${this.pickerDefaultExtension || "md"}`;+ },++ validatePickerFilename(updateError = true) {+ if (!this.isSaveAsPicker()) return true;+ const raw = String(this.pickerFilename || "").trim();+ const filename = this.pickerFilenameValue();+ let error = "";+ if (!raw) {+ error = "File name is required.";+ } else if (raw === "." || raw === "..") {+ error = "File name cannot be '.' or '..'.";+ } else if (raw.includes("/") || raw.includes("\\")) {+ error = "File name cannot include path separators.";+ } else if (!EDITOR_TEXT_EXTENSIONS.has(this.fileExtension({ name: filename }))) {+ error = "Use a .md or .txt file name.";+ } else if ((this.browser.entries || []).some((entry) => entry?.name === filename)) {+ error = `An item named "${filename}" already exists.`;+ }+ if (updateError) this.pickerFilenameError = error;+ return !error;+ },++ onPickerFilenameInput() {+ if (this.pickerFilenameError) this.validatePickerFilename(true);+ },++ canConfirmPicker() {+ if (this.isTextOpenPicker()) return this.pickerSelectedFiles().length > 0;+ if (this.isSaveAsPicker()) return Boolean(this.pickerFilenameValue()) && !this.pickerFilenameError;+ return false;+ },++ pickerTargetPath() {+ if (!this.isSaveAsPicker()) return "";+ return this.buildChildPath(this.pickerFilenameValue());+ },++ togglePickerFile(file = {}) {+ if (!this.isTextOpenPicker() || file?.is_dir || this.fileSurfaceTarget(file) !== "editor") return;+ file.selected = !file.selected;+ },++ async confirmPicker() {+ if (!this.isPickerMode() || this.isBulkBusy) return;+ if (this.isSaveAsPicker() && !this.validatePickerFilename(true)) return;+ const payload = this.isSaveAsPicker()+ ? {+ mode: this.pickerMode,+ directory: this.browser.currentPath,+ filename: this.pickerFilenameValue(),+ path: this.pickerTargetPath(),+ }+ : {+ mode: this.pickerMode,+ directory: this.browser.currentPath,+ selectedFiles: this.pickerSelectedFiles(),+ };+ try {+ this.isBulkBusy = true;+ const result = await this.pickerOnConfirm?.(payload);+ if (result === false) return;+ this.disposeScopedTooltips();+ window.closeModal(FILE_BROWSER_MODAL_PATH);+ } catch (error) {+ const message = error?.message || "File selection failed";+ if (this.isSaveAsPicker()) this.pickerFilenameError = message;+ window.toastFrontendError?.(message, "File Browser");+ } finally {+ this.isBulkBusy = false;+ }+ },++ cancelPicker() {+ this.disposeScopedTooltips();+ window.closeModal(FILE_BROWSER_MODAL_PATH);+ },++ handleFileNameClick(file = {}) {+ if (file?.is_dir) {+ return this.navigateToFolder(file.path);+ }+ if (this.isTextOpenPicker()) {+ this.togglePickerFile(file);+ }+ },+canOpenInSurface(file = {}) {return Boolean(this.fileSurfaceTarget(file));},+ isEditorSurface(file = {}) {+ return this.fileSurfaceTarget(file) === "editor";+ },++ canOpenInActionMenu(file = {}) {+ const target = this.fileSurfaceTarget(file);+ return Boolean(target && target !== "editor");+ },+surfaceAction(file = {}) {const target = this.fileSurfaceTarget(file);return target ? SURFACE_ACTIONS[target] : null;@@ -1117,7 +1315,7 @@ const model = {if (!this.storeHasPath(editorStore, path)) {const session = await editorStore.openPath(path, { source: "file-browser" });if (!session || session.ok === false) {- throw new Error(editorStore.error || "Markdown could not be opened.");+ throw new Error(editorStore.error || "Text document could not be opened.");}}}diff --git a/webui/components/modals/file-browser/file-browser.html b/webui/components/modals/file-browser/file-browser.htmlindex 886cd7f95..c390caa30 100644--- a/webui/components/modals/file-browser/file-browser.html+++ b/webui/components/modals/file-browser/file-browser.html@@ -103,6 +103,7 @@<buttontype="button"class="btn btn-ok btn-new-item"+ x-show="!$store.fileBrowser.isPickerMode()"@click="$store.fileBrowser.openNewFile()"aria-label="New file"title="New file"@@ -112,6 +113,7 @@<buttontype="button"class="btn btn-ok btn-new-item"+ x-show="!$store.fileBrowser.isTextOpenPicker()"@click="$store.fileBrowser.openNewFolderModal()"aria-label="New folder"title="New folder"@@ -142,7 +144,7 @@</div></div>- <div x-show="$store.fileBrowser.selectedCount > 0" class="mass-action-toolbar file-mass-toolbar">+ <div x-show="$store.fileBrowser.selectedCount > 0 && !$store.fileBrowser.isPickerMode()" class="mass-action-toolbar file-mass-toolbar"><div class="selection-info" x-text="$store.fileBrowser.selectedCountLabel"></div><div class="mass-actions">@@ -201,6 +203,7 @@:checked="$store.fileBrowser.allVisibleSelected":indeterminate="$store.fileBrowser.someVisibleSelected && !$store.fileBrowser.allVisibleSelected"@change="$store.fileBrowser.toggleSelectAllVisible()"+ :disabled="$store.fileBrowser.selectableEntries.length === 0"title="Select visible items"aria-label="Select visible items"/>@@ -219,17 +222,29 @@<inputtype="checkbox"x-model="file.selected"+ :disabled="!$store.fileBrowser.isSelectableEntry(file)":aria-label="`Select ${file.name}`"/></label>- <div class="file-name" @click="file.is_dir && $store.fileBrowser.navigateToFolder(file.path)">+ <div class="file-name" @click="$store.fileBrowser.handleFileNameClick(file)"><img :src="'/public/' + (file.type === 'unknown' ? 'file' : ($store.fileBrowser.isArchive(file.name) ? 'archive' : file.type)) + '.svg'" class="file-icon" :alt="file.type" /><span x-text="file.name"></span></div><div class="file-size" x-text="$store.fileBrowser.formatFileSize(file.size)"></div><div class="file-date" x-text="$store.fileBrowser.formatDate(file.modified)"></div>- <div class="file-actions">- <!-- Single-item actions (Edit/Rename/...) are grouped under a dropdown -->+ <div class="file-actions" x-show="!$store.fileBrowser.isPickerMode()">+ <button+ type="button"+ class="btn-icon-action file-editor-open-action"+ x-show="$store.fileBrowser.isEditorSurface(file)"+ @click.stop="$store.fileBrowser.openInSurface(file)"+ :title="$store.fileBrowser.surfaceActionTitle(file)"+ aria-label="Open in Editor"+ >+ <span class="material-symbols-outlined" aria-hidden="true" x-text="$store.fileBrowser.surfaceActionIcon(file)"></span>+ </button>++ <!-- Secondary single-item actions (Rename/...) are grouped under a dropdown --><divclass="dropdown file-actions-dropdown"@click.outside="$store.fileBrowser.closeDropdown()"@@ -257,7 +272,7 @@<buttontype="button"class="dropdown-item"- x-show="$store.fileBrowser.canOpenInSurface(file)"+ x-show="$store.fileBrowser.canOpenInActionMenu(file)"@click="$store.fileBrowser.openInSurface(file)":title="$store.fileBrowser.surfaceActionTitle(file)">@@ -329,12 +344,45 @@<!-- Modal Footer (outside template x-if so it exists immediately) --><template x-if="$store.fileBrowser"><div class="modal-footer file-browser-footer" data-modal-footer :class="{ 'is-surface': xAttrs($el)?.mode === 'canvas' }">- <label class="btn btn-upload">+ <div class="file-browser-picker-actions" x-show="$store.fileBrowser.isPickerMode()" style="display: none;">+ <template x-if="$store.fileBrowser.isSaveAsPicker()">+ <div class="picker-filename-field">+ <span class="material-symbols-outlined" aria-hidden="true">article</span>+ <input+ type="text"+ class="picker-filename-input"+ x-model="$store.fileBrowser.pickerFilename"+ @input="$store.fileBrowser.onPickerFilenameInput()"+ @keydown.enter.prevent="$store.fileBrowser.confirmPicker()"+ placeholder="File name"+ aria-label="File name"+ spellcheck="false"+ />+ </div>+ </template>+ <span+ class="picker-selection-label"+ x-show="$store.fileBrowser.isTextOpenPicker()"+ x-text="$store.fileBrowser.pickerSelectionLabel()"+ ></span>+ <template x-if="$store.fileBrowser.pickerFilenameError">+ <span class="picker-inline-error" x-text="$store.fileBrowser.pickerFilenameError"></span>+ </template>+ <button+ type="button"+ class="btn btn-ok picker-confirm-button"+ :disabled="!$store.fileBrowser.canConfirmPicker() || $store.fileBrowser.isBulkBusy"+ @click="$store.fileBrowser.confirmPicker()"+ x-text="$store.fileBrowser.pickerConfirmLabel"+ ></button>+ <button type="button" class="btn btn-cancel" :disabled="$store.fileBrowser.isBulkBusy" @click="$store.fileBrowser.cancelPicker()">Cancel</button>+ </div>+ <label class="btn btn-upload" x-show="!$store.fileBrowser.isPickerMode()"><svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 0 0 5.25 21h13.5A2.25 2.25 0 0 0 21 18.75V16.5m-13.5-9L12 3m0 0 4.5 4.5M12 3v13.5"/></svg>Upload Files<input type="file" multiple accept="*" @change="$store.fileBrowser.handleFileUpload" style="display:none;" /></label>- <button class="btn btn-cancel" x-show="xAttrs($el)?.mode !== 'canvas'" @click="$store.fileBrowser.handleClose()">Close Browser</button>+ <button class="btn btn-cancel" x-show="xAttrs($el)?.mode !== 'canvas' && !$store.fileBrowser.isPickerMode()" @click="$store.fileBrowser.handleClose()">Close Browser</button></div></template></div>@@ -510,7 +558,7 @@border-radius: 4px;overflow: hidden;display: grid;- grid-template-columns: 2.5rem minmax(0, 1.5fr) minmax(5.5rem, 0.7fr) minmax(9rem, 1fr) 7.5rem;+ grid-template-columns: 2.5rem minmax(0, 1.5fr) minmax(5.5rem, 0.7fr) minmax(9rem, 1fr) 8.75rem;background: var(--secondary-bg);padding: 8px 0;font-weight: bold;@@ -534,7 +582,7 @@/* File Item Styles */.file-item {display: grid;- grid-template-columns: 2.5rem minmax(0, 1.5fr) minmax(5.5rem, 0.7fr) minmax(9rem, 1fr) 7.5rem;+ grid-template-columns: 2.5rem minmax(0, 1.5fr) minmax(5.5rem, 0.7fr) minmax(9rem, 1fr) 8.75rem;align-items: center;padding: 8px 0;font-size: 0.875rem;@@ -860,6 +908,71 @@background: color-mix(in srgb, var(--color-panel) 90%, var(--color-background) 10%);}+ .file-browser-picker-actions {+ display: flex;+ flex: 1 1 auto;+ align-items: center;+ justify-content: flex-end;+ gap: var(--spacing-sm);+ min-width: 0;+ }++ .picker-filename-field {+ display: flex;+ align-items: center;+ flex: 1 1 16rem;+ max-width: 24rem;+ min-width: 10rem;+ height: 2.35rem;+ border: 1px solid var(--color-border);+ border-radius: 7px;+ background: var(--color-input);+ color: var(--color-text);+ }++ .picker-filename-field .material-symbols-outlined {+ flex: 0 0 auto;+ padding-left: 0.65rem;+ color: var(--color-primary);+ font-size: 1.1rem;+ opacity: 0.78;+ }++ .picker-filename-input {+ flex: 1 1 auto;+ width: 100%;+ min-width: 0;+ height: 100%;+ border: 0;+ outline: 0;+ background: transparent;+ color: var(--color-text);+ padding: 0 0.7rem;+ font: inherit;+ }++ .picker-selection-label,+ .picker-inline-error {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ font-size: 0.82rem;+ font-weight: 700;+ letter-spacing: 0;+ }++ .picker-selection-label {+ color: var(--color-text-secondary);+ }++ .picker-inline-error {+ color: var(--color-error);+ }++ .picker-confirm-button {+ min-width: 7.6rem;+ }+/* File Actions */.file-actions {display: flex;@@ -867,6 +980,10 @@justify-content: flex-end;padding-right: 0.5rem;}+ .file-editor-open-action {+ border-color: color-mix(in srgb, var(--color-primary) 52%, var(--color-border));+ background: color-mix(in srgb, var(--color-primary) 10%, transparent);+ }.file-actions .dropdown-menu {top: auto !important;bottom: 100% !important;@@ -929,15 +1046,19 @@height: 2.5rem;}.file-header {- grid-template-columns: 2.25rem minmax(0, 1fr) minmax(5rem, 0.52fr) 7.5rem;+ grid-template-columns: 2.25rem minmax(0, 1fr) minmax(5rem, 0.52fr) 8.75rem;}.file-item {- grid-template-columns: 2.25rem minmax(0, 1fr) minmax(5rem, 0.5fr) 7.5rem;+ grid-template-columns: 2.25rem minmax(0, 1fr) minmax(5rem, 0.5fr) 8.75rem;}.file-cell-date,.file-date {display: none;}+ .file-actions {+ gap: 0.2rem;+ padding-right: 0.2rem;+ }}@media (max-width: 540px) {.path-navigator .back-button {@@ -949,7 +1070,7 @@}.file-header,.file-item {- grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 5.25rem;+ grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 8rem;}.file-cell-date,.file-date {@@ -959,14 +1080,26 @@@container file-browser (max-width: 620px) {.file-header,.file-item {- grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 5.25rem;+ grid-template-columns: 2.25rem minmax(0, 1fr) minmax(4.25rem, max-content) 8rem;}.file-cell-date,.file-date {display: none;}.file-actions {- padding-right: 0.35rem;+ gap: 0.2rem;+ padding-right: 0.2rem;+ }+ .file-browser-picker-actions {+ flex-wrap: wrap;+ justify-content: stretch;+ }+ .picker-filename-field {+ flex-basis: 100%;+ max-width: none;+ }+ .picker-confirm-button {+ flex: 1 1 auto;}}</style>