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): windowed desktop Apps — Files, Editor, Terminal aligned to design (#691)

Call Whitef6ad2a2b322c
diff --git a/core/file_browser_service.py b/core/file_browser_service.py
index bb7b5727e..b9b38fed9 100644
--- a/core/file_browser_service.py
+++ b/core/file_browser_service.py
@@ -517,7 +517,9 @@ def _write_lock_for(path: Path) -> threading.Lock:
return lock
-def write_file(raw_path: str, content: str, *, expected_mtime: float | None = None) -> dict[str, Any]:
+def write_file(
+ raw_path: str, content: str, *, expected_mtime: float | None = None, create_only: bool = False
+) -> dict[str, Any]:
if not isinstance(content, str):
raise FileBrowserError("invalid_content", "Content must be UTF-8 text", 400)
data = content.encode("utf-8")
@@ -551,6 +553,37 @@ def write_file(raw_path: str, content: str, *, expected_mtime: float | None = No
raise FileBrowserError("is_symlink", "Refusing to write through a symlink", 400)
if target.exists() and not target.is_file():
raise FileBrowserError("not_file", "Path is not a regular file", 400)
+ # create_only ("New File"): create the final path atomically with O_EXCL — no temp +
+ # replace, so it can never overwrite a file another writer/move/external process slipped
+ # in. O_EXCL fails outright if the path already exists.
+ if create_only:
+ try:
+ excl_fd = os.open(target, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
+ except FileExistsError as exc:
+ raise ConflictError("exists", "Path already exists") from exc
+ except PermissionError as exc:
+ raise FileBrowserError("permission_denied", "Permission denied", 403) from exc
+ except OSError as exc:
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ created_ino = os.fstat(excl_fd).st_ino
+ try:
+ with os.fdopen(excl_fd, "wb") as handle:
+ handle.write(data)
+ handle.flush()
+ os.fsync(handle.fileno())
+ except OSError as exc:
+ # Remove the partial file we created so a retry isn't blocked by a stale
+ # `exists` — but ONLY if the path still resolves to OUR inode, so we never delete
+ # a file an external writer slipped in between the failure and here (mirrors the
+ # hard-link rollback guard).
+ try:
+ if os.stat(target).st_ino == created_ino:
+ os.unlink(target)
+ except OSError:
+ pass
+ raise FileBrowserError("fs_error", str(exc), 400) from exc
+ _fsync_dir(parent)
+ return {"ok": True, "mtime": _mtime_seconds(target.stat())}
fd = -1
temp_name = ""
try:
diff --git a/core/terminal_service.py b/core/terminal_service.py
index 93f3c332f..cfb2b42be 100644
--- a/core/terminal_service.py
+++ b/core/terminal_service.py
@@ -600,6 +600,21 @@ def _tmux_launch_command(tmux_binary: str, session_id: str) -> list[str]:
"-g",
"status",
"off",
+ # tmux drives the outer terminal's ALTERNATE screen, so the browser xterm keeps no
+ # scrollback of its own — without mouse mode the wheel does nothing and earlier output
+ # is unreachable. `mouse on` routes the wheel into tmux copy-mode (scroll history), and
+ # `set-clipboard on` lets a mouse selection reach the system clipboard via OSC 52 so
+ # copy still works once tmux owns the mouse.
+ ";",
+ "set-option",
+ "-g",
+ "mouse",
+ "on",
+ ";",
+ "set-option",
+ "-g",
+ "set-clipboard",
+ "on",
]
diff --git a/docs/plans/apps-design-alignment.md b/docs/plans/apps-design-alignment.md
new file mode 100644
index 000000000..4ccc758b6
--- /dev/null
+++ b/docs/plans/apps-design-alignment.md
@@ -0,0 +1,59 @@
+# Apps — design-fidelity alignment (post-#679 polish)
+
+After #679 shipped windowed Apps, runtime eyeballing surfaced that the three apps
+drifted from their **design.pen** frames (built code-green but never visually
+verified against the design). Alex's directive: **strictly align all three apps to
+their design frames, design-first, no free-styling.** Build → Codex real-browser
+visual cross-check vs the frames → PR. (See memory `feedback_design_fidelity_visual_gate`.)
+
+Branch: `feat/apps-windowing-polish` off origin/master.
+
+## Design targets (all confirmed in design.pen, 2026-06-28)
+- **File Browser → `nknn2`** — pure full-width Finder: favorites/projects rail +
+ Name/Size/Modified columns + toolbar (breadcrumb, search, New File/New Folder) +
+ status bar. **No in-pane editor** (browser does not edit). Clicking a code file
+ opens the Editor window (open-by-default model, refine later); unsupported files
+ show a prompt.
+- **File Editor → `dnYPx` + `w0qoC` (welcome)** — VS-Code IDE: activity bar +
+ collapsible explorer file-tree + editor tabs + Monaco + cyan status bar; welcome/
+ empty state (Open Folder / New File / Open Recent) when no folder. Monaco fully
+ integrated here. **Terminal embeddable later** as an integrated panel (build the
+ Terminal reusably; design that variant first when we get to it).
+- **Terminal → `iwYIX`** — multi-tab (each tab = a session) + `tmux · persistent`
+ badge + accessory key bar. Built as a **reusable component**. Also fixes the
+ sizing/scrollback bug (rows must fit the container; scroll history works).
+
+## Windowing / sidebar (new gap designs, confirmed)
+- Editor welcome state `w0qoC`; sidebar bottom `bVke5` (prominent Apps pill wider
+ than a compact Settings gear; version row = green dot left, version right);
+ Dock new-window menu `UkkCV` (right-click / hover + → New Window / Show All
+ Windows; multi-instance reachable); maximize-over-sidebar `If1Tt` (window layer =
+ full viewport, over the sidebar; Apps button / Dock float on top, always reachable).
+
+## Small fixes
+- AppWindow traffic-light ×/–/+ glyph vertical centering.
+- `/admin` label "工作区" → "设置".
+
+## Process
+Build strictly to the frames → `npm run build` + UI vitest green → **Codex views it
+in a real browser and cross-checks each app vs its design frame for omissions** →
+open PR (not draft) → Codex review loop to pass → Alex eyeballs.
+
+## Drifts caught by the self visual cross-check (fixed pre-Codex)
+Running the branch in a real browser (chrome-devtools) against the frames surfaced
+four drifts that build-green never would — the exact reason for the visual gate:
+- **Editor had a redundant header.** Each tab rendered the FileEditorPane's own
+ `filename + Save` bar on top of the editor tab → two headers. `dnYPx` shows tabs →
+ Monaco directly. Fixed: `FileEditorPane` gains a `chromeless` mode (used by the IDE);
+ save is now ⌘S (wired through Monaco), dirty shows as the tab dot.
+- **Editor status bar showed the file path**, not `Ln x, Col y · Spaces: 2 · <Lang>`
+ as in `dnYPx`. Fixed: live cursor + language surfaced from Monaco into the bar.
+- **Terminal scrollback was dead.** tmux drives the outer terminal's ALTERNATE screen,
+ so the browser xterm keeps no scrollback and the wheel did nothing. Root-cause fix:
+ the tmux launch now sets `mouse on` (wheel → tmux copy-mode history) + `set-clipboard on`
+ (selection → OSC 52 clipboard). The fill-height half was the RAF-refit from the rebuild.
+- **Maximize did not cover the sidebar.** The `<aside>` was `z-30` (and `position:fixed`
+ always forms a stacking context), so the whole sidebar floated above the window layer.
+ Fixed per `If1Tt`: aside un-stacked so a maximized window covers the nav; a second Apps
+ launcher (`FloatingApps`) renders outside the aside and shows only while maximized, so
+ the Dock stays reachable on top.
diff --git a/tests/test_file_browser_backend.py b/tests/test_file_browser_backend.py
index 8b1344240..c3aa315e8 100644
--- a/tests/test_file_browser_backend.py
+++ b/tests/test_file_browser_backend.py
@@ -430,6 +430,21 @@ def test_write_normal_path_still_succeeds(tmp_path):
assert path.read_text(encoding="utf-8") == "ok"
+def test_write_create_only_refuses_to_clobber_existing(tmp_path):
+ path = tmp_path / "new.txt"
+
+ # A brand-new file with create_only succeeds.
+ result = fs.write_file(str(path), "first", create_only=True)
+ assert result["ok"] is True
+ assert path.read_text(encoding="utf-8") == "first"
+
+ # A second create_only write for the same name is refused and must NOT truncate the file.
+ with pytest.raises(fs.ConflictError) as excinfo:
+ fs.write_file(str(path), "second", create_only=True)
+ assert excinfo.value.code == "exists"
+ assert path.read_text(encoding="utf-8") == "first"
+
+
def test_write_long_legal_basename_uses_bounded_temp_name(tmp_path, monkeypatch):
name = "a" * 250
path = tmp_path / name
diff --git a/tests/test_terminal_backend.py b/tests/test_terminal_backend.py
index 4dabcfc24..30675f631 100644
--- a/tests/test_terminal_backend.py
+++ b/tests/test_terminal_backend.py
@@ -362,6 +362,19 @@ def test_terminal_tmux_launch_command_uses_safe_session():
"-g",
"status",
"off",
+ # mouse mode routes the browser xterm's wheel into tmux copy-mode so history is
+ # scrollable (tmux owns the alternate screen); set-clipboard lets a selection reach
+ # the system clipboard via OSC 52.
+ ";",
+ "set-option",
+ "-g",
+ "mouse",
+ "on",
+ ";",
+ "set-option",
+ "-g",
+ "set-clipboard",
+ "on",
]
assert _tmux_socket_name().startswith("avibe-")
diff --git a/ui/src/components/AppShell.tsx b/ui/src/components/AppShell.tsx
index 0ede25952..dfc18e43a 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 } from '../context/WindowManagerContext';
+import { WindowManagerProvider, useWindowManager } from '../context/WindowManagerContext';
import { WindowLayer } from './apps/WindowLayer';
import { NewSessionSheet } from './workbench/NewSessionSheet';
import { SearchPalette } from './workbench/search/SearchPalette';
@@ -207,6 +207,30 @@ 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 (
+ // data-theme="dark" so the floating Dock popover matches the always-dark windows it sits over.
+ // 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.
+ <div
+ data-theme="dark"
+ 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();
@@ -374,7 +398,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">
- <aside className="fixed inset-y-0 left-0 z-30 hidden w-[240px] flex-col border-r border-border bg-surface md:flex">
+ {/* 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">
<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
@@ -408,8 +436,10 @@ 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. */}
- <div className="flex flex-col gap-3">
+ + 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). */}
+ <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
centered Chat composer. Workbench → Settings (control panel);
@@ -419,10 +449,11 @@ export const AppShell: React.FC = () => {
{shellMode === 'workbench' ? (
<Link
to="/admin/dashboard"
- className="group flex flex-1 items-center justify-center gap-2 rounded-lg border border-border-strong px-3 py-2.5 text-[13px] font-medium text-foreground transition-colors hover:bg-foreground/[0.04]"
+ title={t('appShell.openControlPanel')}
+ aria-label={t('appShell.openControlPanel')}
+ className="group flex w-11 shrink-0 items-center justify-center rounded-lg border border-border-strong text-foreground transition-colors hover:bg-foreground/[0.04]"
>
- <Settings className="size-4 text-muted group-hover:text-foreground" />
- <span>{t('appShell.openControlPanel')}</span>
+ <Settings className="size-[18px] text-muted group-hover:text-foreground" />
</Link>
) : (
<Link
@@ -453,18 +484,18 @@ export const AppShell: React.FC = () => {
</div>
)}
- {/* Row 2 — version + a compact run-state dot at the very bottom. The
- green/grey dot conveys running vs stopped (hover shows the text). */}
- <div className="flex items-center gap-2">
+ {/* Row 2 (design bVke5) — run-state dot + label on the LEFT, version on the RIGHT. */}
+ <div className="flex items-center justify-between gap-2">
+ <span className="flex items-center gap-1.5 text-[11px] font-medium text-muted">
+ <span
+ className={clsx(
+ 'size-2 shrink-0 rounded-full',
+ isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
+ )}
+ />
+ {isRunning ? t('common.running') : t('common.stopped')}
+ </span>
<VersionBadge openUpward />
- <span
- title={isRunning ? t('common.running') : t('common.stopped')}
- aria-label={isRunning ? t('common.running') : t('common.stopped')}
- className={clsx(
- 'ml-auto size-2.5 shrink-0 rounded-full',
- isRunning ? 'bg-mint shadow-[0_0_8px_rgba(91,255,160,0.9)]' : 'bg-muted'
- )}
- />
</div>
</div>
</div>
@@ -563,6 +594,8 @@ 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. */}
<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 75f6713de..9f7c1b52a 100644
--- a/ui/src/components/AppsLauncher.tsx
+++ b/ui/src/components/AppsLauncher.tsx
@@ -55,7 +55,10 @@ export const AppsLauncher: React.FC = () => {
};
return (
- <div className="relative flex-1" onMouseEnter={openHover} onMouseLeave={queueClose}>
+ // 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}>
<button
type="button"
onClick={onClick}
@@ -63,14 +66,14 @@ export const AppsLauncher: React.FC = () => {
aria-expanded={visible}
aria-pressed={pinned}
className={clsx(
- 'group flex w-full items-center gap-2.5 rounded-lg border px-3 py-2.5 text-[13px] font-medium transition-colors',
+ 'group flex w-full items-center gap-2.5 rounded-full border bg-cyan-soft px-4 py-2.5 text-[13px] font-bold text-foreground transition-colors',
visible
- ? 'border-cyan/40 bg-cyan-soft text-foreground shadow-[0_0_16px_-4px_rgba(63,224,229,0.5)]'
- : 'border-border-strong text-foreground hover:bg-foreground/[0.04]',
+ ? 'border-cyan shadow-[0_0_22px_-4px_rgba(63,224,229,0.7)]'
+ : 'border-cyan/45 shadow-[0_0_14px_-5px_rgba(63,224,229,0.55)] hover:border-cyan/70',
)}
>
- <LayoutGrid className={clsx('size-4', visible ? 'text-cyan' : 'text-muted group-hover:text-foreground')} />
- <span className="flex-1 text-left">{t('apps.title')}</span>
+ <LayoutGrid className="size-4 shrink-0 text-cyan" />
+ <span className="flex-1 whitespace-nowrap text-left">{t('apps.title')}</span>
{pinned ? (
<Pin className="size-3.5 shrink-0 rotate-45 fill-cyan text-cyan" />
) : (
diff --git a/ui/src/components/apps/AppWindow.tsx b/ui/src/components/apps/AppWindow.tsx
index 4f6cac8ce..d5f724493 100644
--- a/ui/src/components/apps/AppWindow.tsx
+++ b/ui/src/components/apps/AppWindow.tsx
@@ -1,6 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
+import { Minus, Plus, X, type LucideIcon } from 'lucide-react';
import { APP_REGISTRY } from '../../apps/registry';
import { useWindowManager, type WindowInstance } from '../../context/WindowManagerContext';
@@ -102,11 +103,11 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
? { left: 0, top: 0, width: layerWidth, height: layerHeight, zIndex: win.z }
: { left: win.bounds.x, top: win.bounds.y, width: win.bounds.width, height: win.bounds.height, zIndex: win.z };
- const lights: { key: string; color: string; glyph: string; onClick: () => void; label: string }[] = [
+ const lights: { key: string; color: string; Glyph: LucideIcon; onClick: () => void; label: string }[] = [
{
key: 'close',
color: '#ff5f57',
- glyph: '×',
+ Glyph: X,
// A dirty editor body can veto the close (confirm) before the exit animation.
onClick: () => {
if (wm.confirmClose(win.id)) setExitKind((k) => k ?? 'close');
@@ -115,8 +116,8 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
},
// Minimize is a mounted hide (no exit animation): the body keeps running and
// `inert` on the root pulls focus out, so nothing is trapped in a hidden window.
- { key: 'min', color: '#febc2e', glyph: '–', onClick: () => wm.minimize(win.id), label: t('apps.window.minimize') },
- { key: 'max', color: '#28c840', glyph: '+', onClick: () => wm.toggleMaximize(win.id), label: t('apps.window.maximize') },
+ { key: 'min', color: '#febc2e', Glyph: Minus, onClick: () => wm.minimize(win.id), label: t('apps.window.minimize') },
+ { key: 'max', color: '#28c840', Glyph: Plus, onClick: () => wm.toggleMaximize(win.id), label: t('apps.window.maximize') },
];
return (
@@ -181,7 +182,7 @@ export const AppWindow: React.FC<{ win: WindowInstance; layerWidth: number; laye
className="grid size-3 place-items-center rounded-full text-[9px] font-bold leading-none text-black/55 opacity-100"
style={{ backgroundColor: l.color }}
>
- <span className="opacity-0 transition-opacity group-hover/win:opacity-100">{l.glyph}</span>
+ <l.Glyph className="size-2 opacity-0 transition-opacity group-hover/win:opacity-100" strokeWidth={3.5} />
</button>
))}
</div>
diff --git a/ui/src/components/apps/Dock.tsx b/ui/src/components/apps/Dock.tsx
index cc058ec40..fbe4ac5af 100644
--- a/ui/src/components/apps/Dock.tsx
+++ b/ui/src/components/apps/Dock.tsx
@@ -1,3 +1,5 @@
+import { useEffect, useState } from 'react';
+import { Copy, Plus, SquarePlus } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import clsx from 'clsx';
@@ -6,93 +8,162 @@ import { useWindowManager } from '../../context/WindowManagerContext';
// The unified Dock panel: app launcher + running indicators + minimized-window
// thumbnails. Headless of how it's revealed — the AppsLauncher trigger floats it
-// above the bottom-left Apps button (hover = preview, click = pin).
+// above the bottom-left Apps button (hover = preview, click = pin). A running app's
+// tile reveals a + (and right-click menu) to open another window — windows are
+// multi-instance, so this is the explicit path to a second Files/Terminal/Editor.
export const Dock: React.FC = () => {
const { t } = useTranslation();
const wm = useWindowManager();
const { windows, focusedId } = wm;
const focusedApp = windows.find((w) => w.id === focusedId)?.appId;
const minimized = windows.filter((w) => w.minimized);
+ const [menuApp, setMenuApp] = useState<AppId | null>(null);
- // Click an app: focus its front window, else un-minimize its top window, else
- // launch a fresh one.
+ // The per-tile context menu is a transient popover — Esc dismisses it (the backdrop handles
+ // click-outside). Without this it lingered on screen after the user moved on (Codex).
+ useEffect(() => {
+ if (!menuApp) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') setMenuApp(null);
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [menuApp]);
+
+ // Click an app: focus its front window, else un-minimize its top window, else launch one.
const activate = (appId: AppId) => {
+ setMenuApp(null); // any tile interaction dismisses a lingering context menu
const own = windows.filter((w) => w.appId === appId);
const visible = own.filter((w) => !w.minimized);
if (visible.length > 0) {
const top = visible.reduce((a, b) => (b.z > a.z ? b : a));
wm.focus(top.id);
- // Pull DOM focus straight to it: if it was already the top window, wm.focus is a
- // no-op so the focusedId-keyed focus effect won't re-fire, and the chord (routed by
- // document.activeElement) would otherwise stay on this Dock button. The element is
- // already rendered + visible here, so focusing it directly is safe.
(document.querySelector(`[data-window-id="${top.id}"]`) as HTMLElement | null)?.focus?.({ preventScroll: true });
} else if (own.length > 0) {
- // Restored from minimized: the element is inert until the next render, so DOM focus is
- // handled by AppWindow's focus-on-becoming-top effect rather than a direct call here.
wm.restore(own.reduce((a, b) => (b.z > a.z ? b : a)).id);
} else {
wm.openApp(appId);
}
};
+ const openNew = (appId: AppId) => {
+ wm.openApp(appId);
+ setMenuApp(null);
+ };
+ const showAll = (appId: AppId) => {
+ const own = windows.filter((w) => w.appId === appId);
+ own.filter((w) => w.minimized).forEach((w) => wm.restore(w.id));
+ const visible = own.filter((w) => !w.minimized);
+ if (visible.length > 0) wm.focus(visible.reduce((a, b) => (b.z > a.z ? b : a)).id);
+ setMenuApp(null);
+ };
+
return (
- <div className="flex items-center gap-2 rounded-2xl border border-border-strong bg-surface-2/95 p-2 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.65)] backdrop-blur-xl">
- {APP_LIST.map((app) => {
- const Icon = app.icon;
- const running = windows.some((w) => w.appId === app.id);
- const active = focusedApp === app.id;
- return (
- <button
- key={app.id}
- type="button"
- title={running ? `${t(app.titleKey)} · ${t('apps.dock.newInstanceHint')}` : t(app.titleKey)}
- aria-label={t(app.titleKey)}
- // Plain click focuses/restores the existing window; a modifier-click
- // (⌘/Ctrl/Alt) always opens another instance — windows are multi-instance,
- // but otherwise there'd be no UI path to a second Files/Terminal window.
- onClick={(e) => (e.metaKey || e.ctrlKey || e.altKey ? wm.openApp(app.id) : activate(app.id))}
- className="flex flex-col items-center gap-1.5"
- >
- <span
- className={clsx(
- 'grid size-12 place-items-center rounded-xl border transition',
- active ? 'border-2 bg-foreground/[0.07]' : 'border-border bg-foreground/[0.03] hover:bg-foreground/[0.07]',
+ <div className="relative">
+ {menuApp && <div className="fixed inset-0 z-0" onClick={() => setMenuApp(null)} aria-hidden />}
+ <div className="relative flex items-center gap-2 rounded-2xl border border-border-strong bg-surface-2/95 p-2 shadow-[0_24px_64px_-12px_rgba(0,0,0,0.65)] backdrop-blur-xl">
+ {APP_LIST.map((app) => {
+ const Icon = app.icon;
+ const running = windows.some((w) => w.appId === app.id);
+ const active = focusedApp === app.id;
+ return (
+ <div key={app.id} className="group/tile relative flex flex-col items-center gap-1.5">
+ <button
+ type="button"
+ title={t(app.titleKey)}
+ aria-label={t(app.titleKey)}
+ onClick={(e) => (e.metaKey || e.ctrlKey || e.altKey ? openNew(app.id) : activate(app.id))}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ setMenuApp((cur) => (cur === app.id ? null : app.id));
+ }}
+ className={clsx(
+ 'grid size-12 place-items-center rounded-xl border transition',
+ active ? 'border-2 bg-foreground/[0.07]' : 'border-border bg-foreground/[0.03] hover:bg-foreground/[0.07]',
+ )}
+ style={active ? { borderColor: `var(${app.accent})` } : undefined}
+ >
+ <Icon className="size-6" style={{ color: `var(${app.accent})` }} />
+ </button>
+ <span className="size-1.5 rounded-full" style={{ backgroundColor: running ? `var(${app.accent})` : 'transparent' }} />
+
+ {/* + reveals on hover and directly opens another window (the one-click affordance the
+ label advertises). The New Window / Show All Windows menu is the tile's right-click. */}
+ <button
+ type="button"
+ title={t('apps.dock.newWindow')}
+ aria-label={t('apps.dock.newWindow')}
+ onClick={(e) => {
+ e.stopPropagation();
+ openNew(app.id);
+ }}
+ className={clsx(
+ 'absolute -right-1 -top-1 grid size-4 place-items-center rounded-full border border-border-strong bg-surface-2 text-muted shadow transition hover:text-foreground',
+ menuApp === app.id ? 'opacity-100' : 'opacity-0 group-hover/tile:opacity-100',
+ )}
+ >
+ <Plus className="size-2.5" strokeWidth={3} />
+ </button>
+
+ {menuApp === app.id && (
+ <div
+ role="menu"
+ // Anchor to the tile's LEFT edge (opens rightward), not centered: the Dock sits at
+ // the bottom-left, so a centered menu's left half spilled past the viewport edge and
+ // got clipped (Codex). Left-anchored keeps the whole menu on-screen.
+ className="absolute bottom-full left-0 z-10 mb-2 w-44 rounded-xl border border-border bg-surface-3 p-1.5 shadow-[0_10px_28px_-8px_rgba(0,0,0,0.7)]"
+ >
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => openNew(app.id)}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[12.5px] font-medium text-foreground transition hover:bg-cyan-soft"
+ >
+ <SquarePlus className="size-[15px] text-cyan" />
+ {t('apps.dock.newWindow')}
+ </button>
+ <button
+ type="button"
+ role="menuitem"
+ onClick={() => showAll(app.id)}
+ disabled={!running}
+ className="flex w-full items-center gap-2.5 rounded-lg px-2.5 py-2 text-left text-[12.5px] text-muted transition hover:bg-foreground/[0.05] disabled:opacity-40 disabled:hover:bg-transparent"
+ >
+ <Copy className="size-[15px]" />
+ {t('apps.dock.showAllWindows')}
+ </button>
+ </div>
)}
- style={active ? { borderColor: `var(${app.accent})` } : undefined}
- >
- <Icon className="size-6" style={{ color: `var(${app.accent})` }} />
- </span>
- <span className="size-1.5 rounded-full" style={{ backgroundColor: running ? `var(${app.accent})` : 'transparent' }} />
- </button>
- );
- })}
+ </div>
+ );
+ })}
- {minimized.length > 0 && <div className="mx-1 h-11 w-px shrink-0 bg-border-strong" />}
+ {minimized.length > 0 && <div className="mx-1 h-11 w-px shrink-0 bg-border-strong" />}
- {minimized.map((w) => {
- const def = APP_REGISTRY[w.appId];
- const Icon = def.icon;
- return (
- <button
- key={w.id}
- type="button"
- title={w.title ?? t(def.titleKey)}
- aria-label={t('apps.window.restore', { defaultValue: 'Restore' })}
- onClick={() => wm.restore(w.id)}
- className="flex h-[52px] w-[76px] shrink-0 flex-col overflow-hidden rounded-lg border border-border-strong bg-surface transition hover:border-foreground/30"
- >
- <span className="flex items-center gap-1 bg-surface-2 px-1.5 py-1">
- {['#ff5f57', '#febc2e', '#28c840'].map((c) => (
- <span key={c} className="size-1 rounded-full" style={{ backgroundColor: c }} />
- ))}
- </span>
- <span className="flex flex-1 items-center justify-center">
- <Icon className="size-4" style={{ color: `var(${def.accent})` }} />
- </span>
- </button>
- );
- })}
+ {minimized.map((w) => {
+ const def = APP_REGISTRY[w.appId];
+ const Icon = def.icon;
+ return (
+ <button
+ key={w.id}
+ type="button"
+ title={w.title ?? t(def.titleKey)}
+ aria-label={t('apps.window.restore', { defaultValue: 'Restore' })}
+ onClick={() => wm.restore(w.id)}
+ className="flex h-[52px] w-[76px] shrink-0 flex-col overflow-hidden rounded-lg border border-border-strong bg-surface transition hover:border-foreground/30"
+ >
+ <span className="flex items-center gap-1 bg-surface-2 px-1.5 py-1">
+ {['#ff5f57', '#febc2e', '#28c840'].map((c) => (
+ <span key={c} className="size-1 rounded-full" style={{ backgroundColor: c }} />
+ ))}
+ </span>
+ <span className="flex flex-1 items-center justify-center">
+ <Icon className="size-4" style={{ color: `var(${def.accent})` }} />
+ </span>
+ </button>
+ );
+ })}
+ </div>
</div>
);
};
diff --git a/ui/src/components/apps/WindowLayer.tsx b/ui/src/components/apps/WindowLayer.tsx
index 48e2a36f8..700c4dc7c 100644
--- a/ui/src/components/apps/WindowLayer.tsx
+++ b/ui/src/components/apps/WindowLayer.tsx
@@ -71,7 +71,16 @@ export const WindowLayer: React.FC = () => {
<div
ref={ref}
aria-hidden={!anyShown}
- className="pointer-events-none fixed inset-y-0 left-0 right-0 z-20 hidden md:left-[240px] md:block"
+ // The windowed apps (Editor / Terminal / File Browser) are ALWAYS dark — they're
+ // dark-only in the design (dnYPx / iwYIX / nknn2) with hardcoded-dark content areas
+ // (Monaco, xterm), so a light global theme would otherwise paint light chrome around
+ // dark content (and make the welcome text unreadable). `data-theme="dark"` re-cascades
+ // the dark token set to this whole subtree regardless of the app theme.
+ data-theme="dark"
+ // 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.
+ className="pointer-events-none fixed inset-0 z-20 hidden md:block"
>
{windows.map((w) => (
<AppWindow key={w.id} win={w} layerWidth={size.w} layerHeight={size.h} />
diff --git a/ui/src/components/workbench/AppsFileBrowserPage.tsx b/ui/src/components/workbench/AppsFileBrowserPage.tsx
index c1f51604e..084e41db7 100644
--- a/ui/src/components/workbench/AppsFileBrowserPage.tsx
+++ b/ui/src/components/workbench/AppsFileBrowserPage.tsx
@@ -1,13 +1,32 @@
-import { Suspense, lazy, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { ChevronRight, Download, File as FileIcon, Folder, FolderPlus, Loader2, RefreshCw, Star } from 'lucide-react';
+import {
+ Braces,
+ ChevronRight,
+ Download,
+ FileCode2,
+ FileText,
+ File as FileIcon,
+ Folder,
+ FolderPlus,
+ FilePlus,
+ HardDrive,
+ Hash,
+ Home,
+ Image as ImageIcon,
+ Loader2,
+ Monitor,
+ RefreshCw,
+ Search,
+ type LucideIcon,
+} from 'lucide-react';
import clsx from 'clsx';
import { useWorkbenchProjectsTree } from '../../context/WorkbenchProjectsContext';
import { useWindowManager } from '../../context/WindowManagerContext';
-import { previewKind } from '../../lib/filePreview';
+import { isEditableFile } from '../../lib/filePreview';
import {
- contentUrl,
+ downloadFile,
fileBrowserErrorMessage,
fileMeta,
isPlainEntryName,
@@ -16,30 +35,70 @@ import {
makeDir,
pathCrumbs,
systemFavorites,
+ writeFile,
type Favorite,
type FsEntry,
type FsListing,
} from '../../lib/filesApi';
import { Button } from '../ui/button';
-// Lazy-load the editor so Monaco stays out of the main bundle until a text file
-// is actually opened.
-const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));
+// A code-file extension → its accent + glyph (mirrors design nknn2's colored type icons).
+const EXT_ICON: Record<string, { Icon: LucideIcon; color: string }> = {
+ ts: { Icon: FileCode2, color: 'var(--cyan)' },
+ tsx: { Icon: FileCode2, color: 'var(--cyan)' },
+ js: { Icon: FileCode2, color: 'var(--gold)' },
+ jsx: { Icon: FileCode2, color: 'var(--gold)' },
+ json: { Icon: Braces, color: 'var(--gold)' },
+ css: { Icon: Hash, color: 'var(--violet)' },
+ scss: { Icon: Hash, color: 'var(--violet)' },
+ md: { Icon: FileText, color: 'var(--mint)' },
+ markdown: { Icon: FileText, color: 'var(--mint)' },
+ png: { Icon: ImageIcon, color: 'var(--muted)' },
+ jpg: { Icon: ImageIcon, color: 'var(--muted)' },
+ jpeg: { Icon: ImageIcon, color: 'var(--muted)' },
+ svg: { Icon: ImageIcon, color: 'var(--muted)' },
+};
+
+function entryIcon(e: FsEntry): { Icon: LucideIcon; color: string } {
+ if (e.kind === 'dir') return { Icon: Folder, color: 'var(--cyan)' };
+ return EXT_ICON[e.ext?.toLowerCase()] ?? { Icon: FileIcon, color: 'var(--muted)' };
+}
+
+// A favorite's key → a distinct icon (mirrors the Finder rail in design nknn2:
+// Home / Desktop / Downloads / Documents / drive). Unknown keys fall back to a folder.
+const FAV_ICON: Record<string, LucideIcon> = {
+ home: Home,
+ desktop: Monitor,
+ downloads: Download,
+ documents: FileText,
+ root: HardDrive,
+};
-type Selected = { path: string; name: string; kind: string; mime: string | null; mtime: number | null; size: number | null };
+function formatSize(n: number | null): string {
+ if (n == null) return '—';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
+}
-// Above this size, offer a download instead of loading the file into CodeMirror
-// (mirrors the in-page preview cap; the backend allows /api/files/content up to 25MB).
-const MAX_EDIT_BYTES = 1024 * 1024;
+function formatMtime(seconds: number | null): string {
+ if (seconds == null) return '—';
+ // The backend returns mtime in SECONDS (st_mtime_ns / 1e9); Date expects milliseconds.
+ const d = new Date(seconds * 1000);
+ const now = Date.now();
+ const sameYear = d.getFullYear() === new Date(now).getFullYear();
+ const date = d.toLocaleDateString(undefined, sameYear ? { month: 'short', day: 'numeric' } : { year: 'numeric', month: 'short', day: 'numeric' });
+ const time = d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
+ return `${date} ${time}`;
+}
-// Whole-machine Finder: favorites rail (pinned projects + OS defaults), a
-// breadcrumb + dir/file list (left), and a content pane (right) that views or
-// edits the selected file. Backend contract: src/lib/filesApi.ts → /api/files/*.
-export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: string }> = ({
- windowed = false,
- windowId,
-}) => {
+// Whole-machine Finder: favorites/projects rail + a Name/Size/Modified list + a toolbar
+// (breadcrumb, search, New File/Folder) + a status bar. A pure directory browser — it does
+// not edit files; double-clicking a text/code file opens it in the Editor window. Backend
+// contract: ui/src/lib/filesApi.ts → /api/files/*. Design: design.pen `nknn2`.
+export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: string }> = ({ windowed = false }) => {
const { t } = useTranslation();
+ const wm = useWindowManager();
const { projects } = useWorkbenchProjectsTree();
const [cwd, setCwd] = useState('');
const [listing, setListing] = useState<FsListing | null>(null);
@@ -47,23 +106,19 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
const [error, setError] = useState<string | null>(null);
const [showHidden, setShowHidden] = useState(false);
const [sysFavs, setSysFavs] = useState<Favorite[]>([]);
- const [selected, setSelected] = useState<Selected | null>(null);
+ const [query, setQuery] = useState('');
+ const [selected, setSelected] = useState<string | null>(null);
- // Tokens to drop stale async responses. navSeq guards directory listings; selSeq guards
- // file-metadata selections. Every navigation bumps BOTH, so a slow earlier listDir() can't
- // overwrite cwd/listing with a stale directory AND a pending fileMeta() can't repopulate the
- // pane with a file after the user has moved to another directory (breadcrumb/favorite/toggle).
const navSeq = useRef(0);
- const selSeq = useRef(0);
const navigate = useCallback(
(path: string) => {
const seq = ++navSeq.current;
- selSeq.current += 1; // navigating away invalidates any in-flight file selection
setLoading(true);
setError(null);
+ setSelected(null);
listDir(path, showHidden)
.then((r) => {
- if (seq !== navSeq.current) return; // a newer navigation superseded this response
+ if (seq !== navSeq.current) return;
setCwd(r.path);
setListing(r);
})
@@ -74,14 +129,13 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
if (seq === navSeq.current) setLoading(false);
});
},
- [showHidden],
+ [showHidden, t],
);
useEffect(() => {
systemFavorites().then(setSysFavs).catch(() => {});
}, []);
- // Pick an initial directory once: first pinned project, else the home favorite.
useEffect(() => {
if (cwd) return;
if (projects === null) return;
@@ -90,66 +144,84 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [projects, sysFavs]);
- // Re-list the current dir when the hidden toggle flips.
useEffect(() => {
if (cwd) navigate(cwd);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [showHidden]);
- const openEntry = (entry: FsEntry) => {
- const seq = ++selSeq.current;
- const full = joinPath(cwd, entry.name);
- if (entry.kind === 'dir') {
- setSelected(null);
+ // 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.)
+ const open = async (e: FsEntry) => {
+ const full = joinPath(cwd, e.name);
+ if (e.kind === 'dir') {
navigate(full);
- } else {
- fileMeta(full)
- .then((m) => {
- if (seq !== selSeq.current) return; // a newer click superseded this metadata fetch
- setSelected({ path: full, name: entry.name, kind: m.kind, mime: m.mime, mtime: m.mtime, size: m.size });
- })
- .catch((e: unknown) => {
- if (seq === selSeq.current) setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.openFailed')));
- });
+ 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
+ // the popup.
+ const desktop = window.matchMedia('(min-width: 768px)').matches;
+ if (!isEditableFile(e) || !desktop) {
+ downloadFile(full);
+ return;
+ }
+ // Editable + desktop → editor window. Fetch CURRENT metadata: it gives the save-baseline mtime
+ // AND re-validates the open (the file may have grown past the cap or become a symlink since it
+ // was listed) — if it's no longer editable, download instead. Safe to await: opening an internal
+ // window needs no user activation, and the rare changed-since-listing download is acceptable.
+ try {
+ const m = await fileMeta(full);
+ if (!isEditableFile(m)) {
+ downloadFile(full);
+ return;
+ }
+ wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: m.mtime } });
+ } catch {
+ // Metadata fetch failed — open with the listing mtime as the baseline.
+ wm.openApp('editor', { title: e.name, params: { path: full, filename: e.name, mtime: e.mtime } });
}
};
- const newFolder = async () => {
- const raw = window.prompt(t('apps.fileBrowser.newFolderPrompt'));
+ 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;
- // The prompt collects a name, not a path: reject separators / '.' / '..' before
- // joining, so "New folder" can't silently create a dir outside the current folder.
if (!isPlainEntryName(name)) {
setError(t('apps.fileBrowser.errors.invalid_name'));
return;
}
+ const target = joinPath(cwd, name);
try {
- await makeDir(joinPath(cwd, name));
+ 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);
navigate(cwd);
} catch (e: unknown) {
- setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.createFolderFailed')));
+ setError(fileBrowserErrorMessage(e, t, t(kind === 'dir' ? 'apps.fileBrowser.errors.createFolderFailed' : 'apps.fileBrowser.errors.saveFailed')));
}
};
const projectFavs = useMemo(
- () =>
- (projects || [])
- .filter((p) => !!p.folder_path)
- .map((p) => ({ label: p.display_name, path: p.folder_path as string })),
+ () => (projects || []).filter((p) => !!p.folder_path).map((p) => ({ label: p.display_name, path: p.folder_path as string })),
[projects],
);
const crumbs = cwd ? pathCrumbs(cwd) : [];
+ const entries = useMemo(() => {
+ const all = listing?.entries ?? [];
+ const q = query.trim().toLowerCase();
+ const filtered = q ? all.filter((e) => e.name.toLowerCase().includes(q)) : all;
+ return [...filtered].sort((a, b) => (a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === 'dir' ? -1 : 1));
+ }, [listing, query]);
+ 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'
- : 'flex h-[calc(100dvh-7rem)] min-h-[460px] flex-col gap-3 md:h-[calc(100vh-8rem)]'
- }
- >
+ <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)]'}>
{!windowed && (
<div>
<h1 className="text-[18px] font-semibold text-foreground">{t('apps.fileBrowser.label')}</h1>
@@ -157,257 +229,155 @@ export const AppsFileBrowserPage: React.FC<{ windowed?: boolean; windowId?: stri
</div>
)}
- <div
- className={
- windowed
- ? 'flex min-h-0 flex-1 overflow-hidden bg-surface'
- : 'flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface'
- }
- >
- {/* Left: breadcrumb toolbar + favorites + listing */}
- <div className="flex w-full min-w-0 flex-col md:w-[320px] md:border-r md:border-border">
- <div className="flex items-center gap-1.5 border-b border-border px-2.5 py-2">
- <div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">
- {crumbs.map((c, i) => (
- <span key={c.path} className="flex shrink-0 items-center">
- {i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
- <button
- type="button"
- onClick={() => {
- setSelected(null);
- navigate(c.path);
- }}
- className="max-w-[120px] truncate rounded px-1 py-0.5 text-[12px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"
- >
- {c.label}
- </button>
- </span>
- ))}
- </div>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-7 shrink-0 text-muted"
- aria-label={t('apps.fileBrowser.refresh')}
- onClick={() => cwd && navigate(cwd)}
- >
+ <div className={clsx('flex min-h-0 flex-1 flex-col overflow-hidden', !windowed && 'rounded-xl border border-border')}>
+ {/* Toolbar: breadcrumb (left) + search + New File / New Folder (right) */}
+ <div className="flex items-center gap-2 border-b border-border bg-surface-2/60 px-3 py-2">
+ <div className="flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto">
+ <Button type="button" size="icon" variant="ghost" className="size-7 shrink-0 text-muted" aria-label={t('apps.fileBrowser.refresh')} onClick={() => cwd && navigate(cwd)}>
<RefreshCw className={clsx('size-3.5', loading && 'animate-spin')} />
</Button>
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-7 shrink-0 text-muted"
- aria-label={t('apps.fileBrowser.newFolder')}
- disabled={!cwd}
- onClick={() => void newFolder()}
- >
- <FolderPlus className="size-3.5" />
- </Button>
+ {crumbs.map((c, i) => (
+ <span key={c.path} className="flex shrink-0 items-center">
+ {i > 0 && <ChevronRight className="size-3 shrink-0 text-muted" />}
+ <button
+ type="button"
+ onClick={() => navigate(c.path)}
+ className="max-w-[140px] truncate rounded px-1.5 py-0.5 text-[12.5px] text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"
+ >
+ {c.label}
+ </button>
+ </span>
+ ))}
</div>
+ <label className="flex items-center gap-1.5 rounded-lg border border-border bg-surface px-2 py-1">
+ <Search className="size-3.5 shrink-0 text-muted" />
+ <input
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder={t('apps.fileBrowser.searchPlaceholder')}
+ className="w-28 bg-transparent text-[12px] text-foreground placeholder:text-muted focus:outline-none"
+ />
+ </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')}>
+ <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')}>
+ <FolderPlus className="size-3.5" /> {t('apps.fileBrowser.newFolder')}
+ </Button>
+ </div>
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="flex flex-col gap-0.5 border-b border-border p-2">
- {projectFavs.length > 0 && (
- <div className="px-1 pb-0.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">
- {t('apps.fileBrowser.projects')}
- </div>
- )}
- {projectFavs.map((f) => (
- <FavRow
- key={f.path}
- icon={<Star className="size-3.5 text-mint" />}
- label={f.label}
- active={cwd === f.path}
- onClick={() => {
- setSelected(null);
- navigate(f.path);
- }}
- />
- ))}
- {sysFavs.length > 0 && (
- <div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">
- {t('apps.fileBrowser.system')}
- </div>
- )}
- {sysFavs.map((f) => (
- <FavRow
+ {error && <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive">{error}</div>}
+
+ <div className="flex min-h-0 flex-1 overflow-hidden">
+ {/* Rail: Favorites THEN Projects (design nknn2 order). */}
+ <aside className="hidden w-[196px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border bg-surface-2/40 p-2 md:flex">
+ {sysFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.favorites')}</RailTitle>}
+ {sysFavs.map((f) => {
+ const Icon = FAV_ICON[f.key] ?? Folder;
+ return (
+ <RailRow
key={f.path}
- icon={<Folder className="size-3.5 text-muted" />}
+ icon={<Icon className="size-3.5 text-muted" />}
label={f.path.split('/').filter(Boolean).pop() || f.path}
active={cwd === f.path}
- onClick={() => {
- setSelected(null);
- navigate(f.path);
- }}
+ onClick={() => navigate(f.path)}
/>
- ))}
- </div>
+ );
+ })}
+ {projectFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.projects')}</RailTitle>}
+ {projectFavs.map((f) => (
+ <RailRow key={f.path} icon={<Folder className="size-3.5 text-cyan" />} label={f.label} active={cwd === f.path} onClick={() => navigate(f.path)} />
+ ))}
+ </aside>
- {error && (
- <div className="m-2 rounded-md border border-destructive/40 bg-destructive/[0.06] px-2.5 py-1.5 text-[11.5px] text-destructive">
- {error}
- </div>
- )}
- {listing?.truncated && (
- <div className="mx-2 mt-2 rounded-md border border-border bg-foreground/[0.03] px-2.5 py-1.5 text-[11.5px] text-muted">
- {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? listing.entries.length })}
- </div>
- )}
- <div className="flex flex-col gap-0.5 p-2">
+ {/* 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>
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto py-1">
{loading && !listing && (
- <div className="grid place-items-center py-6">
- <Loader2 className="size-4 animate-spin text-muted" />
- </div>
+ <div className="grid place-items-center py-8"><Loader2 className="size-4 animate-spin text-muted" /></div>
)}
- {listing?.entries.length === 0 && !loading && (
- <div className="px-2 py-6 text-center text-[12px] text-muted">{t('apps.fileBrowser.empty')}</div>
+ {listing && entries.length === 0 && (
+ <div className="px-3 py-8 text-center text-[12px] text-muted">{query ? t('apps.fileBrowser.noMatches') : t('apps.fileBrowser.empty')}</div>
)}
- {listing?.entries.map((entry) => (
- <button
- key={entry.name}
- type="button"
- onClick={() => openEntry(entry)}
- className={clsx(
- 'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
- selected?.path === joinPath(cwd, entry.name)
- ? 'bg-mint/[0.08] text-foreground'
- : 'text-foreground hover:bg-foreground/[0.04]',
- )}
- >
- {entry.kind === 'dir' ? (
- <Folder className="size-4 shrink-0 text-muted" />
- ) : (
- <FileIcon className="size-4 shrink-0 text-muted" />
- )}
- <span className="flex-1 truncate">{entry.name}</span>
- {entry.kind === 'dir' && <ChevronRight className="size-3.5 shrink-0 text-muted" />}
- </button>
- ))}
+ {entries.map((e) => {
+ const { Icon, color } = entryIcon(e);
+ const full = joinPath(cwd, e.name);
+ return (
+ <button
+ key={e.name}
+ type="button"
+ // Mouse: single-click selects, double-click opens. Touch (coarse pointer) has no
+ // double-click, so a single tap opens. Keyboard: Enter/Space opens/navigates.
+ onClick={() => {
+ if (window.matchMedia('(pointer: coarse)').matches) open(e);
+ else setSelected(full);
+ }}
+ onDoubleClick={() => open(e)}
+ onKeyDown={(ev) => {
+ if (ev.key === 'Enter' || ev.key === ' ') {
+ ev.preventDefault();
+ open(e);
+ }
+ }}
+ className={clsx(
+ 'flex w-full items-center px-3 py-1.5 text-left text-[12.5px] transition',
+ selected === full ? 'bg-cyan-soft text-foreground' : 'text-foreground hover:bg-foreground/[0.04]',
+ )}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2">
+ <Icon className="size-4 shrink-0" style={{ color }} />
+ <span className="truncate">{e.name}</span>
+ </span>
+ <span className="w-20 shrink-0 text-right font-mono text-[11px] text-muted">{e.kind === 'dir' ? '—' : formatSize(e.size)}</span>
+ <span className="w-36 shrink-0 pl-4 font-mono text-[11px] text-muted">{formatMtime(e.mtime)}</span>
+ </button>
+ );
+ })}
</div>
</div>
+ </div>
- <label className="flex items-center gap-2 border-t border-border px-3 py-2 text-[11.5px] text-muted">
- <input
- type="checkbox"
- checked={showHidden}
- onChange={(e) => setShowHidden(e.target.checked)}
- className="size-3.5"
- />
+ {/* 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">
+ <input type="checkbox" checked={showHidden} onChange={(e) => setShowHidden(e.target.checked)} className="size-3" />
{t('apps.fileBrowser.showHidden')}
</label>
- </div>
-
- {/* Right: content pane (desktop) */}
- <div className="hidden min-w-0 flex-1 md:flex">
- <ContentPane selected={selected} windowed={windowed} windowId={windowId} />
+ <span className="ml-auto flex min-w-0 items-center gap-2 font-mono">
+ {selectedEntry && (
+ <span className="truncate text-foreground/80">
+ {selectedEntry.name}
+ {selectedEntry.kind !== 'dir' && selectedEntry.size != null ? ` · ${formatSize(selectedEntry.size)}` : ''}
+ </span>
+ )}
+ <span className="shrink-0">{t('apps.fileBrowser.itemCount', { count: entries.length })}</span>
+ {listing?.truncated && <span className="shrink-0">· {t('apps.fileBrowser.listTruncated', { count: listing.limit ?? entries.length })}</span>}
+ </span>
</div>
</div>
-
- {/* Mobile: content opens below the list when a file is selected. This pane is
- md:hidden but still mounted on desktop — and windows only ever render on
- desktop — so it must NOT take `windowId`, or its (clean) editor's close guard
- would clobber the visible desktop editor's (dirty) guard for the same window. */}
- {selected && (
- <div className="flex min-h-[50vh] flex-col overflow-hidden rounded-xl border border-border bg-surface md:hidden">
- <ContentPane selected={selected} windowed={windowed} />
- </div>
- )}
</div>
);
};
-const FavRow: React.FC<{ icon: React.ReactNode; label: string; active: boolean; onClick: () => void }> = ({
- icon,
- label,
- active,
- onClick,
-}) => (
+const RailTitle: React.FC<{ children: React.ReactNode }> = ({ children }) => (
+ <div className="px-1 pb-0.5 pt-1.5 font-mono text-[9px] font-bold uppercase tracking-[0.16em] text-muted">{children}</div>
+);
+
+const RailRow: React.FC<{ icon: React.ReactNode; label: string; active: boolean; onClick: () => void }> = ({ icon, label, active, onClick }) => (
<button
type="button"
onClick={onClick}
className={clsx(
'flex items-center gap-2 rounded-md px-2 py-1.5 text-left text-[12.5px] transition',
- active ? 'bg-mint/[0.08] text-foreground' : 'text-foreground hover:bg-foreground/[0.04]',
+ active ? 'bg-cyan-soft text-foreground' : 'text-muted hover:bg-foreground/[0.04] hover:text-foreground',
)}
>
<span className="shrink-0">{icon}</span>
- <span className="flex-1 truncate">{label}</span>
+ <span className="truncate">{label}</span>
</button>
);
-
-const ContentPane: React.FC<{ selected: Selected | null; windowed: boolean; windowId?: string }> = ({
- selected,
- windowed,
- windowId,
-}) => {
- const { t } = useTranslation();
- const wm = useWindowManager();
- if (!selected) {
- return (
- <div className="grid flex-1 place-items-center p-6 text-center text-[12.5px] text-muted">
- {t('apps.fileBrowser.selectHint')}
- </div>
- );
- }
- const mime = selected.mime || '';
- if (mime.startsWith('image/')) {
- return (
- <div className="grid min-h-0 flex-1 place-items-center overflow-auto bg-foreground/[0.02] p-4">
- <img src={contentUrl(selected.path)} alt={selected.name} className="max-h-full max-w-full object-contain" />
- </div>
- );
- }
- // A symlink reports size:null (server lstat()s the link, not its target), but
- // /api/files/content follows it — so a symlink pointing at a large file would slip past
- // the size cap and load its whole target into CodeMirror. Treat symlinks and any
- // unknown-size entry as non-editable; the download link below can still follow them.
- const tooLargeToEdit =
- selected.kind === 'symlink' || selected.size == null || selected.size > MAX_EDIT_BYTES;
- if (previewKind(selected.name, selected.mime || undefined) && !tooLargeToEdit) {
- return (
- <Suspense
- fallback={<div className="grid flex-1 place-items-center text-[12px] text-muted">{t('common.loading')}</div>}
- >
- {/* key by path: remount per file so an in-flight save/load can never apply its
- result to a different file (stale clean/dirty baseline or wrong expected_mtime). */}
- <FileEditorPane
- key={selected.path}
- path={selected.path}
- filename={selected.name}
- mtime={selected.mtime}
- windowId={windowId}
- // Inside a window, offer to pop the file out into its own Editor window.
- // Carry the editor's live mtime (it may have saved since this row opened),
- // not the row's stale metadata, so the new window won't false-conflict.
- onPopOut={
- windowed
- ? (live) =>
- wm.openApp('editor', {
- title: selected.name,
- params: { path: selected.path, filename: selected.name, mtime: live.mtime },
- })
- : undefined
- }
- />
- </Suspense>
- );
- }
- return (
- <div className="grid flex-1 place-items-center p-6 text-center">
- <div className="flex flex-col items-center gap-3">
- <FileIcon className="size-8 text-muted" />
- <div className="text-[12.5px] text-muted">
- {tooLargeToEdit ? t('apps.fileBrowser.tooLarge') : t('apps.fileBrowser.noPreview')}
- </div>
- <a
- href={contentUrl(selected.path, true)}
- className="inline-flex items-center gap-1.5 rounded-md border border-border-strong px-3 py-1.5 text-[12px] text-foreground transition hover:bg-foreground/[0.04]"
- >
- <Download className="size-3.5" /> {t('apps.fileBrowser.download')}
- </a>
- </div>
- </div>
- );
-};
diff --git a/ui/src/components/workbench/AppsTerminalPage.tsx b/ui/src/components/workbench/AppsTerminalPage.tsx
index b96452d90..e040835e3 100644
--- a/ui/src/components/workbench/AppsTerminalPage.tsx
+++ b/ui/src/components/workbench/AppsTerminalPage.tsx
@@ -1,147 +1,19 @@
-import { Suspense, lazy, useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useApi } from '../../context/ApiContext';
-import { apiFetch } from '../../lib/apiFetch';
-import { acquireTerminalSlot, releaseTerminalSlot } from '../../lib/terminalSlots';
+import { TerminalTabs } from './TerminalTabs';
-// Lazy so xterm.js stays out of the main bundle until the Terminal is opened.
-const TerminalView = lazy(() => import('./TerminalView').then((m) => ({ default: m.TerminalView })));
-
-// A process-unique in-memory fallback id, generated once per page load. Used only when
-// localStorage is unavailable, so privacy-restricted/embedded browsers don't all collapse
-// onto one shared tmux session (which would expose terminal state/commands across clients).
-const FALLBACK_SESSION_ID = `wb-${Math.random().toString(36).slice(2, 10)}`;
-
-// A per-tab token mixed into WINDOWED terminal session ids. The slot pool is module-local
-// (so it's per browser tab), but the localStorage base id is shared across tabs in the same
-// profile — so two tabs would both resolve their first windowed terminal to `<base>-w0` and
-// fight over (reconnect/replace/DELETE) one backend session. This discriminator keeps each
-// tab's windowed terminals distinct. The route terminal is intentionally shared/persistent
-// across tabs (its own shell), so it does NOT use this.
-const TAB_TOKEN = Math.random().toString(36).slice(2, 8);
-
-// A stable per-browser session id so the tmux-backed session reconnects to the same shell
-// after a refresh / network drop (persistence). Falls back to the in-memory id above when
-// localStorage is unavailable. The key is scoped to the signed-in account so a different
-// remote (OIDC) user in the same browser can't inherit — and reconnect to — the previous
-// user's live shell; local/unauthenticated sessions (identity == null) share one key.
-function getSessionId(identity: string | null, windowKey?: string): string {
- const KEY = identity ? `avibe.terminal.sessionId.${encodeURIComponent(identity)}` : 'avibe.terminal.sessionId';
- try {
- let id = window.localStorage.getItem(KEY);
- if (!id) {
- id = `wb-${Math.random().toString(36).slice(2, 10)}`;
- window.localStorage.setItem(KEY, id);
- }
- // A windowed terminal appends its (per-instance, life-stable) window id, so two
- // terminal windows — or a window and the /apps/terminal route — don't share one
- // backend session. The service evicts a session's previous client on attach, so a
- // shared id would make them disconnect each other.
- return windowKey ? `${id}-${windowKey}` : id;
- } catch {
- return windowKey ? `${FALLBACK_SESSION_ID}-${windowKey}` : FALLBACK_SESSION_ID;
- }
-}
-
-// `windowed` renders just the terminal filling its parent (an AppWindow body) — no
-// page header / viewport-height wrapper, since the window chrome supplies the title.
-// A windowed terminal also takes a bounded, reused session slot so each window gets
-// its own backend session without minting unbounded session ids.
+// The Terminal app. `windowed` fills its AppWindow body; the route adds the page header.
+// The multi-tab UI + per-tab session/slot lifecycle lives in the reusable TerminalTabs
+// (so the editor's integrated terminal can mount the same thing later). Design: `iwYIX`.
export const AppsTerminalPage: React.FC<{ windowed?: boolean }> = ({ windowed = false }) => {
const { t } = useTranslation();
- const { getAuthSession } = useApi();
- // Resolve the signed-in identity first, then derive the (account-scoped) session id, so we
- // never briefly mount the terminal under the wrong key. email is null for local/unauth.
- const [sessionId, setSessionId] = useState<string | null>(null);
- const resolvedSessionIdRef = useRef<string | null>(null);
- const slotRef = useRef<number | null>(null);
-
- // Slot + backend-session lifecycle is tied to MOUNT, not to identity: acquire a bounded
- // slot for a windowed terminal on mount (so open/close churn reuses session ids instead
- // of exhausting the backend cap), and dispose the backend session + release the slot only
- // on unmount = window close. Keeping this OUT of the identity effect below is the point:
- // an ApiContext re-render hands `getAuthSession` a fresh identity, and if disposal lived
- // in that effect's cleanup it would DELETE a live terminal on every such refresh.
- useEffect(() => {
- if (!windowed) return;
- const slot = acquireTerminalSlot();
- slotRef.current = slot;
- return () => {
- slotRef.current = null;
- const sid = resolvedSessionIdRef.current;
- if (sid) {
- // Only return the slot to the pool once the backend session is actually GONE.
- // apiFetch resolves on non-2xx and network errors are swallowed, but a failed
- // DELETE (auth/origin/CSRF/server error) means the session may still be alive
- // (only detached via the WS close) — reusing the slot would then mint the same id
- // and reconnect a new window to the old shell, leaking its commands/state. 404 =
- // already gone, so that's safe to release too. On any other failure keep the slot
- // reserved (lost for this page, but the pool just hands out the next free index).
- void apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, { method: 'DELETE', credentials: 'same-origin' })
- .then((res) => {
- if (res.ok || res.status === 404) releaseTerminalSlot(slot);
- })
- .catch(() => undefined);
- } else {
- releaseTerminalSlot(slot);
- }
- };
- }, [windowed]);
-
- // Resolve the (account-scoped) session id from the signed-in identity. May re-run when the
- // identity source changes; it only updates the id — it never disposes a session (that's the
- // mount-scoped effect above) — so a context refresh can't kill a live terminal.
- useEffect(() => {
- let cancelled = false;
- const resolve = (identity: string | null) => {
- if (cancelled) return;
- const slot = slotRef.current;
- const nextSessionId = getSessionId(identity, windowed && slot != null ? `${TAB_TOKEN}-w${slot}` : undefined);
- resolvedSessionIdRef.current = nextSessionId;
- setSessionId(nextSessionId);
- };
- getAuthSession()
- // Prefer the stable OIDC subject; email can be absent or shared across subjects, which
- // would collide or fall back to the shared key. (Backend surfaces sub on /api/session.)
- .then((session) => resolve(session.remote && session.authenticated ? session.sub || session.email : null))
- .catch(() => resolve(null));
- return () => {
- cancelled = true;
- };
- }, [getAuthSession, windowed]);
-
- // The React-cleanup DELETE above frees the session on an in-app window close, but it
- // doesn't run on a tab close / refresh. Dispose on `pagehide` too, with `keepalive` so
- // the request survives the unload — otherwise the windowed (per-tab id) session can't be
- // reattached or deleted on the next load and lingers until the backend idle reaper.
- useEffect(() => {
- if (!windowed) return;
- const dispose = () => {
- const sid = resolvedSessionIdRef.current;
- if (!sid) return;
- void apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, {
- method: 'DELETE',
- credentials: 'same-origin',
- keepalive: true,
- }).catch(() => undefined);
- };
- window.addEventListener('pagehide', dispose);
- return () => window.removeEventListener('pagehide', dispose);
- }, [windowed]);
-
- const loading = <div className="grid h-full w-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>;
- const content =
- sessionId == null ? (
- loading
- ) : (
- <Suspense fallback={loading}>
- <TerminalView sessionId={sessionId} />
- </Suspense>
- );
if (windowed) {
- return <div className="h-full w-full overflow-hidden bg-surface">{content}</div>;
+ return (
+ <div className="h-full w-full overflow-hidden bg-surface">
+ <TerminalTabs windowed />
+ </div>
+ );
}
return (
@@ -150,7 +22,9 @@ export const AppsTerminalPage: React.FC<{ windowed?: boolean }> = ({ windowed =
<h1 className="text-[18px] font-semibold text-foreground">{t('apps.terminal.label')}</h1>
<p className="text-[12px] text-muted">{t('apps.terminal.tagline')}</p>
</div>
- <div className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">{content}</div>
+ <div className="flex min-h-0 flex-1 overflow-hidden rounded-xl border border-border bg-surface">
+ <TerminalTabs />
+ </div>
</div>
);
};
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index 4c0b626fd..483e0b121 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -1,46 +1,352 @@
-import { Suspense, lazy } from 'react';
+import { Suspense, lazy, useCallback, useEffect, useState } from 'react';
+import { Blocks, Bug, Clock, CodeXml, FilePlus, Files, FolderOpen, GitBranch, Search, Settings, X } from 'lucide-react';
import { useTranslation } from 'react-i18next';
-import { FileCode2 } from 'lucide-react';
+import clsx from 'clsx';
+
+import { useWindowCloseGuard, useWindowManager } from '../../context/WindowManagerContext';
+import { downloadFile, fileBrowserErrorMessage, fileMeta, isPlainEntryName, joinPath, listDir, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
+import { isEditableFile } from '../../lib/filePreview';
+import { FileTree } from './FileTree';
-// The Editor window body. Reuses FileEditorPane (Monaco) so the standalone Editor
-// app and the in-Files edit pane share one editor. Files opens a file here via
-// `openApp('editor', { params: { path, filename, mtime } })`; with no file it
-// shows a tasteful empty state.
const FileEditorPane = lazy(() => import('./FileEditorPane').then((m) => ({ default: m.FileEditorPane })));
+// A tab carries the file's mtime captured at open time, so saving stays conditional on it
+// (writeFile's expected_mtime) and the backend can surface a conflict instead of silently
+// clobbering newer on-disk content.
+type Tab = { path: string; name: string; mtime: number | null };
+
+// Human language label for the status bar (design dnYPx shows e.g. "TypeScript React").
+const LANGUAGE_LABEL: Record<string, string> = {
+ ts: 'TypeScript',
+ tsx: 'TypeScript React',
+ cts: 'TypeScript',
+ mts: 'TypeScript',
+ js: 'JavaScript',
+ jsx: 'JavaScript React',
+ cjs: 'JavaScript',
+ mjs: 'JavaScript',
+ json: 'JSON',
+ jsonc: 'JSON',
+ css: 'CSS',
+ scss: 'SCSS',
+ less: 'Less',
+ html: 'HTML',
+ md: 'Markdown',
+ markdown: 'Markdown',
+ py: 'Python',
+ rb: 'Ruby',
+ go: 'Go',
+ rs: 'Rust',
+ java: 'Java',
+ c: 'C',
+ cpp: 'C++',
+ cs: 'C#',
+ php: 'PHP',
+ sh: 'Shell',
+ bash: 'Shell',
+ yml: 'YAML',
+ yaml: 'YAML',
+ toml: 'TOML',
+ sql: 'SQL',
+};
+
+// Canonical language identifier for the status bar (e.g. "TypeScript React"). These are product
+// names shown untranslated, exactly like VS Code's language indicator; the generic "plain text"
+// fallback IS localized, at the call site. Returns undefined when there's no specific language.
+function languageLabel(filename: string | undefined): string | undefined {
+ if (!filename) return undefined;
+ const lower = filename.toLowerCase();
+ if (lower === 'dockerfile') return 'Dockerfile';
+ const ext = lower.includes('.') ? lower.split('.').pop()! : '';
+ return LANGUAGE_LABEL[ext];
+}
+
+// The Editor IDE (design dnYPx + welcome w0qoC): activity bar + collapsible explorer tree +
+// editor tabs + Monaco + cyan status bar; a VS-Code-style welcome when nothing is open.
+// Monaco is fully integrated here. Files opens a file via openApp('editor', { params: { path } }).
export const EditorApp: React.FC<{ windowId?: string; params?: Record<string, unknown> }> = ({ windowId, params }) => {
const { t } = useTranslation();
- const path = typeof params?.path === 'string' ? params.path : null;
- const mtime = typeof params?.mtime === 'number' ? params.mtime : null;
- const filename =
- typeof params?.filename === 'string'
- ? params.filename
- : path
- ? path.split('/').filter(Boolean).pop() ?? path
- : '';
-
- if (!path) {
- return (
- <div className="grid h-full w-full place-items-center bg-surface-2 p-6 text-center">
- <div className="flex max-w-xs flex-col items-center gap-3">
- <div className="grid size-14 place-items-center rounded-2xl border border-border bg-foreground/[0.03]">
- <FileCode2 className="size-7 text-violet" />
+ const wm = useWindowManager();
+ const [root, setRoot] = useState<string | null>(null);
+ const [tabs, setTabs] = useState<Tab[]>([]);
+ const [active, setActive] = useState<string | null>(null);
+ const [dirty, setDirty] = useState<Record<string, boolean>>({});
+ const [cursor, setCursor] = useState<{ line: number; col: number } | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const openFile = useCallback((path: string, name: string, mtime: number | null) => {
+ setRoot((r) => r ?? parentDir(path));
+ setTabs((ts) => (ts.some((x) => x.path === path) ? ts : [...ts, { path, name, mtime }]));
+ setCursor(null);
+ setActive(path);
+ }, []);
+
+ // The explorer tree emits a clicked entry. Gate it like the File Browser: only a regular,
+ // supported, within-cap file opens in Monaco; a symlink (the backend refuses symlink writes),
+ // oversized, or unsupported/binary entry downloads instead. The download branch runs BEFORE any
+ // await so the click's user activation survives (Safari/iOS would block the popup otherwise).
+ const onTreeOpen = useCallback(
+ async (path: string, entry: FsEntry) => {
+ if (!isEditableFile(entry)) {
+ downloadFile(path);
+ return;
+ }
+ // Fetch fresh metadata: gives the save-baseline mtime AND re-validates (the file may have
+ // grown past the cap or become a symlink since it was listed) → download if no longer editable.
+ try {
+ const m = await fileMeta(path);
+ if (!isEditableFile(m)) {
+ downloadFile(path);
+ return;
+ }
+ openFile(path, entry.name, m.mtime);
+ } catch {
+ openFile(path, entry.name, entry.mtime);
+ }
+ },
+ [openFile],
+ );
+
+ // Open the launch file (from the File Browser) once on mount.
+ 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,
+ );
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ const anyDirty = Object.values(dirty).some(Boolean);
+ useWindowCloseGuard(windowId, anyDirty ? t('apps.editor.confirmDiscardClose') : null);
+
+ const closeTab = (path: string) => {
+ // Closing a dirty tab drops its in-memory buffer (only the window-level guard existed before),
+ // so confirm first when there are unsaved edits.
+ if (dirty[path] && !window.confirm(t('apps.editor.confirmDiscardClose'))) return;
+ setTabs((ts) => {
+ const rest = ts.filter((x) => x.path !== path);
+ setActive((cur) => (cur === path ? (rest.length ? rest[rest.length - 1].path : null) : cur));
+ return rest;
+ });
+ setDirty((d) => {
+ const n = { ...d };
+ delete n[path];
+ return n;
+ });
+ };
+
+ // Prompt for + validate a folder, set it as the explorer root, and RETURN it (or null) so
+ // callers like New File can continue the flow with the chosen folder.
+ const openFolder = async (): Promise<string | null> => {
+ const p = window.prompt(t('apps.editor.openFolderPrompt'));
+ const path = p?.trim();
+ if (!path) return null;
+ // Validate it's a listable directory before swapping the explorer root, so a typo doesn't
+ // leave the tree stuck on a bad/non-existent path.
+ try {
+ await listDir(path);
+ setError(null);
+ setRoot(path);
+ return path;
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.listFailed')));
+ return null;
+ }
+ };
+ const newFile = async () => {
+ // From the welcome state there's no folder yet: prompt for one and CONTINUE creating the file
+ // in it (rather than behaving like a bare "Open Folder").
+ const dir = root ?? (await openFolder());
+ if (!dir) return;
+ const raw = window.prompt(t('apps.fileBrowser.newFilePrompt'));
+ if (raw == null) return;
+ const name = raw.trim();
+ if (name === '') return;
+ if (!isPlainEntryName(name)) {
+ setError(t('apps.fileBrowser.errors.invalid_name'));
+ return;
+ }
+ const full = joinPath(dir, name);
+ try {
+ // create-only: the backend atomically refuses (errors.exists) if the name is taken, so a
+ // typo can never truncate an existing file.
+ const result = await writeFile(full, '', undefined, true);
+ openFile(full, name, result.mtime);
+ } catch (e: unknown) {
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.saveFailed')));
+ }
+ };
+
+ const ACTIVITY = [Files, Search, GitBranch, Bug, Blocks];
+
+ return (
+ <div className="flex h-full min-h-0 w-full flex-col bg-surface">
+ <div className="flex min-h-0 flex-1">
+ {/* Activity bar */}
+ <div className="flex w-12 shrink-0 flex-col items-center justify-between border-r border-border bg-surface-3 py-3">
+ <div className="flex flex-col items-center gap-[18px]">
+ {ACTIVITY.map((Icon, i) => (
+ <Icon key={i} className={clsx('size-5', i === 0 ? 'text-foreground' : 'text-muted')} />
+ ))}
</div>
- <div className="text-[14px] font-semibold text-foreground">{t('apps.editor.empty')}</div>
- <p className="text-[12.5px] text-muted">{t('apps.editor.emptyHint')}</p>
+ <Settings className="size-5 text-muted" />
+ </div>
+
+ {/* Explorer — ALWAYS present (design w0qoC keeps it in the welcome state): an
+ empty "No folder opened + Open Folder" state when no folder, else the file tree. */}
+ <div className="flex w-[220px] shrink-0 flex-col overflow-hidden border-r border-border bg-surface-2">
+ <div className="px-3 pb-1 pt-2.5 font-mono text-[10px] font-bold uppercase tracking-[0.12em] text-muted">{t('apps.editor.explorer')}</div>
+ {root == null ? (
+ <div className="flex flex-col gap-2 px-3 py-2">
+ <div className="text-[12px] text-muted">{t('apps.editor.noFolder')}</div>
+ <button
+ type="button"
+ onClick={openFolder}
+ className="flex items-center justify-center gap-1.5 rounded-md border border-mint/40 bg-mint/[0.08] px-2.5 py-1.5 text-[12px] font-semibold text-mint transition hover:bg-mint/[0.14]"
+ >
+ <FolderOpen className="size-3.5" />
+ {t('apps.editor.openFolder')}
+ </button>
+ {/* Folder-validation errors (bad path / permission) must surface here too — the
+ main-area error banner only renders once a folder is open. */}
+ {error && (
+ <div className="rounded-md border border-destructive/40 bg-destructive/[0.06] px-2 py-1.5 text-[11.5px] text-destructive">
+ {error}
+ </div>
+ )}
+ </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={active} onOpenFile={onTreeOpen} />
+ </div>
+ )}
+ </div>
+
+ {/* Main area: welcome (no folder) · tabs + Monaco (file open) · select-a-file hint (folder, no file). */}
+ <div className="flex min-w-0 flex-1 flex-col bg-[#0b0b14]">
+ {root == null ? (
+ <Welcome onOpenFolder={openFolder} onNewFile={newFile} onOpenFiles={() => wm.openApp('files')} />
+ ) : (
+ <>
+ {tabs.length > 0 && (
+ <div className="flex items-center overflow-x-auto border-b border-border bg-surface-2">
+ {tabs.map((tab) => (
+ <div
+ key={tab.path}
+ className={clsx(
+ 'group/tab flex shrink-0 items-center gap-2 border-r border-border px-3 py-2 text-[12px] transition',
+ active === tab.path ? 'bg-[#0b0b14] text-foreground shadow-[inset_0_2px_0_0_var(--cyan)]' : 'text-muted hover:bg-foreground/[0.04]',
+ )}
+ >
+ <button
+ type="button"
+ onClick={() => {
+ if (tab.path !== active) setCursor(null);
+ setActive(tab.path);
+ }}
+ className="flex items-center gap-1.5"
+ >
+ <CodeXml className="size-3.5 text-cyan" />
+ {tab.name}
+ {dirty[tab.path] && <span className="size-1.5 rounded-full bg-mint" />}
+ </button>
+ <button
+ type="button"
+ onClick={() => closeTab(tab.path)}
+ aria-label={t('common.close')}
+ className="grid size-4 place-items-center rounded text-muted opacity-0 transition hover:bg-foreground/10 hover:text-foreground group-hover/tab:opacity-100"
+ >
+ <X className="size-3" strokeWidth={2.5} />
+ </button>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {error && <div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive">{error}</div>}
+
+ <div className="relative min-h-0 flex-1">
+ {tabs.length === 0 ? (
+ <div className="grid h-full place-items-center text-[12.5px] text-muted">{t('apps.editor.selectFileHint')}</div>
+ ) : (
+ tabs.map((tab) => (
+ <div key={tab.path} className={clsx('absolute inset-0', active === tab.path ? '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.path] === d ? prev : { ...prev, [tab.path]: d }))}
+ onCursor={active === tab.path ? (line, col) => setCursor({ line, col }) : undefined}
+ />
+ </Suspense>
+ </div>
+ ))
+ )}
+ </div>
+ </>
+ )}
</div>
</div>
- );
- }
+ {/* Status bar (cyan, design dnYPx). The design mock shows a git branch + problem counts on
+ the left, but we have no real git/diagnostics data for an arbitrary folder — showing a
+ 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 ? (
+ <>
+ <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>
+ <span className="truncate">{languageLabel(tabs.find((x) => x.path === active)?.name) ?? t('apps.editor.plainText')}</span>
+ </>
+ ) : (
+ <span className="ml-auto truncate opacity-80">{t('apps.editor.label')}</span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+const Welcome: React.FC<{ onOpenFolder: () => void; onNewFile: () => void; onOpenFiles: () => void }> = ({ onOpenFolder, onNewFile, onOpenFiles }) => {
+ const { t } = useTranslation();
+ const actions: { Icon: typeof FolderOpen; color: string; label: string; onClick: () => void; sc?: string }[] = [
+ { Icon: FolderOpen, color: 'text-cyan', label: t('apps.editor.openFolder'), onClick: onOpenFolder, sc: '⌘O' },
+ { Icon: FilePlus, color: 'text-mint', label: t('apps.fileBrowser.newFile'), onClick: onNewFile, sc: '⌘N' },
+ { Icon: Files, color: 'text-violet', label: t('apps.editor.browseFiles'), onClick: onOpenFiles },
+ ];
return (
- <div className="h-full w-full bg-surface-2">
- <Suspense
- fallback={<div className="grid h-full w-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>}
- >
- {/* key by path: remount per file so a stale load/save can't apply to a different file. */}
- <FileEditorPane key={path} path={path} filename={filename} mtime={mtime} windowId={windowId} />
- </Suspense>
+ <div className="grid min-w-0 flex-1 place-items-center bg-[#0b0b14] p-10">
+ <div className="flex w-[440px] max-w-full flex-col gap-6">
+ <div className="flex items-center gap-3.5">
+ <span className="grid size-14 place-items-center rounded-2xl border border-cyan/60 bg-cyan-soft">
+ <CodeXml className="size-7 text-cyan" />
+ </span>
+ <div className="flex flex-col gap-1">
+ <div className="text-[24px] font-bold text-foreground">{t('apps.editor.label')}</div>
+ <div className="text-[12.5px] text-muted">{t('apps.editor.welcomeSub')}</div>
+ </div>
+ </div>
+ <div className="font-mono text-[11px] font-bold uppercase tracking-[0.1em] text-muted">{t('apps.editor.start')}</div>
+ <div className="flex flex-col gap-1.5">
+ {actions.map((a) => (
+ <button key={a.label} type="button" onClick={a.onClick} className="flex items-center gap-2.5 rounded-lg px-3 py-2.5 text-left transition hover:bg-foreground/[0.06]">
+ <a.Icon className={clsx('size-4', a.color)} />
+ <span className="text-[13.5px] font-semibold text-foreground">{a.label}</span>
+ <span className="flex-1" />
+ {a.sc && <span className="font-mono text-[11px] text-muted">{a.sc}</span>}
+ </button>
+ ))}
+ </div>
+ <div className="font-mono text-[11px] font-bold uppercase tracking-[0.1em] text-muted">{t('apps.editor.recent')}</div>
+ <div className="flex items-center gap-2 text-[12.5px] text-muted">
+ <Clock className="size-3.5" /> {t('apps.editor.noRecent')}
+ </div>
+ </div>
</div>
);
};
diff --git a/ui/src/components/workbench/FileEditorPane.tsx b/ui/src/components/workbench/FileEditorPane.tsx
index 62f5a8198..4788255a9 100644
--- a/ui/src/components/workbench/FileEditorPane.tsx
+++ b/ui/src/components/workbench/FileEditorPane.tsx
@@ -83,7 +83,17 @@ export const FileEditorPane: React.FC<{
onPopOut?: (live: { mtime: number | null }) => void;
/** The owning window id, when this editor lives in a window — enables the unsaved-close guard. */
windowId?: string;
-}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId }) => {
+ /** Report dirty state up (used by the Editor IDE to aggregate one close guard over its tabs). */
+ onDirtyChange?: (dirty: boolean) => void;
+ /**
+ * Drop the filename + save header strip. The Editor IDE (design dnYPx) shows the
+ * filename + dirty dot in the tab and saves via ⌘S, so the per-pane header would
+ * be a redundant second header. Standalone uses keep the header (default).
+ */
+ chromeless?: boolean;
+ /** Live 1-based cursor position, surfaced in the IDE status bar. */
+ onCursor?: (line: number, column: number) => void;
+}> = ({ path, filename, mtime, readOnly = false, onPopOut, windowId, onDirtyChange, chromeless = false, onCursor }) => {
const { t } = useTranslation();
const { resolvedTheme } = useTheme();
const [text, setText] = useState<string | null>(null);
@@ -117,6 +127,9 @@ export const FileEditorPane: React.FC<{
}, [path, filename, mtime]);
const dirty = !readOnly && text !== null && text !== original;
+ useEffect(() => {
+ onDirtyChange?.(dirty);
+ }, [dirty, onDirtyChange]);
const language = monacoLanguage(filename);
// Monaco reuses models by `path`, so each editor INSTANCE needs a unique model URI.
// Otherwise two panes on the same file share one model while keeping separate
@@ -132,7 +145,9 @@ export const FileEditorPane: React.FC<{
useWindowCloseGuard(windowId, dirty ? t('apps.editor.confirmDiscardClose') : null);
async function save() {
- if (text === null || saving || readOnly) return;
+ // ⌘S reaches here even when the buffer is clean (the visible Save button is disabled but the
+ // Monaco command isn't); skip the no-op PUT so it doesn't bump mtime / wake file watchers.
+ if (text === null || saving || readOnly || !dirty) return;
setSaving(true);
setError(null);
try {
@@ -148,39 +163,41 @@ export const FileEditorPane: React.FC<{
return (
<div className="flex h-full min-h-0 flex-col">
- <div className="flex items-center gap-2 border-b border-border px-3 py-2">
- <span className="flex-1 truncate font-mono text-[12px] text-foreground">{filename}</span>
- {dirty && <span className="size-1.5 shrink-0 rounded-full bg-mint" title={t('apps.fileBrowser.unsaved')} />}
- {onPopOut && (
- <Button
- type="button"
- size="icon"
- variant="ghost"
- className="size-7 shrink-0 text-muted"
- aria-label={t('apps.editor.openInWindow')}
- // Block pop-out while dirty: the new window reloads from disk, so
- // popping out unsaved edits would silently drop them. Save first.
- title={dirty ? t('apps.editor.saveBeforePopOut') : t('apps.editor.openInWindow')}
- disabled={dirty}
- onClick={() => onPopOut({ mtime: savedMtime })}
- >
- <PanelRightOpen className="size-3.5" />
- </Button>
- )}
- {!readOnly && (
- <Button
- type="button"
- size="sm"
- variant="brand"
- disabled={!dirty || saving || text === null}
- onClick={() => void save()}
- className="h-7 gap-1.5 px-2.5 text-[12px]"
- >
- {saving ? <Loader2 className="size-3 animate-spin" /> : <Save className="size-3" />}
- {t('apps.fileBrowser.save')}
- </Button>
- )}
- </div>
+ {!chromeless && (
+ <div className="flex items-center gap-2 border-b border-border px-3 py-2">
+ <span className="flex-1 truncate font-mono text-[12px] text-foreground">{filename}</span>
+ {dirty && <span className="size-1.5 shrink-0 rounded-full bg-mint" title={t('apps.fileBrowser.unsaved')} />}
+ {onPopOut && (
+ <Button
+ type="button"
+ size="icon"
+ variant="ghost"
+ className="size-7 shrink-0 text-muted"
+ aria-label={t('apps.editor.openInWindow')}
+ // Block pop-out while dirty: the new window reloads from disk, so
+ // popping out unsaved edits would silently drop them. Save first.
+ title={dirty ? t('apps.editor.saveBeforePopOut') : t('apps.editor.openInWindow')}
+ disabled={dirty}
+ onClick={() => onPopOut({ mtime: savedMtime })}
+ >
+ <PanelRightOpen className="size-3.5" />
+ </Button>
+ )}
+ {!readOnly && (
+ <Button
+ type="button"
+ size="sm"
+ variant="brand"
+ disabled={!dirty || saving || text === null}
+ onClick={() => void save()}
+ className="h-7 gap-1.5 px-2.5 text-[12px]"
+ >
+ {saving ? <Loader2 className="size-3 animate-spin" /> : <Save className="size-3" />}
+ {t('apps.fileBrowser.save')}
+ </Button>
+ )}
+ </div>
+ )}
{error && (
<div className="border-b border-destructive/40 bg-destructive/[0.06] px-3 py-1.5 text-[11.5px] text-destructive">
@@ -198,8 +215,13 @@ export const FileEditorPane: React.FC<{
language={language}
path={monacoPath}
readOnly={readOnly}
- dark={resolvedTheme === 'dark'}
+ // Monaco is JS-themed (it can't read the window's `data-theme="dark"` CSS), so in the
+ // IDE (chromeless = the always-dark Editor window) force the dark theme; otherwise a
+ // light global theme leaves a white Monaco slab inside a dark window (design dnYPx is dark).
+ dark={chromeless || resolvedTheme === 'dark'}
onChange={(value) => setText(value)}
+ onSave={() => void save()}
+ onCursorChange={onCursor}
/>
</Suspense>
)}
diff --git a/ui/src/components/workbench/FileTree.tsx b/ui/src/components/workbench/FileTree.tsx
new file mode 100644
index 000000000..1f94670b2
--- /dev/null
+++ b/ui/src/components/workbench/FileTree.tsx
@@ -0,0 +1,145 @@
+import { useCallback, useEffect, 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 clsx from 'clsx';
+
+import { fileBrowserErrorMessage, joinPath, listDir, 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 }> = {
+ ts: { Icon: FileCode2, color: 'var(--cyan)' },
+ tsx: { Icon: FileCode2, color: 'var(--cyan)' },
+ js: { Icon: FileCode2, color: 'var(--gold)' },
+ jsx: { Icon: FileCode2, color: 'var(--gold)' },
+ json: { Icon: Braces, color: 'var(--gold)' },
+ css: { Icon: Hash, color: 'var(--violet)' },
+ scss: { Icon: Hash, color: 'var(--violet)' },
+ md: { Icon: FileText, color: 'var(--mint)' },
+ png: { Icon: ImageIcon, color: 'var(--muted)' },
+ jpg: { Icon: ImageIcon, color: 'var(--muted)' },
+ svg: { Icon: ImageIcon, color: 'var(--muted)' },
+};
+
+function fileIcon(e: FsEntry) {
+ return EXT[e.ext?.toLowerCase()] ?? { Icon: FileIcon, color: 'var(--muted)' };
+}
+
+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 }) => (
+ <button
+ type="button"
+ onClick={onClick}
+ 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',
+ active ? 'bg-cyan-soft text-foreground' : 'text-foreground hover:bg-foreground/[0.05]',
+ )}
+ >
+ {children}
+ </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 { t } = useTranslation();
+ 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 load = useCallback(() => {
+ setLoading(true);
+ setError(null);
+ listDir(path, showHidden)
+ .then((r) => 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.
+ setEntries([]);
+ setError(fileBrowserErrorMessage(e, t, t('apps.fileBrowser.errors.listFailed')));
+ })
+ .finally(() => setLoading(false));
+ }, [path, showHidden, t]);
+
+ useEffect(() => {
+ if (open && entries === null) load();
+ }, [open, entries, load]);
+ // Re-list an open folder when the hidden toggle flips.
+ useEffect(() => {
+ if (open) load();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [showHidden]);
+
+ 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>
+ )}
+ {open && (
+ <div>
+ {loading && entries === null && (
+ <div style={{ paddingLeft: 8 + (depth + 1) * 14 }} className="py-1">
+ <Loader2 className="size-3.5 animate-spin text-muted" />
+ </div>
+ )}
+ {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.
+ <button
+ type="button"
+ onClick={load}
+ style={{ paddingLeft: 8 + (depth + 1) * 14 }}
+ className="flex w-full items-center gap-1 truncate py-1 pr-2 text-left text-[11.5px] text-destructive transition hover:bg-destructive/[0.06]"
+ title={`${error} — ${t('common.retry')}`}
+ >
+ <span className="truncate">{error}</span>
+ </button>
+ )}
+ {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} />
+ ) : (
+ (() => {
+ 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>
+ );
+ })()
+ ),
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+// 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} />
+);
diff --git a/ui/src/components/workbench/MonacoEditor.tsx b/ui/src/components/workbench/MonacoEditor.tsx
index 260712920..aeb3972de 100644
--- a/ui/src/components/workbench/MonacoEditor.tsx
+++ b/ui/src/components/workbench/MonacoEditor.tsx
@@ -1,4 +1,4 @@
-import { useRef } from 'react';
+import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { ClipboardCopy, TextSelect } from 'lucide-react';
import * as monaco from 'monaco-editor';
@@ -98,14 +98,31 @@ export interface MonacoEditorProps {
/** Resolved app theme — drives the dark VS Code theme vs the light one. */
dark?: boolean;
onChange?: (value: string) => void;
+ /** Save the file — bound to ⌘S / Ctrl+S inside the editor (the IDE has no visible save button). */
+ onSave?: () => void;
+ /** Live 1-based cursor position, for an IDE status bar (`Ln x, Col y`). */
+ onCursorChange?: (line: number, column: number) => void;
}
-export default function MonacoEditor({ value, language, path, readOnly, dark = true, onChange }: MonacoEditorProps) {
+export default function MonacoEditor({ value, language, path, readOnly, dark = true, onChange, onSave, onCursorChange }: MonacoEditorProps) {
const { t } = useTranslation();
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor | null>(null);
+ // Keep the latest callbacks in refs: the ⌘S command + cursor listener are bound
+ // once on mount (Monaco can't cleanly rebind a command), so they must read live
+ // closures rather than capture the first render's.
+ const onSaveRef = useRef(onSave);
+ const onCursorRef = useRef(onCursorChange);
+ useEffect(() => {
+ onSaveRef.current = onSave;
+ onCursorRef.current = onCursorChange;
+ });
const handleMount: OnMount = (editor) => {
editorRef.current = editor;
+ editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => onSaveRef.current?.());
+ const pos = editor.getPosition();
+ if (pos) onCursorRef.current?.(pos.lineNumber, pos.column);
+ editor.onDidChangeCursorPosition((e) => onCursorRef.current?.(e.position.lineNumber, e.position.column));
};
const handleChange: OnChange = (next) => onChange?.(next ?? '');
diff --git a/ui/src/components/workbench/TerminalTabs.tsx b/ui/src/components/workbench/TerminalTabs.tsx
new file mode 100644
index 000000000..33d965da2
--- /dev/null
+++ b/ui/src/components/workbench/TerminalTabs.tsx
@@ -0,0 +1,193 @@
+import { Suspense, lazy, useEffect, useRef, useState } from 'react';
+import { Plus, SquareTerminal, X } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import clsx from 'clsx';
+
+import { useApi } from '../../context/ApiContext';
+import { apiFetch } from '../../lib/apiFetch';
+import { acquireTerminalSlot, releaseTerminalSlot } from '../../lib/terminalSlots';
+
+// Lazy so xterm.js stays out of the main bundle until a terminal opens.
+const TerminalView = lazy(() => import('./TerminalView').then((m) => ({ default: m.TerminalView })));
+
+const FALLBACK_SESSION_ID = `wb-${Math.random().toString(36).slice(2, 10)}`;
+// Per-tab token, so two browser tabs / windows don't collide on the same slot id.
+const TAB_TOKEN = Math.random().toString(36).slice(2, 8);
+
+function getSessionId(identity: string | null, key?: string): string {
+ const KEY = identity ? `avibe.terminal.sessionId.${encodeURIComponent(identity)}` : 'avibe.terminal.sessionId';
+ try {
+ let id = window.localStorage.getItem(KEY);
+ if (!id) {
+ id = `wb-${Math.random().toString(36).slice(2, 10)}`;
+ window.localStorage.setItem(KEY, id);
+ }
+ return key ? `${id}-${key}` : id;
+ } catch {
+ return key ? `${FALLBACK_SESSION_ID}-${key}` : FALLBACK_SESSION_ID;
+ }
+}
+
+type Tab = { key: number; slot: number | null };
+
+// DELETE a slot-backed terminal session, then release its slot ONLY on a confirmed teardown
+// (HTTP ok or 404). If the delete failed (expired auth, CSRF/origin rejection, network error, 5xx)
+// the tmux session may still be alive, so the slot stays reserved — otherwise the next tab could
+// reuse the same `<base>-wN` id and reconnect to the previous shell, exposing its state.
+function deleteTerminalSession(sid: string, slot: number, keepalive = false): void {
+ apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, { method: 'DELETE', credentials: 'same-origin', keepalive })
+ .then((res) => {
+ if (res.ok || res.status === 404) releaseTerminalSlot(slot);
+ })
+ .catch(() => undefined);
+}
+
+// A multi-tab terminal: a tab bar (each tab = its own backend session) over the lazy
+// xterm view. Reusable — the standalone Terminal app and (later) the editor's integrated
+// terminal both mount this. Design: design.pen `iwYIX`.
+// - windowed: every tab is an ephemeral, slot-bounded session, disposed on close.
+// - route (non-windowed): the FIRST tab keeps the persistent localStorage session (so it
+// reconnects across reloads); extra tabs are slot-bounded like the windowed ones.
+export const TerminalTabs: React.FC<{ windowed?: boolean }> = ({ windowed = false }) => {
+ const { t } = useTranslation();
+ const { getAuthSession } = useApi();
+ const [identity, setIdentity] = useState<string | null | undefined>(undefined); // undefined = resolving
+ const tabSeq = useRef(0);
+ const [tabs, setTabs] = useState<Tab[]>(() => [{ key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null }]);
+ const [active, setActive] = useState<number>(() => tabs[0]?.key ?? 0);
+ // Whether sessions actually persist (tmux available) — reported by TerminalView's ready frame.
+ // Drives the tab-bar badge so it never falsely promises persistence for a plain-shell fallback.
+ const [persistent, setPersistent] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ getAuthSession()
+ .then((s) => !cancelled && setIdentity(s.remote && s.authenticated ? s.sub || s.email : null))
+ .catch(() => !cancelled && setIdentity(null));
+ return () => {
+ cancelled = true;
+ };
+ }, [getAuthSession]);
+
+ const sessionIdFor = (tab: Tab): string | null =>
+ identity === undefined ? null : getSessionId(identity, tab.slot != null ? `${TAB_TOKEN}-w${tab.slot}` : undefined);
+
+ // Best-effort dispose of a slot-backed (ephemeral) session; persistent tabs are left alone.
+ const disposeTab = (tab: Tab, keepalive = false) => {
+ if (tab.slot == null) return;
+ const sid = sessionIdFor(tab);
+ // No session id yet (identity unresolved → TerminalView never mounted) → no backend session
+ // exists, so the slot is safe to release now. Otherwise release only after DELETE confirms.
+ if (sid == null) releaseTerminalSlot(tab.slot);
+ else deleteTerminalSession(sid, tab.slot, keepalive);
+ };
+
+ const addTab = () => {
+ const tab: Tab = { key: ++tabSeq.current, slot: acquireTerminalSlot() };
+ setTabs((ts) => [...ts, tab]);
+ setActive(tab.key);
+ };
+ const closeTab = (key: number) => {
+ setTabs((ts) => {
+ const tab = ts.find((x) => x.key === key);
+ if (tab) disposeTab(tab);
+ const rest = ts.filter((x) => x.key !== key);
+ if (rest.length === 0) {
+ const fresh: Tab = { key: ++tabSeq.current, slot: windowed ? acquireTerminalSlot() : null };
+ setActive(fresh.key);
+ return [fresh];
+ }
+ if (active === key) setActive(rest[rest.length - 1].key);
+ return rest;
+ });
+ };
+
+ // Dispose every ephemeral session on unmount (window close) + on tab/page unload, reading
+ // the live tabs from a ref so the listeners don't churn as tabs change.
+ const liveRef = useRef<{ tabs: Tab[]; resolve: (t: Tab) => string | null }>({ tabs, resolve: sessionIdFor });
+ liveRef.current = { tabs, resolve: sessionIdFor };
+ useEffect(() => {
+ const onHide = () => {
+ for (const tab of liveRef.current.tabs) {
+ if (tab.slot == null) continue;
+ const sid = liveRef.current.resolve(tab);
+ if (sid) void apiFetch(`/api/terminal/${encodeURIComponent(sid)}`, { method: 'DELETE', credentials: 'same-origin', keepalive: true }).catch(() => undefined);
+ }
+ };
+ window.addEventListener('pagehide', onHide);
+ return () => {
+ window.removeEventListener('pagehide', onHide);
+ for (const tab of liveRef.current.tabs) {
+ if (tab.slot == null) continue;
+ const sid = liveRef.current.resolve(tab);
+ if (sid == null) releaseTerminalSlot(tab.slot);
+ else deleteTerminalSession(sid, tab.slot);
+ }
+ };
+ }, []);
+
+ const loading = <div className="grid h-full w-full place-items-center text-[12px] text-muted">{t('common.loading')}</div>;
+
+ return (
+ <div className="flex h-full min-h-0 w-full flex-col bg-surface">
+ {/* Tab bar (iwYIX): tabs + +, persistent badge on the right. */}
+ <div className="flex items-center gap-1 border-b border-border bg-surface-2/70 px-2 py-1">
+ <div className="flex min-w-0 flex-1 items-center gap-1 overflow-x-auto">
+ {tabs.map((tab, i) => (
+ <div
+ key={tab.key}
+ className={clsx(
+ 'group/tab flex shrink-0 items-center gap-1.5 rounded-md px-2.5 py-1 text-[12px] transition',
+ tab.key === active ? 'bg-surface text-foreground shadow-[inset_0_-2px_0_0_var(--mint)]' : 'text-muted hover:bg-foreground/[0.05]',
+ )}
+ >
+ <button type="button" onClick={() => setActive(tab.key)} className="flex items-center gap-1.5">
+ <SquareTerminal className="size-3.5 text-mint" />
+ {t('apps.terminal.tabTitle', { n: i + 1 })}
+ </button>
+ <button
+ type="button"
+ onClick={() => closeTab(tab.key)}
+ aria-label={t('common.close')}
+ className="grid size-4 place-items-center rounded text-muted opacity-0 transition hover:bg-foreground/10 hover:text-foreground group-hover/tab:opacity-100"
+ >
+ <X className="size-3" strokeWidth={2.5} />
+ </button>
+ </div>
+ ))}
+ <button
+ type="button"
+ onClick={addTab}
+ aria-label={t('apps.terminal.newTab')}
+ title={t('apps.terminal.newTab')}
+ className="grid size-6 shrink-0 place-items-center rounded-md text-muted transition hover:bg-foreground/[0.06] hover:text-foreground"
+ >
+ <Plus className="size-3.5" strokeWidth={2.5} />
+ </button>
+ </div>
+ {persistent && (
+ <span className="shrink-0 rounded-full border border-mint/30 bg-mint/[0.08] px-2 py-0.5 text-[10px] font-medium text-mint">
+ {t('apps.terminal.persistent')}
+ </span>
+ )}
+ </div>
+
+ {/* Panels: all tabs stay mounted so switching preserves each shell; hidden ones use
+ display:none, so showing one fires the TerminalView ResizeObserver → refit. */}
+ <div className="relative min-h-0 flex-1">
+ {tabs.map((tab) => {
+ const sid = sessionIdFor(tab);
+ return (
+ <div key={tab.key} className={clsx('absolute inset-0', tab.key === active ? 'block' : 'hidden')}>
+ {sid == null ? loading : (
+ <Suspense fallback={loading}>
+ <TerminalView sessionId={sid} onPersistent={setPersistent} />
+ </Suspense>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/workbench/TerminalView.tsx b/ui/src/components/workbench/TerminalView.tsx
index 4a2c63b15..b7260c965 100644
--- a/ui/src/components/workbench/TerminalView.tsx
+++ b/ui/src/components/workbench/TerminalView.tsx
@@ -38,7 +38,7 @@ function buildWsUrl(sessionId: string): string {
return `${proto}://${window.location.host}/api/terminal/${encodeURIComponent(sessionId)}`;
}
-export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) => {
+export const TerminalView: React.FC<{ sessionId: string; onPersistent?: (persistent: boolean) => void }> = ({ sessionId, onPersistent }) => {
const { t } = useTranslation();
const containerRef = useRef<HTMLDivElement | null>(null);
const termRef = useRef<Terminal | null>(null);
@@ -46,8 +46,12 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
const ctrlStickyRef = useRef(false);
const busyRetriesRef = useRef(0);
const retryTimerRef = useRef<number | null>(null);
+ // Report actual session persistence (from the backend 'ready' frame) up to the tab bar, so its
+ // badge reflects reality — tmux-backed = persistent, plain-shell fallback = not. Held in a ref so
+ // the WS effect (which doesn't depend on the prop) always calls the latest callback.
+ const onPersistentRef = useRef(onPersistent);
+ onPersistentRef.current = onPersistent;
const [status, setStatus] = useState<Status>('connecting');
- const [persistent, setPersistent] = useState(false);
const [exitCode, setExitCode] = useState<number | null>(null);
const [reconnectKey, setReconnectKey] = useState(0);
@@ -62,13 +66,27 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
const fit = new FitAddon();
term.loadAddon(fit);
termRef.current = term;
- if (containerRef.current) {
- term.open(containerRef.current);
+ const refit = () => {
+ const el = containerRef.current;
+ // Skip when the container is hidden (a background tab uses display:none → 0×0): fitting to
+ // zero would send a tiny {cols,rows} resize to the PTY and disrupt full-screen programs /
+ // shells running in inactive tabs. The ResizeObserver fires again with real dimensions when
+ // the tab is shown.
+ if (!el || el.clientWidth === 0 || el.clientHeight === 0) return;
try {
fit.fit();
} catch {
/* container not measured yet */
}
+ };
+ if (containerRef.current) {
+ term.open(containerRef.current);
+ refit();
+ // The window opens with a scale transition (transform doesn't change layout size,
+ // so the container's height is already real) but the first fit can still land before
+ // the panel is laid out — refit on the next frame so xterm uses the FULL height
+ // instead of getting stuck a few rows tall (the "only top half / can't scroll" bug).
+ requestAnimationFrame(refit);
}
const onData = term.onData((data: string) => {
@@ -93,7 +111,7 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
wsRef.current = ws;
ws.onopen = () => {
try {
- fit.fit();
+ refit();
} catch {
/* noop */
}
@@ -105,7 +123,7 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
if (msg.type === 'ready') {
busyRetriesRef.current = 0; // a successful attach resets the transient-retry budget
setStatus('ready');
- setPersistent(!!msg.persistent);
+ onPersistentRef.current?.(!!msg.persistent);
} else if (msg.type === 'exit') {
setExitCode(typeof msg.code === 'number' ? msg.code : null);
setStatus('closed');
@@ -135,13 +153,7 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
);
};
- const ro = new ResizeObserver(() => {
- try {
- fit.fit();
- } catch {
- /* noop */
- }
- });
+ const ro = new ResizeObserver(() => refit());
if (containerRef.current) ro.observe(containerRef.current);
return () => {
@@ -191,9 +203,6 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
{t(`apps.terminal.status.${status}`)}
{status === 'closed' && exitCode != null ? ` · ${t('apps.terminal.exitCode', { code: exitCode })}` : ''}
</span>
- {status === 'ready' && persistent && (
- <span className="rounded-full border border-border px-1.5 text-[10px]">{t('apps.terminal.persistent')}</span>
- )}
{(status === 'closed' || status === 'error') && (
<Button
type="button"
@@ -219,7 +228,9 @@ export const TerminalView: React.FC<{ sessionId: string }> = ({ sessionId }) =>
)}
{status !== 'disabled' && (
- <div className="flex gap-1 overflow-x-auto border-t border-border bg-surface px-2 py-1.5 md:hidden">
+ // The accessory key bar shows on desktop too (design iwYIX): quick esc/tab/ctrl/arrows
+ // without leaving the window. On phones it's essential (soft keyboards lack these keys).
+ <div className="flex gap-1 overflow-x-auto border-t border-border bg-surface px-2 py-1.5">
{KEYS.map((k) => (
<button
key={k.labelKey}
diff --git a/ui/src/context/WindowManagerContext.tsx b/ui/src/context/WindowManagerContext.tsx
index 8ca93a7dd..3b978231d 100644
--- a/ui/src/context/WindowManagerContext.tsx
+++ b/ui/src/context/WindowManagerContext.tsx
@@ -99,7 +99,9 @@ export const WindowManagerProvider: React.FC<{ children: React.ReactNode }> = ({
const id = `win-${++idSeq.current}`;
const z = ++zSeq.current;
const bounds: WindowBounds = {
- x: 40 + i * CASCADE_STEP,
+ // Cascade starts clear of the 240px sidebar so a new window doesn't open over it
+ // (the layer now spans the full viewport); it can still be dragged/maximized over it.
+ x: 264 + i * CASCADE_STEP,
y: 32 + i * CASCADE_STEP,
width: size.width,
height: size.height,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 020fdb4f2..96ff4f1da 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -16,6 +16,7 @@
"configure": "Configure",
"cancel": "Cancel",
"clear": "Clear",
+ "retry": "Retry",
"loading": "Loading...",
"saving": "Saving...",
"saved": "Saved",
@@ -163,7 +164,9 @@
"label": "Custom link",
"hint": "3–64 letters, numbers, dash, or underscore. Must be unique.",
"placeholder": "my-page",
- "toast": { "saved": "Custom link updated" },
+ "toast": {
+ "saved": "Custom link updated"
+ },
"errors": {
"taken": "That custom link is already taken. Pick another.",
"invalid": "Use 3–64 letters, numbers, dash, or underscore, starting and ending with a letter or number.",
@@ -558,9 +561,9 @@
"paired": "Pairing",
"connector": "Remote access",
"flowTitle": "Setup steps",
- "flowStep1": "Open <console>avibe.bot</console>, sign in, click \u201CPair an Avibe\u201D, and claim your own domain.",
+ "flowStep1": "Open <console>avibe.bot</console>, sign in, click “Pair an Avibe”, and claim your own domain.",
"flowStep2": "Copy the pairing key shown there.",
- "flowStep3": "Paste it here to finish pairing \u2014 then reach Avibe from anywhere.",
+ "flowStep3": "Paste it here to finish pairing — then reach Avibe from anywhere.",
"actionNeeded": "Action needed",
"ready": "Ready",
"stateNeedsAttention": "Needs attention"
@@ -604,6 +607,19 @@
"editor": {
"label": "Editor",
"desc": "A fast code editor for files on this machine.",
+ "explorer": "Explorer",
+ "noFolder": "No folder opened",
+ "welcomeSub": "A code editor for files on this machine · VS Code engine",
+ "start": "Start",
+ "recent": "Recent",
+ "noRecent": "No recent folders",
+ "openFolder": "Open Folder…",
+ "openFolderPrompt": "Folder path to open",
+ "browseFiles": "Browse Files…",
+ "selectFileHint": "Select a file from the explorer to edit",
+ "lineCol": "Ln {{line}}, Col {{col}}",
+ "spaces": "Spaces: {{n}}",
+ "plainText": "Plain Text",
"empty": "No file open",
"emptyHint": "Open a file from Files to edit it here.",
"openInWindow": "Open in editor window",
@@ -613,7 +629,9 @@
"copyAll": "Copy all"
},
"dock": {
- "newInstanceHint": "⌘-click for a new window"
+ "newInstanceHint": "⌘-click for a new window",
+ "newWindow": "New Window",
+ "showAllWindows": "Show All Windows"
},
"window": {
"minimize": "Minimize",
@@ -631,8 +649,17 @@
"download": "Download",
"tooLarge": "This file is too large to edit in the browser. Download it to view it instead.",
"refresh": "Refresh",
- "newFolder": "New folder",
+ "newFolder": "New Folder",
"newFolderPrompt": "New folder name",
+ "newFile": "New File",
+ "newFilePrompt": "New file name",
+ "searchPlaceholder": "Search",
+ "colName": "Name",
+ "colSize": "Size",
+ "colModified": "Modified",
+ "favorites": "Favorites",
+ "noMatches": "No matches",
+ "itemCount": "{{count}} items",
"projects": "Projects",
"system": "System",
"showHidden": "Show hidden files",
@@ -666,6 +693,8 @@
"placeholder": "The Terminal arrives in Phase 2: a real shell with tmux-backed persistent sessions.",
"tagline": "A real shell, in your browser.",
"persistent": "Persistent",
+ "tabTitle": "Shell {{n}}",
+ "newTab": "New tab",
"reconnect": "Reconnect",
"exitCode": "exit {{code}}",
"disabled": "Terminal unavailable: it may be turned off on the server (VIBE_UI_ENABLE_TERMINAL=0) or this session isn't authorized.",
@@ -692,7 +721,7 @@
"appShell": {
"title": "Avibe OS",
"subtitle": "Agent OS · Workbench",
- "workspaceLabel": "Workspace",
+ "workspaceLabel": "Settings",
"moreSettings": "More Settings",
"openControlPanel": "Settings",
"backToWorkbench": "Back to Workbench",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index e25adcb68..12894f5a2 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -16,6 +16,7 @@
"configure": "配置",
"cancel": "取消",
"clear": "清除",
+ "retry": "重试",
"loading": "加载中...",
"saving": "保存中...",
"saved": "已保存",
@@ -163,7 +164,9 @@
"label": "自定义链接",
"hint": "3–64 位,可用字母、数字、短横线或下划线,需唯一。",
"placeholder": "my-page",
- "toast": { "saved": "自定义链接已更新" },
+ "toast": {
+ "saved": "自定义链接已更新"
+ },
"errors": {
"taken": "这个自定义链接已被占用,换一个。",
"invalid": "请使用 3–64 位字母、数字、短横线或下划线,且首尾为字母或数字。",
@@ -604,6 +607,19 @@
"editor": {
"label": "编辑器",
"desc": "本机文件的快速代码编辑器。",
+ "explorer": "资源管理器",
+ "noFolder": "未打开文件夹",
+ "welcomeSub": "本机文件的代码编辑器 · VS Code 内核",
+ "start": "开始",
+ "recent": "最近",
+ "noRecent": "暂无最近打开的目录",
+ "openFolder": "打开文件夹…",
+ "openFolderPrompt": "要打开的文件夹路径",
+ "browseFiles": "浏览文件…",
+ "selectFileHint": "从左侧资源管理器选择文件进行编辑",
+ "lineCol": "行 {{line}},列 {{col}}",
+ "spaces": "空格:{{n}}",
+ "plainText": "纯文本",
"empty": "未打开文件",
"emptyHint": "从「文件」中打开一个文件,在这里编辑。",
"openInWindow": "在编辑器窗口中打开",
@@ -613,7 +629,9 @@
"copyAll": "全部复制"
},
"dock": {
- "newInstanceHint": "⌘ 点击可新建窗口"
+ "newInstanceHint": "⌘ 点击可新建窗口",
+ "newWindow": "新建窗口",
+ "showAllWindows": "显示所有窗口"
},
"window": {
"minimize": "最小化",
@@ -633,6 +651,15 @@
"refresh": "刷新",
"newFolder": "新建文件夹",
"newFolderPrompt": "新文件夹名称",
+ "newFile": "新建文件",
+ "newFilePrompt": "新文件名称",
+ "searchPlaceholder": "搜索",
+ "colName": "名称",
+ "colSize": "大小",
+ "colModified": "修改时间",
+ "favorites": "收藏",
+ "noMatches": "无匹配项",
+ "itemCount": "{{count}} 项",
"projects": "项目",
"system": "系统",
"showHidden": "显示隐藏文件",
@@ -666,6 +693,8 @@
"placeholder": "终端将在第二阶段上线:真实 shell,配 tmux 持久化会话。",
"tagline": "在浏览器里跑真实 shell。",
"persistent": "持久会话",
+ "tabTitle": "终端 {{n}}",
+ "newTab": "新建标签",
"reconnect": "重新连接",
"exitCode": "退出码 {{code}}",
"disabled": "终端不可用:可能在服务端被关掉(VIBE_UI_ENABLE_TERMINAL=0),或当前会话未获授权。",
@@ -692,7 +721,7 @@
"appShell": {
"title": "Avibe OS",
"subtitle": "Agent操作系统 · 工作台",
- "workspaceLabel": "工作区",
+ "workspaceLabel": "设置",
"moreSettings": "更多设置",
"openControlPanel": "设置",
"backToWorkbench": "返回工作台",
diff --git a/ui/src/lib/filePreview.ts b/ui/src/lib/filePreview.ts
index 3a537d610..28629a788 100644
--- a/ui/src/lib/filePreview.ts
+++ b/ui/src/lib/filePreview.ts
@@ -82,6 +82,14 @@ export function previewKind(name: string, mime?: string | null, serverExt?: stri
return null;
}
+// Whether a directory entry / file should open in the in-app editor rather than download: a
+// regular file (NOT a symlink — the backend refuses to write through one — or a directory), with a
+// previewable/text kind, within the size cap. Shared by the File Browser and the editor explorer
+// so both gate opens identically.
+export function isEditableFile(entry: { kind: string; size: number | null; name: string }): boolean {
+ return entry.kind === 'file' && previewKind(entry.name) != null && (entry.size == null || entry.size <= 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 752e96a15..1cef3f1f5 100644
--- a/ui/src/lib/filesApi.ts
+++ b/ui/src/lib/filesApi.ts
@@ -122,6 +122,13 @@ export function pathCrumbs(path: string): { label: string; path: string }[] {
return out;
}
+// The parent directory of a path, Windows-aware (reuses pathCrumbs' separator handling) so the
+// editor opens its explorer on the right root for POSIX, Windows drive, and UNC paths alike.
+export function parentDir(path: string): string {
+ const crumbs = pathCrumbs(path);
+ return crumbs.length >= 2 ? crumbs[crumbs.length - 2].path : path;
+}
+
export async function listDir(path: string, showHidden = false): Promise<FsListing> {
const res = await apiFetch(
`/api/files/list?path=${encodeURIComponent(path)}&show_hidden=${showHidden ? '1' : '0'}`,
@@ -137,6 +144,27 @@ export function contentUrl(path: string, download = false): string {
return `/api/files/content?path=${encodeURIComponent(path)}${download ? '&download=1' : ''}`;
}
+// Trigger a file download via a programmatic anchor click rather than window.open. An anchor
+// download is not a popup, so — unlike window.open('_blank') — it isn't popup-blocked and survives
+// an awaited metadata recheck without losing the click's user activation (Safari/iOS). The backend's
+// Content-Disposition (download=1) names the file and forces the save in-place.
+export function downloadFile(path: string): void {
+ const a = document.createElement('a');
+ a.href = contentUrl(path, true);
+ a.rel = 'noopener';
+ // target=_blank: if remote-auth expired, /content 302-redirects to the Cloud login — that
+ // cross-origin redirect would otherwise replace the SPA in this tab. Sending it to a new context
+ // keeps the app intact (a real attachment still downloads in-place, so no stray tab opens).
+ a.target = '_blank';
+ // download attr: keep this a download even if the server returns a JSON error (file removed /
+ // permission) instead of an attachment, so the SPA is never navigated to the error body.
+ a.download = '';
+ a.style.display = 'none';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
+
export async function readText(path: string): Promise<string> {
const res = await apiFetch(contentUrl(path));
if (!res.ok) {
@@ -157,11 +185,14 @@ export async function writeFile(
path: string,
content: string,
expectedMtime?: number | null,
+ // create_only: backend refuses (errors.exists) if the path already exists, checked atomically
+ // under its per-path write lock — used by "New File" so a name typo can never clobber a file.
+ createOnly = false,
): Promise<{ ok: true; mtime: number }> {
const res = await apiFetch('/api/files/write', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ path, content, expected_mtime: expectedMtime ?? undefined }),
+ body: JSON.stringify({ path, content, expected_mtime: expectedMtime ?? undefined, create_only: createOnly || undefined }),
});
return parse<{ ok: true; mtime: number }>(res);
}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 49f2f3322..5977f092f 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5359,6 +5359,7 @@ async def files_write(starlette_request: FastAPIRequest):
payload.get("path") or "",
payload.get("content"),
expected_mtime=payload.get("expected_mtime"),
+ create_only=_parse_explicit_bool(payload.get("create_only")),
)
)
except Exception as exc: