Agent Zero AI framework
Add Editor downloads and archive extraction
Alessandro98589c6357fd
diff --git a/api/extract_work_dir_archive.py b/api/extract_work_dir_archive.pynew file mode 100644index 000000000..1cb61d991--- /dev/null+++ b/api/extract_work_dir_archive.py@@ -0,0 +1,154 @@+from __future__ import annotations++from pathlib import Path+import shutil+import stat+import subprocess+import tarfile+import zipfile++from helpers import extension, files, runtime+from helpers.api import ApiHandler, Input, Output, Request+from api import get_work_dir_files+++ARCHIVE_SUFFIXES = (+ ".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tar", ".tgz", ".tbz", ".tbz2", ".txz",+ ".zip", ".rar", ".7z", ".gz", ".bz2", ".xz", ".zst",+)+TAR_SUFFIXES = (".tar.gz", ".tar.bz2", ".tar.xz", ".tar", ".tgz", ".tbz", ".tbz2", ".txz")+++class ExtractWorkDirArchive(ApiHandler):+ async def process(self, input: Input, request: Request) -> Output:+ path = str(input.get("path") or "").strip()+ if not path:+ return {"error": "Archive path is required"}+ if not path.startswith("/"):+ path = f"/{path}"++ try:+ extracted_path = await runtime.call_development_function(extract_archive, path)+ except (OSError, ValueError) as exc:+ return {"error": str(exc)}++ current_path = str(input.get("currentPath") or "")+ await extension.call_extensions_async(+ "workdir_file_mutation_after",+ agent=None,+ data={+ "action": "extract",+ "path": extracted_path,+ "paths": [path, extracted_path],+ "current_path": current_path,+ },+ )+ listing = await runtime.call_development_function(get_work_dir_files.get_files, current_path)+ return {"data": listing, "extracted_path": extracted_path}+++def extract_archive(path: str) -> str:+ source = resolve_archive_path(path)+ target = create_target_directory(source)+ try:+ kind = archive_kind(source)+ if kind == "zip":+ extract_zip(source, target)+ elif kind == "tar":+ extract_tar(source, target)+ else:+ extract_with_7zip(source, target)+ except Exception:+ shutil.rmtree(target, ignore_errors=True)+ raise+ return str(target)+++def resolve_archive_path(path: str) -> Path:+ base = Path(files.get_base_dir()).resolve()+ candidate = Path(path)+ resolved = candidate.resolve() if candidate.is_absolute() else (base / candidate).resolve()+ try:+ resolved.relative_to(base)+ except ValueError as exc:+ raise ValueError("Invalid archive path") from exc+ if not resolved.is_file():+ raise ValueError("Archive file was not found")+ return resolved+++def archive_kind(path: Path) -> str:+ name = path.name.lower()+ if name.endswith(".zip"):+ return "zip"+ if name.endswith(TAR_SUFFIXES):+ return "tar"+ if name.endswith(ARCHIVE_SUFFIXES):+ return "7zip"+ raise ValueError("Unsupported archive format")+++def create_target_directory(source: Path) -> Path:+ name = source.name+ for suffix in ARCHIVE_SUFFIXES:+ if name.lower().endswith(suffix):+ name = name[:-len(suffix)]+ break+ name = name or "extracted"+ target = source.parent / name+ index = 2+ while target.exists():+ target = source.parent / f"{name}-{index}"+ index += 1+ target.mkdir()+ return target+++def safe_member_path(target: Path, name: str) -> Path:+ if not name or name.startswith(("/", "\\")) or "\\" in name or ".." in Path(name).parts:+ raise ValueError("Archive contains an unsafe path")+ destination = (target / name).resolve(strict=False)+ try:+ destination.relative_to(target.resolve())+ except ValueError as exc:+ raise ValueError("Archive contains an unsafe path") from exc+ return destination+++def extract_zip(source: Path, target: Path) -> None:+ with zipfile.ZipFile(source) as archive:+ for member in archive.infolist():+ safe_member_path(target, member.filename)+ if stat.S_ISLNK(member.external_attr >> 16):+ raise ValueError("Archive contains a symbolic link")+ archive.extractall(target)+++def extract_tar(source: Path, target: Path) -> None:+ with tarfile.open(source, "r:*") as archive:+ for member in archive.getmembers():+ safe_member_path(target, member.name)+ if member.issym() or member.islnk() or member.isdev():+ raise ValueError("Archive contains a symbolic link or device")+ archive.extractall(target, filter="data")+++def extract_with_7zip(source: Path, target: Path) -> None:+ binary = shutil.which("7z") or shutil.which("7zz")+ if not binary:+ raise ValueError("This archive format requires 7-Zip in the runtime image")+ listing = subprocess.run(+ [binary, "l", "-slt", str(source)],+ check=True,+ capture_output=True,+ text=True,+ ).stdout+ marker = "----------"+ if marker not in listing:+ raise ValueError("Could not inspect archive safely")+ for line in listing.split(marker, 1)[1].splitlines():+ if line.startswith("Path = "):+ safe_member_path(target, line.removeprefix("Path = "))+ subprocess.run([binary, "x", "-y", f"-o{target}", str(source)], check=True, capture_output=True)+ if any(path.is_symlink() for path in target.rglob("*")):+ raise ValueError("Archive contains a symbolic link")diff --git a/api/extract_work_dir_archive.py.dox.md b/api/extract_work_dir_archive.py.dox.mdnew file mode 100644index 000000000..0e3fb0eb3--- /dev/null+++ b/api/extract_work_dir_archive.py.dox.md@@ -0,0 +1,21 @@+# extract_work_dir_archive.py DOX++## Purpose++- Own the authenticated, CSRF-protected archive extraction endpoint for File Browser.+- Extract supported archives into a new sibling folder without overwriting existing content.++## Ownership++- `ExtractWorkDirArchive` receives a file `path` and optional listing `currentPath`.+- `extract_archive` validates the source, creates the destination, and removes partial output on failure.++## Runtime Contracts++- ZIP and TAR-family archives use the Python standard library; RAR, 7z, and single-file compression formats use the image `7zip` binary.+- Archive members must remain below the new destination and cannot be links or devices.+- Successful extraction emits `workdir_file_mutation_after` and returns a refreshed file listing plus `extracted_path`.++## Verification++- Run `pytest tests/test_file_browser_archives.py tests/test_file_browser_navigation.py`.diff --git a/docker/base/fs/ins/install_base_packages1.sh b/docker/base/fs/ins/install_base_packages1.shindex fbc21091c..9bd108c1e 100644--- a/docker/base/fs/ins/install_base_packages1.sh+++ b/docker/base/fs/ins/install_base_packages1.sh@@ -6,6 +6,6 @@ echo "====================BASE PACKAGES1 START===================="apt-get update && apt-get upgrade -yapt-get install -y --no-install-recommends \- sudo curl wget git cron unzip+ sudo curl wget git cron unzip 7zipecho "====================BASE PACKAGES1 END===================="diff --git a/plugins/_editor/AGENTS.md b/plugins/_editor/AGENTS.mdindex 90d8dd4e3..6aa878756 100644--- a/plugins/_editor/AGENTS.md+++ b/plugins/_editor/AGENTS.md@@ -18,6 +18,7 @@- 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 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.- Preserve source chat context ids when opening Markdown files from tool-result canvas handoffs.diff --git a/plugins/_editor/webui/editor-panel.html b/plugins/_editor/webui/editor-panel.htmlindex 309c5cb27..4abb20e2f 100644--- a/plugins/_editor/webui/editor-panel.html+++ b/plugins/_editor/webui/editor-panel.html@@ -174,6 +174,10 @@<span class="material-symbols-outlined">more_vert</span></button><div class="editor-new-menu editor-file-menu" role="menu" x-show="open" @click.stop>+ <button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.saving" @click="open = false; $store.editor.downloadActiveFile()">+ <span class="material-symbols-outlined" aria-hidden="true">download</span>+ <span>Download</span>+ </button><button type="button" class="editor-new-menu-item" role="menuitem" :disabled="$store.editor.saving" @click="open = false; $store.editor.renameActiveFile()"><span class="material-symbols-outlined" aria-hidden="true">edit</span><span>Rename</span>diff --git a/plugins/_editor/webui/editor-store.js b/plugins/_editor/webui/editor-store.jsindex 75a4ead8e..7a11c5ead 100644--- a/plugins/_editor/webui/editor-store.js+++ b/plugins/_editor/webui/editor-store.js@@ -1303,6 +1303,14 @@ const model = {}},+ async downloadActiveFile() {+ if (!this.session || this.saving || !this.isTextDocument()) return;+ if (this.dirty) await this.save();+ if (this.dirty) return;+ const path = this.session.path || this.session.document?.path;+ if (path) fileBrowserStore.downloadFile({ path, name: this.tabTitle() });+ },+async saveAs() {if (!this.session || this.saving || !this.isTextDocument()) return;this.applyPreviewEdit({ silent: true });diff --git a/tests/test_file_browser_archives.py b/tests/test_file_browser_archives.pynew file mode 100644index 000000000..a9b285582--- /dev/null+++ b/tests/test_file_browser_archives.py@@ -0,0 +1,53 @@+from pathlib import Path+import sys+import tarfile+import zipfile++import pytest+++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))+++from api.extract_work_dir_archive import extract_archive+from helpers import files+++def test_extract_archive_creates_unique_zip_destination(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(files, "_base_dir", str(tmp_path))+ archive = tmp_path / "notes.zip"+ with zipfile.ZipFile(archive, "w") as bundle:+ bundle.writestr("nested/note.txt", "hello")++ first = Path(extract_archive(str(archive)))+ second = Path(extract_archive(str(archive)))++ assert (first / "nested" / "note.txt").read_text() == "hello"+ assert second.name == "notes-2"+++def test_extract_archive_handles_tar_gz(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(files, "_base_dir", str(tmp_path))+ source = tmp_path / "readme.txt"+ source.write_text("hello")+ archive = tmp_path / "bundle.tar.gz"+ with tarfile.open(archive, "w:gz") as bundle:+ bundle.add(source, arcname="readme.txt")++ destination = Path(extract_archive(str(archive)))++ assert (destination / "readme.txt").read_text() == "hello"+++def test_extract_archive_rejects_zip_path_traversal(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(files, "_base_dir", str(tmp_path))+ archive = tmp_path / "unsafe.zip"+ with zipfile.ZipFile(archive, "w") as bundle:+ bundle.writestr("../escape.txt", "nope")++ with pytest.raises(ValueError, match="unsafe path"):+ extract_archive(str(archive))++ assert not (tmp_path / "unsafe").exists()diff --git a/tests/test_file_browser_navigation.py b/tests/test_file_browser_navigation.pyindex 68bb91339..7918990ab 100644--- a/tests/test_file_browser_navigation.py+++ b/tests/test_file_browser_navigation.py@@ -128,6 +128,23 @@ def test_file_browser_editor_picker_modes_have_primary_footer_actions() -> None:assert 'x-show="$store.fileBrowser.canOpenInActionMenu(file)"' in html+def test_file_browser_extract_and_editor_download_actions() -> None:+ browser_html = read("webui", "components", "modals", "file-browser", "file-browser.html")+ browser_store = read("webui", "components", "modals", "file-browser", "file-browser-store.js")+ editor_html = read("plugins", "_editor", "webui", "editor-panel.html")+ editor_store = read("plugins", "_editor", "webui", "editor-store.js")++ assert 'x-show="!file.is_dir && $store.fileBrowser.isArchive(file.name)"' in browser_html+ assert '$store.fileBrowser.extractArchive(file)' in browser_html+ assert "ARCHIVE_SUFFIXES" in browser_store+ assert 'fetchApi("/extract_work_dir_archive"' in browser_store+ assert "async extractArchive(file = {})" in browser_store+ assert "<span>Extract</span>" in browser_html+ assert "downloadActiveFile()" in editor_store+ assert "$store.editor.downloadActiveFile()" in editor_html+ assert "<span>Download</span>" in editor_html++def test_file_browser_dropdown_escapes_scroll_container_and_header_is_opaque() -> None:html = read("webui", "components", "modals", "file-browser", "file-browser.html")store = read("webui", "components", "modals", "file-browser", "file-browser-store.js")diff --git a/webui/components/modals/file-browser/AGENTS.md b/webui/components/modals/file-browser/AGENTS.mdindex a17eee0d7..225c1fc2c 100644--- a/webui/components/modals/file-browser/AGENTS.md+++ b/webui/components/modals/file-browser/AGENTS.md@@ -19,6 +19,7 @@- 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 Extract available for supported archive files; extraction must create a new sibling folder and reject unsafe member paths and links.- 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.- Keep New file and New folder controls icon-only across canvas and modal modes while preserving accessible labels.diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex 32cae8c34..5e46ef2a2 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -30,6 +30,7 @@ const BROWSER_EXTENSIONS = new Set(["bmp","ico",]);+const ARCHIVE_SUFFIXES = [".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst", ".tar", ".tgz", ".tbz", ".tbz2", ".txz", ".zip", ".rar", ".7z", ".gz", ".bz2", ".xz", ".zst"];const SURFACE_ACTIONS = {editor: {@@ -324,9 +325,7 @@ const model = {},isArchive(filename) {- const archiveExts = ["zip", "tar", "gz", "rar", "7z"];- const ext = filename.split(".").pop().toLowerCase();- return archiveExts.includes(ext);+ return ARCHIVE_SUFFIXES.some((suffix) => String(filename || "").toLowerCase().endsWith(suffix));},saveScrollPosition() {@@ -1118,6 +1117,29 @@ const model = {},// --- File actions --------------------------------------------------------+ async extractArchive(file = {}) {+ if (!file?.path || !this.isArchive(file.name) || this.isBulkBusy) return;+ this.isBulkBusy = true;+ this.closeDropdown();+ try {+ const resp = await fetchApi("/extract_work_dir_archive", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ path: file.path, currentPath: this.browser.currentPath }),+ });+ const data = await resp.json().catch(() => ({}));+ if (!resp.ok || data.error) throw new Error(data.error || "Archive extraction failed");+ this.browser.entries = this.decorateEntries(data.data?.entries || []);+ this.browser.currentPath = data.data?.current_path || this.browser.currentPath;+ this.browser.parentPath = data.data?.parent_path || this.browser.parentPath;+ window.toastFrontendSuccess(`Extracted to ${data.extracted_path || "a new folder"}`, "Archive Extracted");+ } catch (error) {+ window.toastFrontendError(error?.message || "Archive extraction failed", "Archive Extract Error");+ } finally {+ this.isBulkBusy = false;+ }+ },+async deleteFile(file) {try {const resp = await fetchApi("/delete_work_dir_file", {diff --git a/webui/components/modals/file-browser/file-browser.html b/webui/components/modals/file-browser/file-browser.htmlindex f91966304..9ce09a0a7 100644--- a/webui/components/modals/file-browser/file-browser.html+++ b/webui/components/modals/file-browser/file-browser.html@@ -300,6 +300,16 @@<span>Download ZIP</span></button>+ <button+ type="button"+ class="dropdown-item"+ x-show="!file.is_dir && $store.fileBrowser.isArchive(file.name)"+ @click="$store.fileBrowser.extractArchive(file)"+ >+ <span class="material-symbols-outlined">unarchive</span>+ <span>Extract</span>+ </button>+<buttontype="button"class="dropdown-item"