Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(ui): files delete/move safety net — product confirms + undo bar (#843)

Call White05d9ecb99c3c
diff --git a/ui/src/components/ui/confirm-dialog.tsx b/ui/src/components/ui/confirm-dialog.tsx
index 5b7d9d869..772367682 100644
--- a/ui/src/components/ui/confirm-dialog.tsx
+++ b/ui/src/components/ui/confirm-dialog.tsx
@@ -27,6 +27,12 @@ export interface ConfirmDialogProps {
confirmDisabled?: boolean;
/** Runs on confirm; while it's pending a spinner shows and the dialog can't be dismissed. */
onConfirm: () => void | Promise<void>;
+ /**
+ * Re-cascade a fixed theme onto the dialog subtree. The dialog PORTALS to <body>, so inside a
+ * theme-locked surface (e.g. the dark Editor window) it would otherwise render with the global
+ * theme and clash with its opener.
+ */
+ dataTheme?: 'dark';
}
/**
@@ -46,6 +52,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
holdSeconds = 0,
confirmDisabled = false,
onConfirm,
+ dataTheme,
}) => {
const { t } = useTranslation();
const [remaining, setRemaining] = React.useState(0);
@@ -91,7 +98,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({
if (!busy) onOpenChange(next);
}}
>
- <DialogContent className="max-w-md">
+ <DialogContent className="max-w-md" data-theme={dataTheme}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
{description ? <DialogDescription>{description}</DialogDescription> : null}
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index f614f584e..754cb341c 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -24,6 +24,7 @@ import {
Search,
SquareTerminal,
Trash2,
+ Undo2,
Upload,
X,
type LucideIcon,
@@ -37,6 +38,7 @@ import {
contentUrl,
deletePath,
downloadFile,
+ undoDelete,
fileBrowserErrorMessage,
fileMeta,
FilesApiError,
@@ -59,6 +61,7 @@ import {
type NameHit,
} from '../../lib/filesApi';
import { Button } from '../ui/button';
+import { ConfirmDialog } from '../ui/confirm-dialog';
import { ContextMenu, ContextMenuItem } from '../ui/context-menu';
import { FilePreview } from '../ui/file-preview';
import { InlineNameInput } from '../ui/inline-name-input';
@@ -422,21 +425,95 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
[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')));
- }
+ // ---- Undo bar (delete + drag-move) -------------------------------------------------------------
+ // One entry at a time: a new undoable action replaces the bar (the previous action simply ages out
+ // 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 UndoEntry =
+ | { kind: 'delete'; label: string; token: string }
+ | { kind: 'move'; label: string; from: string; to: string };
+ const [undoEntry, setUndoEntry] = useState<UndoEntry | null>(null);
+ const [undoBusy, setUndoBusy] = useState(false);
+ const undoTimerRef = useRef<number | null>(null);
+ const showUndo = useCallback((entry: UndoEntry) => {
+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);
+ setUndoEntry(entry);
+ undoTimerRef.current = window.setTimeout(() => setUndoEntry(null), 8000);
+ }, []);
+ useEffect(
+ () => () => {
+ if (undoTimerRef.current != null) window.clearTimeout(undoTimerRef.current);
},
- [t, refreshAll],
+ [],
);
+ const performUndo = useCallback(async () => {
+ const entry = undoEntry;
+ if (!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);
+ 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.
+ 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).
+ setUndoEntry((cur) => {
+ if (cur !== entry) return cur;
+ undoTimerRef.current = window.setTimeout(() => setUndoEntry(null), 8000);
+ return cur;
+ });
+ }
+ } finally {
+ 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) => {
+ setMenu(null);
+ setPendingDelete(item);
+ }, []);
+ 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);
+ }
+ 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]);
// ---- Context menu ----------------------------------------------------------------------------
// `item` is null for blank space (offers New File/Folder only).
@@ -462,13 +539,18 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// 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));
+ const moved = joinPath(destDir, item.entry.name);
+ await movePath(item.full, moved);
setError(null);
+ // A mis-drop is easy (drop targets are everywhere), so offer a short revert: the reverse
+ // move needs no backend support — just move it back where it came from.
+ showUndo({ kind: 'move', label: item.entry.name, from: moved, to: item.full });
refreshAll();
} catch (e: unknown) {
setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.moveFailed')));
}
},
+ // eslint-disable-next-line react-hooks/exhaustive-deps
[t, refreshAll],
);
// Drop-target props for any folder (row / rail / breadcrumb). Only active while a drag is in flight
@@ -486,6 +568,41 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
},
});
+ // Promise-bridged replace prompt: the upload workers are async, so the dialog answer comes back
+ // as a promise. Prompts are CHAINED — with parallel workers, two simultaneous name clashes must
+ // not overwrite each other's pending dialog; each waits for the previous answer.
+ const [replaceAsk, setReplaceAsk] = useState<{ name: string; resolve: (ok: boolean) => void } | null>(null);
+ const askChainRef = useRef<Promise<unknown>>(Promise.resolve());
+ // Unmount (window closed mid-question) must not hang the upload workers: the CURRENT pending ask
+ // resolves `false` from the cleanup below, and QUEUED asks short-circuit to `false` instead of
+ // setState-ing an unmounted component (which would leave their promises forever pending).
+ const unmountedRef = useRef(false);
+ const pendingAskRef = useRef<{ resolve: (ok: boolean) => void } | null>(null);
+ useEffect(() => {
+ pendingAskRef.current = replaceAsk;
+ }, [replaceAsk]);
+ useEffect(
+ () => () => {
+ unmountedRef.current = true;
+ pendingAskRef.current?.resolve(false);
+ },
+ [],
+ );
+ const confirmReplace = useCallback((name: string) => {
+ const next = askChainRef.current.then(() =>
+ unmountedRef.current ? false : new Promise<boolean>((resolve) => setReplaceAsk({ name, resolve })),
+ );
+ askChainRef.current = next.catch(() => false);
+ return next;
+ }, []);
+ const answerReplace = useCallback(
+ (ok: boolean) => {
+ replaceAsk?.resolve(ok);
+ setReplaceAsk(null);
+ },
+ [replaceAsk],
+ );
+
// ---- Upload (toolbar button + OS drag-drop) --------------------------------------------------
// Files land in the folder that was current when the upload STARTED (`dest`), uploaded with a
// bounded worker pool. Progress + per-file failures surface in the toolbar/status bar and the
@@ -528,8 +645,8 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
refreshAllRef.current();
} catch (e) {
if (e instanceof FilesApiError && e.code === 'exists') {
- // Name clash: ask (the codebase's window.confirm pattern) and retry with overwrite on yes.
- if (window.confirm(t('apps.fileBrowser.uploadReplace', { name: file.name }))) {
+ // Name clash: ask via the product ConfirmDialog and retry with overwrite on yes.
+ if (await confirmReplace(file.name)) {
try {
await uploadFile(dest, file, { overwrite: true });
refreshAllRef.current();
@@ -557,7 +674,7 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
setUploadProgress(null);
setError(failures.length ? failures.join(' · ') : null);
},
- [cwd, t],
+ [cwd, t, confirmReplace],
);
const onUploadPick = useCallback(
@@ -902,6 +1019,35 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</div>
</div>
+ {/* Undo bar: one recent revertible action (delete via backend token / move via reverse
+ move). Auto-dismisses; doesn't steal focus from the listing. */}
+ {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 })}
+ </span>
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="h-6 shrink-0 gap-1 px-2 text-[12px] text-cyan"
+ disabled={undoBusy}
+ onClick={() => void performUndo()}
+ >
+ {undoBusy ? <Loader2 className="size-3 animate-spin" /> : <Undo2 className="size-3" />}
+ {t('apps.fileBrowser.undo')}
+ </Button>
+ <button
+ type="button"
+ aria-label={t('common.close')}
+ onClick={() => setUndoEntry(null)}
+ className="shrink-0 text-muted transition hover:text-foreground"
+ >
+ <X className="size-3" strokeWidth={2.5} />
+ </button>
+ </div>
+ )}
+
{/* Status bar: item count + selection, with the hidden-files toggle. */}
<div className="flex items-center gap-3 border-t border-border bg-surface-2/60 px-3 py-1.5 text-[11px] text-muted">
<label className="flex items-center gap-1.5">
@@ -957,6 +1103,32 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</div>
)}
+ {/* Destructive delete confirmation (product dialog; replaces window.confirm). The wording
+ stays neutral about undoability — whether the backend could stage the entry is only known
+ after the call, and the undo bar communicates it. */}
+ <ConfirmDialog
+ open={pendingDelete !== null}
+ onOpenChange={(open) => {
+ if (!open) setPendingDelete(null);
+ }}
+ title={t('apps.fileBrowser.deleteTitle', { name: pendingDelete?.entry.name ?? '' })}
+ description={pendingDelete?.entry.kind === 'dir' ? t('apps.fileBrowser.deleteDirHint') : undefined}
+ confirmLabel={t('apps.fileBrowser.delete')}
+ destructive
+ onConfirm={performDelete}
+ />
+
+ {/* Upload name-clash replace prompt (promise-bridged from the async upload workers). */}
+ <ConfirmDialog
+ open={replaceAsk !== null}
+ onOpenChange={(open) => {
+ if (!open) answerReplace(false);
+ }}
+ title={t('apps.fileBrowser.uploadReplace', { name: replaceAsk?.name ?? '' })}
+ confirmLabel={t('apps.fileBrowser.replace')}
+ onConfirm={() => answerReplace(true)}
+ />
+
{menu && (
<ContextMenu x={menu.x} y={menu.y} onClose={closeMenu} itemCount={menuItemCount}>
{menu.item ? (
diff --git a/ui/src/components/workbench/FileTree.tsx b/ui/src/components/workbench/FileTree.tsx
index 53a334f33..8666d90c5 100644
--- a/ui/src/components/workbench/FileTree.tsx
+++ b/ui/src/components/workbench/FileTree.tsx
@@ -29,6 +29,7 @@ import {
writeFile,
type FsEntry,
} from '../../lib/filesApi';
+import { ConfirmDialog } from '../ui/confirm-dialog';
import { ContextMenu, ContextMenuItem } from '../ui/context-menu';
import { InlineNameInput } from '../ui/inline-name-input';
@@ -329,22 +330,28 @@ export const FileTree: React.FC<{
}, []);
const closeMenu = useCallback(() => setMenu(null), []);
- const removeEntry = useCallback(
- async (dir: string, entry: FsEntry) => {
- setMenu(null);
- if (!window.confirm(t('apps.fileBrowser.confirmDelete', { name: entry.name }))) return;
- const full = joinPath(dir, entry.name);
- try {
- await deletePath(full, entry.kind === 'dir');
- setError(null);
- bump(dir);
- onEntryDeleted?.(full);
- } catch (e: unknown) {
- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.deleteFailed')));
- }
- },
- [t, bump, onEntryDeleted],
- );
+ // The menu only REQUESTS the delete; the destructive ConfirmDialog performs it. (The staged-undo
+ // bar lives in the Files app; the editor explorer keeps plain confirmed deletes for now.)
+ const [pendingDelete, setPendingDelete] = useState<{ dir: string; entry: FsEntry } | null>(null);
+ const removeEntry = useCallback((dir: string, entry: FsEntry) => {
+ setMenu(null);
+ setPendingDelete({ dir, entry });
+ }, []);
+ const performDelete = useCallback(async () => {
+ const pending = pendingDelete;
+ if (!pending) return;
+ const full = joinPath(pending.dir, pending.entry.name);
+ try {
+ await deletePath(full, pending.entry.kind === 'dir');
+ setError(null);
+ bump(pending.dir);
+ onEntryDeleted?.(full);
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.deleteFailed')));
+ } finally {
+ setPendingDelete(null);
+ }
+ }, [pendingDelete, t, bump, onEntryDeleted]);
const ctx = useMemo<TreeCtx>(
() => ({ activePath, showHidden, onOpenFile, versionOf, edit, startEdit, cancelEdit, commitEdit, openMenu }),
@@ -425,6 +432,21 @@ export const FileTree: React.FC<{
)}
</ContextMenu>
)}
+
+ {/* Destructive delete confirmation. dataTheme keeps the portaled dialog dark inside the
+ dark-locked Editor window instead of picking up the global theme. */}
+ <ConfirmDialog
+ open={pendingDelete !== null}
+ onOpenChange={(open) => {
+ if (!open) setPendingDelete(null);
+ }}
+ title={t('apps.fileBrowser.deleteTitle', { name: pendingDelete?.entry.name ?? '' })}
+ description={pendingDelete?.entry.kind === 'dir' ? t('apps.fileBrowser.deleteDirHint') : undefined}
+ confirmLabel={t('apps.fileBrowser.delete')}
+ destructive
+ dataTheme="dark"
+ onConfirm={performDelete}
+ />
</Ctx.Provider>
);
};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 11940e556..94409ff33 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -732,7 +732,12 @@
"openTerminalHere": "Open Terminal Here",
"rename": "Rename",
"delete": "Delete",
- "confirmDelete": "Delete \"{{name}}\"? This can't be undone.",
+ "deleteTitle": "Delete \"{{name}}\"?",
+ "deleteDirHint": "The folder and everything inside it will be deleted.",
+ "replace": "Replace",
+ "undo": "Undo",
+ "deletedNotice": "Deleted \"{{name}}\"",
+ "movedNotice": "Moved \"{{name}}\"",
"searchPlaceholder": "Search",
"colName": "Name",
"colSize": "Size",
@@ -761,6 +766,8 @@
"invalid_path": "Enter a valid absolute path.",
"invalid_name": "Enter a valid name.",
"exists": "Path already exists.",
+ "expired": "The undo window has passed.",
+ "undoFailed": "Couldn't undo.",
"fs_error": "File system operation failed.",
"listFailed": "Couldn't list this folder.",
"openFailed": "Couldn't open this item.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 50c7038d5..8dd50915b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -732,7 +732,12 @@
"openTerminalHere": "在此处打开终端",
"rename": "重命名",
"delete": "删除",
- "confirmDelete": "删除“{{name}}”?此操作无法撤销。",
+ "deleteTitle": "删除“{{name}}”?",
+ "deleteDirHint": "文件夹及其中所有内容都会被删除。",
+ "replace": "替换",
+ "undo": "撤销",
+ "deletedNotice": "已删除“{{name}}”",
+ "movedNotice": "已移动“{{name}}”",
"searchPlaceholder": "搜索",
"colName": "名称",
"colSize": "大小",
@@ -761,6 +766,8 @@
"invalid_path": "请输入有效的绝对路径。",
"invalid_name": "请输入有效名称。",
"exists": "这个路径已存在。",
+ "expired": "撤销时限已过。",
+ "undoFailed": "无法撤销。",
"fs_error": "文件系统操作失败。",
"listFailed": "无法列出这个文件夹。",
"openFailed": "无法打开这个项目。",
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
index f6b356eb9..717041238 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -261,7 +261,12 @@ export async function uploadFile(
return parse<UploadResult>(await apiFetch('/api/files/upload', { method: 'POST', body: form }));
}
-export async function deletePath(path: string, recursive = false): Promise<{ ok: true }> {
+// Delete stages the entry for a short undo window when the backend can (same-filesystem, within
+// size caps): `undo_token` is non-null then. Cross-device / oversized entries delete permanently
+// (token null) — the UI only offers Undo when a token came back.
+export type DeleteResult = { ok: true; undo_token: string | null; undo_expires_seconds: number | null };
+
+export async function deletePath(path: string, recursive = false): Promise<DeleteResult> {
return parse(
await apiFetch('/api/files/delete', {
method: 'POST',
@@ -271,6 +276,18 @@ export async function deletePath(path: string, recursive = false): Promise<{ ok:
);
}
+// Restore a staged delete. 409 `exists` = the original path is occupied again; 410 `expired` =
+// the token is unknown/expired/purged. Both surface through the standard FilesApiError shape.
+export async function undoDelete(token: string): Promise<{ restored_path: string }> {
+ return parse(
+ await apiFetch('/api/files/delete/undo', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ token }),
+ }),
+ );
+}
+
// Rename an entry in place (same parent). The backend validates the new name and refuses to
// clobber an existing destination (errors.exists). Returns the new absolute path.
export async function renamePath(path: string, newName: string): Promise<{ ok: true; path: string }> {