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(files): add multi-select batch operations (#889)
Call Whitea7ccaaa60d1c
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsxindex 15ea219fb..62bf24c06 100644--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx@@ -6,12 +6,15 @@ import {ChevronDown,ChevronRight,ChevronUp,+ ClipboardPaste,+ Copy,Download,FileCode2,FileSearch,FileText,File as FileIcon,Folder,+ FolderInput,FolderPlus,FilePlus,HardDrive,@@ -37,6 +40,7 @@ import { useWindowManager } from '../../context/WindowManagerContext';import { isEditableFile, isEditableMeta, previewOverlayKind, previewWindowKind } from '../../lib/filePreview';import {contentUrl,+ copyPath,deletePath,downloadFile,undoDelete,@@ -64,11 +68,13 @@ import {type SearchFileResult,} from '../../lib/filesApi';import { Button } from '../ui/button';+import { Checkbox } from '../ui/checkbox';import { ConfirmDialog } from '../ui/confirm-dialog';import { ContextMenu, ContextMenuItem } from '../ui/context-menu';import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '../ui/dialog';import { FilePreview } from '../ui/file-preview';import { InlineNameInput } from '../ui/inline-name-input';+import { FilePicker } from './FilePicker';// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).const EXT_ICON: Record<string, { Icon: LucideIcon; color: string }> = {@@ -180,6 +186,13 @@ function dedupeName(name: string, n: number): string {// large batch doesn't flood the endpoint (mirrors the chat composer's bounded upload pool).const UPLOAD_CONCURRENCY = 3;+// Browsers increasingly gate or throttle bursts of automatic downloads. Keep a batch intentional+// and bounded; the UI reports how many selected files were left for a follow-up batch.+const MAX_BATCH_DOWNLOADS = 10;++const LONG_PRESS_MS = 500;+const LONG_PRESS_MOVE_PX = 8;+// 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;@@ -198,7 +211,34 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striconst [showHidden, setShowHidden] = useState(false);const [sysFavs, setSysFavs] = useState<Favorite[]>([]);const [query, setQuery] = useState('');- const [selected, setSelected] = useState<string | null>(null);+ const [selected, setSelected] = useState<Set<string>>(() => new Set());+ const [touchSelectionMode, setTouchSelectionMode] = useState(false);+ const selectionAnchorRef = useRef<string | null>(null);+ const clearSelection = useCallback(() => {+ setSelected(new Set());+ setTouchSelectionMode(false);+ selectionAnchorRef.current = null;+ }, []);++ // Escape is the universal way out of a selection. Preview/dialog handlers still own their own+ // Escape behavior; clearing a background selection at the same time is harmless and predictable.+ useEffect(() => {+ const onKey = (ev: KeyboardEvent) => {+ if (ev.key === 'Escape') clearSelection();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [clearSelection]);++ // Long-press is only a selection gesture on coarse pointers. Movement beyond a small slop cancels+ // it so scrolling the list never unexpectedly enters selection mode.+ const longPressRef = useRef<{ path: string; x: number; y: number; timer: number } | null>(null);+ const suppressTouchClickRef = useRef<string | null>(null);+ const cancelLongPress = useCallback(() => {+ if (longPressRef.current) window.clearTimeout(longPressRef.current.timer);+ longPressRef.current = null;+ }, []);+ useEffect(() => cancelLongPress, [cancelLongPress]);// Column sort, Finder-like: click a header to cycle asc → desc → none (none = default// dirs-first then name). Persists within the app session; folders always group before files.const [sort, setSort] = useState<{ col: 'name' | 'size' | 'modified'; dir: 'asc' | 'desc' } | null>(null);@@ -229,7 +269,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striconst seq = ++navSeq.current;setLoading(true);setError(null);- setSelected(null);+ clearSelection();listDir(path, showHidden).then((r) => {if (seq !== navSeq.current) return;@@ -243,7 +283,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striif (seq === navSeq.current) setLoading(false);});},- [showHidden, t],+ [showHidden, t, clearSelection],);useEffect(() => {@@ -277,6 +317,12 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striconst searchAbort = useRef<AbortController | null>(null);const inSearch = query.trim().length > 0;+ // Search results are a different row model from the current-folder listing. Clear selection when+ // the query or Name/Content mode changes so invisible/stale paths can never be batch-mutated.+ useEffect(() => {+ clearSelection();+ }, [query, searchMode, clearSelection]);+const runSearch = useCallback((raw: string) => {const q = raw.trim();@@ -514,9 +560,11 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri// of its window — matching the backend's bounded staging). Delete reverts via the backend token;// move reverts with a plain reverse move. The bar auto-dismisses; dismissal ≠ token expiry (the// backend keeps staged deletes far longer), it just keeps the UI calm.+ type DeleteUndoItem = { label: string; token: string };+ type MoveUndoItem = { label: string; from: string; to: string };type UndoEntry =- | { kind: 'delete'; label: string; token: string }- | { kind: 'move'; label: string; from: string; to: string };+ | { kind: 'delete'; label: string; count: number; items: DeleteUndoItem[] }+ | { kind: 'move'; label: string; count: number; items: MoveUndoItem[] };const [undoEntry, setUndoEntry] = useState<UndoEntry | null>(null);const [undoBusy, setUndoBusy] = useState(false);const undoTimerRef = useRef<number | null>(null);@@ -536,83 +584,138 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: striif (!entry || undoBusy) return;if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);setUndoBusy(true);- try {- if (entry.kind === 'delete') await undoDelete(entry.token);- else await movePath(entry.from, entry.to);- setError(null);+ if (entry.kind === 'delete') {+ const failures: { item: DeleteUndoItem; error: unknown }[] = [];+ for (const item of entry.items) {+ try {+ await undoDelete(item.token);+ } catch (error) {+ failures.push({ item, error });+ }+ }refreshAll();- // Only clear OUR entry: a slow in-flight undo must not wipe the bar of a NEWER action the- // user performed meanwhile (that entry's own timer still governs it).- setUndoEntry((cur) => (cur === entry ? null : cur));- } catch (e: unknown) {- // exists → the original spot is occupied again; expired → the staged copy is gone. Both land- // in the standard error strip via the shared code→message mapping.- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.undoFailed')));- const code = e instanceof FilesApiError ? e.code : null;- if (code === 'exists' || code === 'expired') {- // Terminal: the revert can never succeed — drop the bar.+ if (failures.length === 0) {+ setError(null);setUndoEntry((cur) => (cur === entry ? null : cur));} else {- // Transient (network etc.): the staged copy / reverse move is still viable — keep the bar- // for a retry, with a fresh dismiss window (the original timer was cleared above).+ setError(+ failures.length === 1 && entry.items.length === 1+ ? fileBrowserErrorMessage(failures[0].error, t, t('apps.fileBrowser.errors.undoFailed'))+ : failures+ .map(({ item, error }) =>+ t('apps.fileBrowser.operationError', {+ name: item.label,+ message: fileBrowserErrorMessage(error, t, t('apps.fileBrowser.errors.undoFailed')),+ }),+ )+ .join(' · '),+ );+ // Restored tokens are consumed. Keep only retryable failures; exists/expired can never+ // succeed later and must not leave a dead Undo button behind.+ const retryable = failures+ .filter(({ error }) => !(error instanceof FilesApiError && (error.code === 'exists' || error.code === 'expired')))+ .map(({ item }) => item);setUndoEntry((cur) => {if (cur !== entry) return cur;+ if (retryable.length === 0) return null;undoTimerRef.current = window.setTimeout(() => setUndoEntry(null), 8000);- return cur;+ return { ...entry, label: retryable[0].label, count: retryable.length, items: retryable };});}- } finally {setUndoBusy(false);+ return;+ }+ const failures: { item: MoveUndoItem; error: unknown }[] = [];+ // Reverse the original move order so nested or otherwise dependent selections unwind safely.+ for (const item of [...entry.items].reverse()) {+ try {+ await movePath(item.from, item.to);+ } catch (error) {+ failures.push({ item, error });+ }}+ refreshAll();+ if (failures.length === 0) {+ setError(null);+ setUndoEntry((cur) => (cur === entry ? null : cur));+ } else {+ setError(+ failures.length === 1 && entry.items.length === 1+ ? fileBrowserErrorMessage(failures[0].error, t, t('apps.fileBrowser.errors.undoFailed'))+ : failures+ .map(({ item, error }) =>+ t('apps.fileBrowser.operationError', {+ name: item.label,+ message: fileBrowserErrorMessage(error, t, t('apps.fileBrowser.errors.undoFailed')),+ }),+ )+ .join(' · '),+ );+ const retryable = failures+ .filter(({ error }) => !(error instanceof FilesApiError && (error.code === 'exists' || error.code === 'expired')))+ .map(({ item }) => item);+ setUndoEntry((cur) => {+ if (cur !== entry) return cur;+ if (retryable.length === 0) return null;+ undoTimerRef.current = window.setTimeout(() => setUndoEntry(null), 8000);+ return { ...entry, label: retryable[0].label, count: retryable.length, items: retryable };+ });+ }+ setUndoBusy(false);}, [undoEntry, undoBusy, refreshAll, t]);// ---- Delete (product ConfirmDialog + post-delete Undo) ----------------------------------------// The context menu only REQUESTS the delete; the destructive ConfirmDialog performs it. When the// backend staged the entry (undo_token non-null) the undo bar offers a short revert window; a// permanent delete (cross-device / oversized) simply shows no bar.- const [pendingDelete, setPendingDelete] = useState<RowItem | null>(null);- const removeItem = useCallback((item: RowItem) => {+ const [pendingDelete, setPendingDelete] = useState<RowItem[] | null>(null);+ const removeItems = useCallback((items: RowItem[]) => {setMenu(null);- setPendingDelete(item);+ setPendingDelete(items);}, []);const performDelete = useCallback(async () => {- const item = pendingDelete;- if (!item) return;- try {- const result = await deletePath(item.full, item.entry.kind === 'dir');- setError(null);- setSelected((s) => (s === item.full ? null : s));- if (result.undo_token) {- showUndo({ kind: 'delete', label: item.entry.name, token: result.undo_token });- } else {- // Permanent delete: any older bar now describes a stale world (its target may be the very- // entry that just vanished) — the newest action owns the bar, and it has nothing to offer.- if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);- setUndoEntry(null);+ const items = pendingDelete;+ if (!items?.length) return;+ const undoItems: DeleteUndoItem[] = [];+ const failures: string[] = [];+ let deletedCount = 0;+ for (const item of items) {+ try {+ const result = await deletePath(item.full, item.entry.kind === 'dir');+ deletedCount += 1;+ if (result.undo_token) undoItems.push({ label: item.entry.name, token: result.undo_token });+ } catch (e: unknown) {+ const message = fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.deleteFailed'));+ failures.push(items.length === 1 ? message : t('apps.fileBrowser.operationError', { name: item.entry.name, message }));}- refreshAll();- } catch (e: unknown) {- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.deleteFailed')));- } finally {- setPendingDelete(null);}- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [pendingDelete, t, refreshAll]);+ if (undoItems.length > 0) {+ showUndo({ kind: 'delete', label: undoItems[0].label, count: undoItems.length, items: undoItems });+ } else if (deletedCount > 0) {+ // No staged delete in this action is reversible, so an older bar may now refer to a path this+ // action permanently removed. The newest mutation owns the bar and offers no false Undo.+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);+ setUndoEntry(null);+ }+ setPendingDelete(null);+ if (deletedCount > 0) refreshAll();+ setError(failures.length ? failures.join(' · ') : null);+ }, [pendingDelete, t, refreshAll, showUndo]);// ---- 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) => {+ const [menu, setMenu] = useState<{ x: number; y: number; item: RowItem | null; items: RowItem[] } | null>(null);+ const openMenu = useCallback((ev: React.MouseEvent, item: RowItem | null, items: RowItem[] = []) => {ev.preventDefault();ev.stopPropagation();- setMenu({ x: ev.clientX, y: ev.clientY, item });+ setMenu({ x: ev.clientX, y: ev.clientY, item, items });}, []);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 dragRef = useRef<RowItem[] | null>(null);const [dropTarget, setDropTarget] = useState<string | null>(null);// Move `item` into `destDir` under `name`. On success: clear the error and refresh. A name clash// (errors.exists) is NOT swallowed here — it throws so the caller (the drag drop, or the clash@@ -621,99 +724,155 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri// back); an overwrite (Replace) offers none, since the clobbered file is gone and can't be// losslessly restored, so we don't imply it can.const applyMove = useCallback(- async (item: RowItem, destDir: string, name: string, overwrite: boolean) => {+ async (item: RowItem, destDir: string, name: string, overwrite: boolean, refreshAfter = true, manageUndo = true) => {const moved = joinPath(destDir, name);await movePath(item.full, moved, overwrite);- setError(null);+ if (refreshAfter) setError(null);+ const undoItem: MoveUndoItem = { label: name, from: moved, to: item.full };if (overwrite) {// Replace is a non-undoable mutation: any older move/delete undo bar now describes a stale// world (its paths may point at the entry we just clobbered), so clear it — mirroring the// permanent-delete path — rather than leaving a stale Undo that could move the wrong file.- if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);- setUndoEntry(null);- } else {- showUndo({ kind: 'move', label: name, from: moved, to: item.full });+ if (manageUndo) {+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);+ setUndoEntry(null);+ }+ } else if (manageUndo) {+ showUndo({ kind: 'move', label: name, count: 1, items: [undoItem] });}- refreshAll();+ if (refreshAfter) refreshAll();+ return overwrite ? null : undoItem;},[showUndo, refreshAll],);- // ---- Drag-move name-clash dialog (Replace / Keep both / Cancel) --------------------------------- // A drag-move onto a folder that already holds that name opens this dialog instead of the bare- // error strip. Replace overwrites; Keep both retries under `name (2).ext`, `name (3).ext`, … until- // the backend accepts (or MAX_KEEP_BOTH is hit); `busy` names which action is mid-flight.- const [moveClash, setMoveClash] = useState<{ item: RowItem; destDir: string } | null>(null);- const [moveClashBusy, setMoveClashBusy] = useState<'replace' | 'keep' | null>(null);+ // ---- Move/copy name-clash dialog (Replace / Keep both / Cancel) -------------------------------+ // Batch operations are deliberately sequential. A conflicting item pauses the queue on the same+ // dialog used by the original drag-move flow; resolving it resumes with the next selected item.+ type NameClashRequest = {+ item: RowItem;+ destDir: string;+ run: (action: 'replace' | 'keep') => Promise<void>;+ resolve: (completed: boolean) => void;+ reject: (error: unknown) => void;+ };+ const [nameClash, setNameClash] = useState<NameClashRequest | null>(null);+ const [nameClashBusy, setNameClashBusy] = useState<'replace' | 'keep' | null>(null);+ const pendingNameClashRef = useRef<NameClashRequest | null>(null);+ useEffect(() => {+ pendingNameClashRef.current = nameClash;+ }, [nameClash]);- 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;+ const requestNameClash = useCallback(+ (item: RowItem, destDir: string, run: NameClashRequest['run']) =>+ new Promise<boolean>((resolve, reject) => setNameClash({ item, destDir, run, resolve, reject })),+ [],+ );+ const answerNameClash = useCallback((completed: boolean) => {+ const request = pendingNameClashRef.current;+ if (!request) return;+ request.resolve(completed);+ setNameClash(null);+ }, []);+ const runNameClash = useCallback(async (action: 'replace' | 'keep') => {+ const request = pendingNameClashRef.current;+ if (!request) return;+ setNameClashBusy(action);+ try {+ await request.run(action);+ request.resolve(true);+ } catch (error) {+ request.reject(error);+ } finally {+ setNameClash(null);+ setNameClashBusy(null);+ }+ }, []);++ const moveOne = useCallback(+ async (item: RowItem, destDir: string, refreshAfter: boolean, manageUndo: boolean) => {try {- await applyMove(item, destDir, item.entry.name, false);- } catch (e: unknown) {- // A name clash opens the Replace / Keep both / Cancel dialog; any other failure is the strip.- if (e instanceof FilesApiError && e.code === 'exists') {- setMoveClash({ item, destDir });+ const undo = await applyMove(item, destDir, item.entry.name, false, refreshAfter, manageUndo);+ return { completed: true, undo };+ } catch (error) {+ if (!(error instanceof FilesApiError) || error.code !== 'exists') throw error;+ }+ let undo: MoveUndoItem | null = null;+ const completed = await requestNameClash(item, destDir, async (action) => {+ if (action === 'replace') {+ undo = await applyMove(item, destDir, item.entry.name, true, refreshAfter, manageUndo);return;}- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.moveFailed')));- }+ for (let n = 2; n <= MAX_KEEP_BOTH; n++) {+ try {+ undo = await applyMove(item, destDir, dedupeName(item.entry.name, n), false, refreshAfter, manageUndo);+ return;+ } catch (error) {+ if (error instanceof FilesApiError && error.code === 'exists') continue;+ throw error;+ }+ }+ throw new Error(t('apps.fileBrowser.moveClashTooMany'));+ });+ return { completed, undo };},- [applyMove, t],+ [applyMove, requestNameClash, t],);- const replaceClash = useCallback(async () => {- if (!moveClash) return;- setMoveClashBusy('replace');- try {- await applyMove(moveClash.item, moveClash.destDir, moveClash.item.entry.name, true);- setMoveClash(null);- } catch (e: unknown) {- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.moveFailed')));- setMoveClash(null);- } finally {- setMoveClashBusy(null);- }- }, [moveClash, applyMove, t]);-- const keepBothClash = useCallback(async () => {- if (!moveClash) return;- const { item, destDir } = moveClash;- setMoveClashBusy('keep');- try {- // Try `name (2).ext`, `name (3).ext`, … skipping candidates the backend still rejects as- // clashes, until one lands or we hit the cap. overwrite stays false so a de-duped name can- // never clobber a real neighbour.- for (let n = 2; n <= MAX_KEEP_BOTH; n++) {+ const moveItemsInto = useCallback(+ async (items: RowItem[], destDir: string) => {+ const candidates = items.filter((item) => item.dir !== destDir && item.full !== destDir);+ if (candidates.length === 0) return;+ const batch = candidates.length > 1;+ const failures: string[] = [];+ const batchUndo: MoveUndoItem[] = [];+ let batchUndoable = true;+ let moved = 0;+ for (const item of candidates) {try {- await applyMove(item, destDir, dedupeName(item.entry.name, n), false);- setMoveClash(null);- return;- } catch (e: unknown) {- if (e instanceof FilesApiError && e.code === 'exists') continue;- throw e;+ const result = await moveOne(item, destDir, !batch, !batch);+ if (result.completed) {+ moved += 1;+ if (result.undo) batchUndo.push(result.undo);+ else batchUndoable = false;+ }+ } catch (error) {+ const message = fileBrowserErrorMessage(error, t, t('apps.fileBrowser.errors.moveFailed'));+ failures.push(batch ? t('apps.fileBrowser.operationError', { name: item.entry.name, message }) : message);}}- setError(t('apps.fileBrowser.moveClashTooMany'));- setMoveClash(null);- } catch (e: unknown) {- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.moveFailed')));- setMoveClash(null);- } finally {- setMoveClashBusy(null);- }- }, [moveClash, applyMove, t]);+ if (batch && moved > 0) {+ if (batchUndoable && batchUndo.length > 0) {+ showUndo({ kind: 'move', label: batchUndo[0].label, count: batchUndo.length, items: batchUndo });+ } else {+ // One Replace makes the batch only partially reversible. Offer no Undo rather than imply+ // the overwritten destination can be recovered alongside the ordinary moves.+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);+ setUndoEntry(null);+ }+ refreshAll();+ }+ if (batch || failures.length > 0) setError(failures.length ? failures.join(' · ') : null);+ },+ [moveOne, refreshAll, showUndo, t],+ );++ const moveInto = useCallback(+ async (destDir: string) => {+ const items = dragRef.current;+ dragRef.current = null;+ setDropTarget(null);+ if (items) await moveItemsInto(items, destDir);+ },+ [moveItemsInto],+ );++ const [movePickerItems, setMovePickerItems] = useState<RowItem[] | null>(null);// 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;+ if (!dragRef.current || dragRef.current.some((item) => item.full === destDir)) return;e.preventDefault();setDropTarget((d) => (d === destDir ? d : destDir));},@@ -741,6 +900,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri() => () => {unmountedRef.current = true;pendingAskRef.current?.resolve(false);+ pendingNameClashRef.current?.resolve(false);},[],);@@ -916,13 +1076,215 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strireturn all.map((e) => ({ entry: e, full: joinPath(cwd, e.name), dir: cwd }));}, [query, searchRows, listing, sort, cwd]);- const selectedEntry = useMemo(() => (selected ? rows.find((r) => r.full === selected)?.entry ?? null : null), [rows, selected]);+ const selectedItems = useMemo(() => rows.filter((row) => selected.has(row.full)), [rows, selected]);+ const selectedEntry = selectedItems.length === 1 ? selectedItems[0].entry : null;+ const selectedSize = selectedItems.reduce((total, item) => total + (item.entry.size ?? 0), 0);++ const selectRow = (event: React.MouseEvent, item: RowItem) => {+ const coarse = window.matchMedia('(pointer: coarse)').matches;+ if (coarse) {+ if (suppressTouchClickRef.current === item.full) {+ suppressTouchClickRef.current = null;+ return;+ }+ if (!touchSelectionMode) {+ void openItem(item);+ return;+ }+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(item.full)) next.delete(item.full);+ else next.add(item.full);+ return next;+ });+ selectionAnchorRef.current = item.full;+ return;+ }++ if (event.shiftKey && selectionAnchorRef.current) {+ const anchor = rows.findIndex((row) => row.full === selectionAnchorRef.current);+ const target = rows.findIndex((row) => row.full === item.full);+ if (anchor >= 0 && target >= 0) {+ const [start, end] = anchor < target ? [anchor, target] : [target, anchor];+ setSelected(new Set(rows.slice(start, end + 1).map((row) => row.full)));+ return;+ }+ }+ if (event.metaKey || event.ctrlKey) {+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(item.full)) next.delete(item.full);+ else next.add(item.full);+ return next;+ });+ } else {+ setSelected(new Set([item.full]));+ }+ selectionAnchorRef.current = item.full;+ };++ const startLongPress = (event: React.PointerEvent, item: RowItem) => {+ if (event.pointerType !== 'touch' && !window.matchMedia('(pointer: coarse)').matches) return;+ cancelLongPress();+ const timer = window.setTimeout(() => {+ suppressTouchClickRef.current = item.full;+ setTouchSelectionMode(true);+ setSelected(new Set([item.full]));+ selectionAnchorRef.current = item.full;+ longPressRef.current = null;+ }, LONG_PRESS_MS);+ longPressRef.current = { path: item.full, x: event.clientX, y: event.clientY, timer };+ };++ const moveLongPress = (event: React.PointerEvent) => {+ const press = longPressRef.current;+ if (!press) return;+ if (Math.abs(event.clientX - press.x) > LONG_PRESS_MOVE_PX || Math.abs(event.clientY - press.y) > LONG_PRESS_MOVE_PX) {+ cancelLongPress();+ }+ };++ // The in-app clipboard intentionally never touches the OS clipboard and is not persisted. Paths+ // remain usable while navigating between folders in this Files app instance.+ const [clipboard, setClipboard] = useState<RowItem[]>([]);+ const copyRowsToClipboard = useCallback((items: RowItem[]) => {+ if (items.length > 0) setClipboard(items.map((item) => ({ ...item, entry: { ...item.entry } })));+ setMenu(null);+ }, []);++ const applyCopy = useCallback(+ async (item: RowItem, destDir: string, name: string, overwrite: boolean) => {+ await copyPath(item.full, joinPath(destDir, name), overwrite);+ if (overwrite) {+ // Replace destroys the previous destination and has no lossless undo, matching overwrite+ // move. Clear an older bar rather than implying the replacement itself can be reverted.+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);+ setUndoEntry(null);+ }+ },+ [],+ );++ const copyOne = useCallback(+ async (item: RowItem, destDir: string) => {+ // Pasting back into the source parent is inherently a clash. In particular, the backend+ // rejects a directory/symlink `src === dst` before its normal `exists` response, so enter the+ // same Replace / Keep both decision directly instead of surfacing invalid_path/invalid_copy.+ const sameParent = item.dir === destDir;+ if (!sameParent) {+ try {+ await applyCopy(item, destDir, item.entry.name, false);+ return true;+ } catch (error) {+ if (!(error instanceof FilesApiError) || error.code !== 'exists') throw error;+ }+ }+ return requestNameClash(item, destDir, async (action) => {+ if (action === 'replace') {+ // Replacing an entry with itself is already the requested end state. Treat it as a no-op;+ // the backend must not be asked to destroy/rebuild a source through the same path.+ if (sameParent) return;+ await applyCopy(item, destDir, item.entry.name, true);+ return;+ }+ for (let n = 2; n <= MAX_KEEP_BOTH; n++) {+ try {+ await applyCopy(item, destDir, dedupeName(item.entry.name, n), false);+ return;+ } catch (error) {+ if (error instanceof FilesApiError && error.code === 'exists') continue;+ throw error;+ }+ }+ throw new Error(t('apps.fileBrowser.moveClashTooMany'));+ });+ },+ [applyCopy, requestNameClash, t],+ );++ const pasteRows = useCallback(+ async (items: RowItem[], destDir: string) => {+ if (!destDir || items.length === 0) return;+ setMenu(null);+ const failures: string[] = [];+ let copied = 0;+ for (const item of items) {+ try {+ if (await copyOne(item, destDir)) copied += 1;+ } catch (error) {+ failures.push(+ t('apps.fileBrowser.operationError', {+ name: item.entry.name,+ message: fileBrowserErrorMessage(error, t, t('apps.fileBrowser.errors.copyFailed')),+ }),+ );+ }+ }+ if (copied > 0) refreshAll();+ setError(failures.length ? failures.join(' · ') : null);+ },+ [copyOne, refreshAll, t],+ );++ const duplicateItem = useCallback(+ async (item: RowItem) => {+ setMenu(null);+ try {+ for (let n = 2; n <= MAX_KEEP_BOTH; n++) {+ try {+ await applyCopy(item, item.dir, dedupeName(item.entry.name, n), false);+ setError(null);+ refreshAll();+ return;+ } catch (error) {+ if (error instanceof FilesApiError && error.code === 'exists') continue;+ throw error;+ }+ }+ setError(t('apps.fileBrowser.moveClashTooMany'));+ } catch (error) {+ setError(fileBrowserErrorMessage(error, t, t('apps.fileBrowser.errors.copyFailed')));+ }+ },+ [applyCopy, refreshAll, t],+ );++ const downloadItems = useCallback(+ async (items: RowItem[]) => {+ setMenu(null);+ const files = items.filter((item) => item.entry.kind !== 'dir');+ const toDownload = files.slice(0, MAX_BATCH_DOWNLOADS);+ for (const item of toDownload) {+ downloadFile(item.full);+ // Preserve ordering and avoid collapsing the whole batch into one browser event burst.+ await new Promise<void>((resolve) => window.setTimeout(resolve, 80));+ }+ // Advance the capped batch: a second Download action now starts with the next selected files+ // instead of repeating the same first ten. Concurrent selection changes are preserved.+ const downloaded = new Set(toDownload.map((item) => item.full));+ setSelected((current) => new Set([...current].filter((path) => !downloaded.has(path))));+ const hints: string[] = [];+ const skippedDirs = items.length - files.length;+ if (skippedDirs > 0) hints.push(t('apps.fileBrowser.downloadFoldersSkipped', { count: skippedDirs }));+ if (files.length > MAX_BATCH_DOWNLOADS) {+ hints.push(t('apps.fileBrowser.downloadLimit', { count: MAX_BATCH_DOWNLOADS, remaining: files.length - MAX_BATCH_DOWNLOADS }));+ }+ setError(hints.length ? hints.join(' · ') : null);+ },+ [t],+ );const showInitialSpinner = inSearch ? searchBusy && searchRows === null : loading && !listing;const showEmpty = inSearch ? !searchBusy && (searchRows?.length ?? 0) === 0 : !!listing && rows.length === 0 && newEntry === null;- // Row: file = Open/Download/Rename/Delete (4); dir = Open/Open Terminal Here/Rename/Delete (4).- // Blank: New File/New Folder (+ Open Terminal Here when a folder is loaded).- const menuItemCount = menu ? (menu.item ? 4 : cwd ? 3 : 2) : 0;+ // Single row keeps its original four actions plus Copy/Duplicate; a batch has four batch actions.+ // Blank space keeps New File/Folder + Terminal and gains Paste while the in-app clipboard is set.+ const menuItemCount = menu+ ? menu.item+ ? menu.items.length > 1+ ? 4+ : 6+ : (cwd ? 3 : 2) + (clipboard.length > 0 && cwd ? 1 : 0)+ : 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)]'}>@@ -988,23 +1350,55 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri</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')}- </Button>- <Button type="button" size="sm" variant="outline" className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]" disabled={!cwd || newEntry !== null} onClick={() => startNewEntry('folder')}>- <FolderPlus className="size-3.5" /> {t('apps.fileBrowser.newFolder')}- </Button><input ref={uploadInputRef} type="file" multiple className="hidden" onChange={onUploadPick} />- <Button- type="button"- size="sm"- variant="outline"- className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]"- disabled={!cwd || uploadProgress !== null}- onClick={() => uploadInputRef.current?.click()}- >- {uploadProgress ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} {t('apps.fileBrowser.upload')}- </Button>+ {selectedItems.length > 1 || touchSelectionMode ? (+ <div className="flex shrink-0 items-center gap-1 overflow-x-auto">+ <Button type="button" size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-[12px]" onClick={() => copyRowsToClipboard(selectedItems)} disabled={selectedItems.length === 0}>+ <Copy className="size-3.5" /> {t('apps.fileBrowser.copy')}+ </Button>+ {clipboard.length > 0 && (+ <Button type="button" size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-[12px]" disabled={!cwd} onClick={() => void pasteRows(clipboard, cwd)}>+ <ClipboardPaste className="size-3.5" /> {t('apps.fileBrowser.paste')}+ </Button>+ )}+ <Button type="button" size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-[12px]" onClick={() => setMovePickerItems(selectedItems)} disabled={selectedItems.length === 0}>+ <FolderInput className="size-3.5" /> {t('apps.fileBrowser.move')}+ </Button>+ <Button type="button" size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-[12px]" onClick={() => void downloadItems(selectedItems)} disabled={selectedItems.length === 0}>+ <Download className="size-3.5" /> {t('apps.fileBrowser.download')}+ </Button>+ <Button type="button" size="sm" variant="ghost" className="h-7 gap-1.5 px-2 text-[12px] text-destructive" onClick={() => removeItems(selectedItems)} disabled={selectedItems.length === 0}>+ <Trash2 className="size-3.5" /> {t('apps.fileBrowser.delete')}+ </Button>+ <Button type="button" size="icon" variant="ghost" className="size-7 text-muted" aria-label={t('apps.fileBrowser.clearSelection')} onClick={clearSelection}>+ <X className="size-4" />+ </Button>+ </div>+ ) : (+ <>+ {clipboard.length > 0 && (+ <Button type="button" size="sm" variant="ghost" className="h-7 shrink-0 gap-1.5 px-2 text-[12px]" disabled={!cwd} onClick={() => void pasteRows(clipboard, cwd)}>+ <ClipboardPaste className="size-3.5" /> {t('apps.fileBrowser.paste')}+ </Button>+ )}+ <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')}+ </Button>+ <Button type="button" size="sm" variant="outline" className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]" disabled={!cwd || newEntry !== null} onClick={() => startNewEntry('folder')}>+ <FolderPlus className="size-3.5" /> {t('apps.fileBrowser.newFolder')}+ </Button>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]"+ disabled={!cwd || uploadProgress !== null}+ onClick={() => uploadInputRef.current?.click()}+ >+ {uploadProgress ? <Loader2 className="size-3.5 animate-spin" /> : <Upload className="size-3.5" />} {t('apps.fileBrowser.upload')}+ </Button>+ </>+ )}</div>{/* Mobile favorites/projects strip: the rail (below) is hidden under md, so surface the same@@ -1107,6 +1501,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strionDrop={onListingDrop}><div className="flex items-center border-b border-border px-3 py-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted">+ {touchSelectionMode && <span className="mr-2 size-[18px] shrink-0" aria-hidden />}<button type="button" onClick={() => cycleSort('name')} className={clsx('flex min-w-0 flex-1 items-center gap-1 text-left transition hover:text-foreground', sort?.col === 'name' && 'text-foreground')}><span className="truncate">{t('apps.fileBrowser.colName')}</span>{sort?.col === 'name' && (sort.dir === 'asc' ? <ChevronUp className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />)}@@ -1167,12 +1562,15 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri<buttonkey={item.full}type="button"- draggable+ draggable={!touchSelectionMode}+ role={touchSelectionMode ? 'checkbox' : undefined}+ aria-checked={touchSelectionMode ? selected.has(item.full) : undefined}onDragStart={(e) => {- dragRef.current = item;+ const dragged = selected.has(item.full) && selectedItems.length > 1 ? selectedItems : [item];+ dragRef.current = dragged;e.dataTransfer.effectAllowed = 'move';try {- e.dataTransfer.setData('text/plain', item.full);+ e.dataTransfer.setData('text/plain', dragged.map((entry) => entry.full).join('\n'));} catch {// Some browsers throw if setData is called outside a real drag; harmless.}@@ -1182,7 +1580,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strisetDropTarget(null);}}onDragOver={(e) => {- if (!isDir || !dragRef.current || dragRef.current.full === item.full) return;+ if (!isDir || !dragRef.current || dragRef.current.some((entry) => entry.full === item.full)) return;e.preventDefault();setDropTarget((d) => (d === item.full ? d : item.full));}}@@ -1194,29 +1592,51 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strie.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) void openItem(item);- else setSelected(item.full);- }}+ onPointerDown={(event) => startLongPress(event, item)}+ onPointerMove={moveLongPress}+ onPointerUp={cancelLongPress}+ onPointerCancel={cancelLongPress}+ // Mouse: plain single-click selects, modifiers extend/toggle, double-click opens.+ // Touch: tap opens until long-press enters checkbox selection mode, then toggles.+ onClick={(event) => selectRow(event, item)}onDoubleClick={() => void openItem(item)}onKeyDown={(ev) => {if (ev.key === 'Enter' || ev.key === ' ') {ev.preventDefault();- void openItem(item);+ if (touchSelectionMode) {+ setSelected((current) => {+ const next = new Set(current);+ if (next.has(item.full)) next.delete(item.full);+ else next.add(item.full);+ return next;+ });+ } else {+ void openItem(item);+ }+ }+ }}+ onContextMenu={(e) => {+ if (window.matchMedia('(pointer: coarse)').matches) {+ e.preventDefault();+ return;+ }+ const items = selected.has(item.full) ? selectedItems : [item];+ if (!selected.has(item.full)) {+ setSelected(new Set([item.full]));+ selectionAnchorRef.current = item.full;}+ openMenu(e, item, items);}}- onContextMenu={(e) => openMenu(e, item)}className={clsx('flex w-full items-center px-3 py-1.5 text-left text-[12.5px] transition',dropTarget === item.full? 'bg-cyan-soft text-foreground ring-1 ring-inset ring-cyan'- : selected === item.full+ : selected.has(item.full)? 'bg-cyan-soft text-foreground': 'text-foreground hover:bg-foreground/[0.04]',)}>+ {touchSelectionMode && <Checkbox checked={selected.has(item.full)} presentational className="mr-2" />}<span className="flex min-w-0 flex-1 items-center gap-2"><Icon className="size-4 shrink-0" style={{ color }} /><span className="truncate">{item.entry.name}</span>@@ -1251,7 +1671,9 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{undoEntry && (<div className="flex items-center gap-2 border-t border-border bg-surface-2/80 px-3 py-1.5 text-[12px]"><span className="min-w-0 flex-1 truncate text-muted">- {t(undoEntry.kind === 'delete' ? 'apps.fileBrowser.deletedNotice' : 'apps.fileBrowser.movedNotice', { name: undoEntry.label })}+ {undoEntry.count > 1+ ? t(undoEntry.kind === 'delete' ? 'apps.fileBrowser.deletedBatchNotice' : 'apps.fileBrowser.movedBatchNotice', { count: undoEntry.count })+ : t(undoEntry.kind === 'delete' ? 'apps.fileBrowser.deletedNotice' : 'apps.fileBrowser.movedNotice', { name: undoEntry.label })}</span><Buttontype="button"@@ -1288,6 +1710,11 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri</span>)}<span className="ml-auto flex min-w-0 items-center gap-2 font-mono">+ {selectedItems.length > 1 && (+ <span className="truncate text-foreground/80">+ {t('apps.fileBrowser.selectedStatus', { count: selectedItems.length, size: formatSize(selectedSize) })}+ </span>+ )}{selectedEntry && (<span className="truncate text-foreground/80">{selectedEntry.name}@@ -1330,6 +1757,18 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri</div>)}+ {movePickerItems && (+ <FilePicker+ mode="open-directory"+ initialPath={cwd}+ onCancel={() => setMovePickerItems(null)}+ onConfirm={async ({ path }) => {+ await moveItemsInto(movePickerItems, path);+ setMovePickerItems(null);+ }}+ />+ )}+{/* Destructive delete confirmation (product dialog; replaces window.confirm). The wordingstays neutral about undoability — whether the backend could stage the entry is only knownafter the call, and the undo bar communicates it. */}@@ -1338,8 +1777,18 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strionOpenChange={(open) => {if (!open) setPendingDelete(null);}}- title={t('apps.fileBrowser.deleteTitle', { name: pendingDelete?.entry.name ?? '' })}- description={pendingDelete?.entry.kind === 'dir' ? t('apps.fileBrowser.deleteDirHint') : undefined}+ title={+ pendingDelete && pendingDelete.length > 1+ ? t('apps.fileBrowser.deleteBatchTitle', { count: pendingDelete.length })+ : t('apps.fileBrowser.deleteTitle', { name: pendingDelete?.[0]?.entry.name ?? '' })+ }+ description={+ pendingDelete && pendingDelete.length > 1+ ? t('apps.fileBrowser.deleteBatchHint', { count: pendingDelete.length })+ : pendingDelete?.[0]?.entry.kind === 'dir'+ ? t('apps.fileBrowser.deleteDirHint')+ : undefined+ }confirmLabel={t('apps.fileBrowser.delete')}destructiveonConfirm={performDelete}@@ -1356,30 +1805,30 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: strionConfirm={() => answerReplace(true)}/>- {/* Drag-move name-clash: Replace / Keep both / Cancel. Purpose-built on the Dialog primitive+ {/* Move/copy name-clash: Replace / Keep both / Cancel. Purpose-built on the Dialog primitivebecause ConfirmDialog's footer is fixed to two actions — but it reuses the same primitives,so the look matches. Dismissal is blocked while a retry is in flight. */}<Dialog- open={moveClash !== null}+ open={nameClash !== null}onOpenChange={(open) => {- if (!open && moveClashBusy === null) setMoveClash(null);+ if (!open && nameClashBusy === null) answerNameClash(false);}}><DialogContent className="max-w-md"><DialogHeader>- <DialogTitle>{t('apps.fileBrowser.moveClashTitle', { name: moveClash?.item.entry.name ?? '' })}</DialogTitle>+ <DialogTitle>{t('apps.fileBrowser.moveClashTitle', { name: nameClash?.item.entry.name ?? '' })}</DialogTitle><DialogDescription>{t('apps.fileBrowser.moveClashDesc')}</DialogDescription></DialogHeader><DialogFooter>- <Button variant="ghost" onClick={() => setMoveClash(null)} disabled={moveClashBusy !== null}>+ <Button variant="ghost" onClick={() => answerNameClash(false)} disabled={nameClashBusy !== null}>{t('common.cancel')}</Button>- <Button variant="outline" onClick={() => void keepBothClash()} disabled={moveClashBusy !== null}>- {moveClashBusy === 'keep' ? <Loader2 className="size-4 animate-spin" /> : null}+ <Button variant="outline" onClick={() => void runNameClash('keep')} disabled={nameClashBusy !== null}>+ {nameClashBusy === 'keep' ? <Loader2 className="size-4 animate-spin" /> : null}{t('apps.fileBrowser.keepBoth')}</Button>- <Button variant="default" onClick={() => void replaceClash()} disabled={moveClashBusy !== null}>- {moveClashBusy === 'replace' ? <Loader2 className="size-4 animate-spin" /> : null}+ <Button variant="default" onClick={() => void runNameClash('replace')} disabled={nameClashBusy !== null}>+ {nameClashBusy === 'replace' ? <Loader2 className="size-4 animate-spin" /> : null}{t('apps.fileBrowser.replace')}</Button></DialogFooter>@@ -1389,51 +1838,81 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri{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' && (+ menu.items.length > 1 ? (+ <><ContextMenuItem- icon={<SquareTerminal className="size-3.5 text-mint" />}- label={t('apps.fileBrowser.openTerminalHere')}+ icon={<Copy className="size-3.5" />}+ label={t('apps.fileBrowser.copy')}+ onClick={() => copyRowsToClipboard(menu.items)}+ />+ <ContextMenuItem+ icon={<FolderInput className="size-3.5 text-cyan" />}+ label={t('apps.fileBrowser.move')}onClick={() => {- const it = menu.item as RowItem;+ const items = menu.items;closeMenu();- openTerminalHere(it.full);+ setMovePickerItems(items);}}/>- )}- {menu.item.entry.kind !== 'dir' && (<ContextMenuItemicon={<Download className="size-3.5 text-mint" />}label={t('apps.fileBrowser.download')}+ onClick={() => void downloadItems(menu.items)}+ />+ <ContextMenuItem icon={<Trash2 className="size-3.5" />} label={t('apps.fileBrowser.delete')} danger onClick={() => removeItems(menu.items)} />+ </>+ ) : (+ <>+ <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();- downloadFile(it.full);+ void openItem(it);}}/>- )}- <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)} />- </>+ {menu.item.entry.kind === 'dir' && (+ <ContextMenuItem+ icon={<SquareTerminal className="size-3.5 text-mint" />}+ label={t('apps.fileBrowser.openTerminalHere')}+ onClick={() => {+ const it = menu.item as RowItem;+ closeMenu();+ openTerminalHere(it.full);+ }}+ />+ )}+ {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={<Copy className="size-3.5" />} label={t('apps.fileBrowser.copy')} onClick={() => copyRowsToClipboard(menu.items)} />+ <ContextMenuItem icon={<Copy className="size-3.5 text-gold" />} label={t('apps.fileBrowser.duplicate')} onClick={() => void duplicateItem(menu.item as RowItem)} />+ <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={() => removeItems(menu.items)} />+ </>+ )) : (<>+ {clipboard.length > 0 && cwd && (+ <ContextMenuItem icon={<ClipboardPaste className="size-3.5 text-cyan" />} label={t('apps.fileBrowser.paste')} onClick={() => void pasteRows(clipboard, cwd)} />+ )}<ContextMenuItemicon={<FilePlus className="size-3.5 text-mint" />}label={t('apps.fileBrowser.newFile')}diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1c4d453e9..034e9e3c0 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -731,14 +731,22 @@"uploadError": "{{name}}: {{message}}","open": "Open","openTerminalHere": "Open Terminal Here",+ "copy": "Copy",+ "paste": "Paste",+ "duplicate": "Duplicate",+ "move": "Move","rename": "Rename","delete": "Delete","deleteTitle": "Delete \"{{name}}\"?","deleteDirHint": "The folder and everything inside it will be deleted.",+ "deleteBatchTitle": "Delete {{count}} items?",+ "deleteBatchHint": "The selected items and all contents of selected folders will be deleted.","replace": "Replace","undo": "Undo","deletedNotice": "Deleted \"{{name}}\"",+ "deletedBatchNotice": "Deleted {{count}} items","movedNotice": "Moved \"{{name}}\"",+ "movedBatchNotice": "Moved {{count}} items","searchPlaceholder": "Search","colName": "Name","colSize": "Size",@@ -751,6 +759,11 @@"searchContents": "Search file contents","searchContentPlaceholder": "Search contents","matchCount": "{{count}} matches",+ "selectedStatus": "{{count}} selected · {{size}}",+ "clearSelection": "Clear selection",+ "operationError": "{{name}}: {{message}}",+ "downloadLimit": "Downloaded {{count}} files; {{remaining}} remain selected.",+ "downloadFoldersSkipped": "Skipped {{count}} folder(s); download supports files only.","moveClashTitle": "\"{{name}}\" already exists","moveClashDesc": "Something with that name is already in the destination folder.","keepBoth": "Keep both",@@ -785,10 +798,12 @@"deleteFailed": "Couldn't delete this item.","renameFailed": "Couldn't rename this item.","moveFailed": "Couldn't move this item.",+ "copyFailed": "Couldn't copy this item.","searchFailed": "Couldn't search this folder.","uploadFailed": "Couldn't upload this file.","invalid_query": "Enter something to search for.","invalid_move": "That move isn't allowed.",+ "invalid_copy": "That copy 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 0ca2beb75..59d1bc137 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -731,14 +731,22 @@"uploadError": "{{name}}:{{message}}","open": "打开","openTerminalHere": "在此处打开终端",+ "copy": "复制",+ "paste": "粘贴",+ "duplicate": "创建副本",+ "move": "移动","rename": "重命名","delete": "删除","deleteTitle": "删除“{{name}}”?","deleteDirHint": "文件夹及其中所有内容都会被删除。",+ "deleteBatchTitle": "删除 {{count}} 个项目?",+ "deleteBatchHint": "所选项目及所选文件夹中的全部内容都会被删除。","replace": "替换","undo": "撤销","deletedNotice": "已删除“{{name}}”",+ "deletedBatchNotice": "已删除 {{count}} 个项目","movedNotice": "已移动“{{name}}”",+ "movedBatchNotice": "已移动 {{count}} 个项目","searchPlaceholder": "搜索","colName": "名称","colSize": "大小",@@ -751,6 +759,11 @@"searchContents": "搜索文件内容","searchContentPlaceholder": "搜索内容","matchCount": "{{count}} 处匹配",+ "selectedStatus": "已选择 {{count}} 个 · {{size}}",+ "clearSelection": "清除选择",+ "operationError": "{{name}}:{{message}}",+ "downloadLimit": "已下载 {{count}} 个文件,仍有 {{remaining}} 个保持选中。",+ "downloadFoldersSkipped": "已跳过 {{count}} 个文件夹;下载仅支持文件。","moveClashTitle": "“{{name}}”已存在","moveClashDesc": "目标文件夹中已有同名文件或文件夹。","keepBoth": "两者都保留",@@ -785,10 +798,12 @@"deleteFailed": "无法删除这个项目。","renameFailed": "无法重命名这个项目。","moveFailed": "无法移动这个项目。",+ "copyFailed": "无法复制这个项目。","searchFailed": "无法搜索这个文件夹。","uploadFailed": "无法上传这个文件。","invalid_query": "请输入搜索内容。","invalid_move": "不允许这样移动。",+ "invalid_copy": "不允许这样复制。","invalid_response": "服务器返回了异常响应,请重试。"}},diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.tsindex 717041238..649bda481 100644--- a/ui/src/lib/filesApi.ts+++ b/ui/src/lib/filesApi.ts@@ -313,6 +313,19 @@ export async function movePath(src: string, dst: string, overwrite = false): Pro);}+// Copy an entry to an absolute destination. The backend preserves symlinks as links, applies a+// total-size cap to directory copies, and publishes the completed copy atomically. Callers retry+// `exists` with either overwrite=true (Replace) or a de-duplicated destination (Keep both).+export async function copyPath(src: string, dst: string, overwrite = false): Promise<{ ok: true; path: string }> {+ return parse(+ await apiFetch('/api/files/copy', {+ 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.