Skip to content

Agent Zero AI framework

Unify text and code editing in the shared Editor

Alessandro376191cf66d4
diff --git a/plugins/AGENTS.md b/plugins/AGENTS.md
index d206d4fae..42df7df75 100644
--- a/plugins/AGENTS.md
+++ b/plugins/AGENTS.md
@@ -81,7 +81,7 @@ Direct child DOX files:
| [_desktop/AGENTS.md](_desktop/AGENTS.md) | Linux desktop runtime, sessions, and desktop surface. |
| [_discovery/AGENTS.md](_discovery/AGENTS.md) | Welcome-screen plugin discovery cards and promotions. |
| [_document_query/AGENTS.md](_document_query/AGENTS.md) | Document parsing, indexing, and Q&A tools. |
-| [_editor/AGENTS.md](_editor/AGENTS.md) | Native Markdown editor surface and sessions. |
+| [_editor/AGENTS.md](_editor/AGENTS.md) | Shared text/code editor surface and sessions. |
| [_email_integration/AGENTS.md](_email_integration/AGENTS.md) | IMAP/Exchange polling and SMTP reply integration. |
| [_error_retry/AGENTS.md](_error_retry/AGENTS.md) | Critical exception retry lifecycle hooks. |
| [_goal/AGENTS.md](_goal/AGENTS.md) | Built-in chat goal strip, `/goal` slash command, and agent-facing goal tools. |
diff --git a/plugins/_editor/AGENTS.md b/plugins/_editor/AGENTS.md
index 515c86445..d1ea602ce 100644
--- a/plugins/_editor/AGENTS.md
+++ b/plugins/_editor/AGENTS.md
@@ -2,7 +2,7 @@
## Purpose
-- Own the native Markdown and plain text editor surface for canvas and floating modal workflows.
+- Own the shared UTF-8 text and code editor surface for canvas and floating modal workflows.
## Ownership
@@ -14,17 +14,22 @@
## Local Contracts
+- This always-enabled plugin is the sole file-editing UI; Files Edit and New file route here. The retired `modals/file-editor` UI is removed.
+- Ctrl+F in source mode belongs to ACE; the preview search handles only preview mode and closes when returning to source.
+- Source mode uses ACE line numbers and its bundled filename-to-language mapping; JSONL uses JSON highlighting. Preview and formatting controls remain available only for Markdown/plain text.
+- Accept UTF-8 files up to 1 MiB, reject binary content and invalid encoding, and retain save-conflict protection. Authenticated Files opens, creation, Rename, and Save As retain File Browser filesystem access; agent artifact paths remain scoped.
+- Tool-result refreshes update already-open code files as well as Markdown, preserving dirty tabs and the existing explicit Markdown handoff policy.
- 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 Editor Open wired through the File Browser text picker so users can open one or more text or code files with an obvious confirmation action.
- Keep Download in the Editor file-actions menu and save dirty text before downloading it.
-- 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.
+- Keep Save As distinct from Rename: Save As writes the current editor text to a chosen text-file path, including extensionless names, and retargets the active session without removing the original file.
- Keep Markdown and plain text on the same toolbar, with full-document source and preview modes plus shared Undo/Redo buttons and keyboard shortcuts.
- Preserve source chat context ids when opening Markdown files from tool-result canvas handoffs.
- The tab header owns a persistent file-tree toggle, including the empty Editor state. Reuse the shared Files tree component with Editor-owned state, seeded from the active document directory or Files fallback.
-- Opening an already-open document from the tree selects its tab without reloading unsaved text. Unsupported editor formats retain the existing Files surface/editor routing.
+- Opening an already-open document from the tree selects its tab without reloading unsaved text. Code files open here too; binary previews retain the existing Browser/Desktop routing.
- The right-hand tree uses the same content in canvas/modal hosts and overlays the document at narrow panel widths.
- Mount cleanup is host-specific: canvas close passes its panel element so a late canvas close cannot tear down the active modal.
diff --git a/plugins/_editor/api/editor_session.py b/plugins/_editor/api/editor_session.py
index 60dbf4578..8844d7b45 100644
--- a/plugins/_editor/api/editor_session.py
+++ b/plugins/_editor/api/editor_session.py
@@ -36,6 +36,18 @@ class EditorSession(ApiHandler):
file_id="" if store_session_id else file_id,
)
return closed
+ if action == "create" and self._is_file_browser_open(input):
+ try:
+ path = document_store.normalize_path(str(input["path"]), file_browser=True)
+ if not document_store.is_editor_document({"extension": path.suffix.lstrip(".")}):
+ raise ValueError("Use Desktop to create office documents.")
+ data = document_store.editor_text_bytes(str(input.get("content") or ""))
+ with path.open("xb") as stream:
+ stream.write(data)
+ doc = document_store.register_document(path, context_id=context_id, file_browser=True)
+ except Exception as exc:
+ return {"ok": False, "error": str(exc)}
+ return await self._open_document(doc, input, request, context_id=context_id)
if action == "create":
fmt = str(input.get("format") or "md").lower().lstrip(".")
if fmt not in document_store.EDITOR_TEXT_EXTENSIONS:
@@ -61,7 +73,7 @@ class EditorSession(ApiHandler):
else document_store.register_document(
str(input.get("path") or ""),
context_id=context_id,
- allow_base_dir=self._allow_base_dir_open(input),
+ file_browser=self._is_file_browser_open(input),
)
)
except Exception as exc:
@@ -80,7 +92,7 @@ class EditorSession(ApiHandler):
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"))
+ result = markdown_sessions.get_manager().save_as(session_id, path, text=input.get("text"), file_browser=True)
except Exception as exc:
return {"ok": False, "error": str(exc)}
document_store.close_session(session_id=str(input.get("store_session_id") or "").strip())
@@ -107,7 +119,7 @@ class EditorSession(ApiHandler):
request: Request,
context_id: str = "",
) -> dict:
- if str(doc.get("extension") or "").lower() not in document_store.EDITOR_TEXT_EXTENSIONS:
+ if not document_store.is_editor_document(doc):
return {
"ok": False,
"error": f".{doc.get('extension', '')} documents use the Desktop surface.",
@@ -152,6 +164,7 @@ class EditorSession(ApiHandler):
path,
content=input.get("text") if "text" in input else None,
context_id=context_id,
+ file_browser=True,
)
markdown_sessions.get_manager().renamed(
file_id,
@@ -171,7 +184,7 @@ class EditorSession(ApiHandler):
origin = request.headers.get("Origin") or request.host_url.rstrip("/")
return origin.rstrip("/")
- def _allow_base_dir_open(self, input: dict) -> bool:
+ def _is_file_browser_open(self, input: dict) -> bool:
if str(input.get("source") or "").strip() != "file-browser":
return False
return bool(str(input.get("path") or "").strip())
diff --git a/plugins/_editor/extensions/webui/set_messages_after_loop/sync-text-editor-results.js b/plugins/_editor/extensions/webui/set_messages_after_loop/sync-text-editor-results.js
index f4b2947f6..935771465 100644
--- a/plugins/_editor/extensions/webui/set_messages_after_loop/sync-text-editor-results.js
+++ b/plugins/_editor/extensions/webui/set_messages_after_loop/sync-text-editor-results.js
@@ -13,7 +13,7 @@ export default async function syncTextEditorResultsIntoOpenEditor(context) {
if (!shouldSyncTextEditorResult(args, payload)) continue;
const target = textEditorTarget(payload);
- if (!target.path || target.extension !== "md") continue;
+ if (!target.path) continue;
const explicitOpen = shouldOpenEditorUiFromResult(payload, target);
if (context.historyEmpty && !explicitOpen) continue;
diff --git a/plugins/_editor/helpers/markdown_sessions.py b/plugins/_editor/helpers/markdown_sessions.py
index 0347fa3cb..e8e721d05 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 and plain text documents."""
+ """Owns native Editor sessions for UTF-8 text and code files."""
def __init__(self) -> None:
self._sessions: dict[str, MarkdownSession] = {}
@@ -39,13 +39,13 @@ 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 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.")
+ if not document_store.is_editor_document(doc):
+ raise ValueError(f"Editor is only available for text files. Open .{ext} files in the Desktop.")
normalized_context = str(context_id or "")
if refresh:
try:
- doc = document_store.register_document(doc["path"], context_id=normalized_context)
+ doc = document_store.register_document(doc["path"], context_id=normalized_context, file_browser=True)
except Exception:
pass
@@ -123,7 +123,7 @@ class MarkdownSessionManager:
"version": document_store.item_version(updated),
}
- def save_as(self, session_id: str, path: str, text: str | None = None) -> dict[str, Any]:
+ def save_as(self, session_id: str, path: str, text: str | None = None, *, file_browser: bool = False) -> dict[str, Any]:
session = self._require(session_id)
if text is not None:
session.text = str(text)
@@ -133,6 +133,7 @@ class MarkdownSessionManager:
path,
session.text,
context_id=session.context_id,
+ file_browser=file_browser,
)
old_file_id = session.file_id
session.file_id = updated["file_id"]
@@ -173,7 +174,7 @@ class MarkdownSessionManager:
doc = document_store.get_document(normalized)
except Exception:
return {"ok": False, "refreshed": 0, "sessions": []}
- if str(doc.get("extension") or "").lower() not in document_store.EDITOR_TEXT_EXTENSIONS:
+ if not document_store.is_editor_document(doc):
return {"ok": True, "refreshed": 0, "sessions": []}
refreshed = self._refresh_file_sessions(
@@ -203,7 +204,7 @@ class MarkdownSessionManager:
continue
session = sessions[0]
try:
- doc = document_store.register_document(session.path, context_id=session.context_id)
+ doc = document_store.register_document(session.path, context_id=session.context_id, file_browser=True)
except Exception:
try:
doc = document_store.get_document(file_id)
@@ -312,7 +313,7 @@ class MarkdownSessionManager:
if expected_sha and current_sha != expected_sha:
if current_exists and desired_sha == current_sha:
- updated = document_store.register_document(path, context_id=session.context_id)
+ updated = document_store.register_document(path, context_id=session.context_id, file_browser=True)
session.dirty = False
session.path = updated["path"]
session.title = updated["basename"]
@@ -449,7 +450,7 @@ def _refresh_registered_doc(doc: dict[str, Any], context_id: str = "") -> dict[s
try:
path = Path(doc["path"])
if path.exists():
- return document_store.register_document(path, context_id=context_id)
+ return document_store.register_document(path, context_id=context_id, file_browser=True)
except Exception:
pass
return doc
diff --git a/plugins/_editor/plugin.yaml b/plugins/_editor/plugin.yaml
index 16e76409c..bcbfe540f 100644
--- a/plugins/_editor/plugin.yaml
+++ b/plugins/_editor/plugin.yaml
@@ -1,5 +1,5 @@
name: _editor
title: Editor
-description: Native Markdown editor surface for Agent Zero canvas and floating modal workflows.
+description: Text and code editor surface for Agent Zero canvas and floating modal workflows.
version: 1.0.0
-always_enabled: false
+always_enabled: true
diff --git a/plugins/_editor/webui/editor-panel.html b/plugins/_editor/webui/editor-panel.html
index fbf4791db..32d0c4c4d 100644
--- a/plugins/_editor/webui/editor-panel.html
+++ b/plugins/_editor/webui/editor-panel.html
@@ -97,7 +97,7 @@
<button
type="button"
class="editor-icon-button surface-control editor-mode-toggle"
- x-show="$store.editor.isTextDocument()"
+ x-show="$store.editor.canPreview()"
style="display: none;"
:title="$store.editor.viewModeTitle()"
:aria-label="$store.editor.viewModeTitle()"
@@ -115,7 +115,7 @@
</button>
</div>
- <div class="editor-tool-group surface-toolbar-group editor-source-tools" x-show="$store.editor.isTextDocument() && $store.editor.isSourceMode()" style="display: none;">
+ <div class="editor-tool-group surface-toolbar-group editor-source-tools" x-show="$store.editor.canPreview() && $store.editor.isSourceMode()" style="display: none;">
<button type="button" class="editor-icon-button surface-control" title="Bold" aria-label="Bold" @click="$store.editor.format('bold')">
<x-icon name="format_bold"></x-icon>
</button>
@@ -199,7 +199,7 @@
<span>Close File</span>
</button>
<button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.loading || $store.editor.visibleTabs().length === 0" @click="open = false; $store.editor.closeAllFiles()">
- <x-icon aria-hidden="true" name="close"></x-icon>
+ <x-icon aria-hidden="true" name="layers_clear"></x-icon>
<span>Close All</span>
</button>
</div>
@@ -819,14 +819,6 @@
font: 13px/1.55 ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
}
- .editor-ace .ace_gutter {
- display: none !important;
- }
-
- .editor-ace .ace_scroller {
- left: 0 !important;
- }
-
.editor-source-editor {
box-sizing: border-box;
width: 100%;
diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.js
index 8061fff4a..f5166dca6 100644
--- a/plugins/_editor/webui/editor-store.js
+++ b/plugins/_editor/webui/editor-store.js
@@ -55,18 +55,6 @@ 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;
@@ -226,10 +214,10 @@ const model = {
async openTreeEntry(file) {
if (file.is_dir || this.loading || this.saving) return;
- if (fileBrowserStore.isEditorSurface(file)) {
+ if (fileBrowserStore.isEditableFile(file)) {
const tab = this.tabs.find(tab => tab.path === file.path);
if (tab) return this.selectTab(tab.tab_id);
- return this.openPath(file.path);
+ return this.openPath(file.path, { source: "file-browser" });
}
if (fileBrowserStore.canOpenInSurface(file)) return fileBrowserStore.openInSurface(file);
return fileBrowserStore.openFileEditor(file);
@@ -360,13 +348,14 @@ const model = {
},
async setViewMode(mode) {
- const next = mode === PREVIEW_MODE && this.isTextDocument() ? PREVIEW_MODE : SOURCE_MODE;
+ const next = mode === PREVIEW_MODE && this.canPreview() ? PREVIEW_MODE : SOURCE_MODE;
if (this.viewMode === next) return;
this.applyPreviewEdit({ silent: true });
this.syncEditorText();
this.viewMode = next;
this.cancelPendingClose();
if (next === SOURCE_MODE) {
+ this.closeSearch();
this.setSourceEditorText(this.editorText);
this.scheduleSourceEditorInit();
this.refreshSourceEditorLayout();
@@ -709,10 +698,7 @@ const model = {
},
openSearch() {
- if (!this.isTextDocument()) return;
- if (!this.isPreviewMode()) {
- this.setViewMode(PREVIEW_MODE);
- }
+ if (!this.isTextDocument() || !this.isPreviewMode()) return;
this.searchOpen = true;
this.runSearch();
globalThis.requestAnimationFrame?.(() => {
@@ -884,8 +870,9 @@ const model = {
this[historyAction]();
return;
}
- if (key === "f") {
+ if (key === "f" && this.isPreviewMode()) {
event.preventDefault();
+ event.stopPropagation();
this.openSearch();
}
},
@@ -942,6 +929,14 @@ const model = {
},
async openSession(payload = {}) {
+ const tab = this.tabs.find(tab => (payload.file_id && tab.file_id === payload.file_id)
+ || (payload.path && tab.path === payload.path));
+ if (tab && this.isTabDirty(tab)) {
+ this.selectTab(tab.tab_id);
+ return tab;
+ }
+ this.applyPreviewEdit({ silent: true });
+ this.syncEditorText();
this.loading = true;
this.error = "";
try {
@@ -992,6 +987,10 @@ const model = {
hydrateActiveSession(tab, options = {}) {
this.session = tab || null;
+ if (!this.canPreview(tab)) {
+ this.viewMode = SOURCE_MODE;
+ this.closeSearch();
+ }
this.activeTabId = tab?.tab_id || "";
this.editorText = String(tab?.text || "");
this.dirty = Boolean(tab?.dirty);
@@ -1209,11 +1208,11 @@ const model = {
editor.session.setUseWrapMode(true);
editor.setOptions({
fontSize: "13px",
- showGutter: false,
+ showGutter: true,
showPrintMargin: false,
useWorker: false,
});
- editor.renderer.setShowGutter(false);
+ editor.renderer.setShowGutter(true);
editor.renderer.setScrollMargin(14, 14, 0, 0);
editor.setValue(this.editorText || "", -1);
this._sourceEditorChangeHandler = () => {
@@ -1224,12 +1223,14 @@ const model = {
editor.session.on("change", this._sourceEditorChangeHandler);
this.sourceEditor = editor;
this.aceUnavailable = false;
- this.updateSourceEditorMode();
+ globalThis.ace.config.loadModule("ace/ext/modelist", () => this.updateSourceEditorMode());
this.queueRender({ focus: Boolean(this.session), end: false });
},
sourceEditorMode(tab = this.session) {
- return this.isMarkdown(tab) ? "ace/mode/markdown" : "ace/mode/text";
+ const path = tab?.path || tab?.document?.path || tab?.title || "";
+ if (extensionOf(path) === "jsonl") return "ace/mode/json";
+ return globalThis.ace?.require("ace/ext/modelist")?.getModeForPath(path).mode || "ace/mode/text";
},
updateSourceEditorMode(tab = this.session) {
@@ -1335,8 +1336,8 @@ const model = {
}
await fileBrowserStore.openSaveAsPicker(startPath, {
- filename: textDocumentFilename(this.session.path || this.session.title || "Untitled.md"),
- defaultExtension: textDocumentDefaultExtension(this.session.path || this.session.title || "Untitled.md"),
+ filename: basename(this.session.path || this.session.title || "Untitled.md"),
+ defaultExtension: "",
onConfirm: async ({ path } = {}) => {
if (!path) return false;
await this.saveAsPath(path);
@@ -1707,11 +1708,15 @@ const model = {
return ext === "md";
},
- isTextDocument(tab = this.session) {
+ canPreview(tab = this.session) {
const ext = String(tab?.extension || tab?.document?.extension || "").toLowerCase();
return EDITOR_TEXT_EXTENSIONS.has(ext);
},
+ isTextDocument(tab = this.session) {
+ return Boolean(tab?.session_id);
+ },
+
hasActiveFile(tab = this.session) {
return Boolean(tab && this.isTextDocument(tab));
},
diff --git a/plugins/_office/AGENTS.md b/plugins/_office/AGENTS.md
index 0d9c5f2c6..686bf92d8 100644
--- a/plugins/_office/AGENTS.md
+++ b/plugins/_office/AGENTS.md
@@ -14,10 +14,13 @@
## Local Contracts
- Preserve document storage integrity and live session synchronization.
+- 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.
- Route APT commands through `system_packages.run_runtime_apt`; Kali repairs must use the build's snapshot when resolving LibreOffice/UNO dependencies.
- 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.
+- Text registration and Editor writes reject binary content, invalid UTF-8, and files over 1 MiB. Office template formats remain unchanged. Only explicit authenticated Editor/File Browser operations opt into filesystem-root paths; default artifact paths stay workspace-scoped.
+- Editor text Save As storage helpers must preserve exact UTF-8 text for arbitrary text/code filenames and create a new registered document without mutating or deleting the source document.
## Work Guidance
diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.py
index f73077afd..7a4cad12a 100644
--- a/plugins/_office/helpers/document_store.py
+++ b/plugins/_office/helpers/document_store.py
@@ -7,6 +7,7 @@ import json
import os
import re
import sqlite3
+import stat
import time
import uuid
import zipfile
@@ -27,6 +28,7 @@ EDITOR_TEXT_EXTENSIONS = {"md", "txt"}
SUPPORTED_EXTENSIONS = {*EDITOR_TEXT_EXTENSIONS, *OPEN_DOCUMENT_EXTENSIONS, *OOXML_EXTENSIONS}
DEFAULT_TTL_SECONDS = 8 * 60 * 60
MAX_SAVE_BYTES = 512 * 1024 * 1024
+MAX_EDITOR_BYTES = 1024 * 1024
ODF_OFFICE_NS = "urn:oasis:names:tc:opendocument:xmlns:office:1.0"
ODF_TEXT_NS = "urn:oasis:names:tc:opendocument:xmlns:text:1.0"
ODF_TABLE_NS = "urn:oasis:names:tc:opendocument:xmlns:table:1.0"
@@ -59,7 +61,10 @@ def now_iso() -> str:
def ensure_dirs() -> None:
STATE_DIR.mkdir(parents=True, exist_ok=True)
- BACKUP_DIR.mkdir(parents=True, exist_ok=True)
+ BACKUP_DIR.mkdir(mode=0o700, parents=True, exist_ok=True)
+ if BACKUP_DIR.stat().st_uid != os.geteuid():
+ os.chown(BACKUP_DIR, os.geteuid(), -1)
+ BACKUP_DIR.chmod(0o700)
def sha256_bytes(data: bytes) -> str:
@@ -157,10 +162,10 @@ def _settings() -> Any:
return settings
-def normalize_path(path: str | Path, context_id: str = "", allow_base_dir: bool = False) -> Path:
+def normalize_path(path: str | Path, context_id: str = "", allow_base_dir: bool = False, file_browser: bool = False) -> Path:
candidate = _path_from_a0(path)
resolved = candidate.resolve(strict=False)
- roots = allowed_roots(context_id, allow_base_dir=allow_base_dir)
+ roots = [Path("/")] if file_browser else allowed_roots(context_id, allow_base_dir=allow_base_dir)
if not any(_is_relative_to(resolved, root) for root in roots):
raise PermissionError("Document artifacts must stay inside the active project or workdir.")
if candidate.exists():
@@ -243,11 +248,14 @@ def register_document(
owner_id: str = "a0",
context_id: str = "",
allow_base_dir: bool = False,
+ file_browser: bool = False,
) -> dict[str, Any]:
- resolved = normalize_path(path, context_id=context_id, allow_base_dir=allow_base_dir)
+ resolved = normalize_path(path, context_id=context_id, allow_base_dir=allow_base_dir, file_browser=file_browser)
if not resolved.exists():
raise FileNotFoundError(str(resolved))
- ext = normalize_extension(resolved.suffix.lstrip("."))
+ ext = resolved.suffix.lstrip(".").lower()
+ if is_editor_document({"extension": ext}):
+ read_text_for_editor({"path": str(resolved), "extension": ext})
data = resolved.read_bytes()
digest = sha256_bytes(data)
stat = resolved.stat()
@@ -295,7 +303,9 @@ def update_document_path(file_id: str, path: str | Path, context_id: str = "") -
resolved = normalize_path(path, context_id=context_id)
if not resolved.exists():
raise FileNotFoundError(str(resolved))
- ext = normalize_extension(resolved.suffix.lstrip("."))
+ ext = resolved.suffix.lstrip(".").lower()
+ if is_editor_document({"extension": ext}):
+ read_text_for_editor({"path": str(resolved), "extension": ext})
data = resolved.read_bytes()
digest = sha256_bytes(data)
stat = resolved.stat()
@@ -331,16 +341,15 @@ def rename_document(
path: str | Path,
content: str | None = None,
context_id: str = "",
+ file_browser: bool = False,
) -> dict[str, Any]:
- resolved = normalize_path(path, context_id=context_id)
- ext = normalize_extension(resolved.suffix.lstrip("."))
+ resolved = normalize_path(path, context_id=context_id, file_browser=file_browser)
+ ext = resolved.suffix.lstrip(".").lower()
data = None
if content is not None:
- if ext not in EDITOR_TEXT_EXTENSIONS:
+ if not is_editor_document({"extension": ext}):
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")
+ data = editor_text_bytes(str(content or ""))
changed_at = now()
with connect() as conn:
@@ -371,7 +380,7 @@ def rename_document(
elif data is not None:
if content_changed:
_record_version(conn, file_id, source_resolved, item_version(doc), previous)
- _write_atomic(resolved, data)
+ _write_atomic(resolved, data, source=source)
if changed_path and source_exists:
source.unlink(missing_ok=True)
final_data = data
@@ -492,20 +501,39 @@ def close_session(session_id: str = "", file_id: str = "") -> int:
return len(rows)
+def is_editor_document(doc: dict[str, Any]) -> bool:
+ return str(doc.get("extension") or "").lower() not in OPEN_DOCUMENT_EXTENSIONS | OOXML_EXTENSIONS
+
+
+def editor_text_bytes(content: str) -> bytes:
+ data = content.encode("utf-8")
+ if len(data) > MAX_EDITOR_BYTES:
+ raise ValueError("File exceeds 1 MB and cannot be edited")
+ if files.is_probably_binary_bytes(data):
+ raise ValueError("Binary file detected; editing is not supported")
+ return data
+
+
def read_text_for_editor(doc: dict[str, Any]) -> str:
- path = Path(doc["path"])
- ext = str(doc["extension"]).lower()
- 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}.")
+ if not is_editor_document(doc):
+ raise ValueError(f"Text editing is not available for .{doc['extension']}.")
+ with Path(doc["path"]).open("rb") as stream:
+ data = stream.read(MAX_EDITOR_BYTES + 1)
+ if len(data) > MAX_EDITOR_BYTES:
+ raise ValueError("File exceeds 1 MB and cannot be edited")
+ if files.is_probably_binary_bytes(data):
+ raise ValueError("Binary file detected; editing is not supported")
+ try:
+ return data.decode("utf-8")
+ except UnicodeDecodeError as exc:
+ raise ValueError("Unable to decode file as UTF-8; editing is not supported") from exc
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}")
+ if not is_editor_document(doc):
+ raise ValueError(f"Editor text saves are not available for .{doc['extension']}.")
+ return replace_document_bytes(file_id, editor_text_bytes(str(content or "")), actor=f"editor:{doc['extension']}")
def write_markdown(file_id: str, content: str) -> dict[str, Any]:
@@ -517,26 +545,25 @@ def save_text_document_as(
path: str | Path,
content: str,
context_id: str = "",
+ file_browser: bool = False,
) -> 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.")
+ target = normalize_path(path, context_id=context_id, file_browser=file_browser)
+ ext = target.suffix.lstrip(".").lower()
+ if not is_editor_document({"extension": ext}):
+ raise ValueError("Editor Save As requires a text file, not an office document.")
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")
+ data = editor_text_bytes(str(content or ""))
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:
+ if not is_editor_document(source):
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)
+ _write_atomic(target, data, source=Path(source["path"]))
digest = sha256_bytes(data)
stat = target.stat()
new_file_id = uuid.uuid4().hex
@@ -623,13 +650,20 @@ def item_version(doc: dict[str, Any]) -> str:
return f"{int(doc['version'])}-{str(doc['sha256'])[:12]}"
-def _write_atomic(path: Path, data: bytes) -> None:
+def _write_atomic(path: Path, data: bytes, *, source: Path | None = None) -> None:
+ source = source or path
+ metadata = source.stat() if source.exists() else None
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")
try:
- with tmp_path.open("wb") as handle:
+ with os.fdopen(os.open(tmp_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as handle:
handle.write(data)
handle.flush()
+ if metadata:
+ current = os.fstat(handle.fileno())
+ if (current.st_uid, current.st_gid) != (metadata.st_uid, metadata.st_gid):
+ os.fchown(handle.fileno(), metadata.st_uid, metadata.st_gid)
+ os.fchmod(handle.fileno(), stat.S_IMODE(metadata.st_mode))
os.fsync(handle.fileno())
os.replace(tmp_path, path)
finally:
@@ -644,9 +678,9 @@ def _clear_expired_sessions(conn: sqlite3.Connection) -> None:
def _record_version(conn: sqlite3.Connection, file_id: str, path: Path, version: str, data: bytes) -> None:
if not data:
return
- BACKUP_DIR.mkdir(parents=True, exist_ok=True)
- backup_path = BACKUP_DIR / f"{file_id}-{int(time.time() * 1000)}-{version.replace('/', '_')}"
- backup_path.write_bytes(data)
+ backup_path = BACKUP_DIR / f"{file_id}-{uuid.uuid4().hex}-{version.replace('/', '_')}"
+ with os.fdopen(os.open(backup_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as handle:
+ handle.write(data)
conn.execute(
"INSERT INTO versions (file_id, version, path, size, sha256, created_at) VALUES (?, ?, ?, ?, ?, ?)",
(file_id, version, str(backup_path), len(data), sha256_bytes(data), now()),
diff --git a/tests/test_editor_files.py b/tests/test_editor_files.py
new file mode 100644
index 000000000..d20309198
--- /dev/null
+++ b/tests/test_editor_files.py
@@ -0,0 +1,111 @@
+"""File routing and shared Editor state, executed without a browser."""
+from pathlib import Path
+import re
+import subprocess
+
+
+def test_shared_editor_file_routing_and_dirty_tabs():
+ def model(path):
+ source = Path(path).read_text()
+ source = re.sub(r'^import\b[\s\S]*?;\n', '', source, flags=re.M)
+ return source.replace('export const store = createStore', 'const store = createStore')
+
+ browser = model('webui/components/modals/file-browser/file-browser-store.js')
+ editor = model('plugins/_editor/webui/editor-store.js')
+ script = r'''
+import assert from 'node:assert/strict';
+const window = globalThis;
+const createStore = (_name, model) => model;
+const createFileTree = () => ({});
+const getNamespacedClient = () => ({ addHandlers() {} });
+const registerUrlHandler = () => {};
+const opened = [];
+const openLatestSurface = async (...args) => opened.push(args);
+const fileBrowserStore = (() => {
+''' + browser + r'''
+return store;
+})();
+const file = name => ({ name, path: `/a0/${name}`, size: 42 });
+for (const name of ['file.py', 'probe.jsonl', 'config.yaml', 'Dockerfile', '.env', 'file.unknown', 'note.md', 'note.txt']) {
+ assert.equal(fileBrowserStore.fileSurfaceTarget(file(name)), 'editor', name);
+}
+assert.equal(fileBrowserStore.fileSurfaceTarget(file('page.html')), 'browser');
+assert.equal(fileBrowserStore.fileSurfaceTarget(file('sheet.xlsx')), 'desktop');
+assert.equal(fileBrowserStore.isEditableFile(file('page.html')), true);
+assert.equal(fileBrowserStore.isEditableFile(file('image.png')), false);
+assert.equal(fileBrowserStore.isEditableFile({ ...file('big.py'), size: 1048577 }), false);
+fileBrowserStore.configurePicker({ pickerMode: 'text-open' });
+assert.equal(fileBrowserStore.pickerAllowsEntry(file('page.html')), true);
+fileBrowserStore.configurePicker({ pickerMode: 'save-as', filename: 'Dockerfile', defaultExtension: '' });
+assert.equal(fileBrowserStore.pickerFilenameValue(), 'Dockerfile');
+assert.equal(fileBrowserStore.validatePickerFilename(), true);
+fileBrowserStore.pickerFilename = '../escape.py';
+assert.equal(fileBrowserStore.validatePickerFilename(), false);
+const canvasRow = {}, modalRow = {};
+fileBrowserStore.getDropdownStyle = () => ({});
+fileBrowserStore.toggleDropdown('/a0/test.py', { closest: () => canvasRow });
+assert.equal(fileBrowserStore.isDropdownOpen('/a0/test.py', canvasRow), true);
+assert.equal(fileBrowserStore.isDropdownOpen('/a0/test.py', modalRow), false);
+fileBrowserStore.toggleDropdown('/a0/test.py', { closest: () => modalRow });
+assert.equal(fileBrowserStore.isDropdownOpen('/a0/test.py', canvasRow), false);
+assert.equal(fileBrowserStore.isDropdownOpen('/a0/test.py', modalRow), true);
+fileBrowserStore.closeDropdown();
+assert.equal(fileBrowserStore.dropdownOwner, null);
+fileBrowserStore.toggleDropdown('/a0/test.py', { closest: () => modalRow });
+fileBrowserStore.destroy();
+assert.equal(fileBrowserStore.dropdownOwner, null, 'closing Files releases its menu owner');
+fileBrowserStore.openInSurface = async (...args) => opened.push(args);
+await fileBrowserStore.openFileEditor(file('test.py'));
+assert.equal(opened[0][1], 'editor');
+const editorStore = (() => {
+''' + editor + r'''
+return store;
+})();
+const tab = { tab_id: 'tab', session_id: 'session', path: '/a0/test.py', extension: 'py', text: 'unsaved', dirty: true };
+editorStore.tabs = [tab];
+editorStore.session = tab;
+editorStore.activeTabId = tab.tab_id;
+editorStore.selectTab = id => assert.equal(id, tab.tab_id);
+assert.equal(await editorStore.openSession({ path: tab.path }), tab, 'reopening must not fetch over unsaved text');
+assert.equal(editorStore.isTextDocument(tab), true);
+assert.equal(editorStore.canPreview(tab), false);
+assert.equal(editorStore.canPreview({ extension: 'md' }), true);
+assert.equal(editorStore.visibleTabs().length, 1);
+assert.equal(editorStore.sourceEditorMode({ path: '/a0/probe.jsonl' }), 'ace/mode/json');
+globalThis.ace = { require(name) {
+ assert.equal(name, 'ace/ext/modelist');
+ return { getModeForPath(path) { assert.equal(path, tab.path); return { mode: 'ace/mode/python' }; } };
+}};
+assert.equal(editorStore.sourceEditorMode(tab), 'ace/mode/python');
+let prevented = 0, stopped = 0, previewSearches = 0;
+const find = { ctrlKey: true, key: 'f', preventDefault() { prevented++; }, stopPropagation() { stopped++; } };
+editorStore.openSearch = () => previewSearches++;
+editorStore.viewMode = 'source';
+editorStore.handleEditorKeydown(find);
+assert.deepEqual([prevented, stopped, previewSearches], [0, 0, 0], 'source search belongs to ACE');
+editorStore.viewMode = 'preview';
+editorStore.handleEditorKeydown(find);
+assert.deepEqual([prevented, stopped, previewSearches], [1, 1, 1], 'preview search consumes the event once');
+'''
+ subprocess.run(['node', '--input-type=module'], input=script, text=True, check=True)
+
+
+def test_tool_results_refresh_open_code_but_preserve_dirty_text():
+ source = Path('plugins/_editor/extensions/webui/set_messages_after_loop/sync-text-editor-results.js').read_text()
+ source = re.sub(r'^import[^\n]*\n', '', source, flags=re.M).replace('export default ', '')
+ script = r'''
+import assert from 'node:assert/strict';
+const calls = [];
+const editorStore = { session: { path: '/a0/test.py' }, openSession: async payload => calls.push(payload) };
+globalThis.document = { querySelector: () => ({}) };
+globalThis.setTimeout = callback => callback();
+''' + source + r'''
+const result = id => ({ results: [{ args: { id, timestamp: Date.now(), kvps: { tool_name: 'text_editor', action: 'write', path: '/a0/test.py' } } }] });
+await syncTextEditorResultsIntoOpenEditor(result('clean'));
+assert.equal(calls.length, 1);
+assert.equal(calls[0].path, '/a0/test.py');
+editorStore.session.dirty = true;
+await syncTextEditorResultsIntoOpenEditor(result('dirty'));
+assert.equal(calls.length, 1);
+'''
+ subprocess.run(['node', '--input-type=module'], input=script, text=True, check=True)
diff --git a/tests/test_file_browser_navigation.py b/tests/test_file_browser_navigation.py
index d2721964d..f841459f3 100644
--- a/tests/test_file_browser_navigation.py
+++ b/tests/test_file_browser_navigation.py
@@ -102,7 +102,7 @@ def test_file_browser_editor_picker_modes_have_primary_footer_actions() -> None:
assert "PICKER_MODE_SAVE_AS" in store
assert "openTextPicker" in store
assert "openSaveAsPicker" in store
- assert 'new Set(["md", "txt"])' in store
+ assert "isEditableFile(file = {})" in store
assert "pickerSelectedFiles()" in store
assert "validatePickerFilename" in store
assert "handleFileNameClick(file = {})" in store
@@ -111,8 +111,7 @@ def test_file_browser_editor_picker_modes_have_primary_footer_actions() -> None:
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 "file-editor-open-action" not in html
assert "picker-filename-input" in html
assert "Open Selected" in store
assert "Save Here" in store
@@ -123,12 +122,18 @@ def test_file_browser_editor_picker_modes_have_primary_footer_actions() -> None:
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
+ assert "text or code files" in dox
+ assert "Keep Edit inside the overflow menu" in dox
- editor_button_index = html.index("file-editor-open-action")
dropdown_menu_index = html.index('class="dropdown-menu file-actions-menu"')
- assert editor_button_index < dropdown_menu_index
+ assert html.index('class="dropdown file-actions-dropdown"') < html.index('title="Download file"') < html.index('title="Delete item"')
+ assert '<x-extension id="file-browser-actions-menu"></x-extension>' in html[dropdown_menu_index:]
+ assert 'file-browser-actions-menu/*.html' in dox
+ edit_button = html[dropdown_menu_index:html.index('<span>Edit</span>')]
+ assert 'class="dropdown-item"' in edit_button
+ assert 'x-show="$store.fileBrowser.isEditableFile(file)"' in edit_button
+ assert '@click="$store.fileBrowser.openFileEditor(file)"' in edit_button
+ assert 'always_enabled: true' in read("plugins", "_editor", "plugin.yaml")
assert 'x-show="$store.fileBrowser.canOpenInActionMenu(file)"' in html
diff --git a/tests/test_file_tree.py b/tests/test_file_tree.py
index b5acde819..be8b31a26 100644
--- a/tests/test_file_tree.py
+++ b/tests/test_file_tree.py
@@ -91,7 +91,7 @@ const state = {{
{owner}: modal, _mode: 'modal',
flushInput() {{ calls++; }}, destroySourceEditor() {{ calls++; }},
_headerCleanup() {{ calls++; }}, _floatingCleanup() {{ calls++; }},
- cancelMountedDefaultLoad() {{ calls++; }},
+ cancelMountedDefaultLoad() {{ calls++; }}, closeDropdown() {{ calls++; }},
}};
cleanup.call(state, {{}});
assert.equal(calls, 0, 'old canvas must not tear down active modal');
diff --git a/tests/test_office_canvas_setup.py b/tests/test_office_canvas_setup.py
index a76a35a55..c604c077b 100644
--- a/tests/test_office_canvas_setup.py
+++ b/tests/test_office_canvas_setup.py
@@ -166,7 +166,9 @@ def test_right_canvas_uses_desktop_surface_id_and_migrates_legacy_office_state()
assert "openSearch" in editor_store
assert "handlePreviewClick" in editor_store
assert "ace.edit" in editor_store
- assert "showGutter: false" in editor_store
+ assert "showGutter: true" in editor_store
+ assert ".editor-ace .ace_gutter" not in editor_web_panel
+ assert ".editor-ace .ace_scroller" not in editor_web_panel
assert "globalThis.confirm" not in editor_store
assert ".editor-toolbar" in editor_web_panel
assert "overflow: visible;" in editor_web_panel
@@ -604,7 +606,7 @@ def test_editor_uses_full_document_preview_and_matching_markdown_text_tools():
assert "previousPage()" not in editor_store
assert 'x-show="$store.editor.isTextDocument()"' in editor_panel
assert '$store.editor.isTextDocument() && $store.editor.isPreviewMode()' in editor_panel
- assert 'mode === PREVIEW_MODE && this.isTextDocument()' in editor_store
+ assert 'mode === PREVIEW_MODE && this.canPreview()' in editor_store
assert "if (!this.session || !this.isTextDocument()) return;" in editor_store
source_tools_start = editor_panel.index('class="editor-tool-group surface-toolbar-group editor-source-tools"')
diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.py
index 24ef1220a..1c62b6d6f 100644
--- a/tests/test_office_document_store.py
+++ b/tests/test_office_document_store.py
@@ -2014,3 +2014,101 @@ def load_self_update_manager():
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
+
+
[email protected]("name", ["probe.jsonl", "module.py", "settings.yaml", "page.html", "Dockerfile", ".env", "custom.unknown"])
+def test_editor_arbitrary_text_file_lifecycle(office_state, name):
+ path = office_state.workdir / name
+ original = b'first line\r\nsecond line\r\n'
+ path.write_bytes(original)
+ manager = editor_markdown_sessions.get_manager()
+ doc = document_store.register_document(path)
+ session = manager.open(doc)
+ assert session["text"].encode() == original
+ manager.input(session["session_id"], text="local edit\n")
+ path.write_text("external edit\n")
+ assert manager.save(session["session_id"])["code"] == "external_change_conflict"
+ copy = path.with_name("copy-" + name)
+ result = manager.save_as(session["session_id"], str(copy), text="saved copy\n")
+ assert path.read_text() == "external edit\n"
+ assert copy.read_text() == "saved copy\n"
+ assert result["document"]["extension"] == copy.suffix.lstrip(".")
+ with pytest.raises(FileExistsError):
+ manager.save_as(session["session_id"], str(copy))
+ renamed = copy.with_name("renamed-" + name)
+ updated = document_store.rename_document(result["document"]["file_id"], renamed, content="renamed\n")
+ manager.renamed(updated["file_id"], updated, text="renamed\n")
+ assert not copy.exists()
+ assert renamed.read_text() == "renamed\n"
+ assert manager.save(session["session_id"], text="final\n")["ok"]
+ assert renamed.read_text() == "final\n"
+ manager.close(session["session_id"])
+
+
[email protected]("content, message", [(b'a\x00b', "Binary"), (b'\xff\xfe', "UTF-8"), (b'x' * (1024 * 1024 + 1), "1 MB")])
+def test_editor_rejects_binary_invalid_encoding_and_large_files(office_state, content, message):
+ path = office_state.workdir / "unsafe.jsonl"
+ path.write_bytes(content)
+ with pytest.raises(ValueError, match=message):
+ document_store.register_document(path)
+ assert path.read_bytes() == content
+
+
+def test_editor_named_create_and_save_as_match_file_browser_scope(office_state, tmp_path):
+ path = tmp_path / "outside-workdir.py"
+ handler = EditorSession(app=None, thread_lock=None)
+ request = types.SimpleNamespace(headers={}, host_url="http://localhost/")
+ payload = {"action": "create", "path": str(path), "source": "file-browser", "content": "print(1)\n"}
+ opened = asyncio.run(handler.process(payload, request))
+ assert opened["ok"]
+ assert opened["text"] == "print(1)\n"
+ assert not asyncio.run(handler.process(payload, request))["ok"]
+ assert path.read_text() == "print(1)\n"
+ target = tmp_path / "Dockerfile"
+ result = asyncio.run(handler.process({"action": "save_as", "session_id": opened["session_id"], "path": str(target), "text": "FROM scratch\n"}, request))
+ assert result["ok"]
+ assert result["document"]["extension"] == ""
+ assert target.read_text() == "FROM scratch\n"
+ with pytest.raises(PermissionError):
+ document_store.register_document(target)
+
+
[email protected]("mode", [0o755, 0o600])
+def test_editor_preserves_file_permissions_and_private_backups(office_state, mode):
+ import stat
+
+ path = office_state.workdir / "script.sh"
+ path.write_text("echo original\n")
+ path.chmod(mode)
+ original = path.stat()
+ office_state.backups.chmod(0o775)
+ manager = editor_markdown_sessions.get_manager()
+ session = manager.open(document_store.register_document(path))
+ assert manager.save(session["session_id"], text="echo saved\n")["ok"]
+ copy = path.with_name("copy.sh")
+ result = manager.save_as(session["session_id"], str(copy))
+ renamed = path.with_name("renamed.sh")
+ document_store.rename_document(result["document"]["file_id"], renamed, content="echo renamed\n")
+ for target in (path, renamed):
+ saved = target.stat()
+ assert stat.S_IMODE(saved.st_mode) == mode
+ assert (saved.st_uid, saved.st_gid) == (original.st_uid, original.st_gid)
+ assert stat.S_IMODE(office_state.backups.stat().st_mode) == 0o700
+ assert list(office_state.backups.iterdir())
+ assert all(stat.S_IMODE(backup.stat().st_mode) == 0o600 for backup in office_state.backups.iterdir())
+
+
+def test_editor_atomic_metadata_failure_keeps_original(office_state, monkeypatch):
+ path = office_state.workdir / "private.sh"
+ path.write_text("original\n")
+ path.chmod(0o600)
+ doc = document_store.register_document(path)
+
+ def fail_chmod(*_args):
+ raise PermissionError("metadata update failed")
+
+ monkeypatch.setattr(document_store.os, "fchmod", fail_chmod)
+ with pytest.raises(PermissionError, match="metadata update failed"):
+ document_store.write_text_document(doc["file_id"], "replacement\n")
+ assert path.read_text() == "original\n"
+ assert not list(path.parent.glob(".private.sh.*.tmp"))
diff --git a/webui/components/modals/AGENTS.md b/webui/components/modals/AGENTS.md
index c1070ee91..9e9c710c9 100644
--- a/webui/components/modals/AGENTS.md
+++ b/webui/components/modals/AGENTS.md
@@ -6,6 +6,7 @@
## Ownership
+- File editing belongs to the `_editor` plugin shared canvas/modal surface; Files routes Edit and New file there.
- Each direct child folder owns one modal workflow and its store.
- Modal HTML files own body content, titles, scoped styles, and `data-modal-footer` content.
- Modal store files own modal-local state and cleanup.
diff --git a/webui/components/modals/file-browser/AGENTS.md b/webui/components/modals/file-browser/AGENTS.md
index 2f11c5e1e..5e2ee6592 100644
--- a/webui/components/modals/file-browser/AGENTS.md
+++ b/webui/components/modals/file-browser/AGENTS.md
@@ -18,9 +18,12 @@
- 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.
+- Preserve picker modes for Editor Open and Save As: Editor Open selects one or more text or code files with a pinned primary action, and Save As selects the current folder plus a text-file name (including extensionless names).
+- Row actions are ordered More actions, Download, then Delete.
+- `file-browser-actions-menu` is the HTML extension point after the built-in dropdown entries, mounted only while the menu is open. Plugins contribute `extensions/webui/file-browser-actions-menu/*.html`; an `x-data` root inherits the row `file` (`name`, `path`, `is_dir`, etc.) and `$store.fileBrowser`. Use `.dropdown-item` buttons; ordinary clicks bubble to close the menu.
+- Keep Edit inside the overflow menu for editable text/code files, using the same `.dropdown-item` styling as other entries.
- Keep Extract available for supported archive files; extraction must create a new sibling folder and reject unsafe member paths and links.
+- The dropdown tracks its originating `.file-actions` row, so hidden canvas/modal copies cannot open duplicate teleported menus or plugin entries.
- Keep row action menus visible without disabling file-list scrolling; menus may float outside the scroll container but must still close on outside click, Escape, action click, and list scroll.
- Keep the file list readable in narrow canvas/modal containers by hiding the Modified date column before sacrificing the Name or Size columns.
- Use the shared `surface-workspace` lighter palette, 32px flat toolbar controls, and separators between action groups; the file-tree toggle stays available in the path header.
@@ -28,6 +31,7 @@
- Keep the list compact: 4px vertical header padding and 5px vertical item padding. The path-submit arrow is borderless and transparent, with opacity-only hover feedback.
- Keep New file and New folder controls icon-only across canvas and modal modes while preserving accessible labels.
- Keep Up, path, New file, New folder, and the rightmost tree toggle in one compact row, with equal button heights. Do not add a separate search or totals row.
+- New file uses the existing Save As picker and creates an empty file in the shared Editor; existing names must never be overwritten. HTML/XML/SVG retain Browser preview in their action menu and use the same dropdown Edit entry as other editable files.
- Preserve surface actions that route supported files to Browser, Desktop, or Editor.
- Keep native drag moves available outside picker modes: dragging an unselected row moves only that row without changing selection, dragging a selected row moves the selection, folder rows accept drops, and Up moves items to the parent directory. Moves must reject overwrites and self-nesting.
diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.js
index 5146c9ee9..b7df9c7d4 100644
--- a/webui/components/modals/file-browser/file-browser-store.js
+++ b/webui/components/modals/file-browser/file-browser-store.js
@@ -1,7 +1,6 @@
import { createStore } from "/js/AlpineStore.js";
import { callJsonApi, fetchApi } from "/js/api.js";
import { formatDateTime } from "/js/time-utils.js";
-import { store as fileEditorStore } from "/components/modals/file-editor/file-editor-store.js";
import { createFileTree } from "/components/modals/file-browser/file-tree.js";
import {
openLatest as openLatestSurface,
@@ -14,7 +13,6 @@ const DEFAULT_REMEMBER_LAST_DIRECTORY = true;
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",
@@ -35,9 +33,9 @@ const ARCHIVE_SUFFIXES = [".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tar",
const SURFACE_ACTIONS = {
editor: {
- label: "Open in Editor",
- icon: "article",
- title: "Open text in Editor",
+ label: "Edit",
+ icon: "edit",
+ title: "Edit",
},
desktop: {
label: "Open in Desktop",
@@ -106,6 +104,7 @@ const model = {
renamePerformAction: null,
renameValidateName: null,
openDropdownPath: null, // Track which dropdown is currently open
+ dropdownOwner: null,
dropdownStyle: {},
searchQuery: "",
isBulkBusy: false,
@@ -145,6 +144,7 @@ const model = {
onUnmount(element = null) {
if (element && element !== this._mountedElement) return;
this._mountedElement = null;
+ this.closeDropdown();
this._floatingCleanup?.();
this._floatingCleanup = null;
this.cancelMountedDefaultLoad();
@@ -229,7 +229,7 @@ const model = {
this.browser.currentPath = "";
this.browser.parentPath = "";
this.browser.entries = [];
- this.openDropdownPath = null;
+ this.closeDropdown();
this.searchQuery = "";
this.isBulkBusy = false;
this.clearDragState();
@@ -277,6 +277,7 @@ const model = {
// --- Helpers -------------------------------------------------------------
resetOpenState(options = {}) {
+ this.closeDropdown();
this.cancelMountedDefaultLoad();
this.isLoading = true;
this.error = null;
@@ -298,7 +299,7 @@ const model = {
|| (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",
+ options?.defaultExtension ?? this.fileExtension({ name: this.pickerFilename }),
);
this.pickerFilenameError = "";
this.pickerOnConfirm = typeof options?.onConfirm === "function" ? options.onConfirm : null;
@@ -485,7 +486,7 @@ const model = {
isSelectableEntry(file = {}) {
if (this.isSaveAsPicker()) return false;
- if (this.isTextOpenPicker()) return !file?.is_dir && this.fileSurfaceTarget(file) === "editor";
+ if (this.isTextOpenPicker()) return !file?.is_dir && this.isEditableFile(file);
return true;
},
@@ -583,20 +584,26 @@ const model = {
fileSurfaceTarget(file = {}) {
if (!file || file.is_dir) return "";
const ext = this.fileExtension(file);
- if (EDITOR_TEXT_EXTENSIONS.has(ext)) return "editor";
if (BROWSER_EXTENSIONS.has(ext)) return "browser";
if (DESKTOP_EXTENSIONS.has(ext)) return "desktop";
- return "";
+ return this.isEditableFile(file) ? "editor" : "";
+ },
+
+ isEditableFile(file = {}) {
+ if (!file || file.is_dir || file.size > 1048576 || this.isArchive(file.name || file.path)) return false;
+ const ext = this.fileExtension(file);
+ return !DESKTOP_EXTENSIONS.has(ext)
+ && !["pdf", "png", "jpg", "jpeg", "gif", "webp", "bmp", "ico", "mp3", "mp4", "wav", "webm", "ogg", "woff", "woff2", "ttf"].includes(ext);
},
pickerAllowsEntry(file = {}) {
if (!this.isTextOpenPicker()) return true;
- return Boolean(file?.is_dir || this.fileSurfaceTarget(file) === "editor");
+ return Boolean(file?.is_dir || this.isEditableFile(file));
},
pickerSelectedFiles() {
if (!this.isTextOpenPicker()) return [];
- return this.selectedFiles.filter((file) => !file.is_dir && this.fileSurfaceTarget(file) === "editor");
+ return this.selectedFiles.filter((file) => !file.is_dir && this.isEditableFile(file));
},
pickerSelectionLabel() {
@@ -608,14 +615,14 @@ const model = {
normalizedEditorTextExtension(value = "") {
const ext = String(value || "").toLowerCase().trim().replace(/^\./, "");
- return EDITOR_TEXT_EXTENSIONS.has(ext) ? ext : "md";
+ return ext;
},
pickerFilenameValue() {
const raw = String(this.pickerFilename || "").trim();
if (!raw) return "";
const ext = this.fileExtension({ name: raw });
- return ext ? raw : `${raw}.${this.pickerDefaultExtension || "md"}`;
+ return ext || !this.pickerDefaultExtension ? raw : `${raw}.${this.pickerDefaultExtension}`;
},
validatePickerFilename(updateError = true) {
@@ -629,8 +636,6 @@ const model = {
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.`;
}
@@ -654,7 +659,7 @@ const model = {
},
togglePickerFile(file = {}) {
- if (!this.isTextOpenPicker() || file?.is_dir || this.fileSurfaceTarget(file) !== "editor") return;
+ if (!this.isTextOpenPicker() || file?.is_dir || !this.isEditableFile(file)) return;
file.selected = !file.selected;
},
@@ -809,20 +814,23 @@ const model = {
// --- Dropdown Management -------------------------------------------------
toggleDropdown(filePath, triggerElement = null) {
// Toggle: if already open, close it; otherwise open this one (closing any other)
- if (this.openDropdownPath === filePath) {
+ const owner = triggerElement?.closest(".file-actions") || null;
+ if (this.isDropdownOpen(filePath, owner)) {
this.closeDropdown();
return;
}
this.openDropdownPath = filePath;
+ this.dropdownOwner = owner;
this.dropdownStyle = this.getDropdownStyle(triggerElement);
},
- isDropdownOpen(filePath) {
- return this.openDropdownPath === filePath;
+ isDropdownOpen(filePath, owner = null) {
+ return this.openDropdownPath === filePath && (!owner || owner === this.dropdownOwner);
},
closeDropdown() {
this.openDropdownPath = null;
+ this.dropdownOwner = null;
this.dropdownStyle = {};
},
@@ -1206,21 +1214,22 @@ const model = {
}
},
- // --- File Editor (Delegated to FileEditorStore) --------------------------
+ // --- Shared Editor -------------------------------------------------------
async openFileEditor(file) {
- await fileEditorStore.openFile(file, async () => {
- // Callback on successful save to refresh file list
- await this.fetchFiles(this.browser.currentPath);
- });
+ return this.openInSurface(file, "editor");
},
async openNewFile() {
- const existingNames = (this.browser.entries || [])
- .map((e) => e?.name)
- .filter(Boolean);
- await fileEditorStore.openNewFile(this.browser.currentPath, existingNames, async () => {
- // Callback on successful save to refresh file list
- await this.fetchFiles(this.browser.currentPath);
+ await this.openSaveAsPicker(this.browser.currentPath, {
+ filename: "Untitled.txt",
+ defaultExtension: "",
+ onConfirm: async ({ path }) => {
+ const { store: editorStore } = await import("/plugins/_editor/webui/editor-store.js");
+ const session = await editorStore.openSession({ action: "create", path, source: "file-browser" });
+ if (!session) throw new Error(editorStore.error || "Could not create file.");
+ await openLatestSurface("editor", {});
+ return true;
+ },
});
},
@@ -1450,8 +1459,7 @@ const model = {
return store._handleFileUpload(event); // bind to model to ensure correct context
},
- async openInSurface(file = {}) {
- const target = this.fileSurfaceTarget(file);
+ async openInSurface(file = {}, target = this.fileSurfaceTarget(file)) {
const path = this.normalizePath(String(file?.path || ""));
if (!target || !path) return;
diff --git a/webui/components/modals/file-browser/file-browser.html b/webui/components/modals/file-browser/file-browser.html
index 159feb27e..c073b7cee 100644
--- a/webui/components/modals/file-browser/file-browser.html
+++ b/webui/components/modals/file-browser/file-browser.html
@@ -213,18 +213,7 @@
</div>
<div class="file-size" x-text="file.is_dir ? '—' : $store.fileBrowser.formatFileSize(file.size)"></div>
<div class="file-date" x-text="$store.fileBrowser.formatDate(file.modified)"></div>
- <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"
- >
- <x-icon aria-hidden="true" :name="$store.fileBrowser.surfaceActionIcon(file)"></x-icon>
- </button>
-
+ <div class="file-actions" x-data="{ fileActions: $el }" x-show="!$store.fileBrowser.isPickerMode()">
<!-- Secondary single-item actions (Rename/...) are grouped under a dropdown -->
<div
class="dropdown file-actions-dropdown"
@@ -235,7 +224,7 @@
type="button"
class="btn-icon-action dropdown-trigger"
@click.stop="$store.fileBrowser.toggleDropdown(file.path, $event.currentTarget)"
- :aria-expanded="$store.fileBrowser.isDropdownOpen(file.path).toString()"
+ :aria-expanded="$store.fileBrowser.isDropdownOpen(file.path, fileActions).toString()"
aria-label="More actions"
title="More actions"
>
@@ -245,7 +234,7 @@
<template x-teleport="body">
<div
class="dropdown-menu file-actions-menu"
- x-show="$store.fileBrowser.isDropdownOpen(file.path)"
+ x-show="$store.fileBrowser.isDropdownOpen(file.path, fileActions)"
x-transition
:style="$store.fileBrowser.dropdownStyle"
style="display: none;"
@@ -254,22 +243,22 @@
<button
type="button"
class="dropdown-item"
- x-show="$store.fileBrowser.canOpenInActionMenu(file)"
- @click="$store.fileBrowser.openInSurface(file)"
- :title="$store.fileBrowser.surfaceActionTitle(file)"
+ x-show="$store.fileBrowser.isEditableFile(file)"
+ @click="$store.fileBrowser.openFileEditor(file)"
>
- <x-icon :name="$store.fileBrowser.surfaceActionIcon(file)"></x-icon>
- <span x-text="$store.fileBrowser.surfaceActionLabel(file)"></span>
+ <x-icon name="edit"></x-icon>
+ <span>Edit</span>
</button>
<button
type="button"
class="dropdown-item"
- x-show="!file.is_dir && file.size <= 1048576 && !$store.fileBrowser.canOpenInSurface(file)"
- @click="$store.fileBrowser.openFileEditor(file)"
+ x-show="$store.fileBrowser.canOpenInActionMenu(file)"
+ @click="$store.fileBrowser.openInSurface(file)"
+ :title="$store.fileBrowser.surfaceActionTitle(file)"
>
- <x-icon name="file_open"></x-icon>
- <span>Edit</span>
+ <x-icon :name="$store.fileBrowser.surfaceActionIcon(file)"></x-icon>
+ <span x-text="$store.fileBrowser.surfaceActionLabel(file)"></span>
</button>
<button
@@ -300,6 +289,9 @@
<x-icon name="drive_file_rename_outline"></x-icon>
<span>Rename</span>
</button>
+ <template x-if="$store.fileBrowser.isDropdownOpen(file.path, fileActions)">
+ <x-extension id="file-browser-actions-menu"></x-extension>
+ </template>
</div>
</template>
</div>
@@ -921,10 +913,6 @@
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-menu {
margin: 0;
}
diff --git a/webui/components/modals/file-editor/file-edit-modal.html b/webui/components/modals/file-editor/file-edit-modal.html
deleted file mode 100644
index 601c3befa..000000000
--- a/webui/components/modals/file-editor/file-edit-modal.html
+++ /dev/null
@@ -1,162 +0,0 @@
-<html>
-<head>
- <title>File Editor</title>
- <script type="module">
- import { store } from "/components/modals/file-editor/file-editor-store.js";
- </script>
-</head>
-<body>
- <div x-data>
- <template x-if="$store.fileEditor">
- <div class="file-edit-modal-root">
- <template x-if="$store.fileEditor.isEditLoading">
- <div class="loading-state">
- <div class="loading-spinner"></div>
- <p>Loading file…</p>
- </div>
- </template>
-
- <template x-if="$store.fileEditor.editError">
- <div class="error-state">
- <p class="error-message" x-text="$store.fileEditor.editError"></p>
- </div>
- </template>
-
- <template x-if="!$store.fileEditor.isEditLoading && !$store.fileEditor.editError">
- <div class="file-edit-content">
- <div class="file-edit-meta">
- <div class="file-edit-field">
- <label>File name</label>
- <input
- type="text"
- x-model="$store.fileEditor.editFileName"
- @input="$store.fileEditor.updateEditorMode()"
- :disabled="!$store.fileEditor.editIsNew"
- />
- <template x-if="$store.fileEditor.editSaveError">
- <p class="file-edit-inline-error" x-text="$store.fileEditor.editSaveError"></p>
- </template>
- </div>
- <div class="file-edit-path" x-text="$store.fileEditor.editPathLabel()"></div>
- </div>
- <div id="file-editor-container" class="no-scrollbar"></div>
- </div>
- </template>
- </div>
- </template>
- </div>
-
- <template x-if="$store.fileEditor">
- <div class="modal-footer" data-modal-footer>
- <button
- class="btn btn-ok"
- @click="$store.fileEditor.saveFileEdits()"
- :disabled="$store.fileEditor.isSaving || $store.fileEditor.isEditLoading || $store.fileEditor.editError"
- x-text="$store.fileEditor.isSaving ? 'Saving…' : 'Save'"
- ></button>
- <button class="btn btn-cancel" @click="$store.fileEditor.closeFileEditor()" :disabled="$store.fileEditor.isSaving">Cancel</button>
- </div>
- </template>
-
- <style>
- .file-edit-modal-root {
- display: flex;
- flex-direction: column;
- width: 100%;
- min-height: 400px;
- }
-
- .file-edit-content {
- display: flex;
- flex-direction: column;
- gap: var(--spacing-md);
- margin: 1rem;
- }
-
- .file-edit-meta {
- display: flex;
- flex-direction: column;
- gap: var(--spacing-xs);
- }
-
- .file-edit-field {
- display: flex;
- flex-direction: column;
- gap: 6px;
- }
-
- .file-edit-field label {
- font-weight: 600;
- color: var(--color-text);
- }
-
- .file-edit-field input {
- padding: 8px 12px;
- border-radius: 6px;
- border: 1px solid var(--color-border);
- background: var(--color-background);
- color: var(--color-text);
- }
-
- .file-edit-field input:disabled {
- opacity: 0.7;
- cursor: not-allowed;
- }
-
- .file-edit-inline-error {
- margin: 0;
- color: var(--color-error);
- font-weight: 500;
- font-size: 0.85rem;
- }
-
- .file-edit-path {
- font-size: 0.85rem;
- color: var(--color-text-secondary);
- word-break: break-all;
- }
-
- #file-editor-container {
- width: 100%;
- min-height: 55vh;
- border-radius: 0.4rem;
- overflow: auto;
- }
-
- .ace_scrollbar-v {
- overflow-y: auto;
- }
-
- .loading-state,
- .error-state {
- display: flex;
- flex-direction: column;
- align-items: center;
- justify-content: center;
- padding: var(--spacing-lg);
- min-height: 200px;
- }
-
- .loading-spinner {
- width: 40px;
- height: 40px;
- border: 3px solid var(--color-border);
- border-top: 3px solid var(--color-primary);
- border-radius: 50%;
- animation: spin 1s linear infinite;
- margin-bottom: var(--spacing-md);
- }
-
- @keyframes spin {
- 0% { transform: rotate(0deg); }
- 100% { transform: rotate(360deg); }
- }
-
- .error-message {
- color: var(--color-error);
- font-weight: 500;
- margin: 0;
- }
- </style>
-</body>
-</html>
diff --git a/webui/components/modals/file-editor/file-editor-store.js b/webui/components/modals/file-editor/file-editor-store.js
deleted file mode 100644
index b78d8eaf9..000000000
--- a/webui/components/modals/file-editor/file-editor-store.js
+++ /dev/null
@@ -1,369 +0,0 @@
-import { createStore } from "/js/AlpineStore.js";
-import { fetchApi } from "/js/api.js";
-
-const model = {
- // --- State ---------------------------------------------------------------
- editor: null,
- editTarget: null,
- editFileName: "",
- editOriginalName: "",
- editContent: "",
- editOriginalContent: "",
- editMimeType: "text/plain",
- editIsNew: false,
- isEditLoading: false,
- isSaving: false,
- editError: null,
- editSaveError: null,
- editClosePromise: null,
-
- // Context
- currentPath: "", // Required for new file creation
- existingNames: [],
- onSaveSuccess: null, // Callback to refresh parent list
-
- // --- Public API ----------------------------------------------------------
-
- /**
- * Open the editor for an existing file
- * @param {object} file - The file object { name, path, ... }
- * @param {function} onSaveSuccess - Callback when save completes
- */
- async openFile(file, onSaveSuccess) {
- if (this.isEditLoading) return;
- this.resetEditState();
-
- this.editTarget = file;
- this.editFileName = file?.name || "";
- this.editOriginalName = this.editFileName;
- this.editIsNew = false;
- this.isEditLoading = true;
- this.editError = null;
- this.editSaveError = null;
- this.onSaveSuccess = onSaveSuccess;
-
- this.editClosePromise = window.openModal(
- "modals/file-editor/file-edit-modal.html",
- () => this.beforeCloseFileEditor()
- );
-
- if (this.editClosePromise && typeof this.editClosePromise.then === "function") {
- this.editClosePromise.then(() => this.resetEditState());
- }
-
- try {
- const resp = await fetchApi(
- `/edit_work_dir_file?path=${encodeURIComponent(file.path)}`
- );
- const data = await resp.json().catch(() => ({}));
-
- if (!resp.ok || data.error) {
- throw new Error(data.error || "Failed to load file");
- }
-
- const payload = data.data || {};
-
- this.editContent = payload.content || "";
- this.editFileName = payload.name || this.editFileName;
- this.editOriginalName = this.editFileName;
- this.editOriginalContent = this.editContent;
- this.editMimeType = payload.mime_type || "text/plain";
- this.isEditLoading = false;
- this.scheduleEditorInit();
- } catch (error) {
- let message = error?.message || "Failed to load file";
- message = this._extractErrorMessage(message);
- this.editError = message;
- this.isEditLoading = false;
- window.toastFrontendError(message, "File Edit Error");
- }
- },
-
- /**
- * Open the editor for a new file
- * @param {string} currentPath - The directory where the file will be created
- * @param {string[]} existingNames - Names that already exist in the directory (for UX duplicate checks)
- * @param {function} onSaveSuccess - Callback when save completes
- */
- async openNewFile(currentPath, existingNames, onSaveSuccess) {
- this.resetEditState();
-
- this.currentPath = currentPath;
- this.existingNames = Array.isArray(existingNames) ? existingNames : [];
- this.editIsNew = true;
- this.editFileName = "";
- this.editOriginalName = "";
- this.editContent = "";
- this.editOriginalContent = "";
- this.editMimeType = "text/plain";
- this.isEditLoading = false;
- this.editError = null;
- this.editSaveError = null;
- this.onSaveSuccess = onSaveSuccess;
-
- this.editClosePromise = window.openModal(
- "modals/file-editor/file-edit-modal.html",
- () => this.beforeCloseFileEditor()
- );
-
- if (this.editClosePromise && typeof this.editClosePromise.then === "function") {
- this.editClosePromise.then(() => this.resetEditState());
- }
-
- this.scheduleEditorInit();
- },
-
- // --- Actions -------------------------------------------------------------
-
- async saveFileEdits() {
- if (this.isSaving || this.isEditLoading || this.editError) return;
- this.editSaveError = null;
-
- const fileName = this.editFileName.trim();
- if (!fileName) {
- this.editSaveError = "File name is required.";
- return;
- }
- if (fileName === "." || fileName === "..") {
- this.editSaveError = "File name cannot be '.' or '..'.";
- return;
- }
- if (fileName.includes("/") || fileName.includes("\\")) {
- this.editSaveError = "File name cannot include path separators.";
- return;
- }
- if (this.editIsNew && (this.existingNames || []).includes(fileName)) {
- this.editSaveError = `An item named "${fileName}" already exists.`;
- return;
- }
-
- const content = this.editor ? this.editor.getValue() : this.editContent;
- const targetPath = this.editIsNew
- ? this.buildChildPath(fileName)
- : this.editTarget?.path || ""; // Note: was normalizePath(this.editTarget?.path) but path should be absolute from API
-
- if (!targetPath) {
- window.toastFrontendError("File path is missing.", "Save File");
- return;
- }
-
- this.isSaving = true;
-
- try {
- const resp = await fetchApi("/edit_work_dir_file", {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({ path: targetPath, content }),
- });
-
- const data = await resp.json().catch(() => ({}));
-
- if (!resp.ok || data.error) {
- throw new Error(data.error || "Failed to save file");
- }
-
- this.editOriginalContent = content;
- this.editOriginalName = fileName;
- this.editIsNew = false;
- if (this.editTarget) {
- this.editTarget.name = fileName;
- this.editTarget.path = targetPath;
- }
-
- // Trigger success callback
- if (typeof this.onSaveSuccess === 'function') {
- await this.onSaveSuccess();
- }
-
- // Reset isSaving before closing so beforeCloseFileEditor() allows it
- this.isSaving = false;
- this.closeFileEditor();
- } catch (error) {
- const message = error?.message || "Failed to save file";
- this.editSaveError = message;
- window.toastFrontendError(message, "Save File Error");
- this.isSaving = false;
- }
- },
-
- closeFileEditor() {
- window.closeModal("modals/file-editor/file-edit-modal.html");
- },
-
- beforeCloseFileEditor() {
- if (this.isSaving) return false;
- if (!this.editor) return true;
- if (!this.hasEditChanges()) return true;
- return confirm("You have unsaved changes. Close without saving?");
- },
-
- // --- Helpers -------------------------------------------------------------
-
- _extractErrorMessage(msg) {
- if (typeof msg !== 'string') return msg;
- // Extract clean error from traceback strings
- const lines = msg.split('\n');
- for (let i = lines.length - 1; i >= 0; i--) {
- const line = lines[i].trim();
- if (line.includes(': ') && /Exception|Error/.test(line)) {
- return line.split(': ').slice(1).join(': ').trim();
- }
- }
- return msg;
- },
-
- resetEditState() {
- if (this.editor?.destroy) {
- this.editor.destroy();
- }
- this.editor = null;
- this.editTarget = null;
- this.editFileName = "";
- this.editOriginalName = "";
- this.editContent = "";
- this.editOriginalContent = "";
- this.editMimeType = "text/plain";
- this.editIsNew = false;
- this.isEditLoading = false;
- this.isSaving = false;
- this.editError = null;
- this.editSaveError = null;
- this.editClosePromise = null;
- this.existingNames = [];
- this.onSaveSuccess = null;
- },
-
- normalizePath(path) {
- if (!path) return "";
- return path.startsWith("/") ? path : `/${path}`;
- },
-
- buildChildPath(name) {
- const base = this.normalizePath(this.currentPath || "");
- const trimmedBase = base.replace(/\/$/, "");
- if (!trimmedBase) return `/${name}`;
- return `${trimmedBase}/${name}`;
- },
-
- hasEditChanges() {
- const currentValue = this.editor ? this.editor.getValue() : this.editContent;
- const nameChanged = (this.editFileName || "") !== (this.editOriginalName || "");
- if (this.editIsNew) {
- return Boolean((this.editFileName || "").trim() || currentValue);
- }
- return currentValue !== this.editOriginalContent || nameChanged;
- },
-
- editPathLabel() {
- if (this.editIsNew) {
- const name = this.editFileName?.trim();
- return name ? this.buildChildPath(name) : this.normalizePath(this.currentPath || "");
- }
- return this.editTarget?.path ? this.normalizePath(this.editTarget.path) : "";
- },
-
- // --- Editor (ACE) integration --------------------------------------------
-
- scheduleEditorInit() {
- window.requestAnimationFrame(() => {
- if (this.isEditLoading || this.editError) return;
- window.requestAnimationFrame(() => this.initEditor());
- });
- },
-
- initEditor() {
- const container = document.getElementById("file-editor-container");
- if (!container) {
- // It's possible the modal hasn't fully rendered yet
- console.warn("File editor container not found, deferring editor init");
- return;
- }
-
- if (this.editor?.destroy) {
- this.editor.destroy();
- }
-
- if (!window.ace?.edit) {
- console.error("ACE editor not available");
- this.editError = "Editor library not loaded";
- return;
- }
-
- const editorInstance = window.ace.edit("file-editor-container");
- if (!editorInstance) {
- console.error("Failed to create ACE editor instance");
- return;
- }
-
- this.editor = editorInstance;
-
- const darkMode = window.localStorage?.getItem("darkMode");
- const theme = darkMode !== "false" ? "ace/theme/github_dark" : "ace/theme/tomorrow";
- this.editor.setTheme(theme);
- this.applyEditorMode();
- this.editor.setValue(this.editContent || "", -1);
- this.editor.clearSelection();
- },
-
- updateEditorMode() {
- this.applyEditorMode();
- },
-
- applyEditorMode() {
- if (!this.editor?.session) return;
- const mode = this.resolveAceMode(this.editMimeType, this.editFileName);
- this.editor.session.setMode(mode);
- },
-
- resolveAceMode(mimeType, fileName) {
- const mime = (mimeType || "").toLowerCase();
- const ext = (fileName || "").split(".").pop()?.toLowerCase();
- const mimeMap = {
- "application/json": "json",
- "application/xml": "xml",
- "application/javascript": "javascript",
- "application/typescript": "typescript",
- "application/x-yaml": "yaml",
- "text/plain": "text",
- "text/markdown": "markdown",
- "text/html": "html",
- "text/css": "css",
- "text/javascript": "javascript",
- "text/typescript": "typescript",
- "text/x-python": "python",
- "text/x-shellscript": "sh",
- "text/x-yaml": "yaml",
- "text/xml": "xml",
- "text/x-toml": "toml",
- };
- const extMap = {
- js: "javascript",
- jsx: "javascript",
- ts: "typescript",
- tsx: "typescript",
- json: "json",
- md: "markdown",
- markdown: "markdown",
- html: "html",
- htm: "html",
- css: "css",
- py: "python",
- sh: "sh",
- bash: "sh",
- zsh: "sh",
- yaml: "yaml",
- yml: "yaml",
- toml: "toml",
- xml: "xml",
- txt: "text",
- csv: "text",
- ini: "ini",
- };
- const mimeMode = mimeMap[mime];
- const extMode = extMap[ext];
- const mode = (mime && mime !== "text/plain" ? mimeMode : null) || extMode || mimeMode || "text";
- return `ace/mode/${mode}`;
- },
-};
-
-export const store = createStore("fileEditor", model);