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(workbench): windowed-apps Finder + Editor explorer/preview polish (#718)

Call Whited7a3633a4391
diff --git a/docs/plans/apps-finder-explorer-polish.md b/docs/plans/apps-finder-explorer-polish.md
new file mode 100644
index 000000000..43b605e9e
--- /dev/null
+++ b/docs/plans/apps-finder-explorer-polish.md
@@ -0,0 +1,51 @@
+# Windowed Apps — File Browser (Finder) + Editor explorer/preview polish
+
+Combined Phase 1 + Phase 2 of the windowed-apps batch (both done on one branch
+`feat/apps-finder-explorer`, atomic commits, one PR). Reuse first: existing
+`<Markdown>`, `highlighter.ts`, `filePreview.ts`, `FilePicker` inline-new-folder,
+`file-viewer` render primitives.
+
+## Phase 1 — File Browser (`AppsFileBrowserPage.tsx`, Finder-like)
+1. **Column sort** — Name / Size / Modified headers are buttons; clicking cycles
+ asc → desc → none (none = default dirs-first, then name). Active column shows a
+ direction caret. Sort persists within the app session (state, not navigation).
+ Dirs always group before files within a direction (Finder-like).
+2. **Inline new-folder** — replace `window.prompt` with an inline editable row at
+ the top of the listing (mirror `FilePicker`'s inline new-folder): Enter creates,
+ Esc/blur cancels, name validated via `isPlainEntryName`, dup → inline error.
+3. **New File → Editor at cwd** — instead of prompt-create, open the Editor rooted
+ at the current dir with a fresh untitled buffer (creation + editing happen in the
+ editor; first save lands in cwd). Pass `params: { newFileDir: cwd }`.
+4. **Refresh** — already present (toolbar `RefreshCw`); keep.
+5. **FloatingApps off in fullscreen** — `AppShell` must not float the Apps launcher
+ button over a maximized window (Dock redesign is later). Hide `FloatingApps` when
+ a window is maximized.
+
+## Phase 2 — Editor explorer + Preview (`EditorApp.tsx`, `FileTree.tsx`)
+6. **Explorer context menu** — right-click: blank → New File / New Folder; file →
+ Open / Rename / Delete; folder → New File / New Folder / Rename / Delete. Reuse
+ backend `makeDir` / `writeFile(create-only)` / `rename` / `delete`; a small reusable
+ context-menu primitive (or `ui/dropdown`).
+7. **Explorer collapse + drag-resize** — toggle the tree pane via the activity-bar
+ Files icon; drag its right border to resize width (min/max clamp, persisted in
+ session). VS Code-like.
+8. **Auto-refresh tree after save/create** — when the editor saves a new file
+ (save-as) or the context menu mutates, re-list the affected folder in the tree.
+9. **Reusable `<FilePreview>`** — one renderer: image (`<img>` fit/zoom), Markdown
+ (existing `<Markdown>`), SVG (as image), code (Shiki via `highlighter.ts`). Used by:
+ - **File Browser**: double-click a previewable file → preview overlay (not download).
+ - **Editor**: open an image → preview pane (no Monaco); Markdown/SVG → a top-right
+ **Preview** toggle (source ⇄ rendered), VS Code-like.
+ Extend `filePreview.ts` `previewKind` with an `image` kind. Reuse `file-viewer-modal`
+ render primitives, NOT the proxy-media-coupled modal itself.
+
+## Evidence
+- Build `npm run build` + vitest. Backend unchanged (Phase 1/2 are UI; context-menu
+ ops reuse existing `/api/files/*`). Manual: Incus regression — sort, inline new
+ folder, new-file→editor, context menu, resize, preview (image/md/svg), no float on
+ maximize.
+
+## Status
+- [ ] P1: column sort · inline new-folder · new-file→editor · FloatingApps off on maximize
+- [ ] P2: explorer context menu · collapse/resize · auto-refresh · reusable FilePreview
+- [ ] build + deploy + verify + PR + Codex
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index f329a63ee..ddf2c043d 100644
--- a/ui/src/components/AppShell.tsx
+++ b/ui/src/components/AppShell.tsx
@@ -13,7 +13,7 @@ import { ThemeToggle } from './ThemeToggle';
import { VersionBadge } from './VersionBadge';
import { WorkbenchSidebar } from './workbench/WorkbenchSidebar';
import { AppsLauncher } from './AppsLauncher';
-import { WindowManagerProvider, useWindowManager } from '../context/WindowManagerContext';
+import { WindowManagerProvider } from '../context/WindowManagerContext';
import { WindowLayer } from './apps/WindowLayer';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
@@ -207,29 +207,6 @@ const MobileTabBar: React.FC<{ items: ShellNavItem[]; center?: CenterButton }> =
);
};
-// When a window is MAXIMIZED it covers the sidebar (design If1Tt), so the in-sidebar Apps
-// launcher is hidden behind it. This floats a second Apps launcher at the bottom-left, ABOVE the
-// window layer, so the Dock stays reachable in full-screen — exactly the "Apps button floats on
-// top" of If1Tt. It must live OUTSIDE the aside: the aside is `position: fixed`, which always
-// forms a stacking context, so anything inside it can't rise above the window layer. Desktop-only
-// (windows are md+). Only one Apps launcher is ever visible — the sidebar's is covered when this shows.
-const FloatingApps: React.FC = () => {
- const { windows } = useWindowManager();
- const anyMaximized = windows.some((w) => w.maximized && !w.minimized);
- if (!anyMaximized) return null;
- return (
- // A solid rounded backing + shadow makes it read as a clean floating Dock launcher (design
- // If1Tt shows the pill clean) so the maximized app's content behind it — the editor activity
- // bar, the file-browser rail — doesn't bleed through the translucent pill. It follows the
- // workbench theme like the windows it sits over (no longer forced dark).
- <div
- className="fixed bottom-5 left-4 z-30 hidden w-[184px] rounded-full bg-surface-3 shadow-[0_10px_34px_-8px_rgba(0,0,0,0.7)] md:flex"
- >
- <AppsLauncher />
- </div>
- );
-};
-
export const AppShell: React.FC = () => {
const { t } = useTranslation();
const { status } = useStatus();
@@ -397,11 +374,11 @@ export const AppShell: React.FC = () => {
// Desktop: normal document flow.
<WindowManagerProvider>
<div className="flex h-[var(--app-shell-h)] flex-col overflow-hidden bg-background text-foreground md:block md:h-auto md:min-h-screen md:overflow-visible">
- {/* No z-index on the aside itself: a maximized window (window layer, z-20) must be able to
- cover the sidebar nav (design If1Tt). Keeping it un-stacked (z-auto, no stacking context)
- lets the Apps launcher inside escape to its own z-30 and float on top while the rest of the
- sidebar stays below the window layer. */}
- <aside className="fixed inset-y-0 left-0 hidden w-[240px] flex-col border-r border-border bg-surface md:flex">
+ {/* The sidebar forms its own stacking context BELOW the window layer (aside z-10 < window
+ layer z-20), so a maximized window covers the WHOLE sidebar — including the Apps launcher.
+ The Apps button no longer floats on top in full-screen (a Dock redesign comes later);
+ un-maximize to reach it. */}
+ <aside className="fixed inset-y-0 left-0 z-10 hidden w-[240px] flex-col border-r border-border bg-surface md:flex">
<div className="flex h-full flex-col justify-between gap-6 px-4 py-5">
{/* Top: Brand + Workspace label + Nav list */}
{/* Workbench mounts a search field right under the brand, so use the
@@ -435,9 +412,8 @@ export const AppShell: React.FC = () => {
{/* Bottom (design.pen NbPMq): row 1 = [Apps | Settings] two equal
buttons; row 2 = [version … run-dot]. Admin keeps its quick-toggles
- + hostname between the rows. Only the Apps launcher floats above a
- maximized window (it carries its own z-30); Settings / version / run-dot
- stay at the sidebar's level and are covered by a maximized window (If1Tt). */}
+ + hostname between the rows. The whole bottom cluster sits at the
+ sidebar's level (z-10) and is covered by a maximized window. */}
<div className="relative flex flex-col gap-3">
{/* Row 1 — Apps (Dock trigger, left) paired with the mode switch
(right). The Dock rises ABOVE the Apps button, clear of the
@@ -592,9 +568,11 @@ export const AppShell: React.FC = () => {
{/* App windows float over the workbench main area (desktop). The Dock (P2)
and the AppsLauncher bridge open windows via the WindowManager. */}
+ {/* A maximized window covers the sidebar Apps launcher. We intentionally do NOT float a
+ second launcher on top in full-screen anymore (product: avoid the fullscreen floating
+ button; a Dock redesign comes later). Un-maximize via the window traffic-lights to reach
+ the sidebar launcher. */}
<WindowLayer />
- {/* The Apps launcher floats back on top when a window is maximized (If1Tt). */}
- <FloatingApps />
</div>
</WindowManagerProvider>
);
diff --git a/ui/src/components/AppsLauncher.tsx b/ui/src/components/AppsLauncher.tsx
index 9f7c1b52a..3ca18ee19 100644
--- a/ui/src/components/AppsLauncher.tsx
+++ b/ui/src/components/AppsLauncher.tsx
@@ -55,10 +55,10 @@ export const AppsLauncher: React.FC = () => {
};
return (
- // z-30 keeps the Apps button (and its Dock popover) above the window layer (z-20) so it stays
- // reachable even under a MAXIMIZED window (design If1Tt). The sidebar aside is intentionally
- // un-stacked, so this z-30 composites at the root, above the window layer.
- <div className="relative z-30 flex-1" onMouseEnter={openHover} onMouseLeave={queueClose}>
+ // The sidebar aside owns the stacking context (z-10, below the window layer z-20), so the Apps
+ // button is covered by a maximized window like the rest of the sidebar. `relative` is just the
+ // positioning context for the Dock popover below; the popover's z-50 is scoped to the sidebar.
+ <div className="relative flex-1" onMouseEnter={openHover} onMouseLeave={queueClose}>
<button
type="button"
onClick={onClick}
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index f644cde5b..b26dcc9f0 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -75,8 +75,8 @@ export const WindowLayer: React.FC = () => {
// Browser follows the workbench light/dark, while the Editor and Terminal stay dark like a VS
// Code editor / a terminal. So the layer itself no longer forces a theme — each window opts in.
// Spans the FULL viewport (no longer offset past the sidebar): windows can move over
- // the sidebar and maximize fills the whole screen. The sidebar's bottom Apps/Dock
- // cluster sits above this layer (z-30) so it stays reachable under a maximized window.
+ // the sidebar and maximize fills the whole screen. This layer (z-20) sits ABOVE the sidebar
+ // (z-10), so a maximized window covers the whole sidebar, Apps launcher included.
className="pointer-events-none fixed inset-0 z-20 hidden md:block"
>
{windows.map((w) => (
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index 084e41db7..cdfb62de5 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -2,7 +2,9 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Braces,
+ ChevronDown,
ChevronRight,
+ ChevronUp,
Download,
FileCode2,
FileText,
@@ -18,14 +20,16 @@ import {
Monitor,
RefreshCw,
Search,
+ X,
type LucideIcon,
} from 'lucide-react';
import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useWindowManager } from '../../context/WindowManagerContext';
-import { isEditableFile } from '../../lib/filePreview';
+import { isEditableFile, isRenderOnlyImage } from '../../lib/filePreview';
import {
+ contentUrl,
downloadFile,
fileBrowserErrorMessage,
fileMeta,
@@ -41,6 +45,7 @@ import {
type FsListing,
} from '../../lib/filesApi';
import { Button } from '../ui/button';
+import { FilePreview } from './FilePreview';
// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).
const EXT_ICON: Record<string, { Icon: LucideIcon; color: string }> = {
@@ -108,6 +113,29 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
const [sysFavs, setSysFavs] = useState<Favorite[]>([]);
const [query, setQuery] = useState('');
const [selected, setSelected] = useState<string | null>(null);
+ // 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);
+ const cycleSort = useCallback(
+ (col: 'name' | 'size' | 'modified') =>
+ setSort((s) => (s?.col !== col ? { col, dir: 'asc' } : s.dir === 'asc' ? { col, dir: 'desc' } : null)),
+ [],
+ );
+ // Quick-look image preview: a raster image opens in an in-window overlay (Finder-style) instead
+ // of downloading. Kept in-window (not a portaled Dialog) so it stays inside the window's dark
+ // data-theme scope and bounds.
+ const [preview, setPreview] = useState<{ path: string; name: string } | null>(null);
+ useEffect(() => {
+ if (!preview) return;
+ const onKey = (ev: KeyboardEvent) => {
+ if (ev.key === 'Escape') {
+ ev.preventDefault();
+ setPreview(null);
+ }
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [preview]);
const navSeq = useRef(0);
const navigate = useCallback(
@@ -149,14 +177,20 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showHidden]);
- // Open: dir → navigate; editable text/code file (within the size cap) → Editor window;
- // anything else → raw download. (Richer per-type "default open" is a later design.)
+ // 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);
return;
}
+ // A raster image has no editable text form (it would otherwise just download) — preview it in an
+ // overlay instead. Works on mobile too (the overlay is in-window, unlike the desktop-only editor).
+ if (isRenderOnlyImage(e)) {
+ setPreview({ path: full, name: e.name });
+ return;
+ }
// Non-editable (symlink / binary / oversized — gated by the listing entry's kind+size) or
// mobile (the editor window layer is hidden below md): download. This branch MUST run
// synchronously, before any await, or the click's user activation is lost and Safari/iOS block
@@ -183,26 +217,51 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
}
};
- const createNamed = async (kind: 'file' | 'dir') => {
- const raw = window.prompt(t(kind === 'dir' ? 'apps.fileBrowser.newFolderPrompt' : 'apps.fileBrowser.newFilePrompt'));
- if (raw == null) return;
- const name = raw.trim();
- if (name === '') return;
+ // 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);
+ const startNewEntry = useCallback((kind: 'file' | 'folder') => {
+ setError(null);
+ setNewEntry({ kind, value: '' });
+ }, []);
+ 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;
}
- const target = joinPath(cwd, name);
try {
- if (kind === 'dir') await makeDir(target);
- // create-only: the backend atomically refuses (errors.exists) when the name is taken, so a
- // typo can't truncate an existing file.
- else await writeFile(target, '', undefined, true);
+ // 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(kind === 'dir' ? 'apps.fileBrowser.errors.createFolderFailed' : 'apps.fileBrowser.errors.saveFailed')));
+ setError(
+ fileBrowserErrorMessage(e, t, t(session.kind === 'folder' ? 'apps.fileBrowser.errors.createFolderFailed' : 'apps.fileBrowser.errors.saveFailed')),
+ );
}
- };
+ }, [cwd, navigate, 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
+ // hidden, so fall back to the inline create row so a file can still be made.
+ const onNewFile = useCallback(() => {
+ if (!cwd) return;
+ if (window.matchMedia('(min-width: 768px)').matches) {
+ wm.openApp('editor', { title: t('apps.fileBrowser.newFile'), params: { newFileDir: cwd } });
+ } else {
+ startNewEntry('file');
+ }
+ }, [cwd, wm, t, startNewEntry]);
const projectFavs = useMemo(
() => (projects || []).filter((p) => !!p.folder_path).map((p) => ({ label: p.display_name, path: p.folder_path as string })),
@@ -213,15 +272,25 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
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) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1));
- }, [listing, query]);
+ return [...filtered].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);
+ let r = 0;
+ if (sort.col === 'size') r = (a.size ?? 0) - (b.size ?? 0);
+ else if (sort.col === 'modified') r = (a.mtime ?? 0) - (b.mtime ?? 0);
+ else r = a.name.localeCompare(b.name);
+ if (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 (
- <div className={windowed ? 'flex h-full w-full flex-col bg-surface' : 'flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'}>
+ <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)]'}>
{!windowed && (
<div>
<h1 className="text-[18px] font-semibold text-foreground">{t('apps.fileBrowser.label')}</h1>
@@ -258,10 +327,10 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
className="w-28 bg-transparent text-[12px] text-foreground placeholder:text-muted focus:outline-none"
/>
</label>
- <Button type="button" size="sm" variant="brand" className="h-7 shrink-0 gap-1.5 px-2.5 text-[12px]" disabled={!cwd} onClick={() => void createNamed('file')}>
+ <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} onClick={() => void createNamed('dir')}>
+ <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>
</div>
@@ -293,15 +362,48 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
{/* Listing: Name / Size / Modified */}
<div className="flex min-w-0 flex-1 flex-col">
<div className="flex items-center border-b border-border px-3 py-1.5 text-[10.5px] font-semibold uppercase tracking-wider text-muted">
- <span className="min-w-0 flex-1">{t('apps.fileBrowser.colName')}</span>
- <span className="w-20 shrink-0 text-right">{t('apps.fileBrowser.colSize')}</span>
- <span className="w-36 shrink-0 pl-4">{t('apps.fileBrowser.colModified')}</span>
+ <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" />)}
+ </button>
+ <button type="button" onClick={() => cycleSort('size')} className={clsx('flex w-20 shrink-0 items-center justify-end gap-1 transition hover:text-foreground', sort?.col === 'size' && 'text-foreground')}>
+ {t('apps.fileBrowser.colSize')}
+ {sort?.col === 'size' && (sort.dir === 'asc' ? <ChevronUp className="size-3 shrink-0" /> : <ChevronDown className="size-3 shrink-0" />)}
+ </button>
+ <button type="button" onClick={() => cycleSort('modified')} className={clsx('flex w-36 shrink-0 items-center gap-1 pl-4 transition hover:text-foreground', sort?.col === 'modified' && 'text-foreground')}>
+ {t('apps.fileBrowser.colModified')}
+ {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 && (
<div className="grid place-items-center py-8"><Loader2 className="size-4 animate-spin text-muted" /></div>
)}
- {listing && entries.length === 0 && (
+ {newEntry !== null && (
+ <div className="flex items-center px-3 py-1.5">
+ <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)}
+ placeholder={t(newEntry.kind === 'folder' ? 'apps.fileBrowser.newFolderPlaceholder' : 'apps.fileBrowser.newFilePrompt')}
+ 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>
)}
{entries.map((e) => {
@@ -360,6 +462,33 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</span>
</div>
</div>
+
+ {/* In-window image preview overlay (Finder-style quick look). In-window, not a portaled
+ Dialog, so it stays inside the window's dark data-theme scope and bounds. */}
+ {preview && (
+ <div className="absolute inset-0 z-20 flex flex-col bg-surface">
+ <div className="flex items-center gap-2 border-b border-border bg-surface-2/60 px-3 py-2">
+ <ImageIcon className="size-4 shrink-0 text-muted" />
+ <span className="min-w-0 flex-1 truncate text-[12.5px] font-medium text-foreground">{preview.name}</span>
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-mint"
+ aria-label={t('apps.fileBrowser.download')}
+ onClick={() => downloadFile(preview.path)}
+ >
+ <Download className="size-3.5" />
+ </Button>
+ <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0 text-muted" aria-label={t('common.close')} onClick={() => setPreview(null)}>
+ <X className="size-4" strokeWidth={2.5} />
+ </Button>
+ </div>
+ <div className="min-h-0 flex-1">
+ <FilePreview kind="image" src={contentUrl(preview.path)} name={preview.name} />
+ </div>
+ </div>
+ )}
</div>
);
};
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index 4306c6159..75bb84922 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -1,12 +1,13 @@
import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react';
-import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FolderOpen, GitBranch, Search, Settings, X } from 'lucide-react';
+import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FolderOpen, GitBranch, Image as ImageIcon, Search, Settings, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
import { useWindowCloseGuard, useWindowManager } from '../../context/WindowManagerContext';
-import { downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
-import { isEditableFile } from '../../lib/filePreview';
+import { contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
+import { imageKind, isEditableFile, isRenderOnlyImage } from '../../lib/filePreview';
import { FileTree } from './FileTree';
+import { FilePreview } from './FilePreview';
import { FilePicker, type FilePickerMode } from './FilePicker';
import { EditorSearchView } from './EditorSearchView';
@@ -17,7 +18,9 @@ const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ defa
// clobbering newer on-disk content. `path` is null for an unsaved "untitled" buffer (a VS
// Code-style new file): it lives only in memory until the first save picks a location. Tabs are
// keyed by a synthetic `id` (not the path) so an untitled tab survives becoming a saved file.
-type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number };
+// `kind` defaults to 'edit' (a Monaco buffer). An 'image' tab renders a read-only FilePreview
+// instead — a raster image has no editable text form, so it's viewed, not edited.
+type Tab = { id: string; path: string | null; name: string; mtime: number | null; reload?: number; kind?: 'edit' | 'image' };
// A pending file dialog, rendered as the in-window FilePicker overlay.
type PickerState = {
@@ -92,9 +95,12 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
// repeat jump to the same spot re-fire even when the tab is already open.
const [reveal, setReveal] = useState<{ tabId: string; line: number; column: number; endColumn: number; nonce: number } | null>(null);
const [searchFocus, setSearchFocus] = useState(0);
+ // Bumped after a save-as writes a new file, so the explorer tree re-lists that folder.
+ const [treeRefresh, setTreeRefresh] = useState<{ path: string; nonce: number } | null>(null);
const tabSeq = useRef(0);
const untitledSeq = useRef(0);
const revealSeq = useRef(0);
+ const treeRefreshSeq = useRef(0);
// Latest tabs + dirty for async callbacks (reloadTabs) so a reload landing after an in-flight
// replace never acts on a stale snapshot and clobbers a buffer the user just edited.
const dirtyRef = useRef(dirty);
@@ -128,6 +134,20 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
[],
);
+ // Open (or focus) a raster image as a read-only preview tab (no Monaco). Dedups by path inside the
+ // updater so a fast double-open can't append two tabs.
+ const openImage = useCallback((path: string, name: string) => {
+ setRoot((r) => r ?? parentDir(path));
+ setTabs((ts) => {
+ const existing = ts.find((x) => x.path === path);
+ const id = existing ? existing.id : `t${++tabSeq.current}`;
+ setActive(id);
+ setCursor(null);
+ if (existing) return ts;
+ return [...ts, { id, path, name, mtime: null, kind: 'image' }];
+ });
+ }, []);
+
// Open (or focus) a file at a search match and select the range in Monaco. Fetch fresh metadata
// for the save baseline + re-validation, mirroring the explorer's open path.
const onJump = useCallback(
@@ -150,6 +170,12 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
// await so the click's user activation survives (Safari/iOS would block the popup otherwise).
const onTreeOpen = useCallback(
async (path: string, entry: FsEntry) => {
+ // A raster image previews in an image tab (no Monaco); SVG/Markdown stay editable (with a
+ // preview toggle inside the pane).
+ if (isRenderOnlyImage(entry)) {
+ openImage(path, entry.name);
+ return;
+ }
if (!isEditableFile(entry)) {
downloadFile(path);
return;
@@ -167,7 +193,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
openFile(path, entry.name, entry.mtime);
}
},
- [openFile],
+ [openFile, openImage],
);
// After a cross-file replace/undo rewrites files on disk, reload any open, non-dirty tab for a
@@ -193,15 +219,59 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
setTabs((ts) => ts.map((tb) => (byId.has(tb.id) && !dirtyRef.current[tb.id] ? { ...tb, mtime: byId.get(tb.id) ?? tb.mtime, reload: (tb.reload ?? 0) + 1 } : tb)));
}, []);
- // Open the launch file (from the File Browser) once on mount.
+ // A tree rename moved a file (or a folder containing open files) on disk. Repoint any matching tab
+ // — the renamed file itself (path + display name) and every descendant (path prefix only) — so
+ // edits keep saving against the live path instead of failing as a deleted-file conflict.
+ const onEntryRenamed = useCallback((from: string, to: string) => {
+ setTabs((ts) =>
+ ts.map((tb) => {
+ if (!tb.path) return tb;
+ if (tb.path === from) return { ...tb, path: to, name: to.split(/[\\/]/).filter(Boolean).pop() || tb.name };
+ // Descendant of a renamed folder — reprefix the path, keeping its own name. Match either
+ // separator so Windows child paths (C:\dir\file.txt) reconcile too.
+ if (tb.path.startsWith(`${from}/`) || tb.path.startsWith(`${from}\\`)) {
+ return { ...tb, path: `${to}${tb.path.slice(from.length)}` };
+ }
+ return tb;
+ }),
+ );
+ }, []);
+
+ // A tree delete removed a file (or a folder containing open files). Auto-close only the CLEAN
+ // matching tabs (the file itself + any descendant) — a dirty tab keeps its unsaved buffer rather
+ // than be silently dropped; its stale-path save then fails loudly, prompting a save-as.
+ const onEntryDeleted = useCallback((deleted: string) => {
+ setTabs((ts) => {
+ const isGone = (p: string | null) => !!p && (p === deleted || p.startsWith(`${deleted}/`) || p.startsWith(`${deleted}\\`));
+ const closeIds = new Set(ts.filter((tb) => isGone(tb.path) && !dirtyRef.current[tb.id]).map((tb) => tb.id));
+ if (!closeIds.size) return ts;
+ const rest = ts.filter((tb) => !closeIds.has(tb.id));
+ setActive((cur) => (cur && closeIds.has(cur) ? (rest.length ? rest[rest.length - 1].id : null) : cur));
+ setDirty((d) => {
+ const n = { ...d };
+ closeIds.forEach((id) => delete n[id]);
+ return n;
+ });
+ return rest;
+ });
+ }, []);
+
+ // Open the launch file (from the File Browser) once on mount, OR — when the File Browser's
+ // "New File" launched us with a target dir — root the explorer there and start a fresh untitled
+ // buffer (its first save lands in that dir).
useEffect(() => {
const p = typeof params?.path === 'string' ? params.path : null;
- if (p)
- openFile(
- p,
- (typeof params?.filename === 'string' ? params.filename : p.split('/').filter(Boolean).pop()) || p,
- typeof params?.mtime === 'number' ? params.mtime : null,
- );
+ if (p) {
+ const name = (typeof params?.filename === 'string' ? params.filename : p.split('/').filter(Boolean).pop()) || p;
+ if (imageKind(name) === 'raster') openImage(p, name);
+ else openFile(p, name, typeof params?.mtime === 'number' ? params.mtime : null);
+ return;
+ }
+ const dir = typeof params?.newFileDir === 'string' ? params.newFileDir : null;
+ if (dir) {
+ setRoot(dir);
+ newFile();
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -266,6 +336,8 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
const result = await writeFile(full, text, undefined, true);
setTabs((ts) => ts.map((x) => (x.id === tabId ? { ...x, path: full, name: name as string, mtime: result.mtime } : x)));
setRoot((r) => r ?? path);
+ // Re-list the folder the new file landed in, so it appears in the explorer tree.
+ setTreeRefresh({ path, nonce: ++treeRefreshSeq.current });
setPicker(null);
},
});
@@ -289,6 +361,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
if (k !== 'f') return;
e.preventDefault();
setView('search');
+ setExplorerCollapsed(false); // ⇧⌘F must reveal the panel even when it's collapsed
setSearchFocus((n) => n + 1);
return;
}
@@ -301,8 +374,39 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
return () => window.removeEventListener('keydown', onKey, true);
}, [windowId, openFolder, newFile, picker, wm.focusedId]);
+ // The left panel collapses (toggled by the active activity-bar icon) and resizes (drag its right
+ // border). Width persists for the window's lifetime (state, not navigation).
+ const [explorerCollapsed, setExplorerCollapsed] = useState(false);
+ const [explorerWidth, setExplorerWidth] = useState(240);
+ // Holds the in-flight drag's teardown so an unmount mid-drag (window closed while dragging) can
+ // still remove the window listeners and restore the body cursor / user-select.
+ const resizeTeardown = useRef<(() => void) | null>(null);
+ const startResize = useCallback(
+ (e: React.MouseEvent) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startW = explorerWidth;
+ const onMove = (ev: MouseEvent) => setExplorerWidth(Math.max(168, Math.min(520, startW + ev.clientX - startX)));
+ const teardown = () => {
+ window.removeEventListener('mousemove', onMove);
+ window.removeEventListener('mouseup', teardown);
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ resizeTeardown.current = null;
+ };
+ resizeTeardown.current = teardown;
+ window.addEventListener('mousemove', onMove);
+ window.addEventListener('mouseup', teardown);
+ document.body.style.cursor = 'col-resize';
+ document.body.style.userSelect = 'none';
+ },
+ [explorerWidth],
+ );
+ useEffect(() => () => resizeTeardown.current?.(), []);
+
const showWelcome = root == null && tabs.length === 0;
- const activeName = tabs.find((x) => x.id === active)?.name;
+ const activeTab = tabs.find((x) => x.id === active);
+ const activeName = activeTab?.name;
return (
<div className="relative flex h-full min-h-0 w-full flex-col bg-surface">
@@ -318,15 +422,25 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
key={key}
type="button"
onClick={() => {
- setView(key);
- if (key === 'search') setSearchFocus((n) => n + 1);
+ // Clicking the already-active view's icon toggles the panel collapsed (VS Code);
+ // switching to the other view always re-opens the panel.
+ if (view === key) {
+ setExplorerCollapsed((c) => !c);
+ } else {
+ setView(key);
+ setExplorerCollapsed(false);
+ if (key === 'search') setSearchFocus((n) => n + 1);
+ }
}}
aria-label={label}
- aria-pressed={view === key}
+ aria-pressed={view === key && !explorerCollapsed}
title={label}
- className={clsx('relative grid h-6 w-12 place-items-center transition', view === key ? 'text-foreground' : 'text-muted hover:text-foreground')}
+ className={clsx(
+ 'relative grid h-6 w-12 place-items-center transition',
+ view === key && !explorerCollapsed ? 'text-foreground' : 'text-muted hover:text-foreground',
+ )}
>
- {view === key && <span className="absolute left-0 top-0 h-full w-0.5 bg-cyan" />}
+ {view === key && !explorerCollapsed && <span className="absolute left-0 top-0 h-full w-0.5 bg-cyan" />}
<Icon className="size-5" />
</button>
))}
@@ -337,9 +451,11 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
<Settings className="size-5 text-muted" />
</div>
- {/* Left panel — Explorer (Files view) or the cross-file Search view. Explorer is ALWAYS
- present in Files view (design w0qoC keeps it in the welcome state). */}
- <div className={clsx('flex shrink-0 flex-col overflow-hidden border-r border-border bg-surface-2', view === 'search' ? 'w-[300px]' : 'w-[220px]')}>
+ {/* Left panel — Explorer (Files view) or the cross-file Search view. Collapses via the
+ active activity-bar icon; drag its right border to resize. Explorer is ALWAYS present in
+ Files view (design w0qoC keeps it in the welcome state). */}
+ {!explorerCollapsed && (
+ <div className="relative flex shrink-0 flex-col overflow-hidden border-r border-border bg-surface-2" style={{ width: explorerWidth }}>
{view === 'search' ? (
<EditorSearchView root={root} focusNonce={searchFocus} onOpenFolder={openFolder} onJump={onJump} onFilesChanged={reloadTabs} />
) : (
@@ -379,12 +495,27 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
</div>
) : (
<div className="min-h-0 flex-1 overflow-y-auto px-1 pb-2">
- <FileTree rootPath={root} rootName={root.split('/').filter(Boolean).pop() || root} activePath={tabs.find((x) => x.id === active)?.path ?? null} onOpenFile={onTreeOpen} />
+ <FileTree
+ rootPath={root}
+ rootName={root.split('/').filter(Boolean).pop() || root}
+ activePath={tabs.find((x) => x.id === active)?.path ?? null}
+ onOpenFile={onTreeOpen}
+ refreshSignal={treeRefresh}
+ onEntryRenamed={onEntryRenamed}
+ onEntryDeleted={onEntryDeleted}
+ />
</div>
)}
</>
)}
+ {/* Drag handle on the right border to resize the panel (VS Code). */}
+ <div
+ onMouseDown={startResize}
+ className="absolute right-0 top-0 z-10 h-full w-1 cursor-col-resize bg-transparent transition hover:bg-cyan/40"
+ aria-hidden
+ />
</div>
+ )}
{/* Main area: welcome (nothing open) · tabs + Monaco (a file or untitled buffer open) ·
select-a-file hint (folder open, no tab). */}
@@ -411,7 +542,7 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
}}
className="flex items-center gap-1.5"
>
- <CodeXml className="size-3.5 text-cyan" />
+ {tab.kind === 'image' ? <ImageIcon className="size-3.5 text-violet" /> : <CodeXml className="size-3.5 text-cyan" />}
{tab.name}
{dirty[tab.id] && <span className="size-1.5 rounded-full bg-mint" />}
</button>
@@ -434,19 +565,24 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
) : (
tabs.map((tab) => (
<div key={tab.id} className={clsx('absolute inset-0', active === tab.id ? 'block' : 'hidden')}>
- <Suspense fallback={<div className="grid h-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}>
- <FileEditorPane
- path={tab.path}
- filename={tab.name}
- mtime={tab.mtime}
- chromeless
- onDirtyChange={(d) => setDirty((prev) => (prev[tab.id] === d ? prev : { ...prev, [tab.id]: d }))}
- onCursor={active === tab.id ? (line, col) => setCursor({ line, col }) : undefined}
- onSaveAs={(textValue) => saveAs(tab.id, textValue)}
- reveal={reveal?.tabId === tab.id ? { line: reveal.line, column: reveal.column, endColumn: reveal.endColumn, nonce: reveal.nonce } : null}
- reloadNonce={tab.reload}
- />
- </Suspense>
+ {tab.kind === 'image' && tab.path ? (
+ <FilePreview kind="image" src={contentUrl(tab.path)} name={tab.name} />
+ ) : (
+ <Suspense fallback={<div className="grid h-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}>
+ <FileEditorPane
+ path={tab.path}
+ filename={tab.name}
+ mtime={tab.mtime}
+ chromeless
+ onDirtyChange={(d) => setDirty((prev) => (prev[tab.id] === d ? prev : { ...prev, [tab.id]: d }))}
+ onCursor={active === tab.id ? (line, col) => setCursor({ line, col }) : undefined}
+ onSaveAs={(textValue) => saveAs(tab.id, textValue)}
+ reveal={reveal?.tabId === tab.id ? { line: reveal.line, column: reveal.column, endColumn: reveal.endColumn, nonce: reveal.nonce } : null}
+ reloadNonce={tab.reload}
+ saveHotkey={active === tab.id && wm.focusedId === windowId}
+ />
+ </Suspense>
+ )}
</div>
))
)}
@@ -461,7 +597,9 @@ export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, un
hardcoded "master · 0 ⚠ 0" would be misleading, so those are omitted until wired. The
right side (cursor / indentation / language) is real. */}
<div className="flex items-center gap-3.5 bg-cyan px-3.5 py-1 font-mono text-[10.5px] font-semibold text-[#06222B]">
- {active ? (
+ {active && activeTab?.kind === 'image' ? (
+ <span className="ml-auto truncate">{t('apps.editor.imagePreview')}</span>
+ ) : active ? (
<>
<span className="ml-auto tabular-nums">{t('apps.editor.lineCol', { line: cursor?.line ?? 1, col: cursor?.col ?? 1 })}</span>
<span>{t('apps.editor.spaces', { n: 2 })}</span>
diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsx
index 88d8348c8..6dedfa37a 100644
--- a/ui/src/components/workbench/FileEditorPane.tsx
+++ b/ui/src/components/workbench/FileEditorPane.tsx
@@ -1,12 +1,14 @@
-import { Suspense, lazy, useEffect, useId, useState } from 'react';
+import { Suspense, lazy, useEffect, useId, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Loader2, PanelRightOpen, Save } from 'lucide-react';
+import { Code2, Eye, Loader2, PanelRightOpen, Save } from 'lucide-react';
import clsx from 'clsx';
import { useTheme } from '../../context/ThemeContext';
import { useWindowCloseGuard } from '../../context/WindowManagerContext';
import { Button } from '../ui/button';
import { fileBrowserErrorMessage, readText, writeFile } from '../../lib/filesApi';
+import { imageKind, previewKind } from '../../lib/filePreview';
+import { FilePreview } from './FilePreview';
// Monaco (the VS Code kernel) is heavy; lazy-load it so it stays out of the main
// bundle and only loads when a file is actually opened for editing.
@@ -103,7 +105,13 @@ export const FileEditorPane: React.FC<{
reveal?: { line: number; column: number; endColumn: number; nonce: number } | null;
/** Bumped to force a re-read from disk (e.g. after a cross-file replace rewrote this file). */
reloadNonce?: number;
-}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onDirtyChange, chromeless = false, onCursor, onSaveAs, reveal, reloadNonce }) => {
+ /**
+ * True when this pane is the focused window's active tab. While previewing Markdown/SVG, Monaco
+ * (the usual ⌘S owner) is unmounted and the IDE has no Save button, so the pane registers a
+ * window-level ⌘S itself — scoped by this flag so only the foreground tab saves.
+ */
+ saveHotkey?: boolean;
+}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onDirtyChange, chromeless = false, onCursor, onSaveAs, reveal, reloadNonce, saveHotkey = false }) => {
const { t } = useTranslation();
const { resolvedTheme } = useTheme();
const [text, setText] = useState<string | null>(null);
@@ -112,8 +120,40 @@ export const FileEditorPane: React.FC<{
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [error, setError] = useState<string | null>(null);
+ // Markdown / SVG can be previewed (rendered) as well as edited, VS-Code-style. `mode` toggles the
+ // body between the Monaco source and the rendered FilePreview, using the LIVE buffer so the
+ // preview reflects unsaved edits.
+ const [mode, setMode] = useState<'source' | 'preview'>('source');
+ const previewable: 'markdown' | 'svg' | null = useMemo(() => {
+ if (previewKind(filename) === 'markdown') return 'markdown';
+ if (imageKind(filename) === 'svg') return 'svg';
+ return null;
+ }, [filename]);
+ // A new file may not be previewable — never strand the body in a preview mode it can't render.
+ useEffect(() => {
+ if (!previewable) setMode('source');
+ }, [previewable]);
+ // While previewing, Monaco (the usual ⌘S owner) is unmounted, so the foreground tab registers a
+ // window-level ⌘S. `saveRef` holds the latest save() so the listener never saves a stale buffer.
+ const saveRef = useRef<() => void>(() => {});
+ useEffect(() => {
+ if (!(saveHotkey && previewable && mode === 'preview')) return;
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && !e.altKey && !e.shiftKey && e.key.toLowerCase() === 's') {
+ e.preventDefault();
+ void saveRef.current();
+ }
+ };
+ window.addEventListener('keydown', onKey, true);
+ return () => window.removeEventListener('keydown', onKey, true);
+ }, [saveHotkey, previewable, mode]);
+ // Tracks the path the last read targeted, so a rename (path changing from one real file to another)
+ // can be told apart from an initial open or a forced reload.
+ const prevPathRef = useRef<string | null>(path);
useEffect(() => {
+ const prev = prevPathRef.current;
+ prevPathRef.current = path;
let cancelled = false;
setError(null);
setSavedMtime(mtime);
@@ -125,6 +165,16 @@ export const FileEditorPane: React.FC<{
setLoading(false);
return;
}
+ // A tab's path only changes from one real file to another when the explorer renamed it (this tab
+ // was repointed) — the bytes on disk are unchanged. Re-reading would silently replace an unsaved
+ // buffer with the last-saved contents, so adopt the new save target WITHOUT reloading — BUT only
+ // once a buffer actually exists to preserve. If the rename lands before the initial read finished
+ // (text still null), fall through and read the new path so the pane doesn't go blank. (Initial
+ // open and reloadNonce-forced reloads — where the path is unchanged — also read below.)
+ if (prev !== null && prev !== path && text !== null) {
+ setLoading(false);
+ return;
+ }
setLoading(true);
setText(null);
readText(path)
@@ -185,6 +235,7 @@ export const FileEditorPane: React.FC<{
setSaving(false);
}
}
+ saveRef.current = save;
return (
<div className="flex h-full min-h-0 flex-col">
@@ -230,10 +281,40 @@ export const FileEditorPane: React.FC<{
</div>
)}
+ {/* Source ⇄ Preview toggle — only for renderable text (Markdown / SVG). Renders the LIVE
+ buffer, so the preview tracks unsaved edits. */}
+ {previewable && !loading && text !== null && (
+ <div className="flex items-center justify-end border-b border-border bg-surface-2/40 px-2 py-1">
+ <div className="inline-flex overflow-hidden rounded-md border border-border">
+ {([
+ { key: 'source' as const, Icon: Code2, label: t('apps.editor.source') },
+ { key: 'preview' as const, Icon: Eye, label: t('apps.editor.preview') },
+ ]).map(({ key, Icon, label }) => (
+ <button
+ key={key}
+ type="button"
+ onClick={() => setMode(key)}
+ aria-pressed={mode === key}
+ className={clsx(
+ 'flex items-center gap-1 px-2 py-0.5 text-[11px] font-medium transition',
+ mode === key ? 'bg-cyan-soft text-foreground' : 'text-muted hover:bg-foreground/[0.05] hover:text-foreground',
+ )}
+ >
+ <Icon className="size-3" /> {label}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
<div className={clsx('min-h-0 flex-1', loading && 'grid place-items-center')}>
{loading ? (
<Loader2 className="size-5 animate-spin text-muted" />
- ) : text === null ? null : (
+ ) : text === null ? null : mode === 'preview' && previewable === 'markdown' ? (
+ <FilePreview kind="markdown" content={text} />
+ ) : mode === 'preview' && previewable === 'svg' ? (
+ <FilePreview kind="image" src={`data:image/svg+xml;charset=utf-8,${encodeURIComponent(text)}`} name={filename} />
+ ) : (
<Suspense fallback={<div className="p-4 text-[12px] text-muted">{t('common.loading')}</div>}>
<MonacoEditor
value={text}
diff --git a/ui/src/components/workbench/FilePreview.tsx b/ui/src/components/workbench/FilePreview.tsx
new file mode 100644
index 000000000..4e750ef17
--- /dev/null
+++ b/ui/src/components/workbench/FilePreview.tsx
@@ -0,0 +1,66 @@
+import { useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import { Markdown } from '../ui/markdown';
+
+// Reusable RENDERED (non-editor) file preview for the windowed apps. Pure/presentational: the
+// caller supplies the image `src` or the markdown `content`, so the same component serves an
+// on-disk image (File Browser overlay, editor image tab — src = contentUrl(path)) and a LIVE buffer
+// the editor is editing (SVG preview via a data: URL, Markdown via the buffer text). Code/JSON/CSV
+// stay in Monaco / the chat FileViewer; this only covers what the editor can't show as text.
+type FilePreviewProps =
+ | { kind: 'image'; src: string; name?: string; className?: string }
+ | { kind: 'markdown'; content: string; className?: string };
+
+export const FilePreview: React.FC<FilePreviewProps> = (props) => {
+ if (props.kind === 'markdown') {
+ return (
+ <div className={clsx('h-full min-h-0 overflow-auto bg-surface', props.className)}>
+ <Markdown content={props.content} interactive={false} className="vr-fileview-md mx-auto max-w-3xl px-6 py-5" />
+ </div>
+ );
+ }
+ return <ImagePreview src={props.src} name={props.name} className={props.className} />;
+};
+
+// Fit-to-container by default; click toggles 1:1 actual size (zoom-in / zoom-out cursor), with the
+// container scrolling when the image overflows. The dark checker-free backdrop keeps transparent
+// PNGs/SVGs legible inside the dark-locked windows.
+const ImagePreview: React.FC<{ src: string; name?: string; className?: string }> = ({ src, name, className }) => {
+ const { t } = useTranslation();
+ const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading');
+ const [actual, setActual] = useState(false);
+ // Reset when the source changes — the live SVG preview re-points `src` on every keystroke, so a
+ // transient error (a momentarily-invalid buffer) must clear once the buffer becomes valid again.
+ useEffect(() => {
+ setStatus('loading');
+ setActual(false);
+ }, [src]);
+
+ if (status === 'error') {
+ return (
+ <div className={clsx('grid h-full min-h-0 place-items-center bg-[#0c0c0f] p-4 text-[12.5px] text-muted', className)}>
+ {t('apps.fileBrowser.previewFailed')}
+ </div>
+ );
+ }
+ return (
+ <div className={clsx('grid h-full min-h-0 place-items-center overflow-auto bg-[#0c0c0f] p-4', className)}>
+ {status === 'loading' && <div className="col-start-1 row-start-1 text-[12px] text-muted">{t('common.loading')}</div>}
+ <img
+ src={src}
+ alt={name || ''}
+ onLoad={() => setStatus('ready')}
+ onError={() => setStatus('error')}
+ onClick={() => setActual((a) => !a)}
+ draggable={false}
+ className={clsx(
+ 'col-start-1 row-start-1 select-none',
+ actual ? 'max-w-none cursor-zoom-out' : 'max-h-full max-w-full cursor-zoom-in object-contain',
+ status !== 'ready' && 'opacity-0',
+ )}
+ />
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/FileTree.tsx b/ui/src/components/workbench/FileTree.tsx
index 1f94670b2..ec60e4fdb 100644
--- a/ui/src/components/workbench/FileTree.tsx
+++ b/ui/src/components/workbench/FileTree.tsx
@@ -1,9 +1,34 @@
-import { useCallback, useEffect, useState } from 'react';
+import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { Braces, ChevronDown, ChevronRight, FileCode2, FileText, File as FileIcon, Hash, Image as ImageIcon, Loader2 } from 'lucide-react';
+import {
+ Braces,
+ ChevronDown,
+ ChevronRight,
+ FileCode2,
+ FilePlus,
+ FileText,
+ File as FileIcon,
+ FolderPlus,
+ Hash,
+ Image as ImageIcon,
+ Loader2,
+ Pencil,
+ Trash2,
+} from 'lucide-react';
import clsx from 'clsx';
-import { fileBrowserErrorMessage, joinPath, listDir, type FsEntry } from '../../lib/filesApi';
+import {
+ deletePath,
+ fileBrowserErrorMessage,
+ isPlainEntryName,
+ joinPath,
+ listDir,
+ makeDir,
+ parentDir,
+ renamePath,
+ writeFile,
+ type FsEntry,
+} from '../../lib/filesApi';
// Icon + accent per file extension (matches the explorer in design dnYPx).
const EXT: Record<string, { Icon: typeof FileIcon; color: string }> = {
@@ -28,10 +53,79 @@ function sortEntries(entries: FsEntry[]): FsEntry[] {
return [...entries].sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1));
}
-const Row: React.FC<{ depth: number; onClick: () => void; active?: boolean; children: React.ReactNode }> = ({ depth, onClick, active, children }) => (
+// One inline edit at a time across the whole tree: creating a new entry inside `dir`, or renaming
+// `target` inside `dir`.
+type EditSession = { dir: string; mode: 'new-file' | 'new-folder' | 'rename'; target?: string };
+// A cursor-positioned context menu. `entry` is null for the blank/root background (offers New only).
+type MenuState = { x: number; y: number; dir: string; entry: FsEntry | null };
+
+type TreeCtx = {
+ activePath: string | null;
+ showHidden: boolean;
+ onOpenFile: (path: string, entry: FsEntry) => void;
+ versionOf: (path: string) => number;
+ edit: EditSession | null;
+ startEdit: (s: EditSession) => void;
+ cancelEdit: () => void;
+ commitEdit: (value: string) => void;
+ openMenu: (ev: React.MouseEvent, dir: string, entry: FsEntry | null) => void;
+};
+
+const Ctx = createContext<TreeCtx | null>(null);
+const useTree = (): TreeCtx => {
+ const c = useContext(Ctx);
+ if (!c) throw new Error('FileTree context missing');
+ 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;
+ onContextMenu?: (e: React.MouseEvent) => void;
+ active?: boolean;
+ children: React.ReactNode;
+}> = ({ depth, onClick, onContextMenu, active, children }) => (
<button
type="button"
onClick={onClick}
+ onContextMenu={onContextMenu}
style={{ paddingLeft: 8 + depth * 14 }}
className={clsx(
'flex w-full items-center gap-1.5 rounded-md py-1 pr-2 text-left text-[12.5px] transition',
@@ -42,53 +136,117 @@ const Row: React.FC<{ depth: number; onClick: () => void; active?: boolean; chil
</button>
);
-const Dir: React.FC<{ path: string; name: string; depth: number; activePath: string | null; showHidden: boolean; onOpenFile: (path: string, entry: FsEntry) => void }> = ({
- path,
- name,
- depth,
- activePath,
- showHidden,
- onOpenFile,
-}) => {
+const FileRow: React.FC<{ path: string; dir: string; entry: FsEntry; depth: number }> = ({ path, dir, entry, depth }) => {
+ const tree = useTree();
+ const { Icon, color } = fileIcon(entry);
+ const renaming = tree.edit?.mode === 'rename' && tree.edit.target === entry.name && tree.edit.dir === dir;
+ if (renaming) {
+ return (
+ <div style={{ paddingLeft: 8 + depth * 14 }} className="flex items-center gap-1.5 py-1 pr-2">
+ <Icon className="size-3.5 shrink-0" style={{ color }} />
+ <InlineNameInput initial={entry.name} onCommit={tree.commitEdit} onCancel={tree.cancelEdit} />
+ </div>
+ );
+ }
+ return (
+ <Row depth={depth} active={tree.activePath === path} onClick={() => tree.onOpenFile(path, entry)} onContextMenu={(e) => tree.openMenu(e, dir, entry)}>
+ <Icon className="size-3.5 shrink-0" style={{ color }} />
+ <span className="truncate">{entry.name}</span>
+ </Row>
+ );
+};
+
+const Dir: React.FC<{ path: string; name: string; depth: number }> = ({ path, name, depth }) => {
const { t } = useTranslation();
+ const tree = useTree();
const [open, setOpen] = useState(depth === 0);
const [entries, setEntries] = useState<FsEntry[] | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
+ const version = tree.versionOf(path);
+ // `menu.dir` is always the PARENT of the clicked entry (consistent with file rows), so new/rename/
+ // delete resolve the same way for files and folders. The ROOT row (depth 0) is special: it has no
+ // meaningful parent here and must not be renamed/deleted, so it opens the menu as blank space
+ // (entry=null, dir=path) — offering only New File/Folder INSIDE the root.
+ const isRoot = depth === 0;
+ const parent = parentDir(path);
+ const renamingSelf = !isRoot && tree.edit?.mode === 'rename' && tree.edit.dir === parent && tree.edit.target === name;
+ // Drop out-of-order responses: a post-mutation reload (bump) can race an in-flight pre-mutation
+ // listDir for the same folder, and the stale one landing last would hide a just-created item or
+ // resurrect a renamed/deleted row. Only the latest request's result is applied.
+ const loadSeq = useRef(0);
const load = useCallback(() => {
+ const seq = ++loadSeq.current;
setLoading(true);
setError(null);
- listDir(path, showHidden)
- .then((r) => setEntries(sortEntries(r.entries)))
+ listDir(path, tree.showHidden)
+ .then((r) => {
+ if (seq === loadSeq.current) setEntries(sortEntries(r.entries));
+ })
.catch((e: unknown) => {
- // Don't render an unlistable folder as an empty one — surface the failure so the user
- // knows entries are hidden by an error (permission/deletion/transient), not absent.
+ if (seq !== loadSeq.current) return;
+ // Don't render an unlistable folder as an empty one — surface the failure so the user knows
+ // entries are hidden by an error (permission/deletion/transient), not absent.
setEntries([]);
setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.listFailed')));
})
- .finally(() => setLoading(false));
- }, [path, showHidden, t]);
+ .finally(() => {
+ if (seq === loadSeq.current) setLoading(false);
+ });
+ }, [path, tree.showHidden, t]);
- useEffect(() => {
- if (open && entries === null) load();
- }, [open, entries, load]);
- // Re-list an open folder when the hidden toggle flips.
+ // Load when opened, when the hidden toggle flips (load identity changes), and when this dir's
+ // version bumps (a mutation re-lists it). Other dirs keep their cached entries.
useEffect(() => {
if (open) load();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [showHidden]);
+ }, [open, load, version]);
+
+ // A new-entry edit targeting this collapsed dir must expand it so the inline input is visible.
+ const wantsExpand = tree.edit?.dir === path && tree.edit.mode !== 'rename';
+ useEffect(() => {
+ if (wantsExpand) setOpen(true);
+ }, [wantsExpand]);
+
+ const newHere = tree.edit?.dir === path && tree.edit.mode !== 'rename';
return (
<div>
- {depth >= 0 && (
- <Row depth={depth} onClick={() => setOpen((o) => !o)}>
- {open ? <ChevronDown className="size-3.5 shrink-0 text-muted" /> : <ChevronRight className="size-3.5 shrink-0 text-muted" />}
- <span className="truncate font-medium text-muted">{name}</span>
- </Row>
- )}
+ {depth >= 0 &&
+ (renamingSelf ? (
+ <div style={{ paddingLeft: 8 + depth * 14 }} className="flex items-center gap-1.5 py-1 pr-2">
+ <ChevronDown className="size-3.5 shrink-0 text-muted" />
+ <InlineNameInput initial={name} onCommit={tree.commitEdit} onCancel={tree.cancelEdit} />
+ </div>
+ ) : (
+ <Row
+ depth={depth}
+ onClick={() => setOpen((o) => !o)}
+ onContextMenu={(e) =>
+ isRoot ? tree.openMenu(e, path, null) : tree.openMenu(e, parent, { name, kind: 'dir', size: null, mtime: null, ext: '' })
+ }
+ >
+ {open ? <ChevronDown className="size-3.5 shrink-0 text-muted" /> : <ChevronRight className="size-3.5 shrink-0 text-muted" />}
+ <span className="truncate font-medium text-muted">{name}</span>
+ </Row>
+ ))}
{open && (
<div>
+ {newHere && (
+ <div style={{ paddingLeft: 8 + (depth + 1) * 14 }} className="flex items-center gap-1.5 py-1 pr-2">
+ {tree.edit?.mode === 'new-folder' ? (
+ <ChevronRight className="size-3.5 shrink-0 text-muted" />
+ ) : (
+ <FileIcon className="size-3.5 shrink-0 text-muted" />
+ )}
+ <InlineNameInput
+ initial=""
+ placeholder={t(tree.edit?.mode === 'new-folder' ? 'apps.fileBrowser.newFolderPlaceholder' : 'apps.fileBrowser.newFilePrompt')}
+ onCommit={tree.commitEdit}
+ onCancel={tree.cancelEdit}
+ />
+ </div>
+ )}
{loading && entries === null && (
<div style={{ paddingLeft: 8 + (depth + 1) * 14 }} className="py-1">
<Loader2 className="size-3.5 animate-spin text-muted" />
@@ -96,8 +254,7 @@ const Dir: React.FC<{ path: string; name: string; depth: number; activePath: str
)}
{error && (
// Clickable so a transient failure (perms fixed, dir recreated, network/auth hiccup) is
- // retryable in place — storing [] on error would otherwise wedge the entries===null
- // load guard and keep showing the stale error until the whole tree remounts.
+ // retryable in place.
<button
type="button"
onClick={load}
@@ -110,18 +267,9 @@ const Dir: React.FC<{ path: string; name: string; depth: number; activePath: str
)}
{entries?.map((e) =>
e.kind === 'dir' ? (
- <Dir key={e.name} path={joinPath(path, e.name)} name={e.name} depth={depth + 1} activePath={activePath} showHidden={showHidden} onOpenFile={onOpenFile} />
+ <Dir key={e.name} path={joinPath(path, e.name)} name={e.name} depth={depth + 1} />
) : (
- (() => {
- const full = joinPath(path, e.name);
- const { Icon, color } = fileIcon(e);
- return (
- <Row key={e.name} depth={depth + 1} active={activePath === full} onClick={() => onOpenFile(full, e)}>
- <Icon className="size-3.5 shrink-0" style={{ color }} />
- <span className="truncate">{e.name}</span>
- </Row>
- );
- })()
+ <FileRow key={e.name} path={joinPath(path, e.name)} dir={path} entry={e} depth={depth + 1} />
),
)}
</div>
@@ -130,16 +278,223 @@ const Dir: React.FC<{ path: string; name: string; depth: number; activePath: str
);
};
-// 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.
-export const FileTree: React.FC<{ rootPath: string; rootName: string; activePath: string | null; showHidden?: boolean; onOpenFile: (path: string, entry: FsEntry) => void }> = ({
- rootPath,
- rootName,
- activePath,
- showHidden = false,
- onOpenFile,
-}) => (
- // key on rootPath so changing the opened folder remounts the tree with fresh state instead of
- // leaving the previous folder's expanded entries behind.
- <Dir key={rootPath} path={rootPath} name={rootName} depth={0} activePath={activePath} showHidden={showHidden} onOpenFile={onOpenFile} />
+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.
+export const FileTree: React.FC<{
+ rootPath: string;
+ rootName: string;
+ activePath: string | null;
+ showHidden?: boolean;
+ onOpenFile: (path: string, entry: FsEntry) => void;
+ /** Bumped by the editor after a save-as creates a file, so the tree re-lists that folder. */
+ refreshSignal?: { path: string; nonce: number } | null;
+ /** A rename happened in the tree (old → new absolute path); the editor repoints any open tab for
+ * that file or its descendants so saves don't fail against the removed path. */
+ onEntryRenamed?: (from: string, to: string) => void;
+ /** An entry was deleted from the tree (absolute path); the editor reconciles tabs for that file or
+ * its descendants. */
+ onEntryDeleted?: (path: string) => void;
+}> = ({ rootPath, rootName, activePath, showHidden = false, onOpenFile, refreshSignal, onEntryRenamed, onEntryDeleted }) => {
+ const { t } = useTranslation();
+ const [versions, setVersions] = useState<Record<string, number>>({});
+ const [edit, setEdit] = useState<EditSession | null>(null);
+ const [menu, setMenu] = useState<MenuState | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const editRef = useRef<EditSession | null>(null);
+ editRef.current = edit;
+
+ const bump = useCallback((path: string) => setVersions((v) => ({ ...v, [path]: (v[path] ?? 0) + 1 })), []);
+ const versionOf = useCallback((path: string) => versions[path] ?? 0, [versions]);
+
+ // External refresh (editor save-as created a file in `path`).
+ useEffect(() => {
+ if (refreshSignal?.path) bump(refreshSignal.path);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [refreshSignal?.nonce]);
+
+ const startEdit = useCallback((s: EditSession) => {
+ setError(null);
+ setEdit(s);
+ }, []);
+ const cancelEdit = useCallback(() => setEdit(null), []);
+
+ const commitEdit = useCallback(
+ async (value: string) => {
+ const session = editRef.current;
+ if (!session) return;
+ const name = value.trim();
+ if (name === '') {
+ setEdit(null);
+ return;
+ }
+ if (!isPlainEntryName(name)) {
+ setError(t('apps.fileBrowser.errors.invalid_name'));
+ return;
+ }
+ try {
+ if (session.mode === 'rename') {
+ if (name === session.target) {
+ setEdit(null);
+ return;
+ }
+ const from = joinPath(session.dir, session.target as string);
+ const res = await renamePath(from, name);
+ onEntryRenamed?.(from, res.path);
+ } else if (session.mode === 'new-folder') {
+ await makeDir(joinPath(session.dir, name));
+ } else {
+ // create-only: the backend atomically refuses a name clash, so this can't clobber a file.
+ await writeFile(joinPath(session.dir, name), '', undefined, true);
+ }
+ setEdit(null);
+ setError(null);
+ bump(session.dir);
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.saveFailed')));
+ }
+ },
+ [t, bump, onEntryRenamed],
+ );
+
+ const openMenu = useCallback((ev: React.MouseEvent, dir: string, entry: FsEntry | null) => {
+ ev.preventDefault();
+ ev.stopPropagation();
+ setMenu({ x: ev.clientX, y: ev.clientY, dir, entry });
+ }, []);
+ 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);
+ 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],
+ );
+
+ const ctx = useMemo<TreeCtx>(
+ () => ({ activePath, showHidden, onOpenFile, versionOf, edit, startEdit, cancelEdit, commitEdit, openMenu }),
+ [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;
+ 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}>
+ {/* The whole tree area is a context-menu target: right-clicking empty space offers New in the
+ root folder. */}
+ <div onContextMenu={(e) => openMenu(e, rootPath, null)}>
+ {error && (
+ <div className="mx-1 mb-1 flex items-start gap-1 rounded border border-destructive/40 bg-destructive/[0.06] px-2 py-1 text-[11px] text-destructive">
+ <span className="min-w-0 flex-1">{error}</span>
+ <button type="button" onClick={() => setError(null)} className="shrink-0 font-bold">
+ ×
+ </button>
+ </div>
+ )}
+ <Dir key={rootPath} path={rootPath} name={rootName} depth={0} />
+ </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')}
+ onClick={() => {
+ const e = menu.entry as FsEntry;
+ onOpenFile(joinPath(menu.dir, e.name), e);
+ 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>
+ </>
+ )}
+ </Ctx.Provider>
+ );
+};
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 12e2c7ea3..396a48096 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -620,6 +620,9 @@
"lineCol": "Ln {{line}}, Col {{col}}",
"spaces": "Spaces: {{n}}",
"plainText": "Plain Text",
+ "imagePreview": "Image preview",
+ "source": "Source",
+ "preview": "Preview",
"empty": "No file open",
"emptyHint": "Open a file from Files to edit it here.",
"openInWindow": "Open in editor window",
@@ -682,6 +685,12 @@
"newFolderPrompt": "New folder name",
"newFile": "New File",
"newFilePrompt": "New file name",
+ "newFolderPlaceholder": "Folder name",
+ "open": "Open",
+ "rename": "Rename",
+ "delete": "Delete",
+ "confirmDelete": "Delete \"{{name}}\"? This can't be undone.",
+ "previewFailed": "Couldn't load this image.",
"searchPlaceholder": "Search",
"colName": "Name",
"colSize": "Size",
@@ -713,7 +722,8 @@
"openFailed": "Couldn't open this item.",
"createFolderFailed": "Couldn't create the folder.",
"loadFailed": "Couldn't load this file.",
- "saveFailed": "Couldn't save this file."
+ "saveFailed": "Couldn't save this file.",
+ "deleteFailed": "Couldn't delete this item."
}
},
"terminal": {
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index d2a18d5b0..1dc44e8c9 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -620,6 +620,9 @@
"lineCol": "行 {{line}},列 {{col}}",
"spaces": "空格:{{n}}",
"plainText": "纯文本",
+ "imagePreview": "图片预览",
+ "source": "源码",
+ "preview": "预览",
"empty": "未打开文件",
"emptyHint": "从「文件」中打开一个文件,在这里编辑。",
"openInWindow": "在编辑器窗口中打开",
@@ -682,6 +685,12 @@
"newFolderPrompt": "新文件夹名称",
"newFile": "新建文件",
"newFilePrompt": "新文件名称",
+ "newFolderPlaceholder": "文件夹名称",
+ "open": "打开",
+ "rename": "重命名",
+ "delete": "删除",
+ "confirmDelete": "删除“{{name}}”?此操作无法撤销。",
+ "previewFailed": "无法加载此图片。",
"searchPlaceholder": "搜索",
"colName": "名称",
"colSize": "大小",
@@ -713,7 +722,8 @@
"openFailed": "无法打开这个项目。",
"createFolderFailed": "无法创建文件夹。",
"loadFailed": "无法加载这个文件。",
- "saveFailed": "无法保存这个文件。"
+ "saveFailed": "无法保存这个文件。",
+ "deleteFailed": "无法删除这个项目。"
}
},
"terminal": {
diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.ts
index 28629a788..f9981576e 100644
--- a/ui/src/lib/filePreview.ts
+++ b/ui/src/lib/filePreview.ts
@@ -90,6 +90,36 @@ export function isEditableFile(entry: { kind: string; size: number | null; name:
return entry.kind === 'file' && previewKind(entry.name) != null && (entry.size == null || entry.size <= PREVIEW_MAX_BYTES);
}
+// Raster image extensions an <img> tag can render directly. SVG is handled separately because it's
+// ALSO editable text (it keeps its 'source' previewKind), so it can be both edited and rendered.
+const RASTER_IMAGE_EXT = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'avif', 'bmp', 'ico', 'apng']);
+
+// Mirrors the backend content cap (core/file_browser_service.MAX_FILE_BYTES): `/api/files/content`
+// refuses anything larger with 413, so an oversized image can't be rendered — it must download.
+export const IMAGE_PREVIEW_MAX_BYTES = 25 * 1024 * 1024;
+
+export type ImageKind = 'raster' | 'svg';
+
+// Whether a file can be rendered as an image preview, and how. Deliberately separate from
+// ``previewKind`` (which classifies EDITABLE text): images have no text kind, and SVG is both an
+// image (renderable here) and source (editable in Monaco), so ``previewKind('x.svg') === 'source'``
+// must stay true while this still reports it as an image.
+export function imageKind(name: string, mime?: string | null): ImageKind | null {
+ const ext = extOf(name);
+ const m = (mime || '').split(';')[0].trim().toLowerCase();
+ if (ext === 'svg' || m === 'image/svg+xml') return 'svg';
+ if (RASTER_IMAGE_EXT.has(ext) || (m.startsWith('image/') && m !== 'image/svg+xml')) return 'raster';
+ return null;
+}
+
+// Whether a file should preview as RENDERED (not edited) when opened from the File Browser: a raster
+// image (no editable text form) within the content cap is the only such case. SVG/Markdown stay
+// editable, gaining a preview TOGGLE inside the editor instead. A directory, symlink, or oversized
+// image (which `/api/files/content` would reject) is never previewed here — it falls to download.
+export function isRenderOnlyImage(entry: { kind: string; name: string; size: number | null }): boolean {
+ return entry.kind === 'file' && imageKind(entry.name) === 'raster' && (entry.size == null || entry.size <= IMAGE_PREVIEW_MAX_BYTES);
+}
+
// Shiki language id for the 'code'/'source' kinds; 'text' (no highlight) otherwise.
export function codeLanguage(name: string, serverExt?: string | null): string {
const b = baseName(name).toLowerCase();
diff --git a/ui/src/lib/filesApi.ts b/ui/src/lib/filesApi.ts
index f2c582962..c6ca2dec4 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -217,6 +217,18 @@ export async function deletePath(path: string, recursive = false): Promise<{ ok:
);
}
+// 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 }> {
+ return parse(
+ await apiFetch('/api/files/rename', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ path, new_name: newName }),
+ }),
+ );
+}
+
// 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.