Agent Zero AI framework
Make file browser paths editable
Alessandrof9d8167a0004
diff --git a/helpers/file_browser.py b/helpers/file_browser.pyindex 4b3ac2746..a4a7e936f 100644--- a/helpers/file_browser.py+++ b/helpers/file_browser.py@@ -313,6 +313,10 @@ class FileBrowser:full_path = (self.base_dir / current_path).resolve()if not str(full_path).startswith(str(self.base_dir)):raise ValueError("Invalid path")+ if not full_path.exists():+ raise FileNotFoundError("Directory not found")+ if not full_path.is_dir():+ raise NotADirectoryError("Path is not a directory")# Use ls command instead of os.scandir for better error handlingfiles, folders = self._get_files_via_ls(full_path)@@ -342,7 +346,12 @@ class FileBrowser:except Exception as e:PrintStyle.error(f"Error reading directory: {e}")- return {"entries": [], "current_path": "", "parent_path": ""}+ return {+ "entries": [],+ "current_path": current_path,+ "parent_path": "",+ "error": str(e),+ }def get_full_path(self, file_path: str, allow_dir: bool = False) -> str:"""Get full file path if it exists and is within base_dir"""diff --git a/helpers/settings.py b/helpers/settings.pyindex e9b707f5e..88eea749e 100644--- a/helpers/settings.py+++ b/helpers/settings.py@@ -66,6 +66,7 @@ class Settings(TypedDict):workdir_max_folders: intworkdir_max_lines: intworkdir_gitignore: str+ file_browser_remember_last_directory: boolapi_keys: dict[str, str]@@ -506,6 +507,10 @@ def get_default_settings() -> Settings:workdir_max_folders=get_default_value("workdir_max_folders", 20),workdir_max_lines=get_default_value("workdir_max_lines", 250),workdir_gitignore=get_default_value("workdir_gitignore", gitignore),+ file_browser_remember_last_directory=get_default_value(+ "file_browser_remember_last_directory",+ True,+ ),rfc_auto_docker=get_default_value("rfc_auto_docker", True),rfc_url=get_default_value("rfc_url", "localhost"),rfc_password="",diff --git a/tests/test_file_browser_navigation.py b/tests/test_file_browser_navigation.pynew file mode 100644index 000000000..62e231359--- /dev/null+++ b/tests/test_file_browser_navigation.py@@ -0,0 +1,58 @@+from pathlib import Path+import sys+++PROJECT_ROOT = Path(__file__).resolve().parents[1]+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))+++from helpers.file_browser import FileBrowser+++def read(*parts: str) -> str:+ return PROJECT_ROOT.joinpath(*parts).read_text(encoding="utf-8")+++def test_file_browser_remember_last_directory_defaults_enabled() -> None:+ settings_source = read("helpers", "settings.py")++ assert "file_browser_remember_last_directory: bool" in settings_source+ assert "file_browser_remember_last_directory=get_default_value(" in settings_source+ assert '"file_browser_remember_last_directory",\n True,' in settings_source+++def test_file_browser_editable_path_bar_and_remembered_directory_contract() -> None:+ html = read("webui", "components", "modals", "file-browser", "file-browser.html")+ store = read("webui", "components", "modals", "file-browser", "file-browser-store.js")+ workdir_settings = read("webui", "components", "settings", "agent", "workdir.html")++ assert 'class="path-navigator"' in html+ assert 'x-model="$store.fileBrowser.pathInput"' in html+ assert '@submit.prevent="$store.fileBrowser.submitPath()"' in html+ assert "Go to directory" in html+ assert "$store.fileBrowser.pathError" in html++ assert "FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY" in store+ assert 'callJsonApi("settings_get", null)' in store+ assert "file_browser_remember_last_directory" in store+ assert "getRememberedDirectory()" in store+ assert "rememberCurrentDirectory(this.browser.currentPath)" in store+ assert "clearRememberedDirectory()" in store++ explicit_path_index = store.index("const explicitPath = this.normalizeOpeningPath")+ remembered_path_index = store.index("const rememberedPath = !explicitPath")+ assert explicit_path_index < remembered_path_index++ assert "Remember last file browser location" in workdir_settings+ assert "$store.settings.settings.file_browser_remember_last_directory" in workdir_settings+++def test_file_browser_reports_missing_directory(tmp_path: Path) -> None:+ missing_directory = tmp_path / "missing"++ result = FileBrowser().get_files(str(missing_directory))++ assert result["entries"] == []+ assert result["current_path"] == str(missing_directory)+ assert result["error"] == "Directory not found"diff --git a/webui/components/modals/file-browser/file-browser-store.js b/webui/components/modals/file-browser/file-browser-store.jsindex a6e0d6bd5..20a32fedb 100644--- a/webui/components/modals/file-browser/file-browser-store.js+++ b/webui/components/modals/file-browser/file-browser-store.js@@ -1,9 +1,11 @@import { createStore } from "/js/AlpineStore.js";-import { fetchApi } from "/js/api.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 { openLatest as openLatestSurface } from "/js/surfaces.js";+const FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY = "fileBrowser.lastDirectory";+const DEFAULT_REMEMBER_LAST_DIRECTORY = true;const MARKDOWN_EXTENSIONS = new Set(["md", "markdown", "mdown"]);const DESKTOP_EXTENSIONS = new Set(["odt", "ods", "odp", "docx", "xlsx", "pptx", "txt"]);const BROWSER_EXTENSIONS = new Set([@@ -60,6 +62,12 @@ const model = {initialPath: "", // Store path for open() callclosePromise: null,error: null,+ pathInput: "",+ pathError: "",+ isPathSubmitting: false,+ rememberLastDirectory: DEFAULT_REMEMBER_LAST_DIRECTORY,+ settingsLoadPromise: null,+ settingsUpdatedHandler: null,renameTarget: null,renameName: "",renameMode: "rename",@@ -74,7 +82,14 @@ const model = {// --- Lifecycle -----------------------------------------------------------init() {- // Nothing special to do here; all methods available immediately+ if (this.settingsUpdatedHandler) return;+ this.settingsUpdatedHandler = (event) => {+ const value = event?.detail?.file_browser_remember_last_directory;+ if (typeof value !== "boolean") return;+ this.rememberLastDirectory = value;+ if (!value) this.clearRememberedDirectory();+ };+ document.addEventListener("settings-updated", this.settingsUpdatedHandler);},// --- Public API (called from button/link) --------------------------------@@ -85,6 +100,8 @@ const model = {this.history = [];this.searchQuery = "";this.isBulkBusy = false;+ this.pathError = "";+ this.isPathSubmitting = false;try {// Open modal FIRST (immediate UI feedback)@@ -92,12 +109,22 @@ const model = {"modals/file-browser/file-browser.html");- // Use stored initial path or default- path = path || this.initialPath || this.browser.currentPath || "$WORK_DIR";+ await this.loadDirectoryPreference();+ const explicitPath = this.normalizeOpeningPath(path || this.initialPath);+ const rememberedPath = !explicitPath ? this.getRememberedDirectory() : "";+ path = explicitPath || rememberedPath || "$WORK_DIR";this.browser.currentPath = path;+ this.syncPathInput();// Fetch files- await this.fetchFiles(this.browser.currentPath);+ const loaded = await this.fetchFiles(this.browser.currentPath, {+ preserveOnError: Boolean(rememberedPath && path === rememberedPath),+ suppressErrorToast: Boolean(rememberedPath && path === rememberedPath),+ });+ if (!loaded && rememberedPath && path === rememberedPath) {+ this.clearRememberedDirectory();+ await this.fetchFiles("$WORK_DIR");+ }// await modal closeawait this.closePromise;@@ -112,6 +139,7 @@ const model = {handleClose() {// Close the modal manually+ this.disposeScopedTooltips();window.closeModal();},@@ -124,6 +152,9 @@ const model = {this.openDropdownPath = null;this.searchQuery = "";this.isBulkBusy = false;+ this.pathInput = "";+ this.pathError = "";+ this.isPathSubmitting = false;this.resetRenameState();},@@ -249,6 +280,85 @@ const model = {});},+ normalizeOpeningPath(path) {+ return String(path || "").trim();+ },++ normalizeSubmittedPath(path) {+ const trimmed = String(path || "").trim();+ if (!trimmed || trimmed === "$WORK_DIR") return trimmed;+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;+ },++ syncPathInput() {+ this.pathInput = this.browser.currentPath || "";+ },++ resetPathInput() {+ this.syncPathInput();+ this.pathError = "";+ },++ async loadDirectoryPreference() {+ if (this.settingsLoadPromise) return await this.settingsLoadPromise;++ this.settingsLoadPromise = (async () => {+ try {+ const response = await callJsonApi("settings_get", null);+ const remember = response?.settings?.file_browser_remember_last_directory;+ this.rememberLastDirectory =+ typeof remember === "boolean" ? remember : DEFAULT_REMEMBER_LAST_DIRECTORY;+ } catch (error) {+ console.warn("Failed to load file browser directory preference:", error);+ this.rememberLastDirectory = DEFAULT_REMEMBER_LAST_DIRECTORY;+ } finally {+ if (!this.rememberLastDirectory) this.clearRememberedDirectory();+ this.settingsLoadPromise = null;+ }+ return this.rememberLastDirectory;+ })();++ return await this.settingsLoadPromise;+ },++ getRememberedDirectory() {+ if (!this.rememberLastDirectory) return "";+ try {+ return localStorage.getItem(FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY) || "";+ } catch {+ return "";+ }+ },++ rememberCurrentDirectory(path = this.browser.currentPath) {+ if (!this.rememberLastDirectory) return;+ const directory = this.normalizeOpeningPath(path);+ if (!directory || directory === "$WORK_DIR") return;+ try {+ localStorage.setItem(FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY, directory);+ } catch {}+ },++ clearRememberedDirectory() {+ try {+ localStorage.removeItem(FILE_BROWSER_LAST_DIRECTORY_STORAGE_KEY);+ } catch {}+ },++ disposeScopedTooltips() {+ const root = document.querySelector(".file-browser-root");+ const tooltipApi = globalThis.bootstrap?.Tooltip;+ if (!root || !tooltipApi) return;++ root.querySelectorAll("[data-bs-tooltip-initialized]").forEach((element) => {+ const instance = tooltipApi.getInstance(element);+ try {+ instance?.dispose();+ } catch {}+ });+ document.querySelectorAll(".tooltip").forEach((tooltip) => tooltip.remove());+ },+// --- Modal helpers -------------------------------------------------------normalizePath(path) {if (!path) return "";@@ -380,7 +490,9 @@ const model = {},// --- Navigation ----------------------------------------------------------- async fetchFiles(path = "") {+ async fetchFiles(path = "", options = {}) {+ const preserveOnError = options?.preserveOnError === true;+ const suppressErrorToast = options?.suppressErrorToast === true;this.isLoading = true;// Preserve scroll position if refreshing the same path@@ -397,14 +509,31 @@ const model = {);const data = await response.json().catch(() => ({}));- if (response.ok && !data.error) {+ const result = data.data || {};+ const requestedPath = String(path || "");+ const resultError =+ data.error ||+ result.error ||+ (+ requestedPath &&+ requestedPath !== "$WORK_DIR" &&+ !result.current_path &&+ !(result.entries || []).length+ ? "Directory not found or not accessible"+ : ""+ );++ if (response.ok && !resultError) {if (!isSamePath) this.searchQuery = "";this.browser.entries = this.decorateEntries(- data.data.entries || [],+ result.entries || [],selectedPaths);- this.browser.currentPath = data.data.current_path;- this.browser.parentPath = data.data.parent_path;+ this.browser.currentPath = result.current_path;+ this.browser.parentPath = result.parent_path;+ this.syncPathInput();+ this.pathError = "";+ this.rememberCurrentDirectory(this.browser.currentPath);// Set isLoading to false BEFORE restoring scroll to avoid reactivity issuesthis.isLoading = false;@@ -413,20 +542,23 @@ const model = {if (scrollPos) {this.restoreScrollPosition(scrollPos);}+ return true;} else {- const msg = data.error || "Error fetching files";+ const msg = resultError || "Error fetching files";console.error("Error fetching files:", msg);- this.browser.entries = [];+ if (!preserveOnError) this.browser.entries = [];this.isLoading = false;- window.toastFrontendError(msg, "File Browser Error");+ if (!suppressErrorToast) window.toastFrontendError(msg, "File Browser Error");+ return false;}} catch (e) {- window.toastFrontendError(- "Error fetching files: " + e.message,- "File Browser Error"- );- this.browser.entries = [];+ const message = "Error fetching files: " + e.message;+ if (!suppressErrorToast) {+ window.toastFrontendError(message, "File Browser Error");+ }+ if (!preserveOnError) this.browser.entries = [];this.isLoading = false;+ return false;}},@@ -437,6 +569,38 @@ const model = {await this.fetchFiles(path);},+ async submitPath() {+ if (this.isPathSubmitting || this.isLoading) return;++ const path = this.normalizeSubmittedPath(this.pathInput);+ if (!path) {+ this.pathError = "Enter a directory path.";+ return;+ }++ this.isPathSubmitting = true;+ this.pathError = "";++ try {+ const previousPath = this.browser.currentPath;+ const loaded = await this.fetchFiles(path, {+ preserveOnError: true,+ suppressErrorToast: true,+ });++ if (loaded) {+ if (previousPath && previousPath !== this.browser.currentPath) {+ this.history.push(previousPath);+ }+ return;+ }++ this.pathError = "Directory not found or not accessible.";+ } finally {+ this.isPathSubmitting = false;+ }+ },+async navigateUp() {if (this.browser.parentPath) {this.history.push(this.browser.currentPath);@@ -855,6 +1019,7 @@ const model = {}}+ this.disposeScopedTooltips();await window.closeModal?.("modals/file-browser/file-browser.html");} catch (error) {window.toastFrontendError?.(diff --git a/webui/components/modals/file-browser/file-browser.html b/webui/components/modals/file-browser/file-browser.htmlindex 7e090dc8e..cca3f1c1c 100644--- a/webui/components/modals/file-browser/file-browser.html+++ b/webui/components/modals/file-browser/file-browser.html@@ -19,14 +19,41 @@<!-- File Browser Content --><div x-show="!$store.fileBrowser.isLoading" class="file-browser-content"><!-- Path navigator -->- <div class="path-navigator">- <button class="text-button back-button" @click="$store.fileBrowser.navigateUp()" aria-label="Navigate Up">- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10.5 15">- <path d="m.75,5.25L5.25.75m0,0l4.5,4.5M5.25.75v13.5" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" />- </svg>- Up- </button>- <div id="current-path"><span id="path-text" x-text="$store.fileBrowser.browser.currentPath"></span></div>+ <div class="path-navigator-wrap">+ <form class="path-navigator" @submit.prevent="$store.fileBrowser.submitPath()">+ <button type="button" class="text-button back-button" @click="$store.fileBrowser.navigateUp()" aria-label="Navigate Up">+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10.5 15">+ <path d="m.75,5.25L5.25.75m0,0l4.5,4.5M5.25.75v13.5" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" />+ </svg>+ Up+ </button>+ <div class="path-input-shell" :class="{ 'has-error': $store.fileBrowser.pathError }">+ <span class="material-symbols-outlined path-input-icon" aria-hidden="true">folder_open</span>+ <input+ id="current-path"+ class="path-input"+ type="text"+ x-model="$store.fileBrowser.pathInput"+ @focus="$event.target.select()"+ @keydown.escape.stop.prevent="$store.fileBrowser.resetPathInput()"+ :aria-invalid="$store.fileBrowser.pathError ? 'true' : 'false'"+ aria-label="Directory path"+ spellcheck="false"+ autocomplete="off"+ />+ <button+ type="submit"+ class="btn-icon-action path-submit"+ :disabled="$store.fileBrowser.isPathSubmitting || $store.fileBrowser.isLoading"+ aria-label="Go to directory"+ >+ <span class="material-symbols-outlined">arrow_forward</span>+ </button>+ </div>+ </form>+ <template x-if="$store.fileBrowser.pathError">+ <div class="path-error" x-text="$store.fileBrowser.pathError"></div>+ </template></div><div class="file-browser-toolbar"><div class="file-search-shell">@@ -442,11 +469,17 @@}/* Path Navigator Styles */+ .path-navigator-wrap {+ display: flex;+ flex-direction: column;+ gap: 0.35rem;+ }+.path-navigator {overflow: hidden;display: flex;align-items: center;- gap: 24px;+ gap: 0.75rem;background-color: var(--color-message-bg);padding: 0.5rem var(--spacing-sm);margin: 0;@@ -454,6 +487,75 @@border-radius: 8px;}+ .path-navigator .back-button {+ flex: 0 0 auto;+ }++ .path-input-shell {+ position: relative;+ display: flex;+ align-items: center;+ flex: 1;+ min-width: 0;+ }++ .path-input-icon {+ position: absolute;+ left: 0.75rem;+ font-size: 1.15rem;+ color: var(--color-primary);+ opacity: 0.8;+ pointer-events: none;+ }++ .path-input {+ width: 100%;+ height: 2.25rem;+ min-width: 0;+ border: 1px solid transparent;+ border-radius: 6px;+ background: color-mix(in srgb, var(--color-input) 78%, transparent);+ color: var(--color-text);+ padding: 0 2.5rem 0 2.35rem;+ font: inherit;+ font-family: 'Roboto Mono', monospace;+ -webkit-font-optical-sizing: auto;+ font-optical-sizing: auto;+ line-height: 1;+ transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;+ }++ .path-input:focus {+ outline: none;+ border-color: var(--color-primary);+ background: var(--color-input-focus);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--color-primary) 20%, transparent);+ }++ .path-input-shell.has-error .path-input {+ border-color: var(--color-error);+ box-shadow: 0 0 0 1px color-mix(in srgb, var(--color-error) 18%, transparent);+ }++ .path-submit {+ position: absolute;+ right: 0.35rem;+ width: 1.75rem;+ height: 1.75rem;+ color: var(--color-text);+ }++ .path-submit:disabled {+ opacity: 0.5;+ cursor: wait;+ }++ .path-error {+ color: var(--color-error);+ font-size: 0.8rem;+ padding: 0 0.25rem;+ }+.file-browser-toolbar {display: flex;align-items: center;@@ -549,16 +651,6 @@.nav-button.back-button:hover {background-color: var(--color-secondary-dark);}- #current-path {- opacity: 0.9;- }- #path-text {- font-family: 'Roboto Mono', monospace;- -webkit-font-optical-sizing: auto;- font-optical-sizing: auto;- opacity: 0.9;- }-/* Folder Specific Styles */.file-item[data-is-dir="true"] {cursor: pointer;@@ -621,6 +713,14 @@}/* Responsive Design */@media (max-width: 768px) {+ .path-navigator {+ align-items: stretch;+ flex-direction: column;+ gap: 0.5rem;+ }+ .path-navigator .back-button {+ align-self: flex-start;+ }.file-browser-toolbar {align-items: stretch;flex-direction: column;diff --git a/webui/components/settings/agent/workdir.html b/webui/components/settings/agent/workdir.htmlindex 30cd30d8d..cb165eb15 100644--- a/webui/components/settings/agent/workdir.html+++ b/webui/components/settings/agent/workdir.html@@ -28,6 +28,21 @@</div></div>+ <div class="field">+ <div class="field-label">+ <div class="field-title">Remember last file browser location</div>+ <div class="field-description">+ Open the file browser at the most recently visited directory when no specific path is requested.+ </div>+ </div>+ <div class="field-control">+ <label class="toggle">+ <input type="checkbox" x-model="$store.settings.settings.file_browser_remember_last_directory" />+ <span class="toggler"></span>+ </label>+ </div>+ </div>+<div class="field"><div class="field-label"><div class="field-title">Show workdir structure to the agent</div>