Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(file-browser): right-click actions, drag-move, and recursive name search (#734)
Call White1304800e1dbd
diff --git a/core/file_browser_service.py b/core/file_browser_service.pyindex 2fce533b3..0c44fd36d 100644--- a/core/file_browser_service.py+++ b/core/file_browser_service.py@@ -927,6 +927,7 @@ SEARCH_MAX_MATCHES = 1000SEARCH_MAX_FILES = 200SEARCH_LINE_PREVIEW_CHARS = 400SEARCH_PREVIEW_CONTEXT = 60+SEARCH_NAME_MAX_RESULTS = 500_BINARY_SNIFF_BYTES = 8192# Directories never worth searching — VCS metadata, dependency/build output,@@ -1183,6 +1184,94 @@ def search(}+def _name_search_hit(path: Path, root: Path) -> dict[str, Any] | None:+ """Build one name-search result row for ``path`` (no-follow stat), or None if it vanished.++ Mirrors ``_entry_payload`` but adds the absolute ``path`` and the ``rel`` path from ``root`` so+ the UI can render the containing folder and navigate/open the hit directly.+ """+ try:+ st = path.lstat()+ except OSError:+ return None+ kind = _kind_from_mode(st.st_mode)+ size = st.st_size if stat.S_ISREG(st.st_mode) else None+ try:+ rel = path.relative_to(root).as_posix()+ except ValueError:+ rel = path.name+ return {+ "name": path.name,+ "kind": kind,+ "size": size,+ "mtime": _mtime_seconds(st),+ "ext": _extension(path) if kind != "dir" else "",+ "path": str(path),+ "rel": rel,+ }+++def search_names(+ raw_root: str,+ query: str,+ *,+ show_hidden: bool = False,+ max_results: int = SEARCH_NAME_MAX_RESULTS,+) -> dict[str, Any]:+ """Recursively find entries under ``root`` whose NAME matches ``query``.++ Case-insensitive substring match over both file AND directory names — the file-browser+ counterpart to the content ``search`` above (which greps file *contents* and never returns+ directories). Prunes the same heavy noise trees (.git / node_modules / build output) so a search+ can't stall descending into them, and skips dotfiles/dirs unless ``show_hidden``. Results come+ back in walk order (shallow first, a rough relevance signal) and are bounded by ``max_results``;+ ``truncated`` is set when the cap is hit so the UI can say results were limited.+ """+ root = _require_directory(raw_root)+ needle = query.strip().lower()+ if not needle:+ raise FileBrowserError("invalid_query", "Search query is required", 400)++ results: list[dict[str, Any]] = []+ truncated = False+ # os.walk swallows per-directory errors by default, so an unreadable subtree is silently skipped+ # (the search keeps going) rather than aborting the whole walk.+ for dirpath, dirnames, filenames in os.walk(root, followlinks=False):+ # Prune in place: drop noise trees and (unless show_hidden) hidden dirs so os.walk never+ # descends into them. The retained dir names are still candidates to MATCH below.+ dirnames[:] = sorted(+ d for d in dirnames if d not in SEARCH_SKIP_DIRS and (show_hidden or not d.startswith("."))+ )+ base = Path(dirpath)+ # Directories first, then files, each alphabetically — mirrors the listing's grouping.+ for name in list(dirnames) + sorted(filenames):+ if not show_hidden and name.startswith("."):+ continue+ if needle not in name.lower():+ continue+ # Check the cap BEFORE recording (mirrors the content search): flagging truncated only on+ # a match BEYOND the cap means a result set of exactly max_results isn't falsely marked+ # truncated (which would make the UI claim results were limited when they weren't).+ if len(results) >= max_results:+ truncated = True+ break+ hit = _name_search_hit(base / name, root)+ if hit is None:+ continue+ results.append(hit)+ if truncated:+ break++ return {+ "ok": True,+ "root": str(root),+ "query": query,+ "results": results,+ "truncated": truncated,+ "limit": max_results if truncated else None,+ }++def _apply_replacement(text: str, matcher: "re.Pattern[str]", replacement: str, *, regex: bool) -> tuple[str, int]:# Per-line replace so the count and behavior match the per-line search/preview.# Literal mode treats the replacement verbatim (a lambda avoids backref expansion);diff --git a/tests/test_file_search.py b/tests/test_file_search.pyindex 0fd4b62d0..3c42c1fff 100644--- a/tests/test_file_search.py+++ b/tests/test_file_search.py@@ -347,3 +347,88 @@ def test_search_root_must_be_directory(tmp_path):f = _write(tmp_path, "a.txt", "x\n")with pytest.raises(FileBrowserError):fbs.search(str(f), "x")+++# ---------------------------------------------------------------------------+# Recursive name search (search_names): matches file AND folder names by name,+# recursively, unlike the content search above.+# ---------------------------------------------------------------------------+++def _names(result: dict) -> set[str]:+ return {entry["rel"] for entry in result["results"]}+++def test_search_names_matches_files_and_dirs_recursively(tmp_path):+ _write(tmp_path, "report.txt", "x")+ _write(tmp_path, "sub/report-2.md", "x")+ (tmp_path / "reports").mkdir() # a DIRECTORY whose name matches — content search would miss this+ _write(tmp_path, "sub/deep/nope.txt", "x")++ result = fbs.search_names(str(tmp_path), "report")++ assert _names(result) == {"report.txt", "sub/report-2.md", "reports"}+ kinds = {entry["rel"]: entry["kind"] for entry in result["results"]}+ assert kinds["reports"] == "dir"+ assert kinds["report.txt"] == "file"+ assert result["truncated"] is False+++def test_search_names_case_insensitive_substring(tmp_path):+ _write(tmp_path, "ReadMe.md", "x")+ _write(tmp_path, "notes/read_later.txt", "x")+ assert _names(fbs.search_names(str(tmp_path), "read")) == {"ReadMe.md", "notes/read_later.txt"}+++def test_search_names_prunes_noise_dirs(tmp_path):+ # A match buried in node_modules must not surface, and the walk must not descend into it.+ _write(tmp_path, "node_modules/pkg/target.js", "x")+ _write(tmp_path, "src/target.ts", "x")+ assert _names(fbs.search_names(str(tmp_path), "target")) == {"src/target.ts"}+++def test_search_names_honors_show_hidden(tmp_path):+ _write(tmp_path, ".secret-target", "x")+ _write(tmp_path, ".hidden/target.txt", "x")+ _write(tmp_path, "target.txt", "x")++ visible = fbs.search_names(str(tmp_path), "target")+ assert _names(visible) == {"target.txt"}++ # show_hidden descends into .hidden/ and matches dotfiles; the .hidden dir itself doesn't match+ # "target", so it isn't a result — but its matching child now is.+ hidden = fbs.search_names(str(tmp_path), "target", show_hidden=True)+ assert _names(hidden) == {".secret-target", ".hidden/target.txt", "target.txt"}+++def test_search_names_empty_query_rejected(tmp_path):+ _write(tmp_path, "a.txt", "x")+ with pytest.raises(FileBrowserError) as exc:+ fbs.search_names(str(tmp_path), " ")+ assert exc.value.code == "invalid_query"+++def test_search_names_truncates_at_cap(tmp_path):+ for i in range(6):+ _write(tmp_path, f"match-{i}.txt", "x")+ result = fbs.search_names(str(tmp_path), "match", max_results=3)+ assert len(result["results"]) == 3+ assert result["truncated"] is True+ assert result["limit"] == 3+++def test_search_names_exactly_at_cap_not_truncated(tmp_path):+ # Exactly max_results matches: everything is returned, so truncated must stay False (matches the+ # content search's before-record cap check; the naive after-append check would false-positive).+ for i in range(3):+ _write(tmp_path, f"match-{i}.txt", "x")+ result = fbs.search_names(str(tmp_path), "match", max_results=3)+ assert len(result["results"]) == 3+ assert result["truncated"] is False+ assert result["limit"] is None+++def test_search_names_root_must_be_directory(tmp_path):+ f = _write(tmp_path, "a.txt", "x")+ with pytest.raises(FileBrowserError):+ fbs.search_names(str(f), "a")diff --git a/ui/src/components/ui/context-menu.tsx b/ui/src/components/ui/context-menu.tsxnew file mode 100644index 000000000..9dbb72b67--- /dev/null+++ b/ui/src/components/ui/context-menu.tsx@@ -0,0 +1,73 @@+import { useEffect } from 'react';+import clsx from 'clsx';++// A cursor-positioned right-click menu, shared by the editor's file tree and the File Browser app.+// Rendered inline (not portaled) so it inherits the surrounding window's theme scope, exactly like+// the original FileTree menu it was extracted from. A full-viewport backdrop closes it on any click+// (or right-click), and Escape closes it too.++export const ContextMenuItem: React.FC<{+ icon?: React.ReactNode;+ label: string;+ danger?: boolean;+ onClick: () => void;+}> = ({ icon, label, danger, onClick }) => (+ <button+ type="button"+ role="menuitem"+ onClick={onClick}+ className={clsx(+ 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-left text-[12.5px] transition',+ danger ? 'text-destructive hover:bg-destructive/[0.1]' : 'text-foreground hover:bg-cyan-soft',+ )}+ >+ {icon !== undefined && <span className="grid size-4 shrink-0 place-items-center">{icon}</span>}+ {label}+ </button>+);++export const ContextMenu: React.FC<{+ x: number;+ y: number;+ onClose: () => void;+ children: React.ReactNode;+ /** Menu width in px (default 196), used for horizontal viewport clamping. */+ width?: number;+ /** Number of items, used to estimate height for vertical viewport clamping. */+ itemCount?: number;+}> = ({ x, y, onClose, children, width = 196, itemCount = 4 }) => {+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === 'Escape') onClose();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [onClose]);++ // Clamp inside the viewport: a cursor near the right/bottom edge would otherwise overflow. The+ // height is an estimate (item count × row height + padding) — good enough to nudge it back in.+ const height = itemCount * 34 + 12;+ const left = Math.max(8, Math.min(x, window.innerWidth - width - 8));+ const top = Math.max(8, Math.min(y, window.innerHeight - height - 8));++ return (+ <>+ <div+ className="fixed inset-0 z-40"+ onClick={onClose}+ onContextMenu={(e) => {+ e.preventDefault();+ onClose();+ }}+ aria-hidden+ />+ <div+ role="menu"+ style={{ left, top, width }}+ className="fixed z-50 rounded-lg border border-border bg-surface-3 p-1 shadow-[0_12px_30px_-8px_rgba(0,0,0,0.7)]"+ >+ {children}+ </div>+ </>+ );+};diff --git a/ui/src/components/ui/inline-name-input.tsx b/ui/src/components/ui/inline-name-input.tsxnew file mode 100644index 000000000..8af80246e--- /dev/null+++ b/ui/src/components/ui/inline-name-input.tsx@@ -0,0 +1,43 @@+import { useRef, useState } from 'react';++// Shared inline name editor for new-entry and rename rows across the file tree and File Browser:+// autofocus, select-all on focus (rename keeps the current name so it can be tweaked), Enter+// commits, Esc/blur cancels. Cancel-on-blur is suppressed right after an Enter/Esc so committing+// (which also blurs) doesn't double-fire.+export const InlineNameInput: React.FC<{+ initial: string;+ placeholder?: string;+ onCommit: (value: string) => void;+ onCancel: () => void;+ className?: string;+}> = ({ initial, placeholder, onCommit, onCancel, className }) => {+ const [value, setValue] = useState(initial);+ const committed = useRef(false);+ return (+ <input+ autoFocus+ value={value}+ placeholder={placeholder}+ onFocus={(e) => e.currentTarget.select()}+ onChange={(e) => setValue(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ committed.current = true;+ onCommit(value);+ } else if (e.key === 'Escape') {+ e.preventDefault();+ committed.current = true;+ onCancel();+ }+ }}+ onBlur={() => {+ if (!committed.current) onCancel();+ }}+ className={+ className ??+ 'min-w-0 flex-1 rounded border border-cyan bg-surface px-1 py-0 text-[12.5px] text-foreground placeholder:text-muted focus:outline-none'+ }+ />+ );+};diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsxindex 88b7aafd2..2d345c9e5 100644--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx@@ -18,8 +18,10 @@ import {Image as ImageIcon,Loader2,Monitor,+ Pencil,RefreshCw,Search,+ Trash2,X,type LucideIcon,} from 'lucide-react';@@ -30,6 +32,7 @@ import { useWindowManager } from '../../context/WindowManagerContext';import { isEditableFile, isEditableMeta, previewOverlayKind, type PreviewOverlayKind } from '../../lib/filePreview';import {contentUrl,+ deletePath,downloadFile,fileBrowserErrorMessage,fileMeta,@@ -37,15 +40,22 @@ import {joinPath,listDir,makeDir,+ movePath,+ parentDir,pathCrumbs,+ renamePath,+ searchNames,systemFavorites,writeFile,type Favorite,type FsEntry,type FsListing,+ type NameHit,} from '../../lib/filesApi';import { Button } from '../ui/button';+import { ContextMenu, ContextMenuItem } from '../ui/context-menu';import { FilePreview } from '../ui/file-preview';+import { InlineNameInput } from '../ui/inline-name-input';// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).const EXT_ICON: Record<string, { Icon: LucideIcon; color: string }> = {@@ -79,6 +89,11 @@ const FAV_ICON: Record<string, LucideIcon> = {root: HardDrive,};+// One row in the listing OR the recursive-search results. `full` is the absolute path; `dir` is its+// parent (where rename/delete/move resolve); `rel` (search hits only) is the path relative to the+// search root, so a nested hit can show the folder it lives in.+type RowItem = { entry: FsEntry; full: string; dir: string; rel?: string };+function formatSize(n: number | null): string {if (n == null) return '—';if (n < 1024) return `${n} B`;@@ -97,10 +112,19 @@ function formatMtime(seconds: number | null): string {return `${date} ${time}`;}-// Whole-machine Finder: favorites/projects rail + a Name/Size/Modified list + a toolbar-// (breadcrumb, search, New File/Folder) + a status bar. A pure directory browser — it does-// not edit files; double-clicking a text/code file opens it in the Editor window. Backend-// contract: ui/src/lib/filesApi.ts → /api/files/*. Design: design.pen `nknn2`.+// The folder an entry lives in, relative to the search root (for search-result rows). Empty for a+// direct child of the search root (rel is just the name).+function relFolder(rel: string | undefined): string {+ if (!rel || !rel.includes('/')) return '';+ return rel.slice(0, rel.lastIndexOf('/'));+}++// Whole-machine Finder: favorites/projects rail + a Name/Size/Modified list + a toolbar (breadcrumb,+// search, New File/Folder) + a status bar. Right-click a row for Open/Download/Rename/Delete, or+// blank space for New File/Folder; drag a row onto a folder (row, rail, or breadcrumb) to move it;+// the search box does a recursive file/folder NAME search under the current folder. Double-clicking a+// text/code file opens it in the Editor window. Backend contract: ui/src/lib/filesApi.ts →+// /api/files/*. Design: design.pen `nknn2`.export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: string }> = ({ windowed = false }) => {const { t } = useTranslation();const wm = useWindowManager();@@ -177,84 +201,139 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri// eslint-disable-next-line react-hooks/exhaustive-deps}, [showHidden]);- // Open: dir → navigate; raster image → in-window preview overlay; editable text/code file (within- // the size cap) → Editor window; anything else → raw download.- const open = async (e: FsEntry) => {- const full = joinPath(cwd, e.name);- if (e.kind === 'dir') {- navigate(full);+ // ---- Recursive name search (backend: /api/files/search_names) --------------------------------+ // A non-empty query switches the listing to recursive file/folder NAME results under `cwd`. The+ // search is debounced and abortable so fast typing doesn't pile up stale requests.+ const [searchResults, setSearchResults] = useState<NameHit[] | null>(null);+ const [searchTruncated, setSearchTruncated] = useState(false);+ const [searchBusy, setSearchBusy] = useState(false);+ const searchSeq = useRef(0);+ const searchAbort = useRef<AbortController | null>(null);+ const inSearch = query.trim().length > 0;++ const runSearch = useCallback(+ (raw: string) => {+ const q = raw.trim();+ searchAbort.current?.abort();+ if (!q || !cwd) {+ setSearchResults(null);+ setSearchBusy(false);+ return;+ }+ const ac = new AbortController();+ searchAbort.current = ac;+ const seq = ++searchSeq.current;+ setSearchBusy(true);+ searchNames(cwd, q, showHidden, ac.signal)+ .then((r) => {+ if (seq !== searchSeq.current) return;+ setSearchResults(r.results);+ setSearchTruncated(r.truncated);+ })+ .catch((e: unknown) => {+ if (seq !== searchSeq.current || (e as { name?: string })?.name === 'AbortError') return;+ setSearchResults([]);+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.searchFailed')));+ })+ .finally(() => {+ if (seq === searchSeq.current) setSearchBusy(false);+ });+ },+ [cwd, showHidden, t],+ );++ // Debounce the search as the user types; also re-fires when cwd/showHidden change (runSearch+ // identity changes), so switching folders re-scopes an active search.+ useEffect(() => {+ const q = query.trim();+ if (!q) {+ searchAbort.current?.abort();+ setSearchResults(null);+ setSearchBusy(false);return;}- // A raster image, PDF, or Office doc (DOCX / XLSX / PPTX) → preview read-only in the in-window- // overlay instead of downloading. Works on mobile too (the overlay is in-window, unlike the- // desktop-only editor). Editable text (incl. svg / html / markdown) is excluded here — it opens in- // the editor, which carries its own Source ⇄ Preview toggle.- const overlay = previewOverlayKind(e);+ const id = window.setTimeout(() => runSearch(query), 220);+ return () => window.clearTimeout(id);+ }, [query, runSearch]);++ useEffect(() => () => searchAbort.current?.abort(), []);++ // After a mutation: re-list the current folder, and re-run the search if one is active.+ const refreshAll = useCallback(() => {+ if (cwd) navigate(cwd);+ if (query.trim()) runSearch(query);+ }, [cwd, navigate, query, runSearch]);++ // Open: dir → navigate (and leave search); raster image / PDF / Office doc → in-window preview+ // overlay; editable text/code file (within the size cap) → Editor window; anything else → download.+ const openItem = async (item: RowItem) => {+ if (item.entry.kind === 'dir') {+ setQuery('');+ navigate(item.full);+ return;+ }+ const overlay = previewOverlayKind(item.entry);if (overlay) {- setPreview({ path: full, name: e.name, kind: overlay });+ setPreview({ path: item.full, name: item.entry.name, kind: overlay });return;}// Mobile has no editor window layer (windows are md+), so a non-previewable file just downloads.const desktop = window.matchMedia('(min-width: 768px)').matches;if (!desktop) {- downloadFile(full);+ downloadFile(item.full);return;}- // Desktop: fetch CURRENT metadata (which content-sniffs `text`) and decide by CONTENT, not just- // the extension — so an extensionless / unknown-type TEXT file (LICENSE, README, a `notes` file)- // opens in the editor instead of downloading, while a symlink / oversized / binary file- // downloads. Awaiting is safe: opening an internal window needs no user activation, and the- // anchor download (the binary branch) isn't a popup, so it survives the await.+ // Desktop: fetch CURRENT metadata (content-sniffs `text`) and decide by CONTENT, not just the+ // extension — so an extensionless TEXT file opens in the editor while a binary file downloads.try {- const m = await fileMeta(full);+ const m = await fileMeta(item.full);if (isEditableMeta(m)) {- wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: m.mtime } });+ wm.openApp('editor', { title: item.entry.name, params: { path: item.full, filename: item.entry.name, mtime: m.mtime } });} else {- downloadFile(full);+ downloadFile(item.full);}} catch {- // Metadata fetch failed — fall back to the name-only guess so a known text type still opens.- if (isEditableFile(e)) {- wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: e.mtime } });+ if (isEditableFile(item.entry)) {+ wm.openApp('editor', { title: item.entry.name, params: { path: item.full, filename: item.entry.name, mtime: item.entry.mtime } });} else {- downloadFile(full);+ downloadFile(item.full);}}};- // New File / New Folder: an inline editable row in the listing (mirrors FilePicker), not a- // window.prompt. null = not creating. Enter creates, Esc/blur cancels.- const [newEntry, setNewEntry] = useState<{ kind: 'file' | 'folder'; value: string } | null>(null);+ // New File / New Folder: an inline editable row in the listing (mirrors FilePicker). Starting one+ // clears any active search so the create row is visible in the current folder.+ const [newEntry, setNewEntry] = useState<{ kind: 'file' | 'folder' } | null>(null);const startNewEntry = useCallback((kind: 'file' | 'folder') => {setError(null);- setNewEntry({ kind, value: '' });+ setQuery('');+ setNewEntry({ kind });}, []);- const newEntryRef = useRef<{ kind: 'file' | 'folder'; value: string } | null>(null);- newEntryRef.current = newEntry;- const commitNewEntry = useCallback(async () => {- const session = newEntryRef.current;- if (!session) return;- const name = session.value.trim();- if (name === '') {- setNewEntry(null);- return;- }- if (!isPlainEntryName(name)) {- setError(t('apps.fileBrowser.errors.invalid_name'));- return;- }- try {- // create-only on files: the backend atomically refuses a name clash, so a typo can't clobber.- if (session.kind === 'folder') await makeDir(joinPath(cwd, name));- else await writeFile(joinPath(cwd, name), '', undefined, true);- setNewEntry(null);- navigate(cwd);- } catch (e: unknown) {- setError(- fileBrowserErrorMessage(e, t, t(session.kind === 'folder' ? 'apps.fileBrowser.errors.createFolderFailed' : 'apps.fileBrowser.errors.saveFailed')),- );- }- }, [cwd, navigate, t]);+ const commitNewEntry = useCallback(+ async (kind: 'file' | 'folder', value: string) => {+ const name = value.trim();+ if (name === '') {+ setNewEntry(null);+ return;+ }+ if (!isPlainEntryName(name)) {+ setError(t('apps.fileBrowser.errors.invalid_name'));+ return;+ }+ try {+ // create-only on files: the backend atomically refuses a name clash, so a typo can't clobber.+ if (kind === 'folder') await makeDir(joinPath(cwd, name));+ else await writeFile(joinPath(cwd, name), '', undefined, true);+ setNewEntry(null);+ refreshAll();+ } catch (e: unknown) {+ setError(+ fileBrowserErrorMessage(e, t, t(kind === 'folder' ? 'apps.fileBrowser.errors.createFolderFailed' : 'apps.fileBrowser.errors.saveFailed')),+ );+ }+ },+ [cwd, refreshAll, t],+ );// New File: on DESKTOP open the Editor rooted at the current dir with a fresh untitled buffer// (richer creation + editing flow; first save lands in cwd). On mobile the editor window layer is@@ -268,16 +347,112 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri}}, [cwd, wm, t, startNewEntry]);+ // ---- Rename (inline) + Delete ----------------------------------------------------------------+ const [rename, setRename] = useState<{ full: string } | null>(null);+ const startRename = useCallback((item: RowItem) => {+ setError(null);+ setRename({ full: item.full });+ }, []);+ const commitRename = useCallback(+ async (item: RowItem, value: string) => {+ const name = value.trim();+ if (name === '' || name === item.entry.name) {+ setRename(null);+ return;+ }+ if (!isPlainEntryName(name)) {+ setError(t('apps.fileBrowser.errors.invalid_name'));+ return;+ }+ try {+ await renamePath(item.full, name);+ setRename(null);+ setError(null);+ refreshAll();+ } catch (e: unknown) {+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.renameFailed')));+ }+ },+ [refreshAll, t],+ );++ const removeItem = useCallback(+ async (item: RowItem) => {+ setMenu(null);+ if (!window.confirm(t('apps.fileBrowser.confirmDelete', { name: item.entry.name }))) return;+ try {+ await deletePath(item.full, item.entry.kind === 'dir');+ setError(null);+ setSelected((s) => (s === item.full ? null : s));+ refreshAll();+ } catch (e: unknown) {+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.deleteFailed')));+ }+ },+ [t, refreshAll],+ );++ // ---- Context menu ----------------------------------------------------------------------------+ // `item` is null for blank space (offers New File/Folder only).+ const [menu, setMenu] = useState<{ x: number; y: number; item: RowItem | null } | null>(null);+ const openMenu = useCallback((ev: React.MouseEvent, item: RowItem | null) => {+ ev.preventDefault();+ ev.stopPropagation();+ setMenu({ x: ev.clientX, y: ev.clientY, item });+ }, []);+ const closeMenu = useCallback(() => setMenu(null), []);++ // ---- Drag-and-drop move ----------------------------------------------------------------------+ // The dragged row is held in a ref (no re-render mid-drag); `dropTarget` (a folder path) drives the+ // hover highlight. Folders — rows, rail favorites/projects, and breadcrumbs — are drop targets.+ const dragRef = useRef<RowItem | null>(null);+ const [dropTarget, setDropTarget] = useState<string | null>(null);+ const moveInto = useCallback(+ async (destDir: string) => {+ const item = dragRef.current;+ dragRef.current = null;+ setDropTarget(null);+ // No-op if it's already in that folder or dropped onto itself; the backend also refuses moving+ // a folder into its own subtree, which surfaces as an error below.+ if (!item || item.dir === destDir || item.full === destDir) return;+ try {+ await movePath(item.full, joinPath(destDir, item.entry.name));+ setError(null);+ refreshAll();+ } catch (e: unknown) {+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.moveFailed')));+ }+ },+ [t, refreshAll],+ );+ // Drop-target props for any folder (row / rail / breadcrumb). Only active while a drag is in flight+ // and never onto the dragged item itself.+ const dropProps = (destDir: string) => ({+ onDragOver: (e: React.DragEvent) => {+ if (!dragRef.current || dragRef.current.full === destDir) return;+ e.preventDefault();+ setDropTarget((d) => (d === destDir ? d : destDir));+ },+ onDragLeave: () => setDropTarget((d) => (d === destDir ? null : d)),+ onDrop: (e: React.DragEvent) => {+ e.preventDefault();+ void moveInto(destDir);+ },+ });+const projectFavs = useMemo(() => (projects || []).filter((p) => !!p.folder_path).map((p) => ({ label: p.display_name, path: p.folder_path as string })),[projects],);const crumbs = cwd ? pathCrumbs(cwd) : [];- const entries = useMemo(() => {- const all = listing?.entries ?? [];- const q = query.trim().toLowerCase();- const filtered = q ? all.filter((e) => e.name.toLowerCase().includes(q)) : all;- return [...filtered].sort((a, b) => {++ // Rows come from the recursive search when a query is active (backend walk order: shallow first),+ // otherwise from the current-folder listing (dirs-first, then the active column sort).+ const rows = useMemo<RowItem[]>(() => {+ if (query.trim()) {+ return (searchResults ?? []).map((h) => ({ entry: h as FsEntry, full: h.path, dir: parentDir(h.path), rel: h.rel }));+ }+ const all = [...(listing?.entries ?? [])].sort((a, b) => {// Folders always group before files, regardless of column/direction (Finder-like).if (a.kind !== b.kind) return a.kind === 'dir' ? -1 : 1;if (!sort) return a.name.localeCompare(b.name);@@ -288,11 +463,14 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striif (r === 0) r = a.name.localeCompare(b.name);return sort.dir === 'asc' ? r : -r;});- }, [listing, query, sort]);- const selectedEntry = useMemo(- () => (selected ? entries.find((e) => joinPath(cwd, e.name) === selected) ?? null : null),- [entries, cwd, selected],- );+ return all.map((e) => ({ entry: e, full: joinPath(cwd, e.name), dir: cwd }));+ }, [query, searchResults, listing, sort, cwd]);++ const selectedEntry = useMemo(() => (selected ? rows.find((r) => r.full === selected)?.entry ?? null : null), [rows, selected]);++ const showInitialSpinner = inSearch ? searchBusy && searchResults === null : loading && !listing;+ const showEmpty = inSearch ? !searchBusy && (searchResults?.length ?? 0) === 0 : !!listing && rows.length === 0 && newEntry === null;+ const menuItemCount = menu ? (menu.item ? (menu.item.entry.kind === 'dir' ? 3 : 4) : 2) : 0;return (<div className={windowed ? 'relative flex h-full w-full flex-col bg-surface' : 'relative flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'}>@@ -307,16 +485,23 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{/* Toolbar: breadcrumb (left) + search + New File / New Folder (right) */}<div className="flex items-center gap-2 border-b border-border bg-surface-2/60 px-3 py-2"><div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">- <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0 text-muted" aria-label={t('apps.fileBrowser.refresh')} onClick={() => cwd && navigate(cwd)}>- <RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />+ <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0 text-muted" aria-label={t('apps.fileBrowser.refresh')} onClick={() => cwd && refreshAll()}>+ <RefreshCw className={clsx('size-3.5', (loading || searchBusy) && 'animate-spin')} /></Button>{crumbs.map((c, i) => (<span key={c.path} className="flex shrink-0 items-center">{i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}<buttontype="button"- onClick={() => navigate(c.path)}- className="max-w-[140px] truncate rounded px-1.5 py-0.5 text-[12.5px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"+ onClick={() => {+ setQuery('');+ navigate(c.path);+ }}+ {...dropProps(c.path)}+ className={clsx(+ 'max-w-[140px] truncate rounded px-1.5 py-0.5 text-[12.5px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground',+ dropTarget === c.path && 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan',+ )}>{c.label}</button>@@ -324,13 +509,18 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri))}</div><label className="flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2 py-1">- <Search className="size-3.5 shrink-0 text-muted" />+ {searchBusy ? <Loader2 className="size-3.5 shrink-0 animate-spin text-muted" /> : <Search className="size-3.5 shrink-0 text-muted" />}<inputvalue={query}onChange={(e) => setQuery(e.target.value)}placeholder={t('apps.fileBrowser.searchPlaceholder')}className="w-28 bg-transparent text-[12px] text-foreground placeholder:text-muted focus:outline-none"/>+ {query && (+ <button type="button" onClick={() => setQuery('')} className="shrink-0 text-muted transition hover:text-foreground" aria-label={t('common.close')}>+ <X className="size-3" strokeWidth={2.5} />+ </button>+ )}</label><Button type="button" size="sm" variant="brand" className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]" disabled={!cwd || newEntry !== null} onClick={onNewFile}><FilePlus className="size-3.5" /> {t('apps.fileBrowser.newFile')}@@ -343,7 +533,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{error && <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive">{error}</div>}<div className="flex min-h-0 flex-1 overflow-hidden">- {/* Rail: Favorites THEN Projects (design nknn2 order). */}+ {/* Rail: Favorites THEN Projects (design nknn2 order). Folders here are drop targets too. */}<aside className="hidden w-[196px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border bg-surface-2/40 p-2 md:flex">{sysFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.favorites')}</RailTitle>}{sysFavs.map((f) => {@@ -354,13 +544,29 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striicon={<Icon className="size-3.5 text-muted" />}label={f.path.split('/').filter(Boolean).pop() || f.path}active={cwd === f.path}- onClick={() => navigate(f.path)}+ dropActive={dropTarget === f.path}+ dropProps={dropProps(f.path)}+ onClick={() => {+ setQuery('');+ navigate(f.path);+ }}/>);})}{projectFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.projects')}</RailTitle>}{projectFavs.map((f) => (- <RailRow key={f.path} icon={<Folder className="size-3.5 text-cyan" />} label={f.label} active={cwd === f.path} onClick={() => navigate(f.path)} />+ <RailRow+ key={f.path}+ icon={<Folder className="size-3.5 text-cyan" />}+ label={f.label}+ active={cwd === f.path}+ dropActive={dropTarget === f.path}+ dropProps={dropProps(f.path)}+ onClick={() => {+ setQuery('');+ navigate(f.path);+ }}+ />))}</aside>@@ -380,68 +586,110 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{sort?.col === 'modified' && (sort.dir === 'asc' ? <ChevronUp className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />)}</button></div>- <div className="min-h-0 flex-1 overflow-y-auto py-1">- {loading && !listing && (+ {/* Right-clicking blank space offers New File / New Folder in the current folder. */}+ <div className="min-h-0 flex-1 overflow-y-auto py-1" onContextMenu={(e) => openMenu(e, null)}>+ {showInitialSpinner && (<div className="grid place-items-center py-8"><Loader2 className="size-4 animate-spin text-muted" /></div>)}- {newEntry !== null && (- <div className="flex items-center px-3 py-1.5">+ {!inSearch && newEntry !== null && (+ // Stop the contextmenu here so right-clicking the input shows the browser's native+ // menu (paste) instead of our blank-space New menu from the container below.+ <div className="flex items-center px-3 py-1.5" onContextMenu={(e) => e.stopPropagation()}><span className="flex min-w-0 flex-1 items-center gap-2">{newEntry.kind === 'folder' ? <Folder className="size-4 shrink-0 text-cyan" /> : <FileIcon className="size-4 shrink-0 text-muted" />}- <input- autoFocus- value={newEntry.value}- onChange={(ev) => setNewEntry((s) => (s ? { ...s, value: ev.target.value } : s))}- onKeyDown={(ev) => {- if (ev.key === 'Enter') {- ev.preventDefault();- void commitNewEntry();- } else if (ev.key === 'Escape') {- ev.preventDefault();- setNewEntry(null);- }- }}- onBlur={() => setNewEntry(null)}+ <InlineNameInput+ initial=""placeholder={t(newEntry.kind === 'folder' ? 'apps.fileBrowser.newFolderPlaceholder' : 'apps.fileBrowser.newFilePrompt')}+ onCommit={(v) => void commitNewEntry(newEntry.kind, v)}+ onCancel={() => setNewEntry(null)}className="min-w-0 flex-1 rounded border border-cyan bg-surface px-1.5 py-0.5 text-[12.5px] text-foreground placeholder:text-muted focus:outline-none"/></span></div>)}- {listing && entries.length === 0 && newEntry === null && (- <div className="px-3 py-8 text-center text-[12px] text-muted">{query ? t('apps.fileBrowser.noMatches') : t('apps.fileBrowser.empty')}</div>+ {showEmpty && (+ <div className="px-3 py-8 text-center text-[12px] text-muted">{inSearch ? t('apps.fileBrowser.noMatches') : t('apps.fileBrowser.empty')}</div>)}- {entries.map((e) => {- const { Icon, color } = entryIcon(e);- const full = joinPath(cwd, e.name);+ {rows.map((item) => {+ const { Icon, color } = entryIcon(item.entry);+ const isDir = item.entry.kind === 'dir';+ const folder = relFolder(item.rel);+ if (rename?.full === item.full) {+ return (+ <div key={item.full} className="flex items-center px-3 py-1.5" onContextMenu={(e) => e.stopPropagation()}>+ <span className="flex min-w-0 flex-1 items-center gap-2">+ <Icon className="size-4 shrink-0" style={{ color }} />+ <InlineNameInput+ initial={item.entry.name}+ onCommit={(v) => void commitRename(item, v)}+ onCancel={() => setRename(null)}+ className="min-w-0 flex-1 rounded border border-cyan bg-surface px-1.5 py-0.5 text-[12.5px] text-foreground placeholder:text-muted focus:outline-none"+ />+ </span>+ </div>+ );+ }return (<button- key={e.name}+ key={item.full}type="button"+ draggable+ onDragStart={(e) => {+ dragRef.current = item;+ e.dataTransfer.effectAllowed = 'move';+ try {+ e.dataTransfer.setData('text/plain', item.full);+ } catch {+ // Some browsers throw if setData is called outside a real drag; harmless.+ }+ }}+ onDragEnd={() => {+ dragRef.current = null;+ setDropTarget(null);+ }}+ onDragOver={(e) => {+ if (!isDir || !dragRef.current || dragRef.current.full === item.full) return;+ e.preventDefault();+ setDropTarget((d) => (d === item.full ? d : item.full));+ }}+ onDragLeave={() => {+ if (isDir) setDropTarget((d) => (d === item.full ? null : d));+ }}+ onDrop={(e) => {+ if (!isDir) return;+ e.preventDefault();+ void moveInto(item.full);+ }}// Mouse: single-click selects, double-click opens. Touch (coarse pointer) has no// double-click, so a single tap opens. Keyboard: Enter/Space opens/navigates.onClick={() => {- if (window.matchMedia('(pointer: coarse)').matches) open(e);- else setSelected(full);+ if (window.matchMedia('(pointer: coarse)').matches) void openItem(item);+ else setSelected(item.full);}}- onDoubleClick={() => open(e)}+ onDoubleClick={() => void openItem(item)}onKeyDown={(ev) => {if (ev.key === 'Enter' || ev.key === ' ') {ev.preventDefault();- open(e);+ void openItem(item);}}}+ onContextMenu={(e) => openMenu(e, item)}className={clsx('flex w-full items-center px-3 py-1.5 text-left text-[12.5px] transition',- selected === full ? 'bg-cyan-soft text-foreground' : 'text-foreground hover:bg-foreground/[0.04]',+ dropTarget === item.full+ ? 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan'+ : selected === item.full+ ? 'bg-cyan-soft text-foreground'+ : 'text-foreground hover:bg-foreground/[0.04]',)}><span className="flex min-w-0 flex-1 items-center gap-2"><Icon className="size-4 shrink-0" style={{ color }} />- <span className="truncate">{e.name}</span>+ <span className="truncate">{item.entry.name}</span>+ {folder && <span className="min-w-0 shrink truncate text-[11px] text-muted">{folder}</span>}</span>- <span className="w-20 shrink-0 text-right font-mono text-[11px] text-muted">{e.kind === 'dir' ? '—' : formatSize(e.size)}</span>- <span className="w-36 shrink-0 pl-4 font-mono text-[11px] text-muted">{formatMtime(e.mtime)}</span>+ <span className="w-20 shrink-0 text-right font-mono text-[11px] text-muted">{isDir ? '—' : formatSize(item.entry.size)}</span>+ <span className="w-36 shrink-0 pl-4 font-mono text-[11px] text-muted">{formatMtime(item.entry.mtime)}</span></button>);})}@@ -462,8 +710,11 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{selectedEntry.kind !== 'dir' && selectedEntry.size != null ? ` · ${formatSize(selectedEntry.size)}` : ''}</span>)}- <span className="shrink-0">{t('apps.fileBrowser.itemCount', { count: entries.length })}</span>- {listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? entries.length })}</span>}+ <span className="shrink-0">+ {inSearch ? t('apps.fileBrowser.searchCount', { count: rows.length }) : t('apps.fileBrowser.itemCount', { count: rows.length })}+ </span>+ {!inSearch && listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? rows.length })}</span>}+ {inSearch && searchTruncated && <span className="shrink-0">· {t('apps.fileBrowser.searchTruncated')}</span>}</span></div></div>@@ -494,6 +745,64 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri</div></div>)}++ {menu && (+ <ContextMenu x={menu.x} y={menu.y} onClose={closeMenu} itemCount={menuItemCount}>+ {menu.item ? (+ <>+ <ContextMenuItem+ icon={menu.item.entry.kind === 'dir' ? <Folder className="size-3.5 text-cyan" /> : <FileText className="size-3.5 text-cyan" />}+ label={t('apps.fileBrowser.open')}+ onClick={() => {+ const it = menu.item as RowItem;+ closeMenu();+ void openItem(it);+ }}+ />+ {menu.item.entry.kind !== 'dir' && (+ <ContextMenuItem+ icon={<Download className="size-3.5 text-mint" />}+ label={t('apps.fileBrowser.download')}+ onClick={() => {+ const it = menu.item as RowItem;+ closeMenu();+ downloadFile(it.full);+ }}+ />+ )}+ <ContextMenuItem+ icon={<Pencil className="size-3.5" />}+ label={t('apps.fileBrowser.rename')}+ onClick={() => {+ const it = menu.item as RowItem;+ closeMenu();+ startRename(it);+ }}+ />+ <ContextMenuItem icon={<Trash2 className="size-3.5" />} label={t('apps.fileBrowser.delete')} danger onClick={() => void removeItem(menu.item as RowItem)} />+ </>+ ) : (+ <>+ <ContextMenuItem+ icon={<FilePlus className="size-3.5 text-mint" />}+ label={t('apps.fileBrowser.newFile')}+ onClick={() => {+ closeMenu();+ startNewEntry('file');+ }}+ />+ <ContextMenuItem+ icon={<FolderPlus className="size-3.5 text-gold" />}+ label={t('apps.fileBrowser.newFolder')}+ onClick={() => {+ closeMenu();+ startNewEntry('folder');+ }}+ />+ </>+ )}+ </ContextMenu>+ )}</div>);};@@ -502,13 +811,29 @@ const RailTitle: React.FC<{ children: React.ReactNode }> = ({ children }) => (<div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">{children}</div>);-const RailRow: React.FC<{ icon: React.ReactNode; label: string; active: boolean; onClick: () => void }> = ({ icon, label, active, onClick }) => (+const RailRow: React.FC<{+ icon: React.ReactNode;+ label: string;+ active: boolean;+ onClick: () => void;+ dropActive?: boolean;+ dropProps?: {+ onDragOver: (e: React.DragEvent) => void;+ onDragLeave: () => void;+ onDrop: (e: React.DragEvent) => void;+ };+}> = ({ icon, label, active, onClick, dropActive, dropProps }) => (<buttontype="button"onClick={onClick}+ {...dropProps}className={clsx('flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',- active ? 'bg-cyan-soft text-foreground' : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',+ dropActive+ ? 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan'+ : active+ ? 'bg-cyan-soft text-foreground'+ : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',)}><span className="shrink-0">{icon}</span>diff --git a/ui/src/components/workbench/FileTree.tsx b/ui/src/components/workbench/FileTree.tsxindex ec60e4fdb..53a334f33 100644--- a/ui/src/components/workbench/FileTree.tsx+++ b/ui/src/components/workbench/FileTree.tsx@@ -29,6 +29,8 @@ import {writeFile,type FsEntry,} from '../../lib/filesApi';+import { ContextMenu, ContextMenuItem } from '../ui/context-menu';+import { InlineNameInput } from '../ui/inline-name-input';// Icon + accent per file extension (matches the explorer in design dnYPx).const EXT: Record<string, { Icon: typeof FileIcon; color: string }> = {@@ -78,43 +80,6 @@ const useTree = (): TreeCtx => {return c;};-// Shared inline name editor for both new-entry and rename rows: autofocus, select (rename keeps the-// name so it can be tweaked), Enter commits, Esc/blur cancels.-const InlineNameInput: React.FC<{ initial: string; placeholder?: string; onCommit: (v: string) => void; onCancel: () => void }> = ({- initial,- placeholder,- onCommit,- onCancel,-}) => {- const [value, setValue] = useState(initial);- // Cancel on blur UNLESS we just committed (Enter), else committing also fires blur → double-fire.- const committed = useRef(false);- return (- <input- autoFocus- value={value}- placeholder={placeholder}- onFocus={(e) => e.currentTarget.select()}- onChange={(e) => setValue(e.target.value)}- onKeyDown={(e) => {- if (e.key === 'Enter') {- e.preventDefault();- committed.current = true;- onCommit(value);- } else if (e.key === 'Escape') {- e.preventDefault();- committed.current = true;- onCancel();- }- }}- onBlur={() => {- if (!committed.current) onCancel();- }}- className="min-w-0 flex-1 rounded border border-cyan bg-surface px-1 py-0 text-[12.5px] text-foreground placeholder:text-muted focus:outline-none"- />- );-};-const Row: React.FC<{depth: number;onClick?: () => void;@@ -278,21 +243,6 @@ const Dir: React.FC<{ path: string; name: string; depth: number }> = ({ path, na);};-const MenuItem: React.FC<{ icon: React.ReactNode; label: string; danger?: boolean; onClick: () => void }> = ({ icon, label, danger, onClick }) => (- <button- type="button"- role="menuitem"- onClick={onClick}- className={clsx(- 'flex w-full items-center gap-2.5 rounded-md px-2.5 py-1.5 text-left text-[12.5px] transition',- danger ? 'text-destructive hover:bg-destructive/[0.1]' : 'text-foreground hover:bg-cyan-soft',- )}- >- <span className="grid size-4 shrink-0 place-items-center">{icon}</span>- {label}- </button>-);-// The VS-Code-style explorer tree (design dnYPx): a root folder whose subfolders lazily expand via// listDir. Reused by the Editor IDE; emits file opens upward. Owns inline new-file/new-folder/rename// + delete via a right-click menu, and re-lists the affected folder after each mutation.@@ -379,15 +329,6 @@ export const FileTree: React.FC<{}, []);const closeMenu = useCallback(() => setMenu(null), []);- useEffect(() => {- if (!menu) return;- const onKey = (e: KeyboardEvent) => {- if (e.key === 'Escape') setMenu(null);- };- window.addEventListener('keydown', onKey);- return () => window.removeEventListener('keydown', onKey);- }, [menu]);-const removeEntry = useCallback(async (dir: string, entry: FsEntry) => {setMenu(null);@@ -410,13 +351,9 @@ export const FileTree: React.FC<{[activePath, showHidden, onOpenFile, versionOf, edit, startEdit, cancelEdit, commitEdit, openMenu],);- // Clamp the menu inside the viewport (the tree scrolls, so a cursor-positioned fixed menu near the- // bottom/right edge would otherwise overflow). Width/height are estimates — good enough to nudge.- const MENU_W = 196;+ // Item count drives the menu's vertical clamp: file → Open+Rename+Delete (3); dir → +New File/+ // Folder inside (4... actually Open/New×2/Rename/Delete); blank → New File/Folder (2).const menuItemCount = menu ? (menu.entry ? (menu.entry.kind === 'dir' ? 4 : 3) : 2) : 0;- const MENU_H = menuItemCount * 34 + 12;- const menuX = menu ? Math.min(menu.x, window.innerWidth - MENU_W - 8) : 0;- const menuY = menu ? Math.min(menu.y, window.innerHeight - MENU_H - 8) : 0;return (<Ctx.Provider value={ctx}>@@ -435,65 +372,58 @@ export const FileTree: React.FC<{</div>{menu && (- <>- <div className="fixed inset-0 z-40" onClick={closeMenu} onContextMenu={(e) => { e.preventDefault(); closeMenu(); }} aria-hidden />- <div- role="menu"- style={{ left: menuX, top: menuY, width: MENU_W }}- className="fixed z-50 rounded-lg border border-border bg-surface-3 p-1 shadow-[0_12px_30px_-8px_rgba(0,0,0,0.7)]"- >- {menu.entry && menu.entry.kind === 'file' && (- <MenuItem- icon={<FileText className="size-3.5 text-cyan" />}- label={t('apps.fileBrowser.open')}+ <ContextMenu x={menu.x} y={menu.y} onClose={closeMenu} itemCount={menuItemCount}>+ {menu.entry && menu.entry.kind === 'file' && (+ <ContextMenuItem+ icon={<FileText className="size-3.5 text-cyan" />}+ label={t('apps.fileBrowser.open')}+ onClick={() => {+ const e = menu.entry as FsEntry;+ onOpenFile(joinPath(menu.dir, e.name), e);+ closeMenu();+ }}+ />+ )}+ {(!menu.entry || menu.entry.kind === 'dir') && (+ <>+ <ContextMenuItem+ icon={<FilePlus className="size-3.5 text-mint" />}+ label={t('apps.fileBrowser.newFile')}+ onClick={() => {+ startEdit({ dir: menu.entry ? joinPath(menu.dir, menu.entry.name) : menu.dir, mode: 'new-file' });+ closeMenu();+ }}+ />+ <ContextMenuItem+ icon={<FolderPlus className="size-3.5 text-gold" />}+ label={t('apps.fileBrowser.newFolder')}+ onClick={() => {+ startEdit({ dir: menu.entry ? joinPath(menu.dir, menu.entry.name) : menu.dir, mode: 'new-folder' });+ closeMenu();+ }}+ />+ </>+ )}+ {menu.entry && (+ <>+ <ContextMenuItem+ icon={<Pencil className="size-3.5" />}+ label={t('apps.fileBrowser.rename')}onClick={() => {const e = menu.entry as FsEntry;- onOpenFile(joinPath(menu.dir, e.name), e);+ startEdit({ dir: menu.dir, mode: 'rename', target: e.name });closeMenu();}}/>- )}- {(!menu.entry || menu.entry.kind === 'dir') && (- <>- <MenuItem- icon={<FilePlus className="size-3.5 text-mint" />}- label={t('apps.fileBrowser.newFile')}- onClick={() => {- startEdit({ dir: menu.entry ? joinPath(menu.dir, menu.entry.name) : menu.dir, mode: 'new-file' });- closeMenu();- }}- />- <MenuItem- icon={<FolderPlus className="size-3.5 text-gold" />}- label={t('apps.fileBrowser.newFolder')}- onClick={() => {- startEdit({ dir: menu.entry ? joinPath(menu.dir, menu.entry.name) : menu.dir, mode: 'new-folder' });- closeMenu();- }}- />- </>- )}- {menu.entry && (- <>- <MenuItem- icon={<Pencil className="size-3.5" />}- label={t('apps.fileBrowser.rename')}- onClick={() => {- const e = menu.entry as FsEntry;- startEdit({ dir: menu.dir, mode: 'rename', target: e.name });- closeMenu();- }}- />- <MenuItem- icon={<Trash2 className="size-3.5" />}- label={t('apps.fileBrowser.delete')}- danger- onClick={() => removeEntry(menu.dir, menu.entry as FsEntry)}- />- </>- )}- </div>- </>+ <ContextMenuItem+ icon={<Trash2 className="size-3.5" />}+ label={t('apps.fileBrowser.delete')}+ danger+ onClick={() => removeEntry(menu.dir, menu.entry as FsEntry)}+ />+ </>+ )}+ </ContextMenu>)}</Ctx.Provider>);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 9a2c97e94..9cd2ff106 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -712,6 +712,8 @@"favorites": "Favorites","noMatches": "No matches","itemCount": "{{count}} items",+ "searchCount": "{{count}} results",+ "searchTruncated": "Showing the first results only.","projects": "Projects","system": "System","showHidden": "Show hidden files",@@ -738,6 +740,11 @@"loadFailed": "Couldn't load this file.","saveFailed": "Couldn't save this file.","deleteFailed": "Couldn't delete this item.",+ "renameFailed": "Couldn't rename this item.",+ "moveFailed": "Couldn't move this item.",+ "searchFailed": "Couldn't search this folder.",+ "invalid_query": "Enter something to search for.",+ "invalid_move": "That move isn't allowed.","invalid_response": "The server returned an unexpected response. Try again."}},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex fc09f8d3a..5fb948cc6 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -712,6 +712,8 @@"favorites": "收藏","noMatches": "无匹配项","itemCount": "{{count}} 项",+ "searchCount": "{{count}} 个结果",+ "searchTruncated": "结果较多,仅显示部分。","projects": "项目","system": "系统","showHidden": "显示隐藏文件",@@ -738,6 +740,11 @@"loadFailed": "无法加载这个文件。","saveFailed": "无法保存这个文件。","deleteFailed": "无法删除这个项目。",+ "renameFailed": "无法重命名这个项目。",+ "moveFailed": "无法移动这个项目。",+ "searchFailed": "无法搜索这个文件夹。",+ "invalid_query": "请输入搜索内容。",+ "invalid_move": "不允许这样移动。","invalid_response": "服务器返回了异常响应,请重试。"}},diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.tsindex 2b9d1c6ba..8e51156e6 100644--- a/ui/src/lib/filesApi.ts+++ b/ui/src/lib/filesApi.ts@@ -20,6 +20,18 @@ export type FsListing = {limit?: number;};+// A recursive name-search hit (`/api/files/search_names`): an entry plus its absolute `path` and+// `rel` (path relative to the search root) so the UI can show where it lives and open/navigate to it.+export type NameHit = FsEntry & { path: string; rel: string };+export type NameSearchResponse = {+ ok: true;+ root: string;+ query: string;+ results: NameHit[];+ truncated: boolean;+ limit: number | null;+};+export type FsMeta = {ok: true;name: string;@@ -248,6 +260,19 @@ export async function renamePath(path: string, newName: string): Promise<{ ok: t);}+// Move an entry from `src` to the absolute `dst` (used by drag-and-drop into a folder). The backend+// is symlink-safe, refuses to move a folder into itself, and — with overwrite=false (the default) —+// refuses to clobber an existing destination (errors.exists), which the UI surfaces to the user.+export async function movePath(src: string, dst: string, overwrite = false): Promise<{ ok: true }> {+ return parse(+ await apiFetch('/api/files/move', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ src, dst, overwrite: overwrite || undefined }),+ }),+ );+}+// Cross-file search + replace (backend: file_browser_service.search/replace/undo_replace).// col/end are full-line UTF-16 offsets (the editor jump target); preview_col/preview_end index// into `text` (the possibly windowed preview) for the row highlight.@@ -283,6 +308,14 @@ export async function searchFiles(root: string, query: string, opts: SearchOptioreturn parse<SearchResponse>(await apiFetch(`/api/files/search?${params.toString()}`, { signal }));}+// Recursive file/folder NAME search under `root` (backend: file_browser_service.search_names).+// Distinct from searchFiles, which greps file contents. `signal` lets the caller abort a stale+// in-flight search as the user keeps typing.+export async function searchNames(root: string, query: string, showHidden = false, signal?: AbortSignal): Promise<NameSearchResponse> {+ const params = new URLSearchParams({ root, query, show_hidden: showHidden ? '1' : '0' });+ return parse<NameSearchResponse>(await apiFetch(`/api/files/search_names?${params.toString()}`, { signal }));+}+export async function replaceInFiles(root: string,query: string,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 2a1b15872..7fe44f19d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5545,6 +5545,27 @@ async def files_search(starlette_request: FastAPIRequest):return await _dispatch_native_ui_request(starlette_request, handler)[email protected]("/api/files/search_names", include_in_schema=False)+async def files_search_names(starlette_request: FastAPIRequest):+ async def handler():+ from core import file_browser_service++ args = request.args+ try:+ return jsonify(+ await asyncio.to_thread(+ file_browser_service.search_names,+ args.get("root") or "",+ args.get("query") or "",+ show_hidden=args.get("show_hidden") == "1",+ )+ )+ except Exception as exc:+ return _file_browser_error_response(exc)++ return await _dispatch_native_ui_request(starlette_request, handler)++@app.post("/api/files/search/replace", include_in_schema=False)async def files_search_replace(starlette_request: FastAPIRequest):async def handler():