Agent Zero AI framework
Allow file browser to open root Markdown in Editor
Alessandro4f2d996ac8ce
diff --git a/plugins/_editor/api/editor_session.py b/plugins/_editor/api/editor_session.pyindex 2a4ceb7fd..5ef197648 100644--- a/plugins/_editor/api/editor_session.py+++ b/plugins/_editor/api/editor_session.py@@ -58,7 +58,11 @@ class EditorSession(ApiHandler):doc = (document_store.get_document(file_id)if file_id- else document_store.register_document(str(input.get("path") or ""), context_id=context_id)+ else document_store.register_document(+ str(input.get("path") or ""),+ context_id=context_id,+ allow_base_dir=self._allow_base_dir_open(input),+ ))except Exception as exc:return {"ok": False, "error": str(exc)}@@ -145,6 +149,11 @@ 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:+ if str(input.get("source") or "").strip() != "file-browser":+ return False+ return bool(str(input.get("path") or "").strip())+def _public_doc(doc: dict) -> dict:return {diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.jsindex 653ff7108..e0e3c3682 100644--- a/plugins/_editor/webui/editor-store.js+++ b/plugins/_editor/webui/editor-store.js@@ -873,8 +873,12 @@ const model = {await fileBrowserStore.open(workdirPath);},- async openPath(path) {- return await this.openSession({ path: String(path || "") });+ async openPath(path, options = {}) {+ return await this.openSession({+ path: String(path || ""),+ source: options?.source || "",+ refresh: options?.refresh === true,+ });},async openSession(payload = {}) {diff --git a/plugins/_office/helpers/document_store.py b/plugins/_office/helpers/document_store.pyindex 906f92cbb..adcea0c8e 100644--- a/plugins/_office/helpers/document_store.py+++ b/plugins/_office/helpers/document_store.py@@ -128,7 +128,7 @@ def _path_from_a0(path: str | Path) -> Path:return Path(raw if os.path.isabs(raw) else files.get_abs_path(raw)).expanduser()-def allowed_roots(context_id: str = "") -> list[Path]:+def allowed_roots(context_id: str = "", allow_base_dir: bool = False) -> list[Path]:project_helpers = _projects()roots = {WORKDIR.resolve(strict=False),@@ -140,6 +140,8 @@ def allowed_roots(context_id: str = "") -> list[Path]:configured = str(_settings().get_settings().get("workdir_path") or "").strip()if configured:roots.add(_path_from_a0(configured).resolve(strict=False))+ if allow_base_dir:+ roots.add(Path(files.get_base_dir()).resolve(strict=False))return sorted(roots, key=lambda item: str(item))@@ -155,10 +157,10 @@ def _settings() -> Any:return settings-def normalize_path(path: str | Path, context_id: str = "") -> Path:+def normalize_path(path: str | Path, context_id: str = "", allow_base_dir: bool = False) -> Path:candidate = _path_from_a0(path)resolved = candidate.resolve(strict=False)- roots = allowed_roots(context_id)+ roots = 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():@@ -236,8 +238,13 @@ def init_db(conn: sqlite3.Connection) -> None:)-def register_document(path: str | Path, owner_id: str = "a0", context_id: str = "") -> dict[str, Any]:- resolved = normalize_path(path, context_id=context_id)+def register_document(+ path: str | Path,+ owner_id: str = "a0",+ context_id: str = "",+ allow_base_dir: bool = False,+) -> dict[str, Any]:+ resolved = normalize_path(path, context_id=context_id, allow_base_dir=allow_base_dir)if not resolved.exists():raise FileNotFoundError(str(resolved))ext = normalize_extension(resolved.suffix.lstrip("."))diff --git a/tests/test_office_document_store.py b/tests/test_office_document_store.pyindex b7d704b63..9e4daa87e 100644--- a/tests/test_office_document_store.py+++ b/tests/test_office_document_store.py@@ -25,6 +25,7 @@ from plugins._editor.helpers import (markdown_sessions as editor_markdown_sessions,open_files_context,)+from plugins._editor.api.editor_session import EditorSessionfrom plugins._office.helpers import (artifact_editor,canvas_context,@@ -94,6 +95,45 @@ def test_text_files_register_as_desktop_documents(office_state):assert "txt" in desktop_session.OFFICIAL_EXTENSIONS+def test_file_browser_can_register_runtime_root_markdown(office_state, monkeypatch):+ runtime_root = office_state.state.parent / "runtime-root"+ runtime_root.mkdir()+ path = runtime_root / "AGENTS.md"+ path.write_text("# Runtime Instructions\n", encoding="utf-8")+ monkeypatch.setattr(document_store.files, "get_base_dir", lambda: str(runtime_root))++ with pytest.raises(PermissionError, match="active project or workdir"):+ document_store.register_document(path)++ doc = document_store.register_document(path, allow_base_dir=True)++ assert doc["basename"] == "AGENTS.md"+ assert doc["path"] == str(path)+++def test_editor_file_browser_source_opens_runtime_root_markdown(office_state, monkeypatch):+ runtime_root = office_state.state.parent / "runtime-root"+ runtime_root.mkdir()+ path = runtime_root / "AGENTS.md"+ path.write_text("# Runtime Instructions\n", encoding="utf-8")+ monkeypatch.setattr(document_store.files, "get_base_dir", lambda: str(runtime_root))+ handler = EditorSession(app=None, thread_lock=None)+ request = types.SimpleNamespace(headers={}, host_url="http://localhost/")++ blocked = asyncio.run(handler.process({"action": "open", "path": str(path)}, request))+ opened = asyncio.run(handler.process({+ "action": "open",+ "path": str(path),+ "source": "file-browser",+ }, request))++ assert blocked["ok"] is False+ assert "active project or workdir" in blocked["error"]+ assert opened["ok"] is True+ assert opened["title"] == "AGENTS.md"+ assert opened["text"] == "# Runtime Instructions\n"++@pytest.mark.parametrize(("kind", "title", "fmt", "expected_name"),[diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex 56967e1dd..a6e0d6bd5 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -838,7 +838,7 @@ const model = {if (target === "editor") {const { store: editorStore } = await import("/plugins/_editor/webui/editor-store.js");if (!this.storeHasPath(editorStore, path)) {- const session = await editorStore.openPath(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.");}